e5c057996353b452329a7f63fdd46c936576765c
[firefly-linux-kernel-4.4.55.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include <drm/drm_atomic_helper.h>
41 #include <drm/drm_dp_helper.h>
42 #include <drm/drm_crtc_helper.h>
43 #include <drm/drm_plane_helper.h>
44 #include <drm/drm_rect.h>
45 #include <linux/dma_remapping.h>
46
47 /* Primary plane formats supported by all gen */
48 #define COMMON_PRIMARY_FORMATS \
49         DRM_FORMAT_C8, \
50         DRM_FORMAT_RGB565, \
51         DRM_FORMAT_XRGB8888, \
52         DRM_FORMAT_ARGB8888
53
54 /* Primary plane formats for gen <= 3 */
55 static const uint32_t intel_primary_formats_gen2[] = {
56         COMMON_PRIMARY_FORMATS,
57         DRM_FORMAT_XRGB1555,
58         DRM_FORMAT_ARGB1555,
59 };
60
61 /* Primary plane formats for gen >= 4 */
62 static const uint32_t intel_primary_formats_gen4[] = {
63         COMMON_PRIMARY_FORMATS, \
64         DRM_FORMAT_XBGR8888,
65         DRM_FORMAT_ABGR8888,
66         DRM_FORMAT_XRGB2101010,
67         DRM_FORMAT_ARGB2101010,
68         DRM_FORMAT_XBGR2101010,
69         DRM_FORMAT_ABGR2101010,
70 };
71
72 /* Cursor formats */
73 static const uint32_t intel_cursor_formats[] = {
74         DRM_FORMAT_ARGB8888,
75 };
76
77 static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
78
79 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
80                                 struct intel_crtc_state *pipe_config);
81 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
82                                    struct intel_crtc_state *pipe_config);
83
84 static int intel_set_mode(struct drm_crtc *crtc, struct drm_display_mode *mode,
85                           int x, int y, struct drm_framebuffer *old_fb);
86 static int intel_framebuffer_init(struct drm_device *dev,
87                                   struct intel_framebuffer *ifb,
88                                   struct drm_mode_fb_cmd2 *mode_cmd,
89                                   struct drm_i915_gem_object *obj);
90 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
91 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
92 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
93                                          struct intel_link_m_n *m_n,
94                                          struct intel_link_m_n *m2_n2);
95 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
96 static void haswell_set_pipeconf(struct drm_crtc *crtc);
97 static void intel_set_pipe_csc(struct drm_crtc *crtc);
98 static void vlv_prepare_pll(struct intel_crtc *crtc,
99                             const struct intel_crtc_state *pipe_config);
100 static void chv_prepare_pll(struct intel_crtc *crtc,
101                             const struct intel_crtc_state *pipe_config);
102 static void intel_begin_crtc_commit(struct drm_crtc *crtc);
103 static void intel_finish_crtc_commit(struct drm_crtc *crtc);
104
105 static struct intel_encoder *intel_find_encoder(struct intel_connector *connector, int pipe)
106 {
107         if (!connector->mst_port)
108                 return connector->encoder;
109         else
110                 return &connector->mst_port->mst_encoders[pipe]->base;
111 }
112
113 typedef struct {
114         int     min, max;
115 } intel_range_t;
116
117 typedef struct {
118         int     dot_limit;
119         int     p2_slow, p2_fast;
120 } intel_p2_t;
121
122 typedef struct intel_limit intel_limit_t;
123 struct intel_limit {
124         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
125         intel_p2_t          p2;
126 };
127
128 int
129 intel_pch_rawclk(struct drm_device *dev)
130 {
131         struct drm_i915_private *dev_priv = dev->dev_private;
132
133         WARN_ON(!HAS_PCH_SPLIT(dev));
134
135         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
136 }
137
138 static inline u32 /* units of 100MHz */
139 intel_fdi_link_freq(struct drm_device *dev)
140 {
141         if (IS_GEN5(dev)) {
142                 struct drm_i915_private *dev_priv = dev->dev_private;
143                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
144         } else
145                 return 27;
146 }
147
148 static const intel_limit_t intel_limits_i8xx_dac = {
149         .dot = { .min = 25000, .max = 350000 },
150         .vco = { .min = 908000, .max = 1512000 },
151         .n = { .min = 2, .max = 16 },
152         .m = { .min = 96, .max = 140 },
153         .m1 = { .min = 18, .max = 26 },
154         .m2 = { .min = 6, .max = 16 },
155         .p = { .min = 4, .max = 128 },
156         .p1 = { .min = 2, .max = 33 },
157         .p2 = { .dot_limit = 165000,
158                 .p2_slow = 4, .p2_fast = 2 },
159 };
160
161 static const intel_limit_t intel_limits_i8xx_dvo = {
162         .dot = { .min = 25000, .max = 350000 },
163         .vco = { .min = 908000, .max = 1512000 },
164         .n = { .min = 2, .max = 16 },
165         .m = { .min = 96, .max = 140 },
166         .m1 = { .min = 18, .max = 26 },
167         .m2 = { .min = 6, .max = 16 },
168         .p = { .min = 4, .max = 128 },
169         .p1 = { .min = 2, .max = 33 },
170         .p2 = { .dot_limit = 165000,
171                 .p2_slow = 4, .p2_fast = 4 },
172 };
173
174 static const intel_limit_t intel_limits_i8xx_lvds = {
175         .dot = { .min = 25000, .max = 350000 },
176         .vco = { .min = 908000, .max = 1512000 },
177         .n = { .min = 2, .max = 16 },
178         .m = { .min = 96, .max = 140 },
179         .m1 = { .min = 18, .max = 26 },
180         .m2 = { .min = 6, .max = 16 },
181         .p = { .min = 4, .max = 128 },
182         .p1 = { .min = 1, .max = 6 },
183         .p2 = { .dot_limit = 165000,
184                 .p2_slow = 14, .p2_fast = 7 },
185 };
186
187 static const intel_limit_t intel_limits_i9xx_sdvo = {
188         .dot = { .min = 20000, .max = 400000 },
189         .vco = { .min = 1400000, .max = 2800000 },
190         .n = { .min = 1, .max = 6 },
191         .m = { .min = 70, .max = 120 },
192         .m1 = { .min = 8, .max = 18 },
193         .m2 = { .min = 3, .max = 7 },
194         .p = { .min = 5, .max = 80 },
195         .p1 = { .min = 1, .max = 8 },
196         .p2 = { .dot_limit = 200000,
197                 .p2_slow = 10, .p2_fast = 5 },
198 };
199
200 static const intel_limit_t intel_limits_i9xx_lvds = {
201         .dot = { .min = 20000, .max = 400000 },
202         .vco = { .min = 1400000, .max = 2800000 },
203         .n = { .min = 1, .max = 6 },
204         .m = { .min = 70, .max = 120 },
205         .m1 = { .min = 8, .max = 18 },
206         .m2 = { .min = 3, .max = 7 },
207         .p = { .min = 7, .max = 98 },
208         .p1 = { .min = 1, .max = 8 },
209         .p2 = { .dot_limit = 112000,
210                 .p2_slow = 14, .p2_fast = 7 },
211 };
212
213
214 static const intel_limit_t intel_limits_g4x_sdvo = {
215         .dot = { .min = 25000, .max = 270000 },
216         .vco = { .min = 1750000, .max = 3500000},
217         .n = { .min = 1, .max = 4 },
218         .m = { .min = 104, .max = 138 },
219         .m1 = { .min = 17, .max = 23 },
220         .m2 = { .min = 5, .max = 11 },
221         .p = { .min = 10, .max = 30 },
222         .p1 = { .min = 1, .max = 3},
223         .p2 = { .dot_limit = 270000,
224                 .p2_slow = 10,
225                 .p2_fast = 10
226         },
227 };
228
229 static const intel_limit_t intel_limits_g4x_hdmi = {
230         .dot = { .min = 22000, .max = 400000 },
231         .vco = { .min = 1750000, .max = 3500000},
232         .n = { .min = 1, .max = 4 },
233         .m = { .min = 104, .max = 138 },
234         .m1 = { .min = 16, .max = 23 },
235         .m2 = { .min = 5, .max = 11 },
236         .p = { .min = 5, .max = 80 },
237         .p1 = { .min = 1, .max = 8},
238         .p2 = { .dot_limit = 165000,
239                 .p2_slow = 10, .p2_fast = 5 },
240 };
241
242 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
243         .dot = { .min = 20000, .max = 115000 },
244         .vco = { .min = 1750000, .max = 3500000 },
245         .n = { .min = 1, .max = 3 },
246         .m = { .min = 104, .max = 138 },
247         .m1 = { .min = 17, .max = 23 },
248         .m2 = { .min = 5, .max = 11 },
249         .p = { .min = 28, .max = 112 },
250         .p1 = { .min = 2, .max = 8 },
251         .p2 = { .dot_limit = 0,
252                 .p2_slow = 14, .p2_fast = 14
253         },
254 };
255
256 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
257         .dot = { .min = 80000, .max = 224000 },
258         .vco = { .min = 1750000, .max = 3500000 },
259         .n = { .min = 1, .max = 3 },
260         .m = { .min = 104, .max = 138 },
261         .m1 = { .min = 17, .max = 23 },
262         .m2 = { .min = 5, .max = 11 },
263         .p = { .min = 14, .max = 42 },
264         .p1 = { .min = 2, .max = 6 },
265         .p2 = { .dot_limit = 0,
266                 .p2_slow = 7, .p2_fast = 7
267         },
268 };
269
270 static const intel_limit_t intel_limits_pineview_sdvo = {
271         .dot = { .min = 20000, .max = 400000},
272         .vco = { .min = 1700000, .max = 3500000 },
273         /* Pineview's Ncounter is a ring counter */
274         .n = { .min = 3, .max = 6 },
275         .m = { .min = 2, .max = 256 },
276         /* Pineview only has one combined m divider, which we treat as m2. */
277         .m1 = { .min = 0, .max = 0 },
278         .m2 = { .min = 0, .max = 254 },
279         .p = { .min = 5, .max = 80 },
280         .p1 = { .min = 1, .max = 8 },
281         .p2 = { .dot_limit = 200000,
282                 .p2_slow = 10, .p2_fast = 5 },
283 };
284
285 static const intel_limit_t intel_limits_pineview_lvds = {
286         .dot = { .min = 20000, .max = 400000 },
287         .vco = { .min = 1700000, .max = 3500000 },
288         .n = { .min = 3, .max = 6 },
289         .m = { .min = 2, .max = 256 },
290         .m1 = { .min = 0, .max = 0 },
291         .m2 = { .min = 0, .max = 254 },
292         .p = { .min = 7, .max = 112 },
293         .p1 = { .min = 1, .max = 8 },
294         .p2 = { .dot_limit = 112000,
295                 .p2_slow = 14, .p2_fast = 14 },
296 };
297
298 /* Ironlake / Sandybridge
299  *
300  * We calculate clock using (register_value + 2) for N/M1/M2, so here
301  * the range value for them is (actual_value - 2).
302  */
303 static const intel_limit_t intel_limits_ironlake_dac = {
304         .dot = { .min = 25000, .max = 350000 },
305         .vco = { .min = 1760000, .max = 3510000 },
306         .n = { .min = 1, .max = 5 },
307         .m = { .min = 79, .max = 127 },
308         .m1 = { .min = 12, .max = 22 },
309         .m2 = { .min = 5, .max = 9 },
310         .p = { .min = 5, .max = 80 },
311         .p1 = { .min = 1, .max = 8 },
312         .p2 = { .dot_limit = 225000,
313                 .p2_slow = 10, .p2_fast = 5 },
314 };
315
316 static const intel_limit_t intel_limits_ironlake_single_lvds = {
317         .dot = { .min = 25000, .max = 350000 },
318         .vco = { .min = 1760000, .max = 3510000 },
319         .n = { .min = 1, .max = 3 },
320         .m = { .min = 79, .max = 118 },
321         .m1 = { .min = 12, .max = 22 },
322         .m2 = { .min = 5, .max = 9 },
323         .p = { .min = 28, .max = 112 },
324         .p1 = { .min = 2, .max = 8 },
325         .p2 = { .dot_limit = 225000,
326                 .p2_slow = 14, .p2_fast = 14 },
327 };
328
329 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
330         .dot = { .min = 25000, .max = 350000 },
331         .vco = { .min = 1760000, .max = 3510000 },
332         .n = { .min = 1, .max = 3 },
333         .m = { .min = 79, .max = 127 },
334         .m1 = { .min = 12, .max = 22 },
335         .m2 = { .min = 5, .max = 9 },
336         .p = { .min = 14, .max = 56 },
337         .p1 = { .min = 2, .max = 8 },
338         .p2 = { .dot_limit = 225000,
339                 .p2_slow = 7, .p2_fast = 7 },
340 };
341
342 /* LVDS 100mhz refclk limits. */
343 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
344         .dot = { .min = 25000, .max = 350000 },
345         .vco = { .min = 1760000, .max = 3510000 },
346         .n = { .min = 1, .max = 2 },
347         .m = { .min = 79, .max = 126 },
348         .m1 = { .min = 12, .max = 22 },
349         .m2 = { .min = 5, .max = 9 },
350         .p = { .min = 28, .max = 112 },
351         .p1 = { .min = 2, .max = 8 },
352         .p2 = { .dot_limit = 225000,
353                 .p2_slow = 14, .p2_fast = 14 },
354 };
355
356 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
357         .dot = { .min = 25000, .max = 350000 },
358         .vco = { .min = 1760000, .max = 3510000 },
359         .n = { .min = 1, .max = 3 },
360         .m = { .min = 79, .max = 126 },
361         .m1 = { .min = 12, .max = 22 },
362         .m2 = { .min = 5, .max = 9 },
363         .p = { .min = 14, .max = 42 },
364         .p1 = { .min = 2, .max = 6 },
365         .p2 = { .dot_limit = 225000,
366                 .p2_slow = 7, .p2_fast = 7 },
367 };
368
369 static const intel_limit_t intel_limits_vlv = {
370          /*
371           * These are the data rate limits (measured in fast clocks)
372           * since those are the strictest limits we have. The fast
373           * clock and actual rate limits are more relaxed, so checking
374           * them would make no difference.
375           */
376         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
377         .vco = { .min = 4000000, .max = 6000000 },
378         .n = { .min = 1, .max = 7 },
379         .m1 = { .min = 2, .max = 3 },
380         .m2 = { .min = 11, .max = 156 },
381         .p1 = { .min = 2, .max = 3 },
382         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
383 };
384
385 static const intel_limit_t intel_limits_chv = {
386         /*
387          * These are the data rate limits (measured in fast clocks)
388          * since those are the strictest limits we have.  The fast
389          * clock and actual rate limits are more relaxed, so checking
390          * them would make no difference.
391          */
392         .dot = { .min = 25000 * 5, .max = 540000 * 5},
393         .vco = { .min = 4860000, .max = 6700000 },
394         .n = { .min = 1, .max = 1 },
395         .m1 = { .min = 2, .max = 2 },
396         .m2 = { .min = 24 << 22, .max = 175 << 22 },
397         .p1 = { .min = 2, .max = 4 },
398         .p2 = { .p2_slow = 1, .p2_fast = 14 },
399 };
400
401 static void vlv_clock(int refclk, intel_clock_t *clock)
402 {
403         clock->m = clock->m1 * clock->m2;
404         clock->p = clock->p1 * clock->p2;
405         if (WARN_ON(clock->n == 0 || clock->p == 0))
406                 return;
407         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
408         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
409 }
410
411 /**
412  * Returns whether any output on the specified pipe is of the specified type
413  */
414 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
415 {
416         struct drm_device *dev = crtc->base.dev;
417         struct intel_encoder *encoder;
418
419         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
420                 if (encoder->type == type)
421                         return true;
422
423         return false;
424 }
425
426 /**
427  * Returns whether any output on the specified pipe will have the specified
428  * type after a staged modeset is complete, i.e., the same as
429  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
430  * encoder->crtc.
431  */
432 static bool intel_pipe_will_have_type(struct intel_crtc *crtc, int type)
433 {
434         struct drm_device *dev = crtc->base.dev;
435         struct intel_encoder *encoder;
436
437         for_each_intel_encoder(dev, encoder)
438                 if (encoder->new_crtc == crtc && encoder->type == type)
439                         return true;
440
441         return false;
442 }
443
444 static const intel_limit_t *intel_ironlake_limit(struct intel_crtc *crtc,
445                                                 int refclk)
446 {
447         struct drm_device *dev = crtc->base.dev;
448         const intel_limit_t *limit;
449
450         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
451                 if (intel_is_dual_link_lvds(dev)) {
452                         if (refclk == 100000)
453                                 limit = &intel_limits_ironlake_dual_lvds_100m;
454                         else
455                                 limit = &intel_limits_ironlake_dual_lvds;
456                 } else {
457                         if (refclk == 100000)
458                                 limit = &intel_limits_ironlake_single_lvds_100m;
459                         else
460                                 limit = &intel_limits_ironlake_single_lvds;
461                 }
462         } else
463                 limit = &intel_limits_ironlake_dac;
464
465         return limit;
466 }
467
468 static const intel_limit_t *intel_g4x_limit(struct intel_crtc *crtc)
469 {
470         struct drm_device *dev = crtc->base.dev;
471         const intel_limit_t *limit;
472
473         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
474                 if (intel_is_dual_link_lvds(dev))
475                         limit = &intel_limits_g4x_dual_channel_lvds;
476                 else
477                         limit = &intel_limits_g4x_single_channel_lvds;
478         } else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_HDMI) ||
479                    intel_pipe_will_have_type(crtc, INTEL_OUTPUT_ANALOG)) {
480                 limit = &intel_limits_g4x_hdmi;
481         } else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_SDVO)) {
482                 limit = &intel_limits_g4x_sdvo;
483         } else /* The option is for other outputs */
484                 limit = &intel_limits_i9xx_sdvo;
485
486         return limit;
487 }
488
489 static const intel_limit_t *intel_limit(struct intel_crtc *crtc, int refclk)
490 {
491         struct drm_device *dev = crtc->base.dev;
492         const intel_limit_t *limit;
493
494         if (HAS_PCH_SPLIT(dev))
495                 limit = intel_ironlake_limit(crtc, refclk);
496         else if (IS_G4X(dev)) {
497                 limit = intel_g4x_limit(crtc);
498         } else if (IS_PINEVIEW(dev)) {
499                 if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS))
500                         limit = &intel_limits_pineview_lvds;
501                 else
502                         limit = &intel_limits_pineview_sdvo;
503         } else if (IS_CHERRYVIEW(dev)) {
504                 limit = &intel_limits_chv;
505         } else if (IS_VALLEYVIEW(dev)) {
506                 limit = &intel_limits_vlv;
507         } else if (!IS_GEN2(dev)) {
508                 if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS))
509                         limit = &intel_limits_i9xx_lvds;
510                 else
511                         limit = &intel_limits_i9xx_sdvo;
512         } else {
513                 if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS))
514                         limit = &intel_limits_i8xx_lvds;
515                 else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_DVO))
516                         limit = &intel_limits_i8xx_dvo;
517                 else
518                         limit = &intel_limits_i8xx_dac;
519         }
520         return limit;
521 }
522
523 /* m1 is reserved as 0 in Pineview, n is a ring counter */
524 static void pineview_clock(int refclk, intel_clock_t *clock)
525 {
526         clock->m = clock->m2 + 2;
527         clock->p = clock->p1 * clock->p2;
528         if (WARN_ON(clock->n == 0 || clock->p == 0))
529                 return;
530         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
531         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
532 }
533
534 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
535 {
536         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
537 }
538
539 static void i9xx_clock(int refclk, intel_clock_t *clock)
540 {
541         clock->m = i9xx_dpll_compute_m(clock);
542         clock->p = clock->p1 * clock->p2;
543         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
544                 return;
545         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
546         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
547 }
548
549 static void chv_clock(int refclk, intel_clock_t *clock)
550 {
551         clock->m = clock->m1 * clock->m2;
552         clock->p = clock->p1 * clock->p2;
553         if (WARN_ON(clock->n == 0 || clock->p == 0))
554                 return;
555         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
556                         clock->n << 22);
557         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
558 }
559
560 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
561 /**
562  * Returns whether the given set of divisors are valid for a given refclk with
563  * the given connectors.
564  */
565
566 static bool intel_PLL_is_valid(struct drm_device *dev,
567                                const intel_limit_t *limit,
568                                const intel_clock_t *clock)
569 {
570         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
571                 INTELPllInvalid("n out of range\n");
572         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
573                 INTELPllInvalid("p1 out of range\n");
574         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
575                 INTELPllInvalid("m2 out of range\n");
576         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
577                 INTELPllInvalid("m1 out of range\n");
578
579         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev))
580                 if (clock->m1 <= clock->m2)
581                         INTELPllInvalid("m1 <= m2\n");
582
583         if (!IS_VALLEYVIEW(dev)) {
584                 if (clock->p < limit->p.min || limit->p.max < clock->p)
585                         INTELPllInvalid("p out of range\n");
586                 if (clock->m < limit->m.min || limit->m.max < clock->m)
587                         INTELPllInvalid("m out of range\n");
588         }
589
590         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
591                 INTELPllInvalid("vco out of range\n");
592         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
593          * connector, etc., rather than just a single range.
594          */
595         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
596                 INTELPllInvalid("dot out of range\n");
597
598         return true;
599 }
600
601 static bool
602 i9xx_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
603                     int target, int refclk, intel_clock_t *match_clock,
604                     intel_clock_t *best_clock)
605 {
606         struct drm_device *dev = crtc->base.dev;
607         intel_clock_t clock;
608         int err = target;
609
610         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
611                 /*
612                  * For LVDS just rely on its current settings for dual-channel.
613                  * We haven't figured out how to reliably set up different
614                  * single/dual channel state, if we even can.
615                  */
616                 if (intel_is_dual_link_lvds(dev))
617                         clock.p2 = limit->p2.p2_fast;
618                 else
619                         clock.p2 = limit->p2.p2_slow;
620         } else {
621                 if (target < limit->p2.dot_limit)
622                         clock.p2 = limit->p2.p2_slow;
623                 else
624                         clock.p2 = limit->p2.p2_fast;
625         }
626
627         memset(best_clock, 0, sizeof(*best_clock));
628
629         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
630              clock.m1++) {
631                 for (clock.m2 = limit->m2.min;
632                      clock.m2 <= limit->m2.max; clock.m2++) {
633                         if (clock.m2 >= clock.m1)
634                                 break;
635                         for (clock.n = limit->n.min;
636                              clock.n <= limit->n.max; clock.n++) {
637                                 for (clock.p1 = limit->p1.min;
638                                         clock.p1 <= limit->p1.max; clock.p1++) {
639                                         int this_err;
640
641                                         i9xx_clock(refclk, &clock);
642                                         if (!intel_PLL_is_valid(dev, limit,
643                                                                 &clock))
644                                                 continue;
645                                         if (match_clock &&
646                                             clock.p != match_clock->p)
647                                                 continue;
648
649                                         this_err = abs(clock.dot - target);
650                                         if (this_err < err) {
651                                                 *best_clock = clock;
652                                                 err = this_err;
653                                         }
654                                 }
655                         }
656                 }
657         }
658
659         return (err != target);
660 }
661
662 static bool
663 pnv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
664                    int target, int refclk, intel_clock_t *match_clock,
665                    intel_clock_t *best_clock)
666 {
667         struct drm_device *dev = crtc->base.dev;
668         intel_clock_t clock;
669         int err = target;
670
671         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
672                 /*
673                  * For LVDS just rely on its current settings for dual-channel.
674                  * We haven't figured out how to reliably set up different
675                  * single/dual channel state, if we even can.
676                  */
677                 if (intel_is_dual_link_lvds(dev))
678                         clock.p2 = limit->p2.p2_fast;
679                 else
680                         clock.p2 = limit->p2.p2_slow;
681         } else {
682                 if (target < limit->p2.dot_limit)
683                         clock.p2 = limit->p2.p2_slow;
684                 else
685                         clock.p2 = limit->p2.p2_fast;
686         }
687
688         memset(best_clock, 0, sizeof(*best_clock));
689
690         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
691              clock.m1++) {
692                 for (clock.m2 = limit->m2.min;
693                      clock.m2 <= limit->m2.max; clock.m2++) {
694                         for (clock.n = limit->n.min;
695                              clock.n <= limit->n.max; clock.n++) {
696                                 for (clock.p1 = limit->p1.min;
697                                         clock.p1 <= limit->p1.max; clock.p1++) {
698                                         int this_err;
699
700                                         pineview_clock(refclk, &clock);
701                                         if (!intel_PLL_is_valid(dev, limit,
702                                                                 &clock))
703                                                 continue;
704                                         if (match_clock &&
705                                             clock.p != match_clock->p)
706                                                 continue;
707
708                                         this_err = abs(clock.dot - target);
709                                         if (this_err < err) {
710                                                 *best_clock = clock;
711                                                 err = this_err;
712                                         }
713                                 }
714                         }
715                 }
716         }
717
718         return (err != target);
719 }
720
721 static bool
722 g4x_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
723                    int target, int refclk, intel_clock_t *match_clock,
724                    intel_clock_t *best_clock)
725 {
726         struct drm_device *dev = crtc->base.dev;
727         intel_clock_t clock;
728         int max_n;
729         bool found;
730         /* approximately equals target * 0.00585 */
731         int err_most = (target >> 8) + (target >> 9);
732         found = false;
733
734         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
735                 if (intel_is_dual_link_lvds(dev))
736                         clock.p2 = limit->p2.p2_fast;
737                 else
738                         clock.p2 = limit->p2.p2_slow;
739         } else {
740                 if (target < limit->p2.dot_limit)
741                         clock.p2 = limit->p2.p2_slow;
742                 else
743                         clock.p2 = limit->p2.p2_fast;
744         }
745
746         memset(best_clock, 0, sizeof(*best_clock));
747         max_n = limit->n.max;
748         /* based on hardware requirement, prefer smaller n to precision */
749         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
750                 /* based on hardware requirement, prefere larger m1,m2 */
751                 for (clock.m1 = limit->m1.max;
752                      clock.m1 >= limit->m1.min; clock.m1--) {
753                         for (clock.m2 = limit->m2.max;
754                              clock.m2 >= limit->m2.min; clock.m2--) {
755                                 for (clock.p1 = limit->p1.max;
756                                      clock.p1 >= limit->p1.min; clock.p1--) {
757                                         int this_err;
758
759                                         i9xx_clock(refclk, &clock);
760                                         if (!intel_PLL_is_valid(dev, limit,
761                                                                 &clock))
762                                                 continue;
763
764                                         this_err = abs(clock.dot - target);
765                                         if (this_err < err_most) {
766                                                 *best_clock = clock;
767                                                 err_most = this_err;
768                                                 max_n = clock.n;
769                                                 found = true;
770                                         }
771                                 }
772                         }
773                 }
774         }
775         return found;
776 }
777
778 static bool
779 vlv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
780                    int target, int refclk, intel_clock_t *match_clock,
781                    intel_clock_t *best_clock)
782 {
783         struct drm_device *dev = crtc->base.dev;
784         intel_clock_t clock;
785         unsigned int bestppm = 1000000;
786         /* min update 19.2 MHz */
787         int max_n = min(limit->n.max, refclk / 19200);
788         bool found = false;
789
790         target *= 5; /* fast clock */
791
792         memset(best_clock, 0, sizeof(*best_clock));
793
794         /* based on hardware requirement, prefer smaller n to precision */
795         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
796                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
797                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
798                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
799                                 clock.p = clock.p1 * clock.p2;
800                                 /* based on hardware requirement, prefer bigger m1,m2 values */
801                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
802                                         unsigned int ppm, diff;
803
804                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
805                                                                      refclk * clock.m1);
806
807                                         vlv_clock(refclk, &clock);
808
809                                         if (!intel_PLL_is_valid(dev, limit,
810                                                                 &clock))
811                                                 continue;
812
813                                         diff = abs(clock.dot - target);
814                                         ppm = div_u64(1000000ULL * diff, target);
815
816                                         if (ppm < 100 && clock.p > best_clock->p) {
817                                                 bestppm = 0;
818                                                 *best_clock = clock;
819                                                 found = true;
820                                         }
821
822                                         if (bestppm >= 10 && ppm < bestppm - 10) {
823                                                 bestppm = ppm;
824                                                 *best_clock = clock;
825                                                 found = true;
826                                         }
827                                 }
828                         }
829                 }
830         }
831
832         return found;
833 }
834
835 static bool
836 chv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
837                    int target, int refclk, intel_clock_t *match_clock,
838                    intel_clock_t *best_clock)
839 {
840         struct drm_device *dev = crtc->base.dev;
841         intel_clock_t clock;
842         uint64_t m2;
843         int found = false;
844
845         memset(best_clock, 0, sizeof(*best_clock));
846
847         /*
848          * Based on hardware doc, the n always set to 1, and m1 always
849          * set to 2.  If requires to support 200Mhz refclk, we need to
850          * revisit this because n may not 1 anymore.
851          */
852         clock.n = 1, clock.m1 = 2;
853         target *= 5;    /* fast clock */
854
855         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
856                 for (clock.p2 = limit->p2.p2_fast;
857                                 clock.p2 >= limit->p2.p2_slow;
858                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
859
860                         clock.p = clock.p1 * clock.p2;
861
862                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
863                                         clock.n) << 22, refclk * clock.m1);
864
865                         if (m2 > INT_MAX/clock.m1)
866                                 continue;
867
868                         clock.m2 = m2;
869
870                         chv_clock(refclk, &clock);
871
872                         if (!intel_PLL_is_valid(dev, limit, &clock))
873                                 continue;
874
875                         /* based on hardware requirement, prefer bigger p
876                          */
877                         if (clock.p > best_clock->p) {
878                                 *best_clock = clock;
879                                 found = true;
880                         }
881                 }
882         }
883
884         return found;
885 }
886
887 bool intel_crtc_active(struct drm_crtc *crtc)
888 {
889         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
890
891         /* Be paranoid as we can arrive here with only partial
892          * state retrieved from the hardware during setup.
893          *
894          * We can ditch the adjusted_mode.crtc_clock check as soon
895          * as Haswell has gained clock readout/fastboot support.
896          *
897          * We can ditch the crtc->primary->fb check as soon as we can
898          * properly reconstruct framebuffers.
899          */
900         return intel_crtc->active && crtc->primary->fb &&
901                 intel_crtc->config->base.adjusted_mode.crtc_clock;
902 }
903
904 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
905                                              enum pipe pipe)
906 {
907         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
908         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
909
910         return intel_crtc->config->cpu_transcoder;
911 }
912
913 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
914 {
915         struct drm_i915_private *dev_priv = dev->dev_private;
916         u32 reg = PIPEDSL(pipe);
917         u32 line1, line2;
918         u32 line_mask;
919
920         if (IS_GEN2(dev))
921                 line_mask = DSL_LINEMASK_GEN2;
922         else
923                 line_mask = DSL_LINEMASK_GEN3;
924
925         line1 = I915_READ(reg) & line_mask;
926         mdelay(5);
927         line2 = I915_READ(reg) & line_mask;
928
929         return line1 == line2;
930 }
931
932 /*
933  * intel_wait_for_pipe_off - wait for pipe to turn off
934  * @crtc: crtc whose pipe to wait for
935  *
936  * After disabling a pipe, we can't wait for vblank in the usual way,
937  * spinning on the vblank interrupt status bit, since we won't actually
938  * see an interrupt when the pipe is disabled.
939  *
940  * On Gen4 and above:
941  *   wait for the pipe register state bit to turn off
942  *
943  * Otherwise:
944  *   wait for the display line value to settle (it usually
945  *   ends up stopping at the start of the next frame).
946  *
947  */
948 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
949 {
950         struct drm_device *dev = crtc->base.dev;
951         struct drm_i915_private *dev_priv = dev->dev_private;
952         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
953         enum pipe pipe = crtc->pipe;
954
955         if (INTEL_INFO(dev)->gen >= 4) {
956                 int reg = PIPECONF(cpu_transcoder);
957
958                 /* Wait for the Pipe State to go off */
959                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
960                              100))
961                         WARN(1, "pipe_off wait timed out\n");
962         } else {
963                 /* Wait for the display line to settle */
964                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
965                         WARN(1, "pipe_off wait timed out\n");
966         }
967 }
968
969 /*
970  * ibx_digital_port_connected - is the specified port connected?
971  * @dev_priv: i915 private structure
972  * @port: the port to test
973  *
974  * Returns true if @port is connected, false otherwise.
975  */
976 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
977                                 struct intel_digital_port *port)
978 {
979         u32 bit;
980
981         if (HAS_PCH_IBX(dev_priv->dev)) {
982                 switch (port->port) {
983                 case PORT_B:
984                         bit = SDE_PORTB_HOTPLUG;
985                         break;
986                 case PORT_C:
987                         bit = SDE_PORTC_HOTPLUG;
988                         break;
989                 case PORT_D:
990                         bit = SDE_PORTD_HOTPLUG;
991                         break;
992                 default:
993                         return true;
994                 }
995         } else {
996                 switch (port->port) {
997                 case PORT_B:
998                         bit = SDE_PORTB_HOTPLUG_CPT;
999                         break;
1000                 case PORT_C:
1001                         bit = SDE_PORTC_HOTPLUG_CPT;
1002                         break;
1003                 case PORT_D:
1004                         bit = SDE_PORTD_HOTPLUG_CPT;
1005                         break;
1006                 default:
1007                         return true;
1008                 }
1009         }
1010
1011         return I915_READ(SDEISR) & bit;
1012 }
1013
1014 static const char *state_string(bool enabled)
1015 {
1016         return enabled ? "on" : "off";
1017 }
1018
1019 /* Only for pre-ILK configs */
1020 void assert_pll(struct drm_i915_private *dev_priv,
1021                 enum pipe pipe, bool state)
1022 {
1023         int reg;
1024         u32 val;
1025         bool cur_state;
1026
1027         reg = DPLL(pipe);
1028         val = I915_READ(reg);
1029         cur_state = !!(val & DPLL_VCO_ENABLE);
1030         I915_STATE_WARN(cur_state != state,
1031              "PLL state assertion failure (expected %s, current %s)\n",
1032              state_string(state), state_string(cur_state));
1033 }
1034
1035 /* XXX: the dsi pll is shared between MIPI DSI ports */
1036 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1037 {
1038         u32 val;
1039         bool cur_state;
1040
1041         mutex_lock(&dev_priv->dpio_lock);
1042         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1043         mutex_unlock(&dev_priv->dpio_lock);
1044
1045         cur_state = val & DSI_PLL_VCO_EN;
1046         I915_STATE_WARN(cur_state != state,
1047              "DSI PLL state assertion failure (expected %s, current %s)\n",
1048              state_string(state), state_string(cur_state));
1049 }
1050 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1051 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1052
1053 struct intel_shared_dpll *
1054 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1055 {
1056         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1057
1058         if (crtc->config->shared_dpll < 0)
1059                 return NULL;
1060
1061         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1062 }
1063
1064 /* For ILK+ */
1065 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1066                         struct intel_shared_dpll *pll,
1067                         bool state)
1068 {
1069         bool cur_state;
1070         struct intel_dpll_hw_state hw_state;
1071
1072         if (WARN (!pll,
1073                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1074                 return;
1075
1076         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1077         I915_STATE_WARN(cur_state != state,
1078              "%s assertion failure (expected %s, current %s)\n",
1079              pll->name, state_string(state), state_string(cur_state));
1080 }
1081
1082 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1083                           enum pipe pipe, bool state)
1084 {
1085         int reg;
1086         u32 val;
1087         bool cur_state;
1088         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1089                                                                       pipe);
1090
1091         if (HAS_DDI(dev_priv->dev)) {
1092                 /* DDI does not have a specific FDI_TX register */
1093                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1094                 val = I915_READ(reg);
1095                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1096         } else {
1097                 reg = FDI_TX_CTL(pipe);
1098                 val = I915_READ(reg);
1099                 cur_state = !!(val & FDI_TX_ENABLE);
1100         }
1101         I915_STATE_WARN(cur_state != state,
1102              "FDI TX state assertion failure (expected %s, current %s)\n",
1103              state_string(state), state_string(cur_state));
1104 }
1105 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1106 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1107
1108 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1109                           enum pipe pipe, bool state)
1110 {
1111         int reg;
1112         u32 val;
1113         bool cur_state;
1114
1115         reg = FDI_RX_CTL(pipe);
1116         val = I915_READ(reg);
1117         cur_state = !!(val & FDI_RX_ENABLE);
1118         I915_STATE_WARN(cur_state != state,
1119              "FDI RX state assertion failure (expected %s, current %s)\n",
1120              state_string(state), state_string(cur_state));
1121 }
1122 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1123 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1124
1125 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1126                                       enum pipe pipe)
1127 {
1128         int reg;
1129         u32 val;
1130
1131         /* ILK FDI PLL is always enabled */
1132         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1133                 return;
1134
1135         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1136         if (HAS_DDI(dev_priv->dev))
1137                 return;
1138
1139         reg = FDI_TX_CTL(pipe);
1140         val = I915_READ(reg);
1141         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1142 }
1143
1144 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1145                        enum pipe pipe, bool state)
1146 {
1147         int reg;
1148         u32 val;
1149         bool cur_state;
1150
1151         reg = FDI_RX_CTL(pipe);
1152         val = I915_READ(reg);
1153         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1154         I915_STATE_WARN(cur_state != state,
1155              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1156              state_string(state), state_string(cur_state));
1157 }
1158
1159 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1160                            enum pipe pipe)
1161 {
1162         struct drm_device *dev = dev_priv->dev;
1163         int pp_reg;
1164         u32 val;
1165         enum pipe panel_pipe = PIPE_A;
1166         bool locked = true;
1167
1168         if (WARN_ON(HAS_DDI(dev)))
1169                 return;
1170
1171         if (HAS_PCH_SPLIT(dev)) {
1172                 u32 port_sel;
1173
1174                 pp_reg = PCH_PP_CONTROL;
1175                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1176
1177                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1178                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1179                         panel_pipe = PIPE_B;
1180                 /* XXX: else fix for eDP */
1181         } else if (IS_VALLEYVIEW(dev)) {
1182                 /* presumably write lock depends on pipe, not port select */
1183                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1184                 panel_pipe = pipe;
1185         } else {
1186                 pp_reg = PP_CONTROL;
1187                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1188                         panel_pipe = PIPE_B;
1189         }
1190
1191         val = I915_READ(pp_reg);
1192         if (!(val & PANEL_POWER_ON) ||
1193             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1194                 locked = false;
1195
1196         I915_STATE_WARN(panel_pipe == pipe && locked,
1197              "panel assertion failure, pipe %c regs locked\n",
1198              pipe_name(pipe));
1199 }
1200
1201 static void assert_cursor(struct drm_i915_private *dev_priv,
1202                           enum pipe pipe, bool state)
1203 {
1204         struct drm_device *dev = dev_priv->dev;
1205         bool cur_state;
1206
1207         if (IS_845G(dev) || IS_I865G(dev))
1208                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1209         else
1210                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1211
1212         I915_STATE_WARN(cur_state != state,
1213              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1214              pipe_name(pipe), state_string(state), state_string(cur_state));
1215 }
1216 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1217 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1218
1219 void assert_pipe(struct drm_i915_private *dev_priv,
1220                  enum pipe pipe, bool state)
1221 {
1222         int reg;
1223         u32 val;
1224         bool cur_state;
1225         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1226                                                                       pipe);
1227
1228         /* if we need the pipe quirk it must be always on */
1229         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1230             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1231                 state = true;
1232
1233         if (!intel_display_power_is_enabled(dev_priv,
1234                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1235                 cur_state = false;
1236         } else {
1237                 reg = PIPECONF(cpu_transcoder);
1238                 val = I915_READ(reg);
1239                 cur_state = !!(val & PIPECONF_ENABLE);
1240         }
1241
1242         I915_STATE_WARN(cur_state != state,
1243              "pipe %c assertion failure (expected %s, current %s)\n",
1244              pipe_name(pipe), state_string(state), state_string(cur_state));
1245 }
1246
1247 static void assert_plane(struct drm_i915_private *dev_priv,
1248                          enum plane plane, bool state)
1249 {
1250         int reg;
1251         u32 val;
1252         bool cur_state;
1253
1254         reg = DSPCNTR(plane);
1255         val = I915_READ(reg);
1256         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1257         I915_STATE_WARN(cur_state != state,
1258              "plane %c assertion failure (expected %s, current %s)\n",
1259              plane_name(plane), state_string(state), state_string(cur_state));
1260 }
1261
1262 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1263 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1264
1265 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1266                                    enum pipe pipe)
1267 {
1268         struct drm_device *dev = dev_priv->dev;
1269         int reg, i;
1270         u32 val;
1271         int cur_pipe;
1272
1273         /* Primary planes are fixed to pipes on gen4+ */
1274         if (INTEL_INFO(dev)->gen >= 4) {
1275                 reg = DSPCNTR(pipe);
1276                 val = I915_READ(reg);
1277                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1278                      "plane %c assertion failure, should be disabled but not\n",
1279                      plane_name(pipe));
1280                 return;
1281         }
1282
1283         /* Need to check both planes against the pipe */
1284         for_each_pipe(dev_priv, i) {
1285                 reg = DSPCNTR(i);
1286                 val = I915_READ(reg);
1287                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1288                         DISPPLANE_SEL_PIPE_SHIFT;
1289                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1290                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1291                      plane_name(i), pipe_name(pipe));
1292         }
1293 }
1294
1295 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1296                                     enum pipe pipe)
1297 {
1298         struct drm_device *dev = dev_priv->dev;
1299         int reg, sprite;
1300         u32 val;
1301
1302         if (INTEL_INFO(dev)->gen >= 9) {
1303                 for_each_sprite(pipe, sprite) {
1304                         val = I915_READ(PLANE_CTL(pipe, sprite));
1305                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1306                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1307                              sprite, pipe_name(pipe));
1308                 }
1309         } else if (IS_VALLEYVIEW(dev)) {
1310                 for_each_sprite(pipe, sprite) {
1311                         reg = SPCNTR(pipe, sprite);
1312                         val = I915_READ(reg);
1313                         I915_STATE_WARN(val & SP_ENABLE,
1314                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1315                              sprite_name(pipe, sprite), pipe_name(pipe));
1316                 }
1317         } else if (INTEL_INFO(dev)->gen >= 7) {
1318                 reg = SPRCTL(pipe);
1319                 val = I915_READ(reg);
1320                 I915_STATE_WARN(val & SPRITE_ENABLE,
1321                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1322                      plane_name(pipe), pipe_name(pipe));
1323         } else if (INTEL_INFO(dev)->gen >= 5) {
1324                 reg = DVSCNTR(pipe);
1325                 val = I915_READ(reg);
1326                 I915_STATE_WARN(val & DVS_ENABLE,
1327                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1328                      plane_name(pipe), pipe_name(pipe));
1329         }
1330 }
1331
1332 static void assert_vblank_disabled(struct drm_crtc *crtc)
1333 {
1334         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1335                 drm_crtc_vblank_put(crtc);
1336 }
1337
1338 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1339 {
1340         u32 val;
1341         bool enabled;
1342
1343         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1344
1345         val = I915_READ(PCH_DREF_CONTROL);
1346         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1347                             DREF_SUPERSPREAD_SOURCE_MASK));
1348         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1349 }
1350
1351 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1352                                            enum pipe pipe)
1353 {
1354         int reg;
1355         u32 val;
1356         bool enabled;
1357
1358         reg = PCH_TRANSCONF(pipe);
1359         val = I915_READ(reg);
1360         enabled = !!(val & TRANS_ENABLE);
1361         I915_STATE_WARN(enabled,
1362              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1363              pipe_name(pipe));
1364 }
1365
1366 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1367                             enum pipe pipe, u32 port_sel, u32 val)
1368 {
1369         if ((val & DP_PORT_EN) == 0)
1370                 return false;
1371
1372         if (HAS_PCH_CPT(dev_priv->dev)) {
1373                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1374                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1375                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1376                         return false;
1377         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1378                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1379                         return false;
1380         } else {
1381                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1382                         return false;
1383         }
1384         return true;
1385 }
1386
1387 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1388                               enum pipe pipe, u32 val)
1389 {
1390         if ((val & SDVO_ENABLE) == 0)
1391                 return false;
1392
1393         if (HAS_PCH_CPT(dev_priv->dev)) {
1394                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1395                         return false;
1396         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1397                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1398                         return false;
1399         } else {
1400                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1401                         return false;
1402         }
1403         return true;
1404 }
1405
1406 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1407                               enum pipe pipe, u32 val)
1408 {
1409         if ((val & LVDS_PORT_EN) == 0)
1410                 return false;
1411
1412         if (HAS_PCH_CPT(dev_priv->dev)) {
1413                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1414                         return false;
1415         } else {
1416                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1417                         return false;
1418         }
1419         return true;
1420 }
1421
1422 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1423                               enum pipe pipe, u32 val)
1424 {
1425         if ((val & ADPA_DAC_ENABLE) == 0)
1426                 return false;
1427         if (HAS_PCH_CPT(dev_priv->dev)) {
1428                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1429                         return false;
1430         } else {
1431                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1432                         return false;
1433         }
1434         return true;
1435 }
1436
1437 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1438                                    enum pipe pipe, int reg, u32 port_sel)
1439 {
1440         u32 val = I915_READ(reg);
1441         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1442              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1443              reg, pipe_name(pipe));
1444
1445         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1446              && (val & DP_PIPEB_SELECT),
1447              "IBX PCH dp port still using transcoder B\n");
1448 }
1449
1450 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1451                                      enum pipe pipe, int reg)
1452 {
1453         u32 val = I915_READ(reg);
1454         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1455              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1456              reg, pipe_name(pipe));
1457
1458         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1459              && (val & SDVO_PIPE_B_SELECT),
1460              "IBX PCH hdmi port still using transcoder B\n");
1461 }
1462
1463 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1464                                       enum pipe pipe)
1465 {
1466         int reg;
1467         u32 val;
1468
1469         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1470         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1471         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1472
1473         reg = PCH_ADPA;
1474         val = I915_READ(reg);
1475         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1476              "PCH VGA enabled on transcoder %c, should be disabled\n",
1477              pipe_name(pipe));
1478
1479         reg = PCH_LVDS;
1480         val = I915_READ(reg);
1481         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1482              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1483              pipe_name(pipe));
1484
1485         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1486         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1487         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1488 }
1489
1490 static void intel_init_dpio(struct drm_device *dev)
1491 {
1492         struct drm_i915_private *dev_priv = dev->dev_private;
1493
1494         if (!IS_VALLEYVIEW(dev))
1495                 return;
1496
1497         /*
1498          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1499          * CHV x1 PHY (DP/HDMI D)
1500          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1501          */
1502         if (IS_CHERRYVIEW(dev)) {
1503                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1504                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1505         } else {
1506                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1507         }
1508 }
1509
1510 static void vlv_enable_pll(struct intel_crtc *crtc,
1511                            const struct intel_crtc_state *pipe_config)
1512 {
1513         struct drm_device *dev = crtc->base.dev;
1514         struct drm_i915_private *dev_priv = dev->dev_private;
1515         int reg = DPLL(crtc->pipe);
1516         u32 dpll = pipe_config->dpll_hw_state.dpll;
1517
1518         assert_pipe_disabled(dev_priv, crtc->pipe);
1519
1520         /* No really, not for ILK+ */
1521         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1522
1523         /* PLL is protected by panel, make sure we can write it */
1524         if (IS_MOBILE(dev_priv->dev))
1525                 assert_panel_unlocked(dev_priv, crtc->pipe);
1526
1527         I915_WRITE(reg, dpll);
1528         POSTING_READ(reg);
1529         udelay(150);
1530
1531         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1532                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1533
1534         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1535         POSTING_READ(DPLL_MD(crtc->pipe));
1536
1537         /* We do this three times for luck */
1538         I915_WRITE(reg, dpll);
1539         POSTING_READ(reg);
1540         udelay(150); /* wait for warmup */
1541         I915_WRITE(reg, dpll);
1542         POSTING_READ(reg);
1543         udelay(150); /* wait for warmup */
1544         I915_WRITE(reg, dpll);
1545         POSTING_READ(reg);
1546         udelay(150); /* wait for warmup */
1547 }
1548
1549 static void chv_enable_pll(struct intel_crtc *crtc,
1550                            const struct intel_crtc_state *pipe_config)
1551 {
1552         struct drm_device *dev = crtc->base.dev;
1553         struct drm_i915_private *dev_priv = dev->dev_private;
1554         int pipe = crtc->pipe;
1555         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1556         u32 tmp;
1557
1558         assert_pipe_disabled(dev_priv, crtc->pipe);
1559
1560         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1561
1562         mutex_lock(&dev_priv->dpio_lock);
1563
1564         /* Enable back the 10bit clock to display controller */
1565         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1566         tmp |= DPIO_DCLKP_EN;
1567         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1568
1569         /*
1570          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1571          */
1572         udelay(1);
1573
1574         /* Enable PLL */
1575         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1576
1577         /* Check PLL is locked */
1578         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1579                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1580
1581         /* not sure when this should be written */
1582         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1583         POSTING_READ(DPLL_MD(pipe));
1584
1585         mutex_unlock(&dev_priv->dpio_lock);
1586 }
1587
1588 static int intel_num_dvo_pipes(struct drm_device *dev)
1589 {
1590         struct intel_crtc *crtc;
1591         int count = 0;
1592
1593         for_each_intel_crtc(dev, crtc)
1594                 count += crtc->active &&
1595                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1596
1597         return count;
1598 }
1599
1600 static void i9xx_enable_pll(struct intel_crtc *crtc)
1601 {
1602         struct drm_device *dev = crtc->base.dev;
1603         struct drm_i915_private *dev_priv = dev->dev_private;
1604         int reg = DPLL(crtc->pipe);
1605         u32 dpll = crtc->config->dpll_hw_state.dpll;
1606
1607         assert_pipe_disabled(dev_priv, crtc->pipe);
1608
1609         /* No really, not for ILK+ */
1610         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1611
1612         /* PLL is protected by panel, make sure we can write it */
1613         if (IS_MOBILE(dev) && !IS_I830(dev))
1614                 assert_panel_unlocked(dev_priv, crtc->pipe);
1615
1616         /* Enable DVO 2x clock on both PLLs if necessary */
1617         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1618                 /*
1619                  * It appears to be important that we don't enable this
1620                  * for the current pipe before otherwise configuring the
1621                  * PLL. No idea how this should be handled if multiple
1622                  * DVO outputs are enabled simultaneosly.
1623                  */
1624                 dpll |= DPLL_DVO_2X_MODE;
1625                 I915_WRITE(DPLL(!crtc->pipe),
1626                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1627         }
1628
1629         /* Wait for the clocks to stabilize. */
1630         POSTING_READ(reg);
1631         udelay(150);
1632
1633         if (INTEL_INFO(dev)->gen >= 4) {
1634                 I915_WRITE(DPLL_MD(crtc->pipe),
1635                            crtc->config->dpll_hw_state.dpll_md);
1636         } else {
1637                 /* The pixel multiplier can only be updated once the
1638                  * DPLL is enabled and the clocks are stable.
1639                  *
1640                  * So write it again.
1641                  */
1642                 I915_WRITE(reg, dpll);
1643         }
1644
1645         /* We do this three times for luck */
1646         I915_WRITE(reg, dpll);
1647         POSTING_READ(reg);
1648         udelay(150); /* wait for warmup */
1649         I915_WRITE(reg, dpll);
1650         POSTING_READ(reg);
1651         udelay(150); /* wait for warmup */
1652         I915_WRITE(reg, dpll);
1653         POSTING_READ(reg);
1654         udelay(150); /* wait for warmup */
1655 }
1656
1657 /**
1658  * i9xx_disable_pll - disable a PLL
1659  * @dev_priv: i915 private structure
1660  * @pipe: pipe PLL to disable
1661  *
1662  * Disable the PLL for @pipe, making sure the pipe is off first.
1663  *
1664  * Note!  This is for pre-ILK only.
1665  */
1666 static void i9xx_disable_pll(struct intel_crtc *crtc)
1667 {
1668         struct drm_device *dev = crtc->base.dev;
1669         struct drm_i915_private *dev_priv = dev->dev_private;
1670         enum pipe pipe = crtc->pipe;
1671
1672         /* Disable DVO 2x clock on both PLLs if necessary */
1673         if (IS_I830(dev) &&
1674             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1675             intel_num_dvo_pipes(dev) == 1) {
1676                 I915_WRITE(DPLL(PIPE_B),
1677                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1678                 I915_WRITE(DPLL(PIPE_A),
1679                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1680         }
1681
1682         /* Don't disable pipe or pipe PLLs if needed */
1683         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1684             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1685                 return;
1686
1687         /* Make sure the pipe isn't still relying on us */
1688         assert_pipe_disabled(dev_priv, pipe);
1689
1690         I915_WRITE(DPLL(pipe), 0);
1691         POSTING_READ(DPLL(pipe));
1692 }
1693
1694 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1695 {
1696         u32 val = 0;
1697
1698         /* Make sure the pipe isn't still relying on us */
1699         assert_pipe_disabled(dev_priv, pipe);
1700
1701         /*
1702          * Leave integrated clock source and reference clock enabled for pipe B.
1703          * The latter is needed for VGA hotplug / manual detection.
1704          */
1705         if (pipe == PIPE_B)
1706                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REFA_CLK_ENABLE_VLV;
1707         I915_WRITE(DPLL(pipe), val);
1708         POSTING_READ(DPLL(pipe));
1709
1710 }
1711
1712 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1713 {
1714         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1715         u32 val;
1716
1717         /* Make sure the pipe isn't still relying on us */
1718         assert_pipe_disabled(dev_priv, pipe);
1719
1720         /* Set PLL en = 0 */
1721         val = DPLL_SSC_REF_CLOCK_CHV | DPLL_REFA_CLK_ENABLE_VLV;
1722         if (pipe != PIPE_A)
1723                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1724         I915_WRITE(DPLL(pipe), val);
1725         POSTING_READ(DPLL(pipe));
1726
1727         mutex_lock(&dev_priv->dpio_lock);
1728
1729         /* Disable 10bit clock to display controller */
1730         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1731         val &= ~DPIO_DCLKP_EN;
1732         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1733
1734         /* disable left/right clock distribution */
1735         if (pipe != PIPE_B) {
1736                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW5_CH0);
1737                 val &= ~(CHV_BUFLEFTENA1_MASK | CHV_BUFRIGHTENA1_MASK);
1738                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW5_CH0, val);
1739         } else {
1740                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW1_CH1);
1741                 val &= ~(CHV_BUFLEFTENA2_MASK | CHV_BUFRIGHTENA2_MASK);
1742                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW1_CH1, val);
1743         }
1744
1745         mutex_unlock(&dev_priv->dpio_lock);
1746 }
1747
1748 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1749                 struct intel_digital_port *dport)
1750 {
1751         u32 port_mask;
1752         int dpll_reg;
1753
1754         switch (dport->port) {
1755         case PORT_B:
1756                 port_mask = DPLL_PORTB_READY_MASK;
1757                 dpll_reg = DPLL(0);
1758                 break;
1759         case PORT_C:
1760                 port_mask = DPLL_PORTC_READY_MASK;
1761                 dpll_reg = DPLL(0);
1762                 break;
1763         case PORT_D:
1764                 port_mask = DPLL_PORTD_READY_MASK;
1765                 dpll_reg = DPIO_PHY_STATUS;
1766                 break;
1767         default:
1768                 BUG();
1769         }
1770
1771         if (wait_for((I915_READ(dpll_reg) & port_mask) == 0, 1000))
1772                 WARN(1, "timed out waiting for port %c ready: 0x%08x\n",
1773                      port_name(dport->port), I915_READ(dpll_reg));
1774 }
1775
1776 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1777 {
1778         struct drm_device *dev = crtc->base.dev;
1779         struct drm_i915_private *dev_priv = dev->dev_private;
1780         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1781
1782         if (WARN_ON(pll == NULL))
1783                 return;
1784
1785         WARN_ON(!pll->config.crtc_mask);
1786         if (pll->active == 0) {
1787                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1788                 WARN_ON(pll->on);
1789                 assert_shared_dpll_disabled(dev_priv, pll);
1790
1791                 pll->mode_set(dev_priv, pll);
1792         }
1793 }
1794
1795 /**
1796  * intel_enable_shared_dpll - enable PCH PLL
1797  * @dev_priv: i915 private structure
1798  * @pipe: pipe PLL to enable
1799  *
1800  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1801  * drives the transcoder clock.
1802  */
1803 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1804 {
1805         struct drm_device *dev = crtc->base.dev;
1806         struct drm_i915_private *dev_priv = dev->dev_private;
1807         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1808
1809         if (WARN_ON(pll == NULL))
1810                 return;
1811
1812         if (WARN_ON(pll->config.crtc_mask == 0))
1813                 return;
1814
1815         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1816                       pll->name, pll->active, pll->on,
1817                       crtc->base.base.id);
1818
1819         if (pll->active++) {
1820                 WARN_ON(!pll->on);
1821                 assert_shared_dpll_enabled(dev_priv, pll);
1822                 return;
1823         }
1824         WARN_ON(pll->on);
1825
1826         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1827
1828         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1829         pll->enable(dev_priv, pll);
1830         pll->on = true;
1831 }
1832
1833 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1834 {
1835         struct drm_device *dev = crtc->base.dev;
1836         struct drm_i915_private *dev_priv = dev->dev_private;
1837         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1838
1839         /* PCH only available on ILK+ */
1840         BUG_ON(INTEL_INFO(dev)->gen < 5);
1841         if (WARN_ON(pll == NULL))
1842                return;
1843
1844         if (WARN_ON(pll->config.crtc_mask == 0))
1845                 return;
1846
1847         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1848                       pll->name, pll->active, pll->on,
1849                       crtc->base.base.id);
1850
1851         if (WARN_ON(pll->active == 0)) {
1852                 assert_shared_dpll_disabled(dev_priv, pll);
1853                 return;
1854         }
1855
1856         assert_shared_dpll_enabled(dev_priv, pll);
1857         WARN_ON(!pll->on);
1858         if (--pll->active)
1859                 return;
1860
1861         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1862         pll->disable(dev_priv, pll);
1863         pll->on = false;
1864
1865         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1866 }
1867
1868 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1869                                            enum pipe pipe)
1870 {
1871         struct drm_device *dev = dev_priv->dev;
1872         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1873         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1874         uint32_t reg, val, pipeconf_val;
1875
1876         /* PCH only available on ILK+ */
1877         BUG_ON(!HAS_PCH_SPLIT(dev));
1878
1879         /* Make sure PCH DPLL is enabled */
1880         assert_shared_dpll_enabled(dev_priv,
1881                                    intel_crtc_to_shared_dpll(intel_crtc));
1882
1883         /* FDI must be feeding us bits for PCH ports */
1884         assert_fdi_tx_enabled(dev_priv, pipe);
1885         assert_fdi_rx_enabled(dev_priv, pipe);
1886
1887         if (HAS_PCH_CPT(dev)) {
1888                 /* Workaround: Set the timing override bit before enabling the
1889                  * pch transcoder. */
1890                 reg = TRANS_CHICKEN2(pipe);
1891                 val = I915_READ(reg);
1892                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1893                 I915_WRITE(reg, val);
1894         }
1895
1896         reg = PCH_TRANSCONF(pipe);
1897         val = I915_READ(reg);
1898         pipeconf_val = I915_READ(PIPECONF(pipe));
1899
1900         if (HAS_PCH_IBX(dev_priv->dev)) {
1901                 /*
1902                  * make the BPC in transcoder be consistent with
1903                  * that in pipeconf reg.
1904                  */
1905                 val &= ~PIPECONF_BPC_MASK;
1906                 val |= pipeconf_val & PIPECONF_BPC_MASK;
1907         }
1908
1909         val &= ~TRANS_INTERLACE_MASK;
1910         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1911                 if (HAS_PCH_IBX(dev_priv->dev) &&
1912                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1913                         val |= TRANS_LEGACY_INTERLACED_ILK;
1914                 else
1915                         val |= TRANS_INTERLACED;
1916         else
1917                 val |= TRANS_PROGRESSIVE;
1918
1919         I915_WRITE(reg, val | TRANS_ENABLE);
1920         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1921                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1922 }
1923
1924 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1925                                       enum transcoder cpu_transcoder)
1926 {
1927         u32 val, pipeconf_val;
1928
1929         /* PCH only available on ILK+ */
1930         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
1931
1932         /* FDI must be feeding us bits for PCH ports */
1933         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1934         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1935
1936         /* Workaround: set timing override bit. */
1937         val = I915_READ(_TRANSA_CHICKEN2);
1938         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1939         I915_WRITE(_TRANSA_CHICKEN2, val);
1940
1941         val = TRANS_ENABLE;
1942         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1943
1944         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1945             PIPECONF_INTERLACED_ILK)
1946                 val |= TRANS_INTERLACED;
1947         else
1948                 val |= TRANS_PROGRESSIVE;
1949
1950         I915_WRITE(LPT_TRANSCONF, val);
1951         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1952                 DRM_ERROR("Failed to enable PCH transcoder\n");
1953 }
1954
1955 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1956                                             enum pipe pipe)
1957 {
1958         struct drm_device *dev = dev_priv->dev;
1959         uint32_t reg, val;
1960
1961         /* FDI relies on the transcoder */
1962         assert_fdi_tx_disabled(dev_priv, pipe);
1963         assert_fdi_rx_disabled(dev_priv, pipe);
1964
1965         /* Ports must be off as well */
1966         assert_pch_ports_disabled(dev_priv, pipe);
1967
1968         reg = PCH_TRANSCONF(pipe);
1969         val = I915_READ(reg);
1970         val &= ~TRANS_ENABLE;
1971         I915_WRITE(reg, val);
1972         /* wait for PCH transcoder off, transcoder state */
1973         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1974                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1975
1976         if (!HAS_PCH_IBX(dev)) {
1977                 /* Workaround: Clear the timing override chicken bit again. */
1978                 reg = TRANS_CHICKEN2(pipe);
1979                 val = I915_READ(reg);
1980                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1981                 I915_WRITE(reg, val);
1982         }
1983 }
1984
1985 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1986 {
1987         u32 val;
1988
1989         val = I915_READ(LPT_TRANSCONF);
1990         val &= ~TRANS_ENABLE;
1991         I915_WRITE(LPT_TRANSCONF, val);
1992         /* wait for PCH transcoder off, transcoder state */
1993         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1994                 DRM_ERROR("Failed to disable PCH transcoder\n");
1995
1996         /* Workaround: clear timing override bit. */
1997         val = I915_READ(_TRANSA_CHICKEN2);
1998         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1999         I915_WRITE(_TRANSA_CHICKEN2, val);
2000 }
2001
2002 /**
2003  * intel_enable_pipe - enable a pipe, asserting requirements
2004  * @crtc: crtc responsible for the pipe
2005  *
2006  * Enable @crtc's pipe, making sure that various hardware specific requirements
2007  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2008  */
2009 static void intel_enable_pipe(struct intel_crtc *crtc)
2010 {
2011         struct drm_device *dev = crtc->base.dev;
2012         struct drm_i915_private *dev_priv = dev->dev_private;
2013         enum pipe pipe = crtc->pipe;
2014         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2015                                                                       pipe);
2016         enum pipe pch_transcoder;
2017         int reg;
2018         u32 val;
2019
2020         assert_planes_disabled(dev_priv, pipe);
2021         assert_cursor_disabled(dev_priv, pipe);
2022         assert_sprites_disabled(dev_priv, pipe);
2023
2024         if (HAS_PCH_LPT(dev_priv->dev))
2025                 pch_transcoder = TRANSCODER_A;
2026         else
2027                 pch_transcoder = pipe;
2028
2029         /*
2030          * A pipe without a PLL won't actually be able to drive bits from
2031          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2032          * need the check.
2033          */
2034         if (!HAS_PCH_SPLIT(dev_priv->dev))
2035                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2036                         assert_dsi_pll_enabled(dev_priv);
2037                 else
2038                         assert_pll_enabled(dev_priv, pipe);
2039         else {
2040                 if (crtc->config->has_pch_encoder) {
2041                         /* if driving the PCH, we need FDI enabled */
2042                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2043                         assert_fdi_tx_pll_enabled(dev_priv,
2044                                                   (enum pipe) cpu_transcoder);
2045                 }
2046                 /* FIXME: assert CPU port conditions for SNB+ */
2047         }
2048
2049         reg = PIPECONF(cpu_transcoder);
2050         val = I915_READ(reg);
2051         if (val & PIPECONF_ENABLE) {
2052                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2053                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2054                 return;
2055         }
2056
2057         I915_WRITE(reg, val | PIPECONF_ENABLE);
2058         POSTING_READ(reg);
2059 }
2060
2061 /**
2062  * intel_disable_pipe - disable a pipe, asserting requirements
2063  * @crtc: crtc whose pipes is to be disabled
2064  *
2065  * Disable the pipe of @crtc, making sure that various hardware
2066  * specific requirements are met, if applicable, e.g. plane
2067  * disabled, panel fitter off, etc.
2068  *
2069  * Will wait until the pipe has shut down before returning.
2070  */
2071 static void intel_disable_pipe(struct intel_crtc *crtc)
2072 {
2073         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2074         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2075         enum pipe pipe = crtc->pipe;
2076         int reg;
2077         u32 val;
2078
2079         /*
2080          * Make sure planes won't keep trying to pump pixels to us,
2081          * or we might hang the display.
2082          */
2083         assert_planes_disabled(dev_priv, pipe);
2084         assert_cursor_disabled(dev_priv, pipe);
2085         assert_sprites_disabled(dev_priv, pipe);
2086
2087         reg = PIPECONF(cpu_transcoder);
2088         val = I915_READ(reg);
2089         if ((val & PIPECONF_ENABLE) == 0)
2090                 return;
2091
2092         /*
2093          * Double wide has implications for planes
2094          * so best keep it disabled when not needed.
2095          */
2096         if (crtc->config->double_wide)
2097                 val &= ~PIPECONF_DOUBLE_WIDE;
2098
2099         /* Don't disable pipe or pipe PLLs if needed */
2100         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2101             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2102                 val &= ~PIPECONF_ENABLE;
2103
2104         I915_WRITE(reg, val);
2105         if ((val & PIPECONF_ENABLE) == 0)
2106                 intel_wait_for_pipe_off(crtc);
2107 }
2108
2109 /*
2110  * Plane regs are double buffered, going from enabled->disabled needs a
2111  * trigger in order to latch.  The display address reg provides this.
2112  */
2113 void intel_flush_primary_plane(struct drm_i915_private *dev_priv,
2114                                enum plane plane)
2115 {
2116         struct drm_device *dev = dev_priv->dev;
2117         u32 reg = INTEL_INFO(dev)->gen >= 4 ? DSPSURF(plane) : DSPADDR(plane);
2118
2119         I915_WRITE(reg, I915_READ(reg));
2120         POSTING_READ(reg);
2121 }
2122
2123 /**
2124  * intel_enable_primary_hw_plane - enable the primary plane on a given pipe
2125  * @plane:  plane to be enabled
2126  * @crtc: crtc for the plane
2127  *
2128  * Enable @plane on @crtc, making sure that the pipe is running first.
2129  */
2130 static void intel_enable_primary_hw_plane(struct drm_plane *plane,
2131                                           struct drm_crtc *crtc)
2132 {
2133         struct drm_device *dev = plane->dev;
2134         struct drm_i915_private *dev_priv = dev->dev_private;
2135         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2136
2137         /* If the pipe isn't enabled, we can't pump pixels and may hang */
2138         assert_pipe_enabled(dev_priv, intel_crtc->pipe);
2139
2140         if (intel_crtc->primary_enabled)
2141                 return;
2142
2143         intel_crtc->primary_enabled = true;
2144
2145         dev_priv->display.update_primary_plane(crtc, plane->fb,
2146                                                crtc->x, crtc->y);
2147
2148         /*
2149          * BDW signals flip done immediately if the plane
2150          * is disabled, even if the plane enable is already
2151          * armed to occur at the next vblank :(
2152          */
2153         if (IS_BROADWELL(dev))
2154                 intel_wait_for_vblank(dev, intel_crtc->pipe);
2155 }
2156
2157 /**
2158  * intel_disable_primary_hw_plane - disable the primary hardware plane
2159  * @plane: plane to be disabled
2160  * @crtc: crtc for the plane
2161  *
2162  * Disable @plane on @crtc, making sure that the pipe is running first.
2163  */
2164 static void intel_disable_primary_hw_plane(struct drm_plane *plane,
2165                                            struct drm_crtc *crtc)
2166 {
2167         struct drm_device *dev = plane->dev;
2168         struct drm_i915_private *dev_priv = dev->dev_private;
2169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2170
2171         if (WARN_ON(!intel_crtc->active))
2172                 return;
2173
2174         if (!intel_crtc->primary_enabled)
2175                 return;
2176
2177         intel_crtc->primary_enabled = false;
2178
2179         dev_priv->display.update_primary_plane(crtc, plane->fb,
2180                                                crtc->x, crtc->y);
2181 }
2182
2183 static bool need_vtd_wa(struct drm_device *dev)
2184 {
2185 #ifdef CONFIG_INTEL_IOMMU
2186         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2187                 return true;
2188 #endif
2189         return false;
2190 }
2191
2192 int
2193 intel_fb_align_height(struct drm_device *dev, int height, unsigned int tiling)
2194 {
2195         int tile_height;
2196
2197         tile_height = tiling ? (IS_GEN2(dev) ? 16 : 8) : 1;
2198         return ALIGN(height, tile_height);
2199 }
2200
2201 int
2202 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2203                            struct drm_framebuffer *fb,
2204                            struct intel_engine_cs *pipelined)
2205 {
2206         struct drm_device *dev = fb->dev;
2207         struct drm_i915_private *dev_priv = dev->dev_private;
2208         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2209         u32 alignment;
2210         int ret;
2211
2212         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2213
2214         switch (obj->tiling_mode) {
2215         case I915_TILING_NONE:
2216                 if (INTEL_INFO(dev)->gen >= 9)
2217                         alignment = 256 * 1024;
2218                 else if (IS_BROADWATER(dev) || IS_CRESTLINE(dev))
2219                         alignment = 128 * 1024;
2220                 else if (INTEL_INFO(dev)->gen >= 4)
2221                         alignment = 4 * 1024;
2222                 else
2223                         alignment = 64 * 1024;
2224                 break;
2225         case I915_TILING_X:
2226                 if (INTEL_INFO(dev)->gen >= 9)
2227                         alignment = 256 * 1024;
2228                 else {
2229                         /* pin() will align the object as required by fence */
2230                         alignment = 0;
2231                 }
2232                 break;
2233         case I915_TILING_Y:
2234                 WARN(1, "Y tiled bo slipped through, driver bug!\n");
2235                 return -EINVAL;
2236         default:
2237                 BUG();
2238         }
2239
2240         /* Note that the w/a also requires 64 PTE of padding following the
2241          * bo. We currently fill all unused PTE with the shadow page and so
2242          * we should always have valid PTE following the scanout preventing
2243          * the VT-d warning.
2244          */
2245         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2246                 alignment = 256 * 1024;
2247
2248         /*
2249          * Global gtt pte registers are special registers which actually forward
2250          * writes to a chunk of system memory. Which means that there is no risk
2251          * that the register values disappear as soon as we call
2252          * intel_runtime_pm_put(), so it is correct to wrap only the
2253          * pin/unpin/fence and not more.
2254          */
2255         intel_runtime_pm_get(dev_priv);
2256
2257         dev_priv->mm.interruptible = false;
2258         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined);
2259         if (ret)
2260                 goto err_interruptible;
2261
2262         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2263          * fence, whereas 965+ only requires a fence if using
2264          * framebuffer compression.  For simplicity, we always install
2265          * a fence as the cost is not that onerous.
2266          */
2267         ret = i915_gem_object_get_fence(obj);
2268         if (ret)
2269                 goto err_unpin;
2270
2271         i915_gem_object_pin_fence(obj);
2272
2273         dev_priv->mm.interruptible = true;
2274         intel_runtime_pm_put(dev_priv);
2275         return 0;
2276
2277 err_unpin:
2278         i915_gem_object_unpin_from_display_plane(obj);
2279 err_interruptible:
2280         dev_priv->mm.interruptible = true;
2281         intel_runtime_pm_put(dev_priv);
2282         return ret;
2283 }
2284
2285 void intel_unpin_fb_obj(struct drm_i915_gem_object *obj)
2286 {
2287         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2288
2289         i915_gem_object_unpin_fence(obj);
2290         i915_gem_object_unpin_from_display_plane(obj);
2291 }
2292
2293 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2294  * is assumed to be a power-of-two. */
2295 unsigned long intel_gen4_compute_page_offset(int *x, int *y,
2296                                              unsigned int tiling_mode,
2297                                              unsigned int cpp,
2298                                              unsigned int pitch)
2299 {
2300         if (tiling_mode != I915_TILING_NONE) {
2301                 unsigned int tile_rows, tiles;
2302
2303                 tile_rows = *y / 8;
2304                 *y %= 8;
2305
2306                 tiles = *x / (512/cpp);
2307                 *x %= 512/cpp;
2308
2309                 return tile_rows * pitch * 8 + tiles * 4096;
2310         } else {
2311                 unsigned int offset;
2312
2313                 offset = *y * pitch + *x * cpp;
2314                 *y = 0;
2315                 *x = (offset & 4095) / cpp;
2316                 return offset & -4096;
2317         }
2318 }
2319
2320 static int i9xx_format_to_fourcc(int format)
2321 {
2322         switch (format) {
2323         case DISPPLANE_8BPP:
2324                 return DRM_FORMAT_C8;
2325         case DISPPLANE_BGRX555:
2326                 return DRM_FORMAT_XRGB1555;
2327         case DISPPLANE_BGRX565:
2328                 return DRM_FORMAT_RGB565;
2329         default:
2330         case DISPPLANE_BGRX888:
2331                 return DRM_FORMAT_XRGB8888;
2332         case DISPPLANE_RGBX888:
2333                 return DRM_FORMAT_XBGR8888;
2334         case DISPPLANE_BGRX101010:
2335                 return DRM_FORMAT_XRGB2101010;
2336         case DISPPLANE_RGBX101010:
2337                 return DRM_FORMAT_XBGR2101010;
2338         }
2339 }
2340
2341 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2342 {
2343         switch (format) {
2344         case PLANE_CTL_FORMAT_RGB_565:
2345                 return DRM_FORMAT_RGB565;
2346         default:
2347         case PLANE_CTL_FORMAT_XRGB_8888:
2348                 if (rgb_order) {
2349                         if (alpha)
2350                                 return DRM_FORMAT_ABGR8888;
2351                         else
2352                                 return DRM_FORMAT_XBGR8888;
2353                 } else {
2354                         if (alpha)
2355                                 return DRM_FORMAT_ARGB8888;
2356                         else
2357                                 return DRM_FORMAT_XRGB8888;
2358                 }
2359         case PLANE_CTL_FORMAT_XRGB_2101010:
2360                 if (rgb_order)
2361                         return DRM_FORMAT_XBGR2101010;
2362                 else
2363                         return DRM_FORMAT_XRGB2101010;
2364         }
2365 }
2366
2367 static bool
2368 intel_alloc_plane_obj(struct intel_crtc *crtc,
2369                       struct intel_initial_plane_config *plane_config)
2370 {
2371         struct drm_device *dev = crtc->base.dev;
2372         struct drm_i915_gem_object *obj = NULL;
2373         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2374         u32 base = plane_config->base;
2375
2376         if (plane_config->size == 0)
2377                 return false;
2378
2379         obj = i915_gem_object_create_stolen_for_preallocated(dev, base, base,
2380                                                              plane_config->size);
2381         if (!obj)
2382                 return false;
2383
2384         obj->tiling_mode = plane_config->tiling;
2385         if (obj->tiling_mode == I915_TILING_X)
2386                 obj->stride = crtc->base.primary->fb->pitches[0];
2387
2388         mode_cmd.pixel_format = crtc->base.primary->fb->pixel_format;
2389         mode_cmd.width = crtc->base.primary->fb->width;
2390         mode_cmd.height = crtc->base.primary->fb->height;
2391         mode_cmd.pitches[0] = crtc->base.primary->fb->pitches[0];
2392
2393         mutex_lock(&dev->struct_mutex);
2394
2395         if (intel_framebuffer_init(dev, to_intel_framebuffer(crtc->base.primary->fb),
2396                                    &mode_cmd, obj)) {
2397                 DRM_DEBUG_KMS("intel fb init failed\n");
2398                 goto out_unref_obj;
2399         }
2400
2401         obj->frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(crtc->pipe);
2402         mutex_unlock(&dev->struct_mutex);
2403
2404         DRM_DEBUG_KMS("plane fb obj %p\n", obj);
2405         return true;
2406
2407 out_unref_obj:
2408         drm_gem_object_unreference(&obj->base);
2409         mutex_unlock(&dev->struct_mutex);
2410         return false;
2411 }
2412
2413 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2414 static void
2415 update_state_fb(struct drm_plane *plane)
2416 {
2417         if (plane->fb == plane->state->fb)
2418                 return;
2419
2420         if (plane->state->fb)
2421                 drm_framebuffer_unreference(plane->state->fb);
2422         plane->state->fb = plane->fb;
2423         if (plane->state->fb)
2424                 drm_framebuffer_reference(plane->state->fb);
2425 }
2426
2427 static void
2428 intel_find_plane_obj(struct intel_crtc *intel_crtc,
2429                      struct intel_initial_plane_config *plane_config)
2430 {
2431         struct drm_device *dev = intel_crtc->base.dev;
2432         struct drm_i915_private *dev_priv = dev->dev_private;
2433         struct drm_crtc *c;
2434         struct intel_crtc *i;
2435         struct drm_i915_gem_object *obj;
2436
2437         if (!intel_crtc->base.primary->fb)
2438                 return;
2439
2440         if (intel_alloc_plane_obj(intel_crtc, plane_config))
2441                 return;
2442
2443         kfree(intel_crtc->base.primary->fb);
2444         intel_crtc->base.primary->fb = NULL;
2445
2446         /*
2447          * Failed to alloc the obj, check to see if we should share
2448          * an fb with another CRTC instead
2449          */
2450         for_each_crtc(dev, c) {
2451                 i = to_intel_crtc(c);
2452
2453                 if (c == &intel_crtc->base)
2454                         continue;
2455
2456                 if (!i->active)
2457                         continue;
2458
2459                 obj = intel_fb_obj(c->primary->fb);
2460                 if (obj == NULL)
2461                         continue;
2462
2463                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2464                         if (obj->tiling_mode != I915_TILING_NONE)
2465                                 dev_priv->preserve_bios_swizzle = true;
2466
2467                         drm_framebuffer_reference(c->primary->fb);
2468                         intel_crtc->base.primary->fb = c->primary->fb;
2469                         obj->frontbuffer_bits |= INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
2470                         break;
2471                 }
2472         }
2473
2474         update_state_fb(intel_crtc->base.primary);
2475 }
2476
2477 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2478                                       struct drm_framebuffer *fb,
2479                                       int x, int y)
2480 {
2481         struct drm_device *dev = crtc->dev;
2482         struct drm_i915_private *dev_priv = dev->dev_private;
2483         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2484         struct drm_i915_gem_object *obj;
2485         int plane = intel_crtc->plane;
2486         unsigned long linear_offset;
2487         u32 dspcntr;
2488         u32 reg = DSPCNTR(plane);
2489         int pixel_size;
2490
2491         if (!intel_crtc->primary_enabled) {
2492                 I915_WRITE(reg, 0);
2493                 if (INTEL_INFO(dev)->gen >= 4)
2494                         I915_WRITE(DSPSURF(plane), 0);
2495                 else
2496                         I915_WRITE(DSPADDR(plane), 0);
2497                 POSTING_READ(reg);
2498                 return;
2499         }
2500
2501         obj = intel_fb_obj(fb);
2502         if (WARN_ON(obj == NULL))
2503                 return;
2504
2505         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2506
2507         dspcntr = DISPPLANE_GAMMA_ENABLE;
2508
2509         dspcntr |= DISPLAY_PLANE_ENABLE;
2510
2511         if (INTEL_INFO(dev)->gen < 4) {
2512                 if (intel_crtc->pipe == PIPE_B)
2513                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2514
2515                 /* pipesrc and dspsize control the size that is scaled from,
2516                  * which should always be the user's requested size.
2517                  */
2518                 I915_WRITE(DSPSIZE(plane),
2519                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2520                            (intel_crtc->config->pipe_src_w - 1));
2521                 I915_WRITE(DSPPOS(plane), 0);
2522         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2523                 I915_WRITE(PRIMSIZE(plane),
2524                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2525                            (intel_crtc->config->pipe_src_w - 1));
2526                 I915_WRITE(PRIMPOS(plane), 0);
2527                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2528         }
2529
2530         switch (fb->pixel_format) {
2531         case DRM_FORMAT_C8:
2532                 dspcntr |= DISPPLANE_8BPP;
2533                 break;
2534         case DRM_FORMAT_XRGB1555:
2535         case DRM_FORMAT_ARGB1555:
2536                 dspcntr |= DISPPLANE_BGRX555;
2537                 break;
2538         case DRM_FORMAT_RGB565:
2539                 dspcntr |= DISPPLANE_BGRX565;
2540                 break;
2541         case DRM_FORMAT_XRGB8888:
2542         case DRM_FORMAT_ARGB8888:
2543                 dspcntr |= DISPPLANE_BGRX888;
2544                 break;
2545         case DRM_FORMAT_XBGR8888:
2546         case DRM_FORMAT_ABGR8888:
2547                 dspcntr |= DISPPLANE_RGBX888;
2548                 break;
2549         case DRM_FORMAT_XRGB2101010:
2550         case DRM_FORMAT_ARGB2101010:
2551                 dspcntr |= DISPPLANE_BGRX101010;
2552                 break;
2553         case DRM_FORMAT_XBGR2101010:
2554         case DRM_FORMAT_ABGR2101010:
2555                 dspcntr |= DISPPLANE_RGBX101010;
2556                 break;
2557         default:
2558                 BUG();
2559         }
2560
2561         if (INTEL_INFO(dev)->gen >= 4 &&
2562             obj->tiling_mode != I915_TILING_NONE)
2563                 dspcntr |= DISPPLANE_TILED;
2564
2565         if (IS_G4X(dev))
2566                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2567
2568         linear_offset = y * fb->pitches[0] + x * pixel_size;
2569
2570         if (INTEL_INFO(dev)->gen >= 4) {
2571                 intel_crtc->dspaddr_offset =
2572                         intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2573                                                        pixel_size,
2574                                                        fb->pitches[0]);
2575                 linear_offset -= intel_crtc->dspaddr_offset;
2576         } else {
2577                 intel_crtc->dspaddr_offset = linear_offset;
2578         }
2579
2580         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2581                 dspcntr |= DISPPLANE_ROTATE_180;
2582
2583                 x += (intel_crtc->config->pipe_src_w - 1);
2584                 y += (intel_crtc->config->pipe_src_h - 1);
2585
2586                 /* Finding the last pixel of the last line of the display
2587                 data and adding to linear_offset*/
2588                 linear_offset +=
2589                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2590                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2591         }
2592
2593         I915_WRITE(reg, dspcntr);
2594
2595         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2596                       i915_gem_obj_ggtt_offset(obj), linear_offset, x, y,
2597                       fb->pitches[0]);
2598         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2599         if (INTEL_INFO(dev)->gen >= 4) {
2600                 I915_WRITE(DSPSURF(plane),
2601                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2602                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2603                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2604         } else
2605                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2606         POSTING_READ(reg);
2607 }
2608
2609 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2610                                           struct drm_framebuffer *fb,
2611                                           int x, int y)
2612 {
2613         struct drm_device *dev = crtc->dev;
2614         struct drm_i915_private *dev_priv = dev->dev_private;
2615         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2616         struct drm_i915_gem_object *obj;
2617         int plane = intel_crtc->plane;
2618         unsigned long linear_offset;
2619         u32 dspcntr;
2620         u32 reg = DSPCNTR(plane);
2621         int pixel_size;
2622
2623         if (!intel_crtc->primary_enabled) {
2624                 I915_WRITE(reg, 0);
2625                 I915_WRITE(DSPSURF(plane), 0);
2626                 POSTING_READ(reg);
2627                 return;
2628         }
2629
2630         obj = intel_fb_obj(fb);
2631         if (WARN_ON(obj == NULL))
2632                 return;
2633
2634         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2635
2636         dspcntr = DISPPLANE_GAMMA_ENABLE;
2637
2638         dspcntr |= DISPLAY_PLANE_ENABLE;
2639
2640         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2641                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2642
2643         switch (fb->pixel_format) {
2644         case DRM_FORMAT_C8:
2645                 dspcntr |= DISPPLANE_8BPP;
2646                 break;
2647         case DRM_FORMAT_RGB565:
2648                 dspcntr |= DISPPLANE_BGRX565;
2649                 break;
2650         case DRM_FORMAT_XRGB8888:
2651         case DRM_FORMAT_ARGB8888:
2652                 dspcntr |= DISPPLANE_BGRX888;
2653                 break;
2654         case DRM_FORMAT_XBGR8888:
2655         case DRM_FORMAT_ABGR8888:
2656                 dspcntr |= DISPPLANE_RGBX888;
2657                 break;
2658         case DRM_FORMAT_XRGB2101010:
2659         case DRM_FORMAT_ARGB2101010:
2660                 dspcntr |= DISPPLANE_BGRX101010;
2661                 break;
2662         case DRM_FORMAT_XBGR2101010:
2663         case DRM_FORMAT_ABGR2101010:
2664                 dspcntr |= DISPPLANE_RGBX101010;
2665                 break;
2666         default:
2667                 BUG();
2668         }
2669
2670         if (obj->tiling_mode != I915_TILING_NONE)
2671                 dspcntr |= DISPPLANE_TILED;
2672
2673         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2674                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2675
2676         linear_offset = y * fb->pitches[0] + x * pixel_size;
2677         intel_crtc->dspaddr_offset =
2678                 intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2679                                                pixel_size,
2680                                                fb->pitches[0]);
2681         linear_offset -= intel_crtc->dspaddr_offset;
2682         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2683                 dspcntr |= DISPPLANE_ROTATE_180;
2684
2685                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2686                         x += (intel_crtc->config->pipe_src_w - 1);
2687                         y += (intel_crtc->config->pipe_src_h - 1);
2688
2689                         /* Finding the last pixel of the last line of the display
2690                         data and adding to linear_offset*/
2691                         linear_offset +=
2692                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2693                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2694                 }
2695         }
2696
2697         I915_WRITE(reg, dspcntr);
2698
2699         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2700                       i915_gem_obj_ggtt_offset(obj), linear_offset, x, y,
2701                       fb->pitches[0]);
2702         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2703         I915_WRITE(DSPSURF(plane),
2704                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2705         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2706                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2707         } else {
2708                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2709                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2710         }
2711         POSTING_READ(reg);
2712 }
2713
2714 static void skylake_update_primary_plane(struct drm_crtc *crtc,
2715                                          struct drm_framebuffer *fb,
2716                                          int x, int y)
2717 {
2718         struct drm_device *dev = crtc->dev;
2719         struct drm_i915_private *dev_priv = dev->dev_private;
2720         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2721         struct intel_framebuffer *intel_fb;
2722         struct drm_i915_gem_object *obj;
2723         int pipe = intel_crtc->pipe;
2724         u32 plane_ctl, stride;
2725
2726         if (!intel_crtc->primary_enabled) {
2727                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
2728                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
2729                 POSTING_READ(PLANE_CTL(pipe, 0));
2730                 return;
2731         }
2732
2733         plane_ctl = PLANE_CTL_ENABLE |
2734                     PLANE_CTL_PIPE_GAMMA_ENABLE |
2735                     PLANE_CTL_PIPE_CSC_ENABLE;
2736
2737         switch (fb->pixel_format) {
2738         case DRM_FORMAT_RGB565:
2739                 plane_ctl |= PLANE_CTL_FORMAT_RGB_565;
2740                 break;
2741         case DRM_FORMAT_XRGB8888:
2742                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2743                 break;
2744         case DRM_FORMAT_XBGR8888:
2745                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
2746                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2747                 break;
2748         case DRM_FORMAT_XRGB2101010:
2749                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
2750                 break;
2751         case DRM_FORMAT_XBGR2101010:
2752                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
2753                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
2754                 break;
2755         default:
2756                 BUG();
2757         }
2758
2759         intel_fb = to_intel_framebuffer(fb);
2760         obj = intel_fb->obj;
2761
2762         /*
2763          * The stride is either expressed as a multiple of 64 bytes chunks for
2764          * linear buffers or in number of tiles for tiled buffers.
2765          */
2766         switch (obj->tiling_mode) {
2767         case I915_TILING_NONE:
2768                 stride = fb->pitches[0] >> 6;
2769                 break;
2770         case I915_TILING_X:
2771                 plane_ctl |= PLANE_CTL_TILED_X;
2772                 stride = fb->pitches[0] >> 9;
2773                 break;
2774         default:
2775                 BUG();
2776         }
2777
2778         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
2779         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180))
2780                 plane_ctl |= PLANE_CTL_ROTATE_180;
2781
2782         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
2783
2784         DRM_DEBUG_KMS("Writing base %08lX %d,%d,%d,%d pitch=%d\n",
2785                       i915_gem_obj_ggtt_offset(obj),
2786                       x, y, fb->width, fb->height,
2787                       fb->pitches[0]);
2788
2789         I915_WRITE(PLANE_POS(pipe, 0), 0);
2790         I915_WRITE(PLANE_OFFSET(pipe, 0), (y << 16) | x);
2791         I915_WRITE(PLANE_SIZE(pipe, 0),
2792                    (intel_crtc->config->pipe_src_h - 1) << 16 |
2793                    (intel_crtc->config->pipe_src_w - 1));
2794         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
2795         I915_WRITE(PLANE_SURF(pipe, 0), i915_gem_obj_ggtt_offset(obj));
2796
2797         POSTING_READ(PLANE_SURF(pipe, 0));
2798 }
2799
2800 /* Assume fb object is pinned & idle & fenced and just update base pointers */
2801 static int
2802 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
2803                            int x, int y, enum mode_set_atomic state)
2804 {
2805         struct drm_device *dev = crtc->dev;
2806         struct drm_i915_private *dev_priv = dev->dev_private;
2807
2808         if (dev_priv->display.disable_fbc)
2809                 dev_priv->display.disable_fbc(dev);
2810
2811         dev_priv->display.update_primary_plane(crtc, fb, x, y);
2812
2813         return 0;
2814 }
2815
2816 static void intel_complete_page_flips(struct drm_device *dev)
2817 {
2818         struct drm_crtc *crtc;
2819
2820         for_each_crtc(dev, crtc) {
2821                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2822                 enum plane plane = intel_crtc->plane;
2823
2824                 intel_prepare_page_flip(dev, plane);
2825                 intel_finish_page_flip_plane(dev, plane);
2826         }
2827 }
2828
2829 static void intel_update_primary_planes(struct drm_device *dev)
2830 {
2831         struct drm_i915_private *dev_priv = dev->dev_private;
2832         struct drm_crtc *crtc;
2833
2834         for_each_crtc(dev, crtc) {
2835                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2836
2837                 drm_modeset_lock(&crtc->mutex, NULL);
2838                 /*
2839                  * FIXME: Once we have proper support for primary planes (and
2840                  * disabling them without disabling the entire crtc) allow again
2841                  * a NULL crtc->primary->fb.
2842                  */
2843                 if (intel_crtc->active && crtc->primary->fb)
2844                         dev_priv->display.update_primary_plane(crtc,
2845                                                                crtc->primary->fb,
2846                                                                crtc->x,
2847                                                                crtc->y);
2848                 drm_modeset_unlock(&crtc->mutex);
2849         }
2850 }
2851
2852 void intel_prepare_reset(struct drm_device *dev)
2853 {
2854         struct drm_i915_private *dev_priv = to_i915(dev);
2855         struct intel_crtc *crtc;
2856
2857         /* no reset support for gen2 */
2858         if (IS_GEN2(dev))
2859                 return;
2860
2861         /* reset doesn't touch the display */
2862         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
2863                 return;
2864
2865         drm_modeset_lock_all(dev);
2866
2867         /*
2868          * Disabling the crtcs gracefully seems nicer. Also the
2869          * g33 docs say we should at least disable all the planes.
2870          */
2871         for_each_intel_crtc(dev, crtc) {
2872                 if (crtc->active)
2873                         dev_priv->display.crtc_disable(&crtc->base);
2874         }
2875 }
2876
2877 void intel_finish_reset(struct drm_device *dev)
2878 {
2879         struct drm_i915_private *dev_priv = to_i915(dev);
2880
2881         /*
2882          * Flips in the rings will be nuked by the reset,
2883          * so complete all pending flips so that user space
2884          * will get its events and not get stuck.
2885          */
2886         intel_complete_page_flips(dev);
2887
2888         /* no reset support for gen2 */
2889         if (IS_GEN2(dev))
2890                 return;
2891
2892         /* reset doesn't touch the display */
2893         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
2894                 /*
2895                  * Flips in the rings have been nuked by the reset,
2896                  * so update the base address of all primary
2897                  * planes to the the last fb to make sure we're
2898                  * showing the correct fb after a reset.
2899                  */
2900                 intel_update_primary_planes(dev);
2901                 return;
2902         }
2903
2904         /*
2905          * The display has been reset as well,
2906          * so need a full re-initialization.
2907          */
2908         intel_runtime_pm_disable_interrupts(dev_priv);
2909         intel_runtime_pm_enable_interrupts(dev_priv);
2910
2911         intel_modeset_init_hw(dev);
2912
2913         spin_lock_irq(&dev_priv->irq_lock);
2914         if (dev_priv->display.hpd_irq_setup)
2915                 dev_priv->display.hpd_irq_setup(dev);
2916         spin_unlock_irq(&dev_priv->irq_lock);
2917
2918         intel_modeset_setup_hw_state(dev, true);
2919
2920         intel_hpd_init(dev_priv);
2921
2922         drm_modeset_unlock_all(dev);
2923 }
2924
2925 static int
2926 intel_finish_fb(struct drm_framebuffer *old_fb)
2927 {
2928         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
2929         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2930         bool was_interruptible = dev_priv->mm.interruptible;
2931         int ret;
2932
2933         /* Big Hammer, we also need to ensure that any pending
2934          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
2935          * current scanout is retired before unpinning the old
2936          * framebuffer.
2937          *
2938          * This should only fail upon a hung GPU, in which case we
2939          * can safely continue.
2940          */
2941         dev_priv->mm.interruptible = false;
2942         ret = i915_gem_object_finish_gpu(obj);
2943         dev_priv->mm.interruptible = was_interruptible;
2944
2945         return ret;
2946 }
2947
2948 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
2949 {
2950         struct drm_device *dev = crtc->dev;
2951         struct drm_i915_private *dev_priv = dev->dev_private;
2952         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2953         bool pending;
2954
2955         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
2956             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
2957                 return false;
2958
2959         spin_lock_irq(&dev->event_lock);
2960         pending = to_intel_crtc(crtc)->unpin_work != NULL;
2961         spin_unlock_irq(&dev->event_lock);
2962
2963         return pending;
2964 }
2965
2966 static void intel_update_pipe_size(struct intel_crtc *crtc)
2967 {
2968         struct drm_device *dev = crtc->base.dev;
2969         struct drm_i915_private *dev_priv = dev->dev_private;
2970         const struct drm_display_mode *adjusted_mode;
2971
2972         if (!i915.fastboot)
2973                 return;
2974
2975         /*
2976          * Update pipe size and adjust fitter if needed: the reason for this is
2977          * that in compute_mode_changes we check the native mode (not the pfit
2978          * mode) to see if we can flip rather than do a full mode set. In the
2979          * fastboot case, we'll flip, but if we don't update the pipesrc and
2980          * pfit state, we'll end up with a big fb scanned out into the wrong
2981          * sized surface.
2982          *
2983          * To fix this properly, we need to hoist the checks up into
2984          * compute_mode_changes (or above), check the actual pfit state and
2985          * whether the platform allows pfit disable with pipe active, and only
2986          * then update the pipesrc and pfit state, even on the flip path.
2987          */
2988
2989         adjusted_mode = &crtc->config->base.adjusted_mode;
2990
2991         I915_WRITE(PIPESRC(crtc->pipe),
2992                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
2993                    (adjusted_mode->crtc_vdisplay - 1));
2994         if (!crtc->config->pch_pfit.enabled &&
2995             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
2996              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
2997                 I915_WRITE(PF_CTL(crtc->pipe), 0);
2998                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
2999                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3000         }
3001         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3002         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3003 }
3004
3005 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3006 {
3007         struct drm_device *dev = crtc->dev;
3008         struct drm_i915_private *dev_priv = dev->dev_private;
3009         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3010         int pipe = intel_crtc->pipe;
3011         u32 reg, temp;
3012
3013         /* enable normal train */
3014         reg = FDI_TX_CTL(pipe);
3015         temp = I915_READ(reg);
3016         if (IS_IVYBRIDGE(dev)) {
3017                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3018                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3019         } else {
3020                 temp &= ~FDI_LINK_TRAIN_NONE;
3021                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3022         }
3023         I915_WRITE(reg, temp);
3024
3025         reg = FDI_RX_CTL(pipe);
3026         temp = I915_READ(reg);
3027         if (HAS_PCH_CPT(dev)) {
3028                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3029                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3030         } else {
3031                 temp &= ~FDI_LINK_TRAIN_NONE;
3032                 temp |= FDI_LINK_TRAIN_NONE;
3033         }
3034         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3035
3036         /* wait one idle pattern time */
3037         POSTING_READ(reg);
3038         udelay(1000);
3039
3040         /* IVB wants error correction enabled */
3041         if (IS_IVYBRIDGE(dev))
3042                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3043                            FDI_FE_ERRC_ENABLE);
3044 }
3045
3046 static bool pipe_has_enabled_pch(struct intel_crtc *crtc)
3047 {
3048         return crtc->base.enabled && crtc->active &&
3049                 crtc->config->has_pch_encoder;
3050 }
3051
3052 static void ivb_modeset_global_resources(struct drm_device *dev)
3053 {
3054         struct drm_i915_private *dev_priv = dev->dev_private;
3055         struct intel_crtc *pipe_B_crtc =
3056                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_B]);
3057         struct intel_crtc *pipe_C_crtc =
3058                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_C]);
3059         uint32_t temp;
3060
3061         /*
3062          * When everything is off disable fdi C so that we could enable fdi B
3063          * with all lanes. Note that we don't care about enabled pipes without
3064          * an enabled pch encoder.
3065          */
3066         if (!pipe_has_enabled_pch(pipe_B_crtc) &&
3067             !pipe_has_enabled_pch(pipe_C_crtc)) {
3068                 WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3069                 WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3070
3071                 temp = I915_READ(SOUTH_CHICKEN1);
3072                 temp &= ~FDI_BC_BIFURCATION_SELECT;
3073                 DRM_DEBUG_KMS("disabling fdi C rx\n");
3074                 I915_WRITE(SOUTH_CHICKEN1, temp);
3075         }
3076 }
3077
3078 /* The FDI link training functions for ILK/Ibexpeak. */
3079 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3080 {
3081         struct drm_device *dev = crtc->dev;
3082         struct drm_i915_private *dev_priv = dev->dev_private;
3083         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3084         int pipe = intel_crtc->pipe;
3085         u32 reg, temp, tries;
3086
3087         /* FDI needs bits from pipe first */
3088         assert_pipe_enabled(dev_priv, pipe);
3089
3090         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3091            for train result */
3092         reg = FDI_RX_IMR(pipe);
3093         temp = I915_READ(reg);
3094         temp &= ~FDI_RX_SYMBOL_LOCK;
3095         temp &= ~FDI_RX_BIT_LOCK;
3096         I915_WRITE(reg, temp);
3097         I915_READ(reg);
3098         udelay(150);
3099
3100         /* enable CPU FDI TX and PCH FDI RX */
3101         reg = FDI_TX_CTL(pipe);
3102         temp = I915_READ(reg);
3103         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3104         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3105         temp &= ~FDI_LINK_TRAIN_NONE;
3106         temp |= FDI_LINK_TRAIN_PATTERN_1;
3107         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3108
3109         reg = FDI_RX_CTL(pipe);
3110         temp = I915_READ(reg);
3111         temp &= ~FDI_LINK_TRAIN_NONE;
3112         temp |= FDI_LINK_TRAIN_PATTERN_1;
3113         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3114
3115         POSTING_READ(reg);
3116         udelay(150);
3117
3118         /* Ironlake workaround, enable clock pointer after FDI enable*/
3119         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3120         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3121                    FDI_RX_PHASE_SYNC_POINTER_EN);
3122
3123         reg = FDI_RX_IIR(pipe);
3124         for (tries = 0; tries < 5; tries++) {
3125                 temp = I915_READ(reg);
3126                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3127
3128                 if ((temp & FDI_RX_BIT_LOCK)) {
3129                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3130                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3131                         break;
3132                 }
3133         }
3134         if (tries == 5)
3135                 DRM_ERROR("FDI train 1 fail!\n");
3136
3137         /* Train 2 */
3138         reg = FDI_TX_CTL(pipe);
3139         temp = I915_READ(reg);
3140         temp &= ~FDI_LINK_TRAIN_NONE;
3141         temp |= FDI_LINK_TRAIN_PATTERN_2;
3142         I915_WRITE(reg, temp);
3143
3144         reg = FDI_RX_CTL(pipe);
3145         temp = I915_READ(reg);
3146         temp &= ~FDI_LINK_TRAIN_NONE;
3147         temp |= FDI_LINK_TRAIN_PATTERN_2;
3148         I915_WRITE(reg, temp);
3149
3150         POSTING_READ(reg);
3151         udelay(150);
3152
3153         reg = FDI_RX_IIR(pipe);
3154         for (tries = 0; tries < 5; tries++) {
3155                 temp = I915_READ(reg);
3156                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3157
3158                 if (temp & FDI_RX_SYMBOL_LOCK) {
3159                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3160                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3161                         break;
3162                 }
3163         }
3164         if (tries == 5)
3165                 DRM_ERROR("FDI train 2 fail!\n");
3166
3167         DRM_DEBUG_KMS("FDI train done\n");
3168
3169 }
3170
3171 static const int snb_b_fdi_train_param[] = {
3172         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3173         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3174         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3175         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3176 };
3177
3178 /* The FDI link training functions for SNB/Cougarpoint. */
3179 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3180 {
3181         struct drm_device *dev = crtc->dev;
3182         struct drm_i915_private *dev_priv = dev->dev_private;
3183         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3184         int pipe = intel_crtc->pipe;
3185         u32 reg, temp, i, retry;
3186
3187         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3188            for train result */
3189         reg = FDI_RX_IMR(pipe);
3190         temp = I915_READ(reg);
3191         temp &= ~FDI_RX_SYMBOL_LOCK;
3192         temp &= ~FDI_RX_BIT_LOCK;
3193         I915_WRITE(reg, temp);
3194
3195         POSTING_READ(reg);
3196         udelay(150);
3197
3198         /* enable CPU FDI TX and PCH FDI RX */
3199         reg = FDI_TX_CTL(pipe);
3200         temp = I915_READ(reg);
3201         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3202         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3203         temp &= ~FDI_LINK_TRAIN_NONE;
3204         temp |= FDI_LINK_TRAIN_PATTERN_1;
3205         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3206         /* SNB-B */
3207         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3208         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3209
3210         I915_WRITE(FDI_RX_MISC(pipe),
3211                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3212
3213         reg = FDI_RX_CTL(pipe);
3214         temp = I915_READ(reg);
3215         if (HAS_PCH_CPT(dev)) {
3216                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3217                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3218         } else {
3219                 temp &= ~FDI_LINK_TRAIN_NONE;
3220                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3221         }
3222         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3223
3224         POSTING_READ(reg);
3225         udelay(150);
3226
3227         for (i = 0; i < 4; i++) {
3228                 reg = FDI_TX_CTL(pipe);
3229                 temp = I915_READ(reg);
3230                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3231                 temp |= snb_b_fdi_train_param[i];
3232                 I915_WRITE(reg, temp);
3233
3234                 POSTING_READ(reg);
3235                 udelay(500);
3236
3237                 for (retry = 0; retry < 5; retry++) {
3238                         reg = FDI_RX_IIR(pipe);
3239                         temp = I915_READ(reg);
3240                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3241                         if (temp & FDI_RX_BIT_LOCK) {
3242                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3243                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3244                                 break;
3245                         }
3246                         udelay(50);
3247                 }
3248                 if (retry < 5)
3249                         break;
3250         }
3251         if (i == 4)
3252                 DRM_ERROR("FDI train 1 fail!\n");
3253
3254         /* Train 2 */
3255         reg = FDI_TX_CTL(pipe);
3256         temp = I915_READ(reg);
3257         temp &= ~FDI_LINK_TRAIN_NONE;
3258         temp |= FDI_LINK_TRAIN_PATTERN_2;
3259         if (IS_GEN6(dev)) {
3260                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3261                 /* SNB-B */
3262                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3263         }
3264         I915_WRITE(reg, temp);
3265
3266         reg = FDI_RX_CTL(pipe);
3267         temp = I915_READ(reg);
3268         if (HAS_PCH_CPT(dev)) {
3269                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3270                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3271         } else {
3272                 temp &= ~FDI_LINK_TRAIN_NONE;
3273                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3274         }
3275         I915_WRITE(reg, temp);
3276
3277         POSTING_READ(reg);
3278         udelay(150);
3279
3280         for (i = 0; i < 4; i++) {
3281                 reg = FDI_TX_CTL(pipe);
3282                 temp = I915_READ(reg);
3283                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3284                 temp |= snb_b_fdi_train_param[i];
3285                 I915_WRITE(reg, temp);
3286
3287                 POSTING_READ(reg);
3288                 udelay(500);
3289
3290                 for (retry = 0; retry < 5; retry++) {
3291                         reg = FDI_RX_IIR(pipe);
3292                         temp = I915_READ(reg);
3293                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3294                         if (temp & FDI_RX_SYMBOL_LOCK) {
3295                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3296                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3297                                 break;
3298                         }
3299                         udelay(50);
3300                 }
3301                 if (retry < 5)
3302                         break;
3303         }
3304         if (i == 4)
3305                 DRM_ERROR("FDI train 2 fail!\n");
3306
3307         DRM_DEBUG_KMS("FDI train done.\n");
3308 }
3309
3310 /* Manual link training for Ivy Bridge A0 parts */
3311 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3312 {
3313         struct drm_device *dev = crtc->dev;
3314         struct drm_i915_private *dev_priv = dev->dev_private;
3315         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3316         int pipe = intel_crtc->pipe;
3317         u32 reg, temp, i, j;
3318
3319         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3320            for train result */
3321         reg = FDI_RX_IMR(pipe);
3322         temp = I915_READ(reg);
3323         temp &= ~FDI_RX_SYMBOL_LOCK;
3324         temp &= ~FDI_RX_BIT_LOCK;
3325         I915_WRITE(reg, temp);
3326
3327         POSTING_READ(reg);
3328         udelay(150);
3329
3330         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3331                       I915_READ(FDI_RX_IIR(pipe)));
3332
3333         /* Try each vswing and preemphasis setting twice before moving on */
3334         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3335                 /* disable first in case we need to retry */
3336                 reg = FDI_TX_CTL(pipe);
3337                 temp = I915_READ(reg);
3338                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3339                 temp &= ~FDI_TX_ENABLE;
3340                 I915_WRITE(reg, temp);
3341
3342                 reg = FDI_RX_CTL(pipe);
3343                 temp = I915_READ(reg);
3344                 temp &= ~FDI_LINK_TRAIN_AUTO;
3345                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3346                 temp &= ~FDI_RX_ENABLE;
3347                 I915_WRITE(reg, temp);
3348
3349                 /* enable CPU FDI TX and PCH FDI RX */
3350                 reg = FDI_TX_CTL(pipe);
3351                 temp = I915_READ(reg);
3352                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3353                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3354                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3355                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3356                 temp |= snb_b_fdi_train_param[j/2];
3357                 temp |= FDI_COMPOSITE_SYNC;
3358                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3359
3360                 I915_WRITE(FDI_RX_MISC(pipe),
3361                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3362
3363                 reg = FDI_RX_CTL(pipe);
3364                 temp = I915_READ(reg);
3365                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3366                 temp |= FDI_COMPOSITE_SYNC;
3367                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3368
3369                 POSTING_READ(reg);
3370                 udelay(1); /* should be 0.5us */
3371
3372                 for (i = 0; i < 4; i++) {
3373                         reg = FDI_RX_IIR(pipe);
3374                         temp = I915_READ(reg);
3375                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3376
3377                         if (temp & FDI_RX_BIT_LOCK ||
3378                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3379                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3380                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3381                                               i);
3382                                 break;
3383                         }
3384                         udelay(1); /* should be 0.5us */
3385                 }
3386                 if (i == 4) {
3387                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3388                         continue;
3389                 }
3390
3391                 /* Train 2 */
3392                 reg = FDI_TX_CTL(pipe);
3393                 temp = I915_READ(reg);
3394                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3395                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3396                 I915_WRITE(reg, temp);
3397
3398                 reg = FDI_RX_CTL(pipe);
3399                 temp = I915_READ(reg);
3400                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3401                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3402                 I915_WRITE(reg, temp);
3403
3404                 POSTING_READ(reg);
3405                 udelay(2); /* should be 1.5us */
3406
3407                 for (i = 0; i < 4; i++) {
3408                         reg = FDI_RX_IIR(pipe);
3409                         temp = I915_READ(reg);
3410                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3411
3412                         if (temp & FDI_RX_SYMBOL_LOCK ||
3413                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3414                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3415                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3416                                               i);
3417                                 goto train_done;
3418                         }
3419                         udelay(2); /* should be 1.5us */
3420                 }
3421                 if (i == 4)
3422                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3423         }
3424
3425 train_done:
3426         DRM_DEBUG_KMS("FDI train done.\n");
3427 }
3428
3429 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3430 {
3431         struct drm_device *dev = intel_crtc->base.dev;
3432         struct drm_i915_private *dev_priv = dev->dev_private;
3433         int pipe = intel_crtc->pipe;
3434         u32 reg, temp;
3435
3436
3437         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3438         reg = FDI_RX_CTL(pipe);
3439         temp = I915_READ(reg);
3440         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3441         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3442         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3443         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3444
3445         POSTING_READ(reg);
3446         udelay(200);
3447
3448         /* Switch from Rawclk to PCDclk */
3449         temp = I915_READ(reg);
3450         I915_WRITE(reg, temp | FDI_PCDCLK);
3451
3452         POSTING_READ(reg);
3453         udelay(200);
3454
3455         /* Enable CPU FDI TX PLL, always on for Ironlake */
3456         reg = FDI_TX_CTL(pipe);
3457         temp = I915_READ(reg);
3458         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3459                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3460
3461                 POSTING_READ(reg);
3462                 udelay(100);
3463         }
3464 }
3465
3466 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3467 {
3468         struct drm_device *dev = intel_crtc->base.dev;
3469         struct drm_i915_private *dev_priv = dev->dev_private;
3470         int pipe = intel_crtc->pipe;
3471         u32 reg, temp;
3472
3473         /* Switch from PCDclk to Rawclk */
3474         reg = FDI_RX_CTL(pipe);
3475         temp = I915_READ(reg);
3476         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3477
3478         /* Disable CPU FDI TX PLL */
3479         reg = FDI_TX_CTL(pipe);
3480         temp = I915_READ(reg);
3481         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3482
3483         POSTING_READ(reg);
3484         udelay(100);
3485
3486         reg = FDI_RX_CTL(pipe);
3487         temp = I915_READ(reg);
3488         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3489
3490         /* Wait for the clocks to turn off. */
3491         POSTING_READ(reg);
3492         udelay(100);
3493 }
3494
3495 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3496 {
3497         struct drm_device *dev = crtc->dev;
3498         struct drm_i915_private *dev_priv = dev->dev_private;
3499         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3500         int pipe = intel_crtc->pipe;
3501         u32 reg, temp;
3502
3503         /* disable CPU FDI tx and PCH FDI rx */
3504         reg = FDI_TX_CTL(pipe);
3505         temp = I915_READ(reg);
3506         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3507         POSTING_READ(reg);
3508
3509         reg = FDI_RX_CTL(pipe);
3510         temp = I915_READ(reg);
3511         temp &= ~(0x7 << 16);
3512         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3513         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3514
3515         POSTING_READ(reg);
3516         udelay(100);
3517
3518         /* Ironlake workaround, disable clock pointer after downing FDI */
3519         if (HAS_PCH_IBX(dev))
3520                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3521
3522         /* still set train pattern 1 */
3523         reg = FDI_TX_CTL(pipe);
3524         temp = I915_READ(reg);
3525         temp &= ~FDI_LINK_TRAIN_NONE;
3526         temp |= FDI_LINK_TRAIN_PATTERN_1;
3527         I915_WRITE(reg, temp);
3528
3529         reg = FDI_RX_CTL(pipe);
3530         temp = I915_READ(reg);
3531         if (HAS_PCH_CPT(dev)) {
3532                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3533                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3534         } else {
3535                 temp &= ~FDI_LINK_TRAIN_NONE;
3536                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3537         }
3538         /* BPC in FDI rx is consistent with that in PIPECONF */
3539         temp &= ~(0x07 << 16);
3540         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3541         I915_WRITE(reg, temp);
3542
3543         POSTING_READ(reg);
3544         udelay(100);
3545 }
3546
3547 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3548 {
3549         struct intel_crtc *crtc;
3550
3551         /* Note that we don't need to be called with mode_config.lock here
3552          * as our list of CRTC objects is static for the lifetime of the
3553          * device and so cannot disappear as we iterate. Similarly, we can
3554          * happily treat the predicates as racy, atomic checks as userspace
3555          * cannot claim and pin a new fb without at least acquring the
3556          * struct_mutex and so serialising with us.
3557          */
3558         for_each_intel_crtc(dev, crtc) {
3559                 if (atomic_read(&crtc->unpin_work_count) == 0)
3560                         continue;
3561
3562                 if (crtc->unpin_work)
3563                         intel_wait_for_vblank(dev, crtc->pipe);
3564
3565                 return true;
3566         }
3567
3568         return false;
3569 }
3570
3571 static void page_flip_completed(struct intel_crtc *intel_crtc)
3572 {
3573         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3574         struct intel_unpin_work *work = intel_crtc->unpin_work;
3575
3576         /* ensure that the unpin work is consistent wrt ->pending. */
3577         smp_rmb();
3578         intel_crtc->unpin_work = NULL;
3579
3580         if (work->event)
3581                 drm_send_vblank_event(intel_crtc->base.dev,
3582                                       intel_crtc->pipe,
3583                                       work->event);
3584
3585         drm_crtc_vblank_put(&intel_crtc->base);
3586
3587         wake_up_all(&dev_priv->pending_flip_queue);
3588         queue_work(dev_priv->wq, &work->work);
3589
3590         trace_i915_flip_complete(intel_crtc->plane,
3591                                  work->pending_flip_obj);
3592 }
3593
3594 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3595 {
3596         struct drm_device *dev = crtc->dev;
3597         struct drm_i915_private *dev_priv = dev->dev_private;
3598
3599         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3600         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3601                                        !intel_crtc_has_pending_flip(crtc),
3602                                        60*HZ) == 0)) {
3603                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3604
3605                 spin_lock_irq(&dev->event_lock);
3606                 if (intel_crtc->unpin_work) {
3607                         WARN_ONCE(1, "Removing stuck page flip\n");
3608                         page_flip_completed(intel_crtc);
3609                 }
3610                 spin_unlock_irq(&dev->event_lock);
3611         }
3612
3613         if (crtc->primary->fb) {
3614                 mutex_lock(&dev->struct_mutex);
3615                 intel_finish_fb(crtc->primary->fb);
3616                 mutex_unlock(&dev->struct_mutex);
3617         }
3618 }
3619
3620 /* Program iCLKIP clock to the desired frequency */
3621 static void lpt_program_iclkip(struct drm_crtc *crtc)
3622 {
3623         struct drm_device *dev = crtc->dev;
3624         struct drm_i915_private *dev_priv = dev->dev_private;
3625         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3626         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3627         u32 temp;
3628
3629         mutex_lock(&dev_priv->dpio_lock);
3630
3631         /* It is necessary to ungate the pixclk gate prior to programming
3632          * the divisors, and gate it back when it is done.
3633          */
3634         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3635
3636         /* Disable SSCCTL */
3637         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3638                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3639                                 SBI_SSCCTL_DISABLE,
3640                         SBI_ICLK);
3641
3642         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3643         if (clock == 20000) {
3644                 auxdiv = 1;
3645                 divsel = 0x41;
3646                 phaseinc = 0x20;
3647         } else {
3648                 /* The iCLK virtual clock root frequency is in MHz,
3649                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3650                  * divisors, it is necessary to divide one by another, so we
3651                  * convert the virtual clock precision to KHz here for higher
3652                  * precision.
3653                  */
3654                 u32 iclk_virtual_root_freq = 172800 * 1000;
3655                 u32 iclk_pi_range = 64;
3656                 u32 desired_divisor, msb_divisor_value, pi_value;
3657
3658                 desired_divisor = (iclk_virtual_root_freq / clock);
3659                 msb_divisor_value = desired_divisor / iclk_pi_range;
3660                 pi_value = desired_divisor % iclk_pi_range;
3661
3662                 auxdiv = 0;
3663                 divsel = msb_divisor_value - 2;
3664                 phaseinc = pi_value;
3665         }
3666
3667         /* This should not happen with any sane values */
3668         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3669                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3670         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3671                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3672
3673         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3674                         clock,
3675                         auxdiv,
3676                         divsel,
3677                         phasedir,
3678                         phaseinc);
3679
3680         /* Program SSCDIVINTPHASE6 */
3681         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3682         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3683         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3684         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3685         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3686         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3687         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3688         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3689
3690         /* Program SSCAUXDIV */
3691         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3692         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3693         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3694         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3695
3696         /* Enable modulator and associated divider */
3697         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3698         temp &= ~SBI_SSCCTL_DISABLE;
3699         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3700
3701         /* Wait for initialization time */
3702         udelay(24);
3703
3704         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3705
3706         mutex_unlock(&dev_priv->dpio_lock);
3707 }
3708
3709 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3710                                                 enum pipe pch_transcoder)
3711 {
3712         struct drm_device *dev = crtc->base.dev;
3713         struct drm_i915_private *dev_priv = dev->dev_private;
3714         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3715
3716         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3717                    I915_READ(HTOTAL(cpu_transcoder)));
3718         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3719                    I915_READ(HBLANK(cpu_transcoder)));
3720         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3721                    I915_READ(HSYNC(cpu_transcoder)));
3722
3723         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3724                    I915_READ(VTOTAL(cpu_transcoder)));
3725         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3726                    I915_READ(VBLANK(cpu_transcoder)));
3727         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3728                    I915_READ(VSYNC(cpu_transcoder)));
3729         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3730                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
3731 }
3732
3733 static void cpt_enable_fdi_bc_bifurcation(struct drm_device *dev)
3734 {
3735         struct drm_i915_private *dev_priv = dev->dev_private;
3736         uint32_t temp;
3737
3738         temp = I915_READ(SOUTH_CHICKEN1);
3739         if (temp & FDI_BC_BIFURCATION_SELECT)
3740                 return;
3741
3742         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3743         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3744
3745         temp |= FDI_BC_BIFURCATION_SELECT;
3746         DRM_DEBUG_KMS("enabling fdi C rx\n");
3747         I915_WRITE(SOUTH_CHICKEN1, temp);
3748         POSTING_READ(SOUTH_CHICKEN1);
3749 }
3750
3751 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
3752 {
3753         struct drm_device *dev = intel_crtc->base.dev;
3754         struct drm_i915_private *dev_priv = dev->dev_private;
3755
3756         switch (intel_crtc->pipe) {
3757         case PIPE_A:
3758                 break;
3759         case PIPE_B:
3760                 if (intel_crtc->config->fdi_lanes > 2)
3761                         WARN_ON(I915_READ(SOUTH_CHICKEN1) & FDI_BC_BIFURCATION_SELECT);
3762                 else
3763                         cpt_enable_fdi_bc_bifurcation(dev);
3764
3765                 break;
3766         case PIPE_C:
3767                 cpt_enable_fdi_bc_bifurcation(dev);
3768
3769                 break;
3770         default:
3771                 BUG();
3772         }
3773 }
3774
3775 /*
3776  * Enable PCH resources required for PCH ports:
3777  *   - PCH PLLs
3778  *   - FDI training & RX/TX
3779  *   - update transcoder timings
3780  *   - DP transcoding bits
3781  *   - transcoder
3782  */
3783 static void ironlake_pch_enable(struct drm_crtc *crtc)
3784 {
3785         struct drm_device *dev = crtc->dev;
3786         struct drm_i915_private *dev_priv = dev->dev_private;
3787         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3788         int pipe = intel_crtc->pipe;
3789         u32 reg, temp;
3790
3791         assert_pch_transcoder_disabled(dev_priv, pipe);
3792
3793         if (IS_IVYBRIDGE(dev))
3794                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
3795
3796         /* Write the TU size bits before fdi link training, so that error
3797          * detection works. */
3798         I915_WRITE(FDI_RX_TUSIZE1(pipe),
3799                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
3800
3801         /* For PCH output, training FDI link */
3802         dev_priv->display.fdi_link_train(crtc);
3803
3804         /* We need to program the right clock selection before writing the pixel
3805          * mutliplier into the DPLL. */
3806         if (HAS_PCH_CPT(dev)) {
3807                 u32 sel;
3808
3809                 temp = I915_READ(PCH_DPLL_SEL);
3810                 temp |= TRANS_DPLL_ENABLE(pipe);
3811                 sel = TRANS_DPLLB_SEL(pipe);
3812                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
3813                         temp |= sel;
3814                 else
3815                         temp &= ~sel;
3816                 I915_WRITE(PCH_DPLL_SEL, temp);
3817         }
3818
3819         /* XXX: pch pll's can be enabled any time before we enable the PCH
3820          * transcoder, and we actually should do this to not upset any PCH
3821          * transcoder that already use the clock when we share it.
3822          *
3823          * Note that enable_shared_dpll tries to do the right thing, but
3824          * get_shared_dpll unconditionally resets the pll - we need that to have
3825          * the right LVDS enable sequence. */
3826         intel_enable_shared_dpll(intel_crtc);
3827
3828         /* set transcoder timing, panel must allow it */
3829         assert_panel_unlocked(dev_priv, pipe);
3830         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
3831
3832         intel_fdi_normal_train(crtc);
3833
3834         /* For PCH DP, enable TRANS_DP_CTL */
3835         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
3836                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
3837                 reg = TRANS_DP_CTL(pipe);
3838                 temp = I915_READ(reg);
3839                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
3840                           TRANS_DP_SYNC_MASK |
3841                           TRANS_DP_BPC_MASK);
3842                 temp |= (TRANS_DP_OUTPUT_ENABLE |
3843                          TRANS_DP_ENH_FRAMING);
3844                 temp |= bpc << 9; /* same format but at 11:9 */
3845
3846                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
3847                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
3848                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
3849                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
3850
3851                 switch (intel_trans_dp_port_sel(crtc)) {
3852                 case PCH_DP_B:
3853                         temp |= TRANS_DP_PORT_SEL_B;
3854                         break;
3855                 case PCH_DP_C:
3856                         temp |= TRANS_DP_PORT_SEL_C;
3857                         break;
3858                 case PCH_DP_D:
3859                         temp |= TRANS_DP_PORT_SEL_D;
3860                         break;
3861                 default:
3862                         BUG();
3863                 }
3864
3865                 I915_WRITE(reg, temp);
3866         }
3867
3868         ironlake_enable_pch_transcoder(dev_priv, pipe);
3869 }
3870
3871 static void lpt_pch_enable(struct drm_crtc *crtc)
3872 {
3873         struct drm_device *dev = crtc->dev;
3874         struct drm_i915_private *dev_priv = dev->dev_private;
3875         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3876         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
3877
3878         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
3879
3880         lpt_program_iclkip(crtc);
3881
3882         /* Set transcoder timing. */
3883         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
3884
3885         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
3886 }
3887
3888 void intel_put_shared_dpll(struct intel_crtc *crtc)
3889 {
3890         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
3891
3892         if (pll == NULL)
3893                 return;
3894
3895         if (!(pll->config.crtc_mask & (1 << crtc->pipe))) {
3896                 WARN(1, "bad %s crtc mask\n", pll->name);
3897                 return;
3898         }
3899
3900         pll->config.crtc_mask &= ~(1 << crtc->pipe);
3901         if (pll->config.crtc_mask == 0) {
3902                 WARN_ON(pll->on);
3903                 WARN_ON(pll->active);
3904         }
3905
3906         crtc->config->shared_dpll = DPLL_ID_PRIVATE;
3907 }
3908
3909 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
3910                                                 struct intel_crtc_state *crtc_state)
3911 {
3912         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
3913         struct intel_shared_dpll *pll;
3914         enum intel_dpll_id i;
3915
3916         if (HAS_PCH_IBX(dev_priv->dev)) {
3917                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
3918                 i = (enum intel_dpll_id) crtc->pipe;
3919                 pll = &dev_priv->shared_dplls[i];
3920
3921                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
3922                               crtc->base.base.id, pll->name);
3923
3924                 WARN_ON(pll->new_config->crtc_mask);
3925
3926                 goto found;
3927         }
3928
3929         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
3930                 pll = &dev_priv->shared_dplls[i];
3931
3932                 /* Only want to check enabled timings first */
3933                 if (pll->new_config->crtc_mask == 0)
3934                         continue;
3935
3936                 if (memcmp(&crtc_state->dpll_hw_state,
3937                            &pll->new_config->hw_state,
3938                            sizeof(pll->new_config->hw_state)) == 0) {
3939                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
3940                                       crtc->base.base.id, pll->name,
3941                                       pll->new_config->crtc_mask,
3942                                       pll->active);
3943                         goto found;
3944                 }
3945         }
3946
3947         /* Ok no matching timings, maybe there's a free one? */
3948         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
3949                 pll = &dev_priv->shared_dplls[i];
3950                 if (pll->new_config->crtc_mask == 0) {
3951                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
3952                                       crtc->base.base.id, pll->name);
3953                         goto found;
3954                 }
3955         }
3956
3957         return NULL;
3958
3959 found:
3960         if (pll->new_config->crtc_mask == 0)
3961                 pll->new_config->hw_state = crtc_state->dpll_hw_state;
3962
3963         crtc_state->shared_dpll = i;
3964         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
3965                          pipe_name(crtc->pipe));
3966
3967         pll->new_config->crtc_mask |= 1 << crtc->pipe;
3968
3969         return pll;
3970 }
3971
3972 /**
3973  * intel_shared_dpll_start_config - start a new PLL staged config
3974  * @dev_priv: DRM device
3975  * @clear_pipes: mask of pipes that will have their PLLs freed
3976  *
3977  * Starts a new PLL staged config, copying the current config but
3978  * releasing the references of pipes specified in clear_pipes.
3979  */
3980 static int intel_shared_dpll_start_config(struct drm_i915_private *dev_priv,
3981                                           unsigned clear_pipes)
3982 {
3983         struct intel_shared_dpll *pll;
3984         enum intel_dpll_id i;
3985
3986         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
3987                 pll = &dev_priv->shared_dplls[i];
3988
3989                 pll->new_config = kmemdup(&pll->config, sizeof pll->config,
3990                                           GFP_KERNEL);
3991                 if (!pll->new_config)
3992                         goto cleanup;
3993
3994                 pll->new_config->crtc_mask &= ~clear_pipes;
3995         }
3996
3997         return 0;
3998
3999 cleanup:
4000         while (--i >= 0) {
4001                 pll = &dev_priv->shared_dplls[i];
4002                 kfree(pll->new_config);
4003                 pll->new_config = NULL;
4004         }
4005
4006         return -ENOMEM;
4007 }
4008
4009 static void intel_shared_dpll_commit(struct drm_i915_private *dev_priv)
4010 {
4011         struct intel_shared_dpll *pll;
4012         enum intel_dpll_id i;
4013
4014         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4015                 pll = &dev_priv->shared_dplls[i];
4016
4017                 WARN_ON(pll->new_config == &pll->config);
4018
4019                 pll->config = *pll->new_config;
4020                 kfree(pll->new_config);
4021                 pll->new_config = NULL;
4022         }
4023 }
4024
4025 static void intel_shared_dpll_abort_config(struct drm_i915_private *dev_priv)
4026 {
4027         struct intel_shared_dpll *pll;
4028         enum intel_dpll_id i;
4029
4030         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4031                 pll = &dev_priv->shared_dplls[i];
4032
4033                 WARN_ON(pll->new_config == &pll->config);
4034
4035                 kfree(pll->new_config);
4036                 pll->new_config = NULL;
4037         }
4038 }
4039
4040 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4041 {
4042         struct drm_i915_private *dev_priv = dev->dev_private;
4043         int dslreg = PIPEDSL(pipe);
4044         u32 temp;
4045
4046         temp = I915_READ(dslreg);
4047         udelay(500);
4048         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4049                 if (wait_for(I915_READ(dslreg) != temp, 5))
4050                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4051         }
4052 }
4053
4054 static void skylake_pfit_enable(struct intel_crtc *crtc)
4055 {
4056         struct drm_device *dev = crtc->base.dev;
4057         struct drm_i915_private *dev_priv = dev->dev_private;
4058         int pipe = crtc->pipe;
4059
4060         if (crtc->config->pch_pfit.enabled) {
4061                 I915_WRITE(PS_CTL(pipe), PS_ENABLE);
4062                 I915_WRITE(PS_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4063                 I915_WRITE(PS_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4064         }
4065 }
4066
4067 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4068 {
4069         struct drm_device *dev = crtc->base.dev;
4070         struct drm_i915_private *dev_priv = dev->dev_private;
4071         int pipe = crtc->pipe;
4072
4073         if (crtc->config->pch_pfit.enabled) {
4074                 /* Force use of hard-coded filter coefficients
4075                  * as some pre-programmed values are broken,
4076                  * e.g. x201.
4077                  */
4078                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4079                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4080                                                  PF_PIPE_SEL_IVB(pipe));
4081                 else
4082                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4083                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4084                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4085         }
4086 }
4087
4088 static void intel_enable_sprite_planes(struct drm_crtc *crtc)
4089 {
4090         struct drm_device *dev = crtc->dev;
4091         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4092         struct drm_plane *plane;
4093         struct intel_plane *intel_plane;
4094
4095         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4096                 intel_plane = to_intel_plane(plane);
4097                 if (intel_plane->pipe == pipe)
4098                         intel_plane_restore(&intel_plane->base);
4099         }
4100 }
4101
4102 static void intel_disable_sprite_planes(struct drm_crtc *crtc)
4103 {
4104         struct drm_device *dev = crtc->dev;
4105         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4106         struct drm_plane *plane;
4107         struct intel_plane *intel_plane;
4108
4109         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4110                 intel_plane = to_intel_plane(plane);
4111                 if (intel_plane->pipe == pipe)
4112                         plane->funcs->disable_plane(plane);
4113         }
4114 }
4115
4116 void hsw_enable_ips(struct intel_crtc *crtc)
4117 {
4118         struct drm_device *dev = crtc->base.dev;
4119         struct drm_i915_private *dev_priv = dev->dev_private;
4120
4121         if (!crtc->config->ips_enabled)
4122                 return;
4123
4124         /* We can only enable IPS after we enable a plane and wait for a vblank */
4125         intel_wait_for_vblank(dev, crtc->pipe);
4126
4127         assert_plane_enabled(dev_priv, crtc->plane);
4128         if (IS_BROADWELL(dev)) {
4129                 mutex_lock(&dev_priv->rps.hw_lock);
4130                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4131                 mutex_unlock(&dev_priv->rps.hw_lock);
4132                 /* Quoting Art Runyan: "its not safe to expect any particular
4133                  * value in IPS_CTL bit 31 after enabling IPS through the
4134                  * mailbox." Moreover, the mailbox may return a bogus state,
4135                  * so we need to just enable it and continue on.
4136                  */
4137         } else {
4138                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4139                 /* The bit only becomes 1 in the next vblank, so this wait here
4140                  * is essentially intel_wait_for_vblank. If we don't have this
4141                  * and don't wait for vblanks until the end of crtc_enable, then
4142                  * the HW state readout code will complain that the expected
4143                  * IPS_CTL value is not the one we read. */
4144                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4145                         DRM_ERROR("Timed out waiting for IPS enable\n");
4146         }
4147 }
4148
4149 void hsw_disable_ips(struct intel_crtc *crtc)
4150 {
4151         struct drm_device *dev = crtc->base.dev;
4152         struct drm_i915_private *dev_priv = dev->dev_private;
4153
4154         if (!crtc->config->ips_enabled)
4155                 return;
4156
4157         assert_plane_enabled(dev_priv, crtc->plane);
4158         if (IS_BROADWELL(dev)) {
4159                 mutex_lock(&dev_priv->rps.hw_lock);
4160                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4161                 mutex_unlock(&dev_priv->rps.hw_lock);
4162                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4163                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4164                         DRM_ERROR("Timed out waiting for IPS disable\n");
4165         } else {
4166                 I915_WRITE(IPS_CTL, 0);
4167                 POSTING_READ(IPS_CTL);
4168         }
4169
4170         /* We need to wait for a vblank before we can disable the plane. */
4171         intel_wait_for_vblank(dev, crtc->pipe);
4172 }
4173
4174 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4175 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4176 {
4177         struct drm_device *dev = crtc->dev;
4178         struct drm_i915_private *dev_priv = dev->dev_private;
4179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4180         enum pipe pipe = intel_crtc->pipe;
4181         int palreg = PALETTE(pipe);
4182         int i;
4183         bool reenable_ips = false;
4184
4185         /* The clocks have to be on to load the palette. */
4186         if (!crtc->enabled || !intel_crtc->active)
4187                 return;
4188
4189         if (!HAS_PCH_SPLIT(dev_priv->dev)) {
4190                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4191                         assert_dsi_pll_enabled(dev_priv);
4192                 else
4193                         assert_pll_enabled(dev_priv, pipe);
4194         }
4195
4196         /* use legacy palette for Ironlake */
4197         if (!HAS_GMCH_DISPLAY(dev))
4198                 palreg = LGC_PALETTE(pipe);
4199
4200         /* Workaround : Do not read or write the pipe palette/gamma data while
4201          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4202          */
4203         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4204             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4205              GAMMA_MODE_MODE_SPLIT)) {
4206                 hsw_disable_ips(intel_crtc);
4207                 reenable_ips = true;
4208         }
4209
4210         for (i = 0; i < 256; i++) {
4211                 I915_WRITE(palreg + 4 * i,
4212                            (intel_crtc->lut_r[i] << 16) |
4213                            (intel_crtc->lut_g[i] << 8) |
4214                            intel_crtc->lut_b[i]);
4215         }
4216
4217         if (reenable_ips)
4218                 hsw_enable_ips(intel_crtc);
4219 }
4220
4221 static void intel_crtc_dpms_overlay(struct intel_crtc *intel_crtc, bool enable)
4222 {
4223         if (!enable && intel_crtc->overlay) {
4224                 struct drm_device *dev = intel_crtc->base.dev;
4225                 struct drm_i915_private *dev_priv = dev->dev_private;
4226
4227                 mutex_lock(&dev->struct_mutex);
4228                 dev_priv->mm.interruptible = false;
4229                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4230                 dev_priv->mm.interruptible = true;
4231                 mutex_unlock(&dev->struct_mutex);
4232         }
4233
4234         /* Let userspace switch the overlay on again. In most cases userspace
4235          * has to recompute where to put it anyway.
4236          */
4237 }
4238
4239 static void intel_crtc_enable_planes(struct drm_crtc *crtc)
4240 {
4241         struct drm_device *dev = crtc->dev;
4242         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4243         int pipe = intel_crtc->pipe;
4244
4245         intel_enable_primary_hw_plane(crtc->primary, crtc);
4246         intel_enable_sprite_planes(crtc);
4247         intel_crtc_update_cursor(crtc, true);
4248         intel_crtc_dpms_overlay(intel_crtc, true);
4249
4250         hsw_enable_ips(intel_crtc);
4251
4252         mutex_lock(&dev->struct_mutex);
4253         intel_fbc_update(dev);
4254         mutex_unlock(&dev->struct_mutex);
4255
4256         /*
4257          * FIXME: Once we grow proper nuclear flip support out of this we need
4258          * to compute the mask of flip planes precisely. For the time being
4259          * consider this a flip from a NULL plane.
4260          */
4261         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4262 }
4263
4264 static void intel_crtc_disable_planes(struct drm_crtc *crtc)
4265 {
4266         struct drm_device *dev = crtc->dev;
4267         struct drm_i915_private *dev_priv = dev->dev_private;
4268         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4269         int pipe = intel_crtc->pipe;
4270         int plane = intel_crtc->plane;
4271
4272         intel_crtc_wait_for_pending_flips(crtc);
4273
4274         if (dev_priv->fbc.plane == plane)
4275                 intel_fbc_disable(dev);
4276
4277         hsw_disable_ips(intel_crtc);
4278
4279         intel_crtc_dpms_overlay(intel_crtc, false);
4280         intel_crtc_update_cursor(crtc, false);
4281         intel_disable_sprite_planes(crtc);
4282         intel_disable_primary_hw_plane(crtc->primary, crtc);
4283
4284         /*
4285          * FIXME: Once we grow proper nuclear flip support out of this we need
4286          * to compute the mask of flip planes precisely. For the time being
4287          * consider this a flip to a NULL plane.
4288          */
4289         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4290 }
4291
4292 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4293 {
4294         struct drm_device *dev = crtc->dev;
4295         struct drm_i915_private *dev_priv = dev->dev_private;
4296         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4297         struct intel_encoder *encoder;
4298         int pipe = intel_crtc->pipe;
4299
4300         WARN_ON(!crtc->enabled);
4301
4302         if (intel_crtc->active)
4303                 return;
4304
4305         if (intel_crtc->config->has_pch_encoder)
4306                 intel_prepare_shared_dpll(intel_crtc);
4307
4308         if (intel_crtc->config->has_dp_encoder)
4309                 intel_dp_set_m_n(intel_crtc);
4310
4311         intel_set_pipe_timings(intel_crtc);
4312
4313         if (intel_crtc->config->has_pch_encoder) {
4314                 intel_cpu_transcoder_set_m_n(intel_crtc,
4315                                      &intel_crtc->config->fdi_m_n, NULL);
4316         }
4317
4318         ironlake_set_pipeconf(crtc);
4319
4320         intel_crtc->active = true;
4321
4322         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4323         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4324
4325         for_each_encoder_on_crtc(dev, crtc, encoder)
4326                 if (encoder->pre_enable)
4327                         encoder->pre_enable(encoder);
4328
4329         if (intel_crtc->config->has_pch_encoder) {
4330                 /* Note: FDI PLL enabling _must_ be done before we enable the
4331                  * cpu pipes, hence this is separate from all the other fdi/pch
4332                  * enabling. */
4333                 ironlake_fdi_pll_enable(intel_crtc);
4334         } else {
4335                 assert_fdi_tx_disabled(dev_priv, pipe);
4336                 assert_fdi_rx_disabled(dev_priv, pipe);
4337         }
4338
4339         ironlake_pfit_enable(intel_crtc);
4340
4341         /*
4342          * On ILK+ LUT must be loaded before the pipe is running but with
4343          * clocks enabled
4344          */
4345         intel_crtc_load_lut(crtc);
4346
4347         intel_update_watermarks(crtc);
4348         intel_enable_pipe(intel_crtc);
4349
4350         if (intel_crtc->config->has_pch_encoder)
4351                 ironlake_pch_enable(crtc);
4352
4353         assert_vblank_disabled(crtc);
4354         drm_crtc_vblank_on(crtc);
4355
4356         for_each_encoder_on_crtc(dev, crtc, encoder)
4357                 encoder->enable(encoder);
4358
4359         if (HAS_PCH_CPT(dev))
4360                 cpt_verify_modeset(dev, intel_crtc->pipe);
4361
4362         intel_crtc_enable_planes(crtc);
4363 }
4364
4365 /* IPS only exists on ULT machines and is tied to pipe A. */
4366 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4367 {
4368         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4369 }
4370
4371 /*
4372  * This implements the workaround described in the "notes" section of the mode
4373  * set sequence documentation. When going from no pipes or single pipe to
4374  * multiple pipes, and planes are enabled after the pipe, we need to wait at
4375  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
4376  */
4377 static void haswell_mode_set_planes_workaround(struct intel_crtc *crtc)
4378 {
4379         struct drm_device *dev = crtc->base.dev;
4380         struct intel_crtc *crtc_it, *other_active_crtc = NULL;
4381
4382         /* We want to get the other_active_crtc only if there's only 1 other
4383          * active crtc. */
4384         for_each_intel_crtc(dev, crtc_it) {
4385                 if (!crtc_it->active || crtc_it == crtc)
4386                         continue;
4387
4388                 if (other_active_crtc)
4389                         return;
4390
4391                 other_active_crtc = crtc_it;
4392         }
4393         if (!other_active_crtc)
4394                 return;
4395
4396         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4397         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4398 }
4399
4400 static void haswell_crtc_enable(struct drm_crtc *crtc)
4401 {
4402         struct drm_device *dev = crtc->dev;
4403         struct drm_i915_private *dev_priv = dev->dev_private;
4404         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4405         struct intel_encoder *encoder;
4406         int pipe = intel_crtc->pipe;
4407
4408         WARN_ON(!crtc->enabled);
4409
4410         if (intel_crtc->active)
4411                 return;
4412
4413         if (intel_crtc_to_shared_dpll(intel_crtc))
4414                 intel_enable_shared_dpll(intel_crtc);
4415
4416         if (intel_crtc->config->has_dp_encoder)
4417                 intel_dp_set_m_n(intel_crtc);
4418
4419         intel_set_pipe_timings(intel_crtc);
4420
4421         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4422                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4423                            intel_crtc->config->pixel_multiplier - 1);
4424         }
4425
4426         if (intel_crtc->config->has_pch_encoder) {
4427                 intel_cpu_transcoder_set_m_n(intel_crtc,
4428                                      &intel_crtc->config->fdi_m_n, NULL);
4429         }
4430
4431         haswell_set_pipeconf(crtc);
4432
4433         intel_set_pipe_csc(crtc);
4434
4435         intel_crtc->active = true;
4436
4437         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4438         for_each_encoder_on_crtc(dev, crtc, encoder)
4439                 if (encoder->pre_enable)
4440                         encoder->pre_enable(encoder);
4441
4442         if (intel_crtc->config->has_pch_encoder) {
4443                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4444                                                       true);
4445                 dev_priv->display.fdi_link_train(crtc);
4446         }
4447
4448         intel_ddi_enable_pipe_clock(intel_crtc);
4449
4450         if (IS_SKYLAKE(dev))
4451                 skylake_pfit_enable(intel_crtc);
4452         else
4453                 ironlake_pfit_enable(intel_crtc);
4454
4455         /*
4456          * On ILK+ LUT must be loaded before the pipe is running but with
4457          * clocks enabled
4458          */
4459         intel_crtc_load_lut(crtc);
4460
4461         intel_ddi_set_pipe_settings(crtc);
4462         intel_ddi_enable_transcoder_func(crtc);
4463
4464         intel_update_watermarks(crtc);
4465         intel_enable_pipe(intel_crtc);
4466
4467         if (intel_crtc->config->has_pch_encoder)
4468                 lpt_pch_enable(crtc);
4469
4470         if (intel_crtc->config->dp_encoder_is_mst)
4471                 intel_ddi_set_vc_payload_alloc(crtc, true);
4472
4473         assert_vblank_disabled(crtc);
4474         drm_crtc_vblank_on(crtc);
4475
4476         for_each_encoder_on_crtc(dev, crtc, encoder) {
4477                 encoder->enable(encoder);
4478                 intel_opregion_notify_encoder(encoder, true);
4479         }
4480
4481         /* If we change the relative order between pipe/planes enabling, we need
4482          * to change the workaround. */
4483         haswell_mode_set_planes_workaround(intel_crtc);
4484         intel_crtc_enable_planes(crtc);
4485 }
4486
4487 static void skylake_pfit_disable(struct intel_crtc *crtc)
4488 {
4489         struct drm_device *dev = crtc->base.dev;
4490         struct drm_i915_private *dev_priv = dev->dev_private;
4491         int pipe = crtc->pipe;
4492
4493         /* To avoid upsetting the power well on haswell only disable the pfit if
4494          * it's in use. The hw state code will make sure we get this right. */
4495         if (crtc->config->pch_pfit.enabled) {
4496                 I915_WRITE(PS_CTL(pipe), 0);
4497                 I915_WRITE(PS_WIN_POS(pipe), 0);
4498                 I915_WRITE(PS_WIN_SZ(pipe), 0);
4499         }
4500 }
4501
4502 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4503 {
4504         struct drm_device *dev = crtc->base.dev;
4505         struct drm_i915_private *dev_priv = dev->dev_private;
4506         int pipe = crtc->pipe;
4507
4508         /* To avoid upsetting the power well on haswell only disable the pfit if
4509          * it's in use. The hw state code will make sure we get this right. */
4510         if (crtc->config->pch_pfit.enabled) {
4511                 I915_WRITE(PF_CTL(pipe), 0);
4512                 I915_WRITE(PF_WIN_POS(pipe), 0);
4513                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4514         }
4515 }
4516
4517 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4518 {
4519         struct drm_device *dev = crtc->dev;
4520         struct drm_i915_private *dev_priv = dev->dev_private;
4521         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4522         struct intel_encoder *encoder;
4523         int pipe = intel_crtc->pipe;
4524         u32 reg, temp;
4525
4526         if (!intel_crtc->active)
4527                 return;
4528
4529         intel_crtc_disable_planes(crtc);
4530
4531         for_each_encoder_on_crtc(dev, crtc, encoder)
4532                 encoder->disable(encoder);
4533
4534         drm_crtc_vblank_off(crtc);
4535         assert_vblank_disabled(crtc);
4536
4537         if (intel_crtc->config->has_pch_encoder)
4538                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4539
4540         intel_disable_pipe(intel_crtc);
4541
4542         ironlake_pfit_disable(intel_crtc);
4543
4544         for_each_encoder_on_crtc(dev, crtc, encoder)
4545                 if (encoder->post_disable)
4546                         encoder->post_disable(encoder);
4547
4548         if (intel_crtc->config->has_pch_encoder) {
4549                 ironlake_fdi_disable(crtc);
4550
4551                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4552
4553                 if (HAS_PCH_CPT(dev)) {
4554                         /* disable TRANS_DP_CTL */
4555                         reg = TRANS_DP_CTL(pipe);
4556                         temp = I915_READ(reg);
4557                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4558                                   TRANS_DP_PORT_SEL_MASK);
4559                         temp |= TRANS_DP_PORT_SEL_NONE;
4560                         I915_WRITE(reg, temp);
4561
4562                         /* disable DPLL_SEL */
4563                         temp = I915_READ(PCH_DPLL_SEL);
4564                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4565                         I915_WRITE(PCH_DPLL_SEL, temp);
4566                 }
4567
4568                 /* disable PCH DPLL */
4569                 intel_disable_shared_dpll(intel_crtc);
4570
4571                 ironlake_fdi_pll_disable(intel_crtc);
4572         }
4573
4574         intel_crtc->active = false;
4575         intel_update_watermarks(crtc);
4576
4577         mutex_lock(&dev->struct_mutex);
4578         intel_fbc_update(dev);
4579         mutex_unlock(&dev->struct_mutex);
4580 }
4581
4582 static void haswell_crtc_disable(struct drm_crtc *crtc)
4583 {
4584         struct drm_device *dev = crtc->dev;
4585         struct drm_i915_private *dev_priv = dev->dev_private;
4586         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4587         struct intel_encoder *encoder;
4588         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4589
4590         if (!intel_crtc->active)
4591                 return;
4592
4593         intel_crtc_disable_planes(crtc);
4594
4595         for_each_encoder_on_crtc(dev, crtc, encoder) {
4596                 intel_opregion_notify_encoder(encoder, false);
4597                 encoder->disable(encoder);
4598         }
4599
4600         drm_crtc_vblank_off(crtc);
4601         assert_vblank_disabled(crtc);
4602
4603         if (intel_crtc->config->has_pch_encoder)
4604                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4605                                                       false);
4606         intel_disable_pipe(intel_crtc);
4607
4608         if (intel_crtc->config->dp_encoder_is_mst)
4609                 intel_ddi_set_vc_payload_alloc(crtc, false);
4610
4611         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
4612
4613         if (IS_SKYLAKE(dev))
4614                 skylake_pfit_disable(intel_crtc);
4615         else
4616                 ironlake_pfit_disable(intel_crtc);
4617
4618         intel_ddi_disable_pipe_clock(intel_crtc);
4619
4620         if (intel_crtc->config->has_pch_encoder) {
4621                 lpt_disable_pch_transcoder(dev_priv);
4622                 intel_ddi_fdi_disable(crtc);
4623         }
4624
4625         for_each_encoder_on_crtc(dev, crtc, encoder)
4626                 if (encoder->post_disable)
4627                         encoder->post_disable(encoder);
4628
4629         intel_crtc->active = false;
4630         intel_update_watermarks(crtc);
4631
4632         mutex_lock(&dev->struct_mutex);
4633         intel_fbc_update(dev);
4634         mutex_unlock(&dev->struct_mutex);
4635
4636         if (intel_crtc_to_shared_dpll(intel_crtc))
4637                 intel_disable_shared_dpll(intel_crtc);
4638 }
4639
4640 static void ironlake_crtc_off(struct drm_crtc *crtc)
4641 {
4642         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4643         intel_put_shared_dpll(intel_crtc);
4644 }
4645
4646
4647 static void i9xx_pfit_enable(struct intel_crtc *crtc)
4648 {
4649         struct drm_device *dev = crtc->base.dev;
4650         struct drm_i915_private *dev_priv = dev->dev_private;
4651         struct intel_crtc_state *pipe_config = crtc->config;
4652
4653         if (!pipe_config->gmch_pfit.control)
4654                 return;
4655
4656         /*
4657          * The panel fitter should only be adjusted whilst the pipe is disabled,
4658          * according to register description and PRM.
4659          */
4660         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
4661         assert_pipe_disabled(dev_priv, crtc->pipe);
4662
4663         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
4664         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
4665
4666         /* Border color in case we don't scale up to the full screen. Black by
4667          * default, change to something else for debugging. */
4668         I915_WRITE(BCLRPAT(crtc->pipe), 0);
4669 }
4670
4671 static enum intel_display_power_domain port_to_power_domain(enum port port)
4672 {
4673         switch (port) {
4674         case PORT_A:
4675                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
4676         case PORT_B:
4677                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
4678         case PORT_C:
4679                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
4680         case PORT_D:
4681                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
4682         default:
4683                 WARN_ON_ONCE(1);
4684                 return POWER_DOMAIN_PORT_OTHER;
4685         }
4686 }
4687
4688 #define for_each_power_domain(domain, mask)                             \
4689         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
4690                 if ((1 << (domain)) & (mask))
4691
4692 enum intel_display_power_domain
4693 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
4694 {
4695         struct drm_device *dev = intel_encoder->base.dev;
4696         struct intel_digital_port *intel_dig_port;
4697
4698         switch (intel_encoder->type) {
4699         case INTEL_OUTPUT_UNKNOWN:
4700                 /* Only DDI platforms should ever use this output type */
4701                 WARN_ON_ONCE(!HAS_DDI(dev));
4702         case INTEL_OUTPUT_DISPLAYPORT:
4703         case INTEL_OUTPUT_HDMI:
4704         case INTEL_OUTPUT_EDP:
4705                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
4706                 return port_to_power_domain(intel_dig_port->port);
4707         case INTEL_OUTPUT_DP_MST:
4708                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
4709                 return port_to_power_domain(intel_dig_port->port);
4710         case INTEL_OUTPUT_ANALOG:
4711                 return POWER_DOMAIN_PORT_CRT;
4712         case INTEL_OUTPUT_DSI:
4713                 return POWER_DOMAIN_PORT_DSI;
4714         default:
4715                 return POWER_DOMAIN_PORT_OTHER;
4716         }
4717 }
4718
4719 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
4720 {
4721         struct drm_device *dev = crtc->dev;
4722         struct intel_encoder *intel_encoder;
4723         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4724         enum pipe pipe = intel_crtc->pipe;
4725         unsigned long mask;
4726         enum transcoder transcoder;
4727
4728         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
4729
4730         mask = BIT(POWER_DOMAIN_PIPE(pipe));
4731         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
4732         if (intel_crtc->config->pch_pfit.enabled ||
4733             intel_crtc->config->pch_pfit.force_thru)
4734                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
4735
4736         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
4737                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
4738
4739         return mask;
4740 }
4741
4742 static void modeset_update_crtc_power_domains(struct drm_device *dev)
4743 {
4744         struct drm_i915_private *dev_priv = dev->dev_private;
4745         unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
4746         struct intel_crtc *crtc;
4747
4748         /*
4749          * First get all needed power domains, then put all unneeded, to avoid
4750          * any unnecessary toggling of the power wells.
4751          */
4752         for_each_intel_crtc(dev, crtc) {
4753                 enum intel_display_power_domain domain;
4754
4755                 if (!crtc->base.enabled)
4756                         continue;
4757
4758                 pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
4759
4760                 for_each_power_domain(domain, pipe_domains[crtc->pipe])
4761                         intel_display_power_get(dev_priv, domain);
4762         }
4763
4764         if (dev_priv->display.modeset_global_resources)
4765                 dev_priv->display.modeset_global_resources(dev);
4766
4767         for_each_intel_crtc(dev, crtc) {
4768                 enum intel_display_power_domain domain;
4769
4770                 for_each_power_domain(domain, crtc->enabled_power_domains)
4771                         intel_display_power_put(dev_priv, domain);
4772
4773                 crtc->enabled_power_domains = pipe_domains[crtc->pipe];
4774         }
4775
4776         intel_display_set_init_power(dev_priv, false);
4777 }
4778
4779 /* returns HPLL frequency in kHz */
4780 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
4781 {
4782         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
4783
4784         /* Obtain SKU information */
4785         mutex_lock(&dev_priv->dpio_lock);
4786         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
4787                 CCK_FUSE_HPLL_FREQ_MASK;
4788         mutex_unlock(&dev_priv->dpio_lock);
4789
4790         return vco_freq[hpll_freq] * 1000;
4791 }
4792
4793 static void vlv_update_cdclk(struct drm_device *dev)
4794 {
4795         struct drm_i915_private *dev_priv = dev->dev_private;
4796
4797         dev_priv->vlv_cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
4798         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
4799                          dev_priv->vlv_cdclk_freq);
4800
4801         /*
4802          * Program the gmbus_freq based on the cdclk frequency.
4803          * BSpec erroneously claims we should aim for 4MHz, but
4804          * in fact 1MHz is the correct frequency.
4805          */
4806         I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->vlv_cdclk_freq, 1000));
4807 }
4808
4809 /* Adjust CDclk dividers to allow high res or save power if possible */
4810 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
4811 {
4812         struct drm_i915_private *dev_priv = dev->dev_private;
4813         u32 val, cmd;
4814
4815         WARN_ON(dev_priv->display.get_display_clock_speed(dev) != dev_priv->vlv_cdclk_freq);
4816
4817         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
4818                 cmd = 2;
4819         else if (cdclk == 266667)
4820                 cmd = 1;
4821         else
4822                 cmd = 0;
4823
4824         mutex_lock(&dev_priv->rps.hw_lock);
4825         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
4826         val &= ~DSPFREQGUAR_MASK;
4827         val |= (cmd << DSPFREQGUAR_SHIFT);
4828         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
4829         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
4830                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
4831                      50)) {
4832                 DRM_ERROR("timed out waiting for CDclk change\n");
4833         }
4834         mutex_unlock(&dev_priv->rps.hw_lock);
4835
4836         if (cdclk == 400000) {
4837                 u32 divider;
4838
4839                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
4840
4841                 mutex_lock(&dev_priv->dpio_lock);
4842                 /* adjust cdclk divider */
4843                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
4844                 val &= ~DISPLAY_FREQUENCY_VALUES;
4845                 val |= divider;
4846                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
4847
4848                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
4849                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
4850                              50))
4851                         DRM_ERROR("timed out waiting for CDclk change\n");
4852                 mutex_unlock(&dev_priv->dpio_lock);
4853         }
4854
4855         mutex_lock(&dev_priv->dpio_lock);
4856         /* adjust self-refresh exit latency value */
4857         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
4858         val &= ~0x7f;
4859
4860         /*
4861          * For high bandwidth configs, we set a higher latency in the bunit
4862          * so that the core display fetch happens in time to avoid underruns.
4863          */
4864         if (cdclk == 400000)
4865                 val |= 4500 / 250; /* 4.5 usec */
4866         else
4867                 val |= 3000 / 250; /* 3.0 usec */
4868         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
4869         mutex_unlock(&dev_priv->dpio_lock);
4870
4871         vlv_update_cdclk(dev);
4872 }
4873
4874 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
4875 {
4876         struct drm_i915_private *dev_priv = dev->dev_private;
4877         u32 val, cmd;
4878
4879         WARN_ON(dev_priv->display.get_display_clock_speed(dev) != dev_priv->vlv_cdclk_freq);
4880
4881         switch (cdclk) {
4882         case 400000:
4883                 cmd = 3;
4884                 break;
4885         case 333333:
4886         case 320000:
4887                 cmd = 2;
4888                 break;
4889         case 266667:
4890                 cmd = 1;
4891                 break;
4892         case 200000:
4893                 cmd = 0;
4894                 break;
4895         default:
4896                 MISSING_CASE(cdclk);
4897                 return;
4898         }
4899
4900         mutex_lock(&dev_priv->rps.hw_lock);
4901         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
4902         val &= ~DSPFREQGUAR_MASK_CHV;
4903         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
4904         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
4905         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
4906                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
4907                      50)) {
4908                 DRM_ERROR("timed out waiting for CDclk change\n");
4909         }
4910         mutex_unlock(&dev_priv->rps.hw_lock);
4911
4912         vlv_update_cdclk(dev);
4913 }
4914
4915 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
4916                                  int max_pixclk)
4917 {
4918         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
4919
4920         /* FIXME: Punit isn't quite ready yet */
4921         if (IS_CHERRYVIEW(dev_priv->dev))
4922                 return 400000;
4923
4924         /*
4925          * Really only a few cases to deal with, as only 4 CDclks are supported:
4926          *   200MHz
4927          *   267MHz
4928          *   320/333MHz (depends on HPLL freq)
4929          *   400MHz
4930          * So we check to see whether we're above 90% of the lower bin and
4931          * adjust if needed.
4932          *
4933          * We seem to get an unstable or solid color picture at 200MHz.
4934          * Not sure what's wrong. For now use 200MHz only when all pipes
4935          * are off.
4936          */
4937         if (max_pixclk > freq_320*9/10)
4938                 return 400000;
4939         else if (max_pixclk > 266667*9/10)
4940                 return freq_320;
4941         else if (max_pixclk > 0)
4942                 return 266667;
4943         else
4944                 return 200000;
4945 }
4946
4947 /* compute the max pixel clock for new configuration */
4948 static int intel_mode_max_pixclk(struct drm_i915_private *dev_priv)
4949 {
4950         struct drm_device *dev = dev_priv->dev;
4951         struct intel_crtc *intel_crtc;
4952         int max_pixclk = 0;
4953
4954         for_each_intel_crtc(dev, intel_crtc) {
4955                 if (intel_crtc->new_enabled)
4956                         max_pixclk = max(max_pixclk,
4957                                          intel_crtc->new_config->base.adjusted_mode.crtc_clock);
4958         }
4959
4960         return max_pixclk;
4961 }
4962
4963 static void valleyview_modeset_global_pipes(struct drm_device *dev,
4964                                             unsigned *prepare_pipes)
4965 {
4966         struct drm_i915_private *dev_priv = dev->dev_private;
4967         struct intel_crtc *intel_crtc;
4968         int max_pixclk = intel_mode_max_pixclk(dev_priv);
4969
4970         if (valleyview_calc_cdclk(dev_priv, max_pixclk) ==
4971             dev_priv->vlv_cdclk_freq)
4972                 return;
4973
4974         /* disable/enable all currently active pipes while we change cdclk */
4975         for_each_intel_crtc(dev, intel_crtc)
4976                 if (intel_crtc->base.enabled)
4977                         *prepare_pipes |= (1 << intel_crtc->pipe);
4978 }
4979
4980 static void valleyview_modeset_global_resources(struct drm_device *dev)
4981 {
4982         struct drm_i915_private *dev_priv = dev->dev_private;
4983         int max_pixclk = intel_mode_max_pixclk(dev_priv);
4984         int req_cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
4985
4986         if (req_cdclk != dev_priv->vlv_cdclk_freq) {
4987                 /*
4988                  * FIXME: We can end up here with all power domains off, yet
4989                  * with a CDCLK frequency other than the minimum. To account
4990                  * for this take the PIPE-A power domain, which covers the HW
4991                  * blocks needed for the following programming. This can be
4992                  * removed once it's guaranteed that we get here either with
4993                  * the minimum CDCLK set, or the required power domains
4994                  * enabled.
4995                  */
4996                 intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
4997
4998                 if (IS_CHERRYVIEW(dev))
4999                         cherryview_set_cdclk(dev, req_cdclk);
5000                 else
5001                         valleyview_set_cdclk(dev, req_cdclk);
5002
5003                 intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5004         }
5005 }
5006
5007 static void valleyview_crtc_enable(struct drm_crtc *crtc)
5008 {
5009         struct drm_device *dev = crtc->dev;
5010         struct drm_i915_private *dev_priv = to_i915(dev);
5011         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5012         struct intel_encoder *encoder;
5013         int pipe = intel_crtc->pipe;
5014         bool is_dsi;
5015
5016         WARN_ON(!crtc->enabled);
5017
5018         if (intel_crtc->active)
5019                 return;
5020
5021         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
5022
5023         if (!is_dsi) {
5024                 if (IS_CHERRYVIEW(dev))
5025                         chv_prepare_pll(intel_crtc, intel_crtc->config);
5026                 else
5027                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
5028         }
5029
5030         if (intel_crtc->config->has_dp_encoder)
5031                 intel_dp_set_m_n(intel_crtc);
5032
5033         intel_set_pipe_timings(intel_crtc);
5034
5035         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
5036                 struct drm_i915_private *dev_priv = dev->dev_private;
5037
5038                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5039                 I915_WRITE(CHV_CANVAS(pipe), 0);
5040         }
5041
5042         i9xx_set_pipeconf(intel_crtc);
5043
5044         intel_crtc->active = true;
5045
5046         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5047
5048         for_each_encoder_on_crtc(dev, crtc, encoder)
5049                 if (encoder->pre_pll_enable)
5050                         encoder->pre_pll_enable(encoder);
5051
5052         if (!is_dsi) {
5053                 if (IS_CHERRYVIEW(dev))
5054                         chv_enable_pll(intel_crtc, intel_crtc->config);
5055                 else
5056                         vlv_enable_pll(intel_crtc, intel_crtc->config);
5057         }
5058
5059         for_each_encoder_on_crtc(dev, crtc, encoder)
5060                 if (encoder->pre_enable)
5061                         encoder->pre_enable(encoder);
5062
5063         i9xx_pfit_enable(intel_crtc);
5064
5065         intel_crtc_load_lut(crtc);
5066
5067         intel_update_watermarks(crtc);
5068         intel_enable_pipe(intel_crtc);
5069
5070         assert_vblank_disabled(crtc);
5071         drm_crtc_vblank_on(crtc);
5072
5073         for_each_encoder_on_crtc(dev, crtc, encoder)
5074                 encoder->enable(encoder);
5075
5076         intel_crtc_enable_planes(crtc);
5077
5078         /* Underruns don't raise interrupts, so check manually. */
5079         i9xx_check_fifo_underruns(dev_priv);
5080 }
5081
5082 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5083 {
5084         struct drm_device *dev = crtc->base.dev;
5085         struct drm_i915_private *dev_priv = dev->dev_private;
5086
5087         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5088         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5089 }
5090
5091 static void i9xx_crtc_enable(struct drm_crtc *crtc)
5092 {
5093         struct drm_device *dev = crtc->dev;
5094         struct drm_i915_private *dev_priv = to_i915(dev);
5095         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5096         struct intel_encoder *encoder;
5097         int pipe = intel_crtc->pipe;
5098
5099         WARN_ON(!crtc->enabled);
5100
5101         if (intel_crtc->active)
5102                 return;
5103
5104         i9xx_set_pll_dividers(intel_crtc);
5105
5106         if (intel_crtc->config->has_dp_encoder)
5107                 intel_dp_set_m_n(intel_crtc);
5108
5109         intel_set_pipe_timings(intel_crtc);
5110
5111         i9xx_set_pipeconf(intel_crtc);
5112
5113         intel_crtc->active = true;
5114
5115         if (!IS_GEN2(dev))
5116                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5117
5118         for_each_encoder_on_crtc(dev, crtc, encoder)
5119                 if (encoder->pre_enable)
5120                         encoder->pre_enable(encoder);
5121
5122         i9xx_enable_pll(intel_crtc);
5123
5124         i9xx_pfit_enable(intel_crtc);
5125
5126         intel_crtc_load_lut(crtc);
5127
5128         intel_update_watermarks(crtc);
5129         intel_enable_pipe(intel_crtc);
5130
5131         assert_vblank_disabled(crtc);
5132         drm_crtc_vblank_on(crtc);
5133
5134         for_each_encoder_on_crtc(dev, crtc, encoder)
5135                 encoder->enable(encoder);
5136
5137         intel_crtc_enable_planes(crtc);
5138
5139         /*
5140          * Gen2 reports pipe underruns whenever all planes are disabled.
5141          * So don't enable underrun reporting before at least some planes
5142          * are enabled.
5143          * FIXME: Need to fix the logic to work when we turn off all planes
5144          * but leave the pipe running.
5145          */
5146         if (IS_GEN2(dev))
5147                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5148
5149         /* Underruns don't raise interrupts, so check manually. */
5150         i9xx_check_fifo_underruns(dev_priv);
5151 }
5152
5153 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5154 {
5155         struct drm_device *dev = crtc->base.dev;
5156         struct drm_i915_private *dev_priv = dev->dev_private;
5157
5158         if (!crtc->config->gmch_pfit.control)
5159                 return;
5160
5161         assert_pipe_disabled(dev_priv, crtc->pipe);
5162
5163         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5164                          I915_READ(PFIT_CONTROL));
5165         I915_WRITE(PFIT_CONTROL, 0);
5166 }
5167
5168 static void i9xx_crtc_disable(struct drm_crtc *crtc)
5169 {
5170         struct drm_device *dev = crtc->dev;
5171         struct drm_i915_private *dev_priv = dev->dev_private;
5172         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5173         struct intel_encoder *encoder;
5174         int pipe = intel_crtc->pipe;
5175
5176         if (!intel_crtc->active)
5177                 return;
5178
5179         /*
5180          * Gen2 reports pipe underruns whenever all planes are disabled.
5181          * So diasble underrun reporting before all the planes get disabled.
5182          * FIXME: Need to fix the logic to work when we turn off all planes
5183          * but leave the pipe running.
5184          */
5185         if (IS_GEN2(dev))
5186                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5187
5188         /*
5189          * Vblank time updates from the shadow to live plane control register
5190          * are blocked if the memory self-refresh mode is active at that
5191          * moment. So to make sure the plane gets truly disabled, disable
5192          * first the self-refresh mode. The self-refresh enable bit in turn
5193          * will be checked/applied by the HW only at the next frame start
5194          * event which is after the vblank start event, so we need to have a
5195          * wait-for-vblank between disabling the plane and the pipe.
5196          */
5197         intel_set_memory_cxsr(dev_priv, false);
5198         intel_crtc_disable_planes(crtc);
5199
5200         /*
5201          * On gen2 planes are double buffered but the pipe isn't, so we must
5202          * wait for planes to fully turn off before disabling the pipe.
5203          * We also need to wait on all gmch platforms because of the
5204          * self-refresh mode constraint explained above.
5205          */
5206         intel_wait_for_vblank(dev, pipe);
5207
5208         for_each_encoder_on_crtc(dev, crtc, encoder)
5209                 encoder->disable(encoder);
5210
5211         drm_crtc_vblank_off(crtc);
5212         assert_vblank_disabled(crtc);
5213
5214         intel_disable_pipe(intel_crtc);
5215
5216         i9xx_pfit_disable(intel_crtc);
5217
5218         for_each_encoder_on_crtc(dev, crtc, encoder)
5219                 if (encoder->post_disable)
5220                         encoder->post_disable(encoder);
5221
5222         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
5223                 if (IS_CHERRYVIEW(dev))
5224                         chv_disable_pll(dev_priv, pipe);
5225                 else if (IS_VALLEYVIEW(dev))
5226                         vlv_disable_pll(dev_priv, pipe);
5227                 else
5228                         i9xx_disable_pll(intel_crtc);
5229         }
5230
5231         if (!IS_GEN2(dev))
5232                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5233
5234         intel_crtc->active = false;
5235         intel_update_watermarks(crtc);
5236
5237         mutex_lock(&dev->struct_mutex);
5238         intel_fbc_update(dev);
5239         mutex_unlock(&dev->struct_mutex);
5240 }
5241
5242 static void i9xx_crtc_off(struct drm_crtc *crtc)
5243 {
5244 }
5245
5246 /* Master function to enable/disable CRTC and corresponding power wells */
5247 void intel_crtc_control(struct drm_crtc *crtc, bool enable)
5248 {
5249         struct drm_device *dev = crtc->dev;
5250         struct drm_i915_private *dev_priv = dev->dev_private;
5251         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5252         enum intel_display_power_domain domain;
5253         unsigned long domains;
5254
5255         if (enable) {
5256                 if (!intel_crtc->active) {
5257                         domains = get_crtc_power_domains(crtc);
5258                         for_each_power_domain(domain, domains)
5259                                 intel_display_power_get(dev_priv, domain);
5260                         intel_crtc->enabled_power_domains = domains;
5261
5262                         dev_priv->display.crtc_enable(crtc);
5263                 }
5264         } else {
5265                 if (intel_crtc->active) {
5266                         dev_priv->display.crtc_disable(crtc);
5267
5268                         domains = intel_crtc->enabled_power_domains;
5269                         for_each_power_domain(domain, domains)
5270                                 intel_display_power_put(dev_priv, domain);
5271                         intel_crtc->enabled_power_domains = 0;
5272                 }
5273         }
5274 }
5275
5276 /**
5277  * Sets the power management mode of the pipe and plane.
5278  */
5279 void intel_crtc_update_dpms(struct drm_crtc *crtc)
5280 {
5281         struct drm_device *dev = crtc->dev;
5282         struct intel_encoder *intel_encoder;
5283         bool enable = false;
5284
5285         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5286                 enable |= intel_encoder->connectors_active;
5287
5288         intel_crtc_control(crtc, enable);
5289 }
5290
5291 static void intel_crtc_disable(struct drm_crtc *crtc)
5292 {
5293         struct drm_device *dev = crtc->dev;
5294         struct drm_connector *connector;
5295         struct drm_i915_private *dev_priv = dev->dev_private;
5296
5297         /* crtc should still be enabled when we disable it. */
5298         WARN_ON(!crtc->enabled);
5299
5300         dev_priv->display.crtc_disable(crtc);
5301         dev_priv->display.off(crtc);
5302
5303         crtc->primary->funcs->disable_plane(crtc->primary);
5304
5305         /* Update computed state. */
5306         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
5307                 if (!connector->encoder || !connector->encoder->crtc)
5308                         continue;
5309
5310                 if (connector->encoder->crtc != crtc)
5311                         continue;
5312
5313                 connector->dpms = DRM_MODE_DPMS_OFF;
5314                 to_intel_encoder(connector->encoder)->connectors_active = false;
5315         }
5316 }
5317
5318 void intel_encoder_destroy(struct drm_encoder *encoder)
5319 {
5320         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5321
5322         drm_encoder_cleanup(encoder);
5323         kfree(intel_encoder);
5324 }
5325
5326 /* Simple dpms helper for encoders with just one connector, no cloning and only
5327  * one kind of off state. It clamps all !ON modes to fully OFF and changes the
5328  * state of the entire output pipe. */
5329 static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
5330 {
5331         if (mode == DRM_MODE_DPMS_ON) {
5332                 encoder->connectors_active = true;
5333
5334                 intel_crtc_update_dpms(encoder->base.crtc);
5335         } else {
5336                 encoder->connectors_active = false;
5337
5338                 intel_crtc_update_dpms(encoder->base.crtc);
5339         }
5340 }
5341
5342 /* Cross check the actual hw state with our own modeset state tracking (and it's
5343  * internal consistency). */
5344 static void intel_connector_check_state(struct intel_connector *connector)
5345 {
5346         if (connector->get_hw_state(connector)) {
5347                 struct intel_encoder *encoder = connector->encoder;
5348                 struct drm_crtc *crtc;
5349                 bool encoder_enabled;
5350                 enum pipe pipe;
5351
5352                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
5353                               connector->base.base.id,
5354                               connector->base.name);
5355
5356                 /* there is no real hw state for MST connectors */
5357                 if (connector->mst_port)
5358                         return;
5359
5360                 I915_STATE_WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
5361                      "wrong connector dpms state\n");
5362                 I915_STATE_WARN(connector->base.encoder != &encoder->base,
5363                      "active connector not linked to encoder\n");
5364
5365                 if (encoder) {
5366                         I915_STATE_WARN(!encoder->connectors_active,
5367                              "encoder->connectors_active not set\n");
5368
5369                         encoder_enabled = encoder->get_hw_state(encoder, &pipe);
5370                         I915_STATE_WARN(!encoder_enabled, "encoder not enabled\n");
5371                         if (I915_STATE_WARN_ON(!encoder->base.crtc))
5372                                 return;
5373
5374                         crtc = encoder->base.crtc;
5375
5376                         I915_STATE_WARN(!crtc->enabled, "crtc not enabled\n");
5377                         I915_STATE_WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
5378                         I915_STATE_WARN(pipe != to_intel_crtc(crtc)->pipe,
5379                              "encoder active on the wrong pipe\n");
5380                 }
5381         }
5382 }
5383
5384 /* Even simpler default implementation, if there's really no special case to
5385  * consider. */
5386 void intel_connector_dpms(struct drm_connector *connector, int mode)
5387 {
5388         /* All the simple cases only support two dpms states. */
5389         if (mode != DRM_MODE_DPMS_ON)
5390                 mode = DRM_MODE_DPMS_OFF;
5391
5392         if (mode == connector->dpms)
5393                 return;
5394
5395         connector->dpms = mode;
5396
5397         /* Only need to change hw state when actually enabled */
5398         if (connector->encoder)
5399                 intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
5400
5401         intel_modeset_check_state(connector->dev);
5402 }
5403
5404 /* Simple connector->get_hw_state implementation for encoders that support only
5405  * one connector and no cloning and hence the encoder state determines the state
5406  * of the connector. */
5407 bool intel_connector_get_hw_state(struct intel_connector *connector)
5408 {
5409         enum pipe pipe = 0;
5410         struct intel_encoder *encoder = connector->encoder;
5411
5412         return encoder->get_hw_state(encoder, &pipe);
5413 }
5414
5415 static bool ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
5416                                      struct intel_crtc_state *pipe_config)
5417 {
5418         struct drm_i915_private *dev_priv = dev->dev_private;
5419         struct intel_crtc *pipe_B_crtc =
5420                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_B]);
5421
5422         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
5423                       pipe_name(pipe), pipe_config->fdi_lanes);
5424         if (pipe_config->fdi_lanes > 4) {
5425                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
5426                               pipe_name(pipe), pipe_config->fdi_lanes);
5427                 return false;
5428         }
5429
5430         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
5431                 if (pipe_config->fdi_lanes > 2) {
5432                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
5433                                       pipe_config->fdi_lanes);
5434                         return false;
5435                 } else {
5436                         return true;
5437                 }
5438         }
5439
5440         if (INTEL_INFO(dev)->num_pipes == 2)
5441                 return true;
5442
5443         /* Ivybridge 3 pipe is really complicated */
5444         switch (pipe) {
5445         case PIPE_A:
5446                 return true;
5447         case PIPE_B:
5448                 if (dev_priv->pipe_to_crtc_mapping[PIPE_C]->enabled &&
5449                     pipe_config->fdi_lanes > 2) {
5450                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
5451                                       pipe_name(pipe), pipe_config->fdi_lanes);
5452                         return false;
5453                 }
5454                 return true;
5455         case PIPE_C:
5456                 if (!pipe_has_enabled_pch(pipe_B_crtc) ||
5457                     pipe_B_crtc->config->fdi_lanes <= 2) {
5458                         if (pipe_config->fdi_lanes > 2) {
5459                                 DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
5460                                               pipe_name(pipe), pipe_config->fdi_lanes);
5461                                 return false;
5462                         }
5463                 } else {
5464                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
5465                         return false;
5466                 }
5467                 return true;
5468         default:
5469                 BUG();
5470         }
5471 }
5472
5473 #define RETRY 1
5474 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
5475                                        struct intel_crtc_state *pipe_config)
5476 {
5477         struct drm_device *dev = intel_crtc->base.dev;
5478         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
5479         int lane, link_bw, fdi_dotclock;
5480         bool setup_ok, needs_recompute = false;
5481
5482 retry:
5483         /* FDI is a binary signal running at ~2.7GHz, encoding
5484          * each output octet as 10 bits. The actual frequency
5485          * is stored as a divider into a 100MHz clock, and the
5486          * mode pixel clock is stored in units of 1KHz.
5487          * Hence the bw of each lane in terms of the mode signal
5488          * is:
5489          */
5490         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
5491
5492         fdi_dotclock = adjusted_mode->crtc_clock;
5493
5494         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
5495                                            pipe_config->pipe_bpp);
5496
5497         pipe_config->fdi_lanes = lane;
5498
5499         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
5500                                link_bw, &pipe_config->fdi_m_n);
5501
5502         setup_ok = ironlake_check_fdi_lanes(intel_crtc->base.dev,
5503                                             intel_crtc->pipe, pipe_config);
5504         if (!setup_ok && pipe_config->pipe_bpp > 6*3) {
5505                 pipe_config->pipe_bpp -= 2*3;
5506                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
5507                               pipe_config->pipe_bpp);
5508                 needs_recompute = true;
5509                 pipe_config->bw_constrained = true;
5510
5511                 goto retry;
5512         }
5513
5514         if (needs_recompute)
5515                 return RETRY;
5516
5517         return setup_ok ? 0 : -EINVAL;
5518 }
5519
5520 static void hsw_compute_ips_config(struct intel_crtc *crtc,
5521                                    struct intel_crtc_state *pipe_config)
5522 {
5523         pipe_config->ips_enabled = i915.enable_ips &&
5524                                    hsw_crtc_supports_ips(crtc) &&
5525                                    pipe_config->pipe_bpp <= 24;
5526 }
5527
5528 static int intel_crtc_compute_config(struct intel_crtc *crtc,
5529                                      struct intel_crtc_state *pipe_config)
5530 {
5531         struct drm_device *dev = crtc->base.dev;
5532         struct drm_i915_private *dev_priv = dev->dev_private;
5533         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
5534
5535         /* FIXME should check pixel clock limits on all platforms */
5536         if (INTEL_INFO(dev)->gen < 4) {
5537                 int clock_limit =
5538                         dev_priv->display.get_display_clock_speed(dev);
5539
5540                 /*
5541                  * Enable pixel doubling when the dot clock
5542                  * is > 90% of the (display) core speed.
5543                  *
5544                  * GDG double wide on either pipe,
5545                  * otherwise pipe A only.
5546                  */
5547                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
5548                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
5549                         clock_limit *= 2;
5550                         pipe_config->double_wide = true;
5551                 }
5552
5553                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
5554                         return -EINVAL;
5555         }
5556
5557         /*
5558          * Pipe horizontal size must be even in:
5559          * - DVO ganged mode
5560          * - LVDS dual channel mode
5561          * - Double wide pipe
5562          */
5563         if ((intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) &&
5564              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
5565                 pipe_config->pipe_src_w &= ~1;
5566
5567         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
5568          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
5569          */
5570         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
5571                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
5572                 return -EINVAL;
5573
5574         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)) && pipe_config->pipe_bpp > 10*3) {
5575                 pipe_config->pipe_bpp = 10*3; /* 12bpc is gen5+ */
5576         } else if (INTEL_INFO(dev)->gen <= 4 && pipe_config->pipe_bpp > 8*3) {
5577                 /* only a 8bpc pipe, with 6bpc dither through the panel fitter
5578                  * for lvds. */
5579                 pipe_config->pipe_bpp = 8*3;
5580         }
5581
5582         if (HAS_IPS(dev))
5583                 hsw_compute_ips_config(crtc, pipe_config);
5584
5585         if (pipe_config->has_pch_encoder)
5586                 return ironlake_fdi_compute_config(crtc, pipe_config);
5587
5588         return 0;
5589 }
5590
5591 static int valleyview_get_display_clock_speed(struct drm_device *dev)
5592 {
5593         struct drm_i915_private *dev_priv = dev->dev_private;
5594         u32 val;
5595         int divider;
5596
5597         /* FIXME: Punit isn't quite ready yet */
5598         if (IS_CHERRYVIEW(dev))
5599                 return 400000;
5600
5601         if (dev_priv->hpll_freq == 0)
5602                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
5603
5604         mutex_lock(&dev_priv->dpio_lock);
5605         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5606         mutex_unlock(&dev_priv->dpio_lock);
5607
5608         divider = val & DISPLAY_FREQUENCY_VALUES;
5609
5610         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
5611              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5612              "cdclk change in progress\n");
5613
5614         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
5615 }
5616
5617 static int i945_get_display_clock_speed(struct drm_device *dev)
5618 {
5619         return 400000;
5620 }
5621
5622 static int i915_get_display_clock_speed(struct drm_device *dev)
5623 {
5624         return 333000;
5625 }
5626
5627 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
5628 {
5629         return 200000;
5630 }
5631
5632 static int pnv_get_display_clock_speed(struct drm_device *dev)
5633 {
5634         u16 gcfgc = 0;
5635
5636         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5637
5638         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5639         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
5640                 return 267000;
5641         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
5642                 return 333000;
5643         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
5644                 return 444000;
5645         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
5646                 return 200000;
5647         default:
5648                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
5649         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
5650                 return 133000;
5651         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
5652                 return 167000;
5653         }
5654 }
5655
5656 static int i915gm_get_display_clock_speed(struct drm_device *dev)
5657 {
5658         u16 gcfgc = 0;
5659
5660         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5661
5662         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
5663                 return 133000;
5664         else {
5665                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5666                 case GC_DISPLAY_CLOCK_333_MHZ:
5667                         return 333000;
5668                 default:
5669                 case GC_DISPLAY_CLOCK_190_200_MHZ:
5670                         return 190000;
5671                 }
5672         }
5673 }
5674
5675 static int i865_get_display_clock_speed(struct drm_device *dev)
5676 {
5677         return 266000;
5678 }
5679
5680 static int i855_get_display_clock_speed(struct drm_device *dev)
5681 {
5682         u16 hpllcc = 0;
5683         /* Assume that the hardware is in the high speed state.  This
5684          * should be the default.
5685          */
5686         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
5687         case GC_CLOCK_133_200:
5688         case GC_CLOCK_100_200:
5689                 return 200000;
5690         case GC_CLOCK_166_250:
5691                 return 250000;
5692         case GC_CLOCK_100_133:
5693                 return 133000;
5694         }
5695
5696         /* Shouldn't happen */
5697         return 0;
5698 }
5699
5700 static int i830_get_display_clock_speed(struct drm_device *dev)
5701 {
5702         return 133000;
5703 }
5704
5705 static void
5706 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
5707 {
5708         while (*num > DATA_LINK_M_N_MASK ||
5709                *den > DATA_LINK_M_N_MASK) {
5710                 *num >>= 1;
5711                 *den >>= 1;
5712         }
5713 }
5714
5715 static void compute_m_n(unsigned int m, unsigned int n,
5716                         uint32_t *ret_m, uint32_t *ret_n)
5717 {
5718         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
5719         *ret_m = div_u64((uint64_t) m * *ret_n, n);
5720         intel_reduce_m_n_ratio(ret_m, ret_n);
5721 }
5722
5723 void
5724 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
5725                        int pixel_clock, int link_clock,
5726                        struct intel_link_m_n *m_n)
5727 {
5728         m_n->tu = 64;
5729
5730         compute_m_n(bits_per_pixel * pixel_clock,
5731                     link_clock * nlanes * 8,
5732                     &m_n->gmch_m, &m_n->gmch_n);
5733
5734         compute_m_n(pixel_clock, link_clock,
5735                     &m_n->link_m, &m_n->link_n);
5736 }
5737
5738 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
5739 {
5740         if (i915.panel_use_ssc >= 0)
5741                 return i915.panel_use_ssc != 0;
5742         return dev_priv->vbt.lvds_use_ssc
5743                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
5744 }
5745
5746 static int i9xx_get_refclk(struct intel_crtc *crtc, int num_connectors)
5747 {
5748         struct drm_device *dev = crtc->base.dev;
5749         struct drm_i915_private *dev_priv = dev->dev_private;
5750         int refclk;
5751
5752         if (IS_VALLEYVIEW(dev)) {
5753                 refclk = 100000;
5754         } else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
5755             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
5756                 refclk = dev_priv->vbt.lvds_ssc_freq;
5757                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
5758         } else if (!IS_GEN2(dev)) {
5759                 refclk = 96000;
5760         } else {
5761                 refclk = 48000;
5762         }
5763
5764         return refclk;
5765 }
5766
5767 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
5768 {
5769         return (1 << dpll->n) << 16 | dpll->m2;
5770 }
5771
5772 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
5773 {
5774         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
5775 }
5776
5777 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
5778                                      struct intel_crtc_state *crtc_state,
5779                                      intel_clock_t *reduced_clock)
5780 {
5781         struct drm_device *dev = crtc->base.dev;
5782         u32 fp, fp2 = 0;
5783
5784         if (IS_PINEVIEW(dev)) {
5785                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
5786                 if (reduced_clock)
5787                         fp2 = pnv_dpll_compute_fp(reduced_clock);
5788         } else {
5789                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
5790                 if (reduced_clock)
5791                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
5792         }
5793
5794         crtc_state->dpll_hw_state.fp0 = fp;
5795
5796         crtc->lowfreq_avail = false;
5797         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
5798             reduced_clock && i915.powersave) {
5799                 crtc_state->dpll_hw_state.fp1 = fp2;
5800                 crtc->lowfreq_avail = true;
5801         } else {
5802                 crtc_state->dpll_hw_state.fp1 = fp;
5803         }
5804 }
5805
5806 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
5807                 pipe)
5808 {
5809         u32 reg_val;
5810
5811         /*
5812          * PLLB opamp always calibrates to max value of 0x3f, force enable it
5813          * and set it to a reasonable value instead.
5814          */
5815         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
5816         reg_val &= 0xffffff00;
5817         reg_val |= 0x00000030;
5818         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
5819
5820         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
5821         reg_val &= 0x8cffffff;
5822         reg_val = 0x8c000000;
5823         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
5824
5825         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
5826         reg_val &= 0xffffff00;
5827         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
5828
5829         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
5830         reg_val &= 0x00ffffff;
5831         reg_val |= 0xb0000000;
5832         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
5833 }
5834
5835 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
5836                                          struct intel_link_m_n *m_n)
5837 {
5838         struct drm_device *dev = crtc->base.dev;
5839         struct drm_i915_private *dev_priv = dev->dev_private;
5840         int pipe = crtc->pipe;
5841
5842         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
5843         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
5844         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
5845         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
5846 }
5847
5848 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
5849                                          struct intel_link_m_n *m_n,
5850                                          struct intel_link_m_n *m2_n2)
5851 {
5852         struct drm_device *dev = crtc->base.dev;
5853         struct drm_i915_private *dev_priv = dev->dev_private;
5854         int pipe = crtc->pipe;
5855         enum transcoder transcoder = crtc->config->cpu_transcoder;
5856
5857         if (INTEL_INFO(dev)->gen >= 5) {
5858                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
5859                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
5860                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
5861                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
5862                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
5863                  * for gen < 8) and if DRRS is supported (to make sure the
5864                  * registers are not unnecessarily accessed).
5865                  */
5866                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
5867                         crtc->config->has_drrs) {
5868                         I915_WRITE(PIPE_DATA_M2(transcoder),
5869                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
5870                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
5871                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
5872                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
5873                 }
5874         } else {
5875                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
5876                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
5877                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
5878                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
5879         }
5880 }
5881
5882 void intel_dp_set_m_n(struct intel_crtc *crtc)
5883 {
5884         if (crtc->config->has_pch_encoder)
5885                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
5886         else
5887                 intel_cpu_transcoder_set_m_n(crtc, &crtc->config->dp_m_n,
5888                                                    &crtc->config->dp_m2_n2);
5889 }
5890
5891 static void vlv_update_pll(struct intel_crtc *crtc,
5892                            struct intel_crtc_state *pipe_config)
5893 {
5894         u32 dpll, dpll_md;
5895
5896         /*
5897          * Enable DPIO clock input. We should never disable the reference
5898          * clock for pipe B, since VGA hotplug / manual detection depends
5899          * on it.
5900          */
5901         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REFA_CLK_ENABLE_VLV |
5902                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_CLOCK_VLV;
5903         /* We should never disable this, set it here for state tracking */
5904         if (crtc->pipe == PIPE_B)
5905                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
5906         dpll |= DPLL_VCO_ENABLE;
5907         pipe_config->dpll_hw_state.dpll = dpll;
5908
5909         dpll_md = (pipe_config->pixel_multiplier - 1)
5910                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
5911         pipe_config->dpll_hw_state.dpll_md = dpll_md;
5912 }
5913
5914 static void vlv_prepare_pll(struct intel_crtc *crtc,
5915                             const struct intel_crtc_state *pipe_config)
5916 {
5917         struct drm_device *dev = crtc->base.dev;
5918         struct drm_i915_private *dev_priv = dev->dev_private;
5919         int pipe = crtc->pipe;
5920         u32 mdiv;
5921         u32 bestn, bestm1, bestm2, bestp1, bestp2;
5922         u32 coreclk, reg_val;
5923
5924         mutex_lock(&dev_priv->dpio_lock);
5925
5926         bestn = pipe_config->dpll.n;
5927         bestm1 = pipe_config->dpll.m1;
5928         bestm2 = pipe_config->dpll.m2;
5929         bestp1 = pipe_config->dpll.p1;
5930         bestp2 = pipe_config->dpll.p2;
5931
5932         /* See eDP HDMI DPIO driver vbios notes doc */
5933
5934         /* PLL B needs special handling */
5935         if (pipe == PIPE_B)
5936                 vlv_pllb_recal_opamp(dev_priv, pipe);
5937
5938         /* Set up Tx target for periodic Rcomp update */
5939         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
5940
5941         /* Disable target IRef on PLL */
5942         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
5943         reg_val &= 0x00ffffff;
5944         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
5945
5946         /* Disable fast lock */
5947         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
5948
5949         /* Set idtafcrecal before PLL is enabled */
5950         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
5951         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
5952         mdiv |= ((bestn << DPIO_N_SHIFT));
5953         mdiv |= (1 << DPIO_K_SHIFT);
5954
5955         /*
5956          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
5957          * but we don't support that).
5958          * Note: don't use the DAC post divider as it seems unstable.
5959          */
5960         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
5961         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
5962
5963         mdiv |= DPIO_ENABLE_CALIBRATION;
5964         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
5965
5966         /* Set HBR and RBR LPF coefficients */
5967         if (pipe_config->port_clock == 162000 ||
5968             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
5969             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
5970                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
5971                                  0x009f0003);
5972         else
5973                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
5974                                  0x00d0000f);
5975
5976         if (pipe_config->has_dp_encoder) {
5977                 /* Use SSC source */
5978                 if (pipe == PIPE_A)
5979                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5980                                          0x0df40000);
5981                 else
5982                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5983                                          0x0df70000);
5984         } else { /* HDMI or VGA */
5985                 /* Use bend source */
5986                 if (pipe == PIPE_A)
5987                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5988                                          0x0df70000);
5989                 else
5990                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5991                                          0x0df40000);
5992         }
5993
5994         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
5995         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
5996         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
5997             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
5998                 coreclk |= 0x01000000;
5999         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6000
6001         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6002         mutex_unlock(&dev_priv->dpio_lock);
6003 }
6004
6005 static void chv_update_pll(struct intel_crtc *crtc,
6006                            struct intel_crtc_state *pipe_config)
6007 {
6008         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLOCK_CHV |
6009                 DPLL_REFA_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
6010                 DPLL_VCO_ENABLE;
6011         if (crtc->pipe != PIPE_A)
6012                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6013
6014         pipe_config->dpll_hw_state.dpll_md =
6015                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6016 }
6017
6018 static void chv_prepare_pll(struct intel_crtc *crtc,
6019                             const struct intel_crtc_state *pipe_config)
6020 {
6021         struct drm_device *dev = crtc->base.dev;
6022         struct drm_i915_private *dev_priv = dev->dev_private;
6023         int pipe = crtc->pipe;
6024         int dpll_reg = DPLL(crtc->pipe);
6025         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6026         u32 loopfilter, intcoeff;
6027         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6028         int refclk;
6029
6030         bestn = pipe_config->dpll.n;
6031         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6032         bestm1 = pipe_config->dpll.m1;
6033         bestm2 = pipe_config->dpll.m2 >> 22;
6034         bestp1 = pipe_config->dpll.p1;
6035         bestp2 = pipe_config->dpll.p2;
6036
6037         /*
6038          * Enable Refclk and SSC
6039          */
6040         I915_WRITE(dpll_reg,
6041                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6042
6043         mutex_lock(&dev_priv->dpio_lock);
6044
6045         /* p1 and p2 divider */
6046         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6047                         5 << DPIO_CHV_S1_DIV_SHIFT |
6048                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6049                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6050                         1 << DPIO_CHV_K_DIV_SHIFT);
6051
6052         /* Feedback post-divider - m2 */
6053         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6054
6055         /* Feedback refclk divider - n and m1 */
6056         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6057                         DPIO_CHV_M1_DIV_BY_2 |
6058                         1 << DPIO_CHV_N_DIV_SHIFT);
6059
6060         /* M2 fraction division */
6061         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6062
6063         /* M2 fraction division enable */
6064         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port),
6065                        DPIO_CHV_FRAC_DIV_EN |
6066                        (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT));
6067
6068         /* Loop filter */
6069         refclk = i9xx_get_refclk(crtc, 0);
6070         loopfilter = 5 << DPIO_CHV_PROP_COEFF_SHIFT |
6071                 2 << DPIO_CHV_GAIN_CTRL_SHIFT;
6072         if (refclk == 100000)
6073                 intcoeff = 11;
6074         else if (refclk == 38400)
6075                 intcoeff = 10;
6076         else
6077                 intcoeff = 9;
6078         loopfilter |= intcoeff << DPIO_CHV_INT_COEFF_SHIFT;
6079         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6080
6081         /* AFC Recal */
6082         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6083                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6084                         DPIO_AFC_RECAL);
6085
6086         mutex_unlock(&dev_priv->dpio_lock);
6087 }
6088
6089 /**
6090  * vlv_force_pll_on - forcibly enable just the PLL
6091  * @dev_priv: i915 private structure
6092  * @pipe: pipe PLL to enable
6093  * @dpll: PLL configuration
6094  *
6095  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6096  * in cases where we need the PLL enabled even when @pipe is not going to
6097  * be enabled.
6098  */
6099 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
6100                       const struct dpll *dpll)
6101 {
6102         struct intel_crtc *crtc =
6103                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
6104         struct intel_crtc_state pipe_config = {
6105                 .pixel_multiplier = 1,
6106                 .dpll = *dpll,
6107         };
6108
6109         if (IS_CHERRYVIEW(dev)) {
6110                 chv_update_pll(crtc, &pipe_config);
6111                 chv_prepare_pll(crtc, &pipe_config);
6112                 chv_enable_pll(crtc, &pipe_config);
6113         } else {
6114                 vlv_update_pll(crtc, &pipe_config);
6115                 vlv_prepare_pll(crtc, &pipe_config);
6116                 vlv_enable_pll(crtc, &pipe_config);
6117         }
6118 }
6119
6120 /**
6121  * vlv_force_pll_off - forcibly disable just the PLL
6122  * @dev_priv: i915 private structure
6123  * @pipe: pipe PLL to disable
6124  *
6125  * Disable the PLL for @pipe. To be used in cases where we need
6126  * the PLL enabled even when @pipe is not going to be enabled.
6127  */
6128 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
6129 {
6130         if (IS_CHERRYVIEW(dev))
6131                 chv_disable_pll(to_i915(dev), pipe);
6132         else
6133                 vlv_disable_pll(to_i915(dev), pipe);
6134 }
6135
6136 static void i9xx_update_pll(struct intel_crtc *crtc,
6137                             struct intel_crtc_state *crtc_state,
6138                             intel_clock_t *reduced_clock,
6139                             int num_connectors)
6140 {
6141         struct drm_device *dev = crtc->base.dev;
6142         struct drm_i915_private *dev_priv = dev->dev_private;
6143         u32 dpll;
6144         bool is_sdvo;
6145         struct dpll *clock = &crtc_state->dpll;
6146
6147         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6148
6149         is_sdvo = intel_pipe_will_have_type(crtc, INTEL_OUTPUT_SDVO) ||
6150                 intel_pipe_will_have_type(crtc, INTEL_OUTPUT_HDMI);
6151
6152         dpll = DPLL_VGA_MODE_DIS;
6153
6154         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS))
6155                 dpll |= DPLLB_MODE_LVDS;
6156         else
6157                 dpll |= DPLLB_MODE_DAC_SERIAL;
6158
6159         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
6160                 dpll |= (crtc_state->pixel_multiplier - 1)
6161                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6162         }
6163
6164         if (is_sdvo)
6165                 dpll |= DPLL_SDVO_HIGH_SPEED;
6166
6167         if (crtc_state->has_dp_encoder)
6168                 dpll |= DPLL_SDVO_HIGH_SPEED;
6169
6170         /* compute bitmask from p1 value */
6171         if (IS_PINEVIEW(dev))
6172                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6173         else {
6174                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6175                 if (IS_G4X(dev) && reduced_clock)
6176                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6177         }
6178         switch (clock->p2) {
6179         case 5:
6180                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6181                 break;
6182         case 7:
6183                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6184                 break;
6185         case 10:
6186                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6187                 break;
6188         case 14:
6189                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6190                 break;
6191         }
6192         if (INTEL_INFO(dev)->gen >= 4)
6193                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6194
6195         if (crtc_state->sdvo_tv_clock)
6196                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6197         else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
6198                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6199                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6200         else
6201                 dpll |= PLL_REF_INPUT_DREFCLK;
6202
6203         dpll |= DPLL_VCO_ENABLE;
6204         crtc_state->dpll_hw_state.dpll = dpll;
6205
6206         if (INTEL_INFO(dev)->gen >= 4) {
6207                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6208                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6209                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
6210         }
6211 }
6212
6213 static void i8xx_update_pll(struct intel_crtc *crtc,
6214                             struct intel_crtc_state *crtc_state,
6215                             intel_clock_t *reduced_clock,
6216                             int num_connectors)
6217 {
6218         struct drm_device *dev = crtc->base.dev;
6219         struct drm_i915_private *dev_priv = dev->dev_private;
6220         u32 dpll;
6221         struct dpll *clock = &crtc_state->dpll;
6222
6223         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6224
6225         dpll = DPLL_VGA_MODE_DIS;
6226
6227         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
6228                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6229         } else {
6230                 if (clock->p1 == 2)
6231                         dpll |= PLL_P1_DIVIDE_BY_TWO;
6232                 else
6233                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6234                 if (clock->p2 == 4)
6235                         dpll |= PLL_P2_DIVIDE_BY_4;
6236         }
6237
6238         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc, INTEL_OUTPUT_DVO))
6239                 dpll |= DPLL_DVO_2X_MODE;
6240
6241         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
6242                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6243                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6244         else
6245                 dpll |= PLL_REF_INPUT_DREFCLK;
6246
6247         dpll |= DPLL_VCO_ENABLE;
6248         crtc_state->dpll_hw_state.dpll = dpll;
6249 }
6250
6251 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
6252 {
6253         struct drm_device *dev = intel_crtc->base.dev;
6254         struct drm_i915_private *dev_priv = dev->dev_private;
6255         enum pipe pipe = intel_crtc->pipe;
6256         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
6257         struct drm_display_mode *adjusted_mode =
6258                 &intel_crtc->config->base.adjusted_mode;
6259         uint32_t crtc_vtotal, crtc_vblank_end;
6260         int vsyncshift = 0;
6261
6262         /* We need to be careful not to changed the adjusted mode, for otherwise
6263          * the hw state checker will get angry at the mismatch. */
6264         crtc_vtotal = adjusted_mode->crtc_vtotal;
6265         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
6266
6267         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
6268                 /* the chip adds 2 halflines automatically */
6269                 crtc_vtotal -= 1;
6270                 crtc_vblank_end -= 1;
6271
6272                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
6273                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
6274                 else
6275                         vsyncshift = adjusted_mode->crtc_hsync_start -
6276                                 adjusted_mode->crtc_htotal / 2;
6277                 if (vsyncshift < 0)
6278                         vsyncshift += adjusted_mode->crtc_htotal;
6279         }
6280
6281         if (INTEL_INFO(dev)->gen > 3)
6282                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
6283
6284         I915_WRITE(HTOTAL(cpu_transcoder),
6285                    (adjusted_mode->crtc_hdisplay - 1) |
6286                    ((adjusted_mode->crtc_htotal - 1) << 16));
6287         I915_WRITE(HBLANK(cpu_transcoder),
6288                    (adjusted_mode->crtc_hblank_start - 1) |
6289                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
6290         I915_WRITE(HSYNC(cpu_transcoder),
6291                    (adjusted_mode->crtc_hsync_start - 1) |
6292                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
6293
6294         I915_WRITE(VTOTAL(cpu_transcoder),
6295                    (adjusted_mode->crtc_vdisplay - 1) |
6296                    ((crtc_vtotal - 1) << 16));
6297         I915_WRITE(VBLANK(cpu_transcoder),
6298                    (adjusted_mode->crtc_vblank_start - 1) |
6299                    ((crtc_vblank_end - 1) << 16));
6300         I915_WRITE(VSYNC(cpu_transcoder),
6301                    (adjusted_mode->crtc_vsync_start - 1) |
6302                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
6303
6304         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
6305          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
6306          * documented on the DDI_FUNC_CTL register description, EDP Input Select
6307          * bits. */
6308         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
6309             (pipe == PIPE_B || pipe == PIPE_C))
6310                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
6311
6312         /* pipesrc controls the size that is scaled from, which should
6313          * always be the user's requested size.
6314          */
6315         I915_WRITE(PIPESRC(pipe),
6316                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
6317                    (intel_crtc->config->pipe_src_h - 1));
6318 }
6319
6320 static void intel_get_pipe_timings(struct intel_crtc *crtc,
6321                                    struct intel_crtc_state *pipe_config)
6322 {
6323         struct drm_device *dev = crtc->base.dev;
6324         struct drm_i915_private *dev_priv = dev->dev_private;
6325         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6326         uint32_t tmp;
6327
6328         tmp = I915_READ(HTOTAL(cpu_transcoder));
6329         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
6330         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
6331         tmp = I915_READ(HBLANK(cpu_transcoder));
6332         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
6333         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
6334         tmp = I915_READ(HSYNC(cpu_transcoder));
6335         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
6336         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
6337
6338         tmp = I915_READ(VTOTAL(cpu_transcoder));
6339         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
6340         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
6341         tmp = I915_READ(VBLANK(cpu_transcoder));
6342         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
6343         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
6344         tmp = I915_READ(VSYNC(cpu_transcoder));
6345         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
6346         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
6347
6348         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
6349                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
6350                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
6351                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
6352         }
6353
6354         tmp = I915_READ(PIPESRC(crtc->pipe));
6355         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
6356         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
6357
6358         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
6359         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
6360 }
6361
6362 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
6363                                  struct intel_crtc_state *pipe_config)
6364 {
6365         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
6366         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
6367         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
6368         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
6369
6370         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
6371         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
6372         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
6373         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
6374
6375         mode->flags = pipe_config->base.adjusted_mode.flags;
6376
6377         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
6378         mode->flags |= pipe_config->base.adjusted_mode.flags;
6379 }
6380
6381 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
6382 {
6383         struct drm_device *dev = intel_crtc->base.dev;
6384         struct drm_i915_private *dev_priv = dev->dev_private;
6385         uint32_t pipeconf;
6386
6387         pipeconf = 0;
6388
6389         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
6390             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
6391                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
6392
6393         if (intel_crtc->config->double_wide)
6394                 pipeconf |= PIPECONF_DOUBLE_WIDE;
6395
6396         /* only g4x and later have fancy bpc/dither controls */
6397         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
6398                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
6399                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
6400                         pipeconf |= PIPECONF_DITHER_EN |
6401                                     PIPECONF_DITHER_TYPE_SP;
6402
6403                 switch (intel_crtc->config->pipe_bpp) {
6404                 case 18:
6405                         pipeconf |= PIPECONF_6BPC;
6406                         break;
6407                 case 24:
6408                         pipeconf |= PIPECONF_8BPC;
6409                         break;
6410                 case 30:
6411                         pipeconf |= PIPECONF_10BPC;
6412                         break;
6413                 default:
6414                         /* Case prevented by intel_choose_pipe_bpp_dither. */
6415                         BUG();
6416                 }
6417         }
6418
6419         if (HAS_PIPE_CXSR(dev)) {
6420                 if (intel_crtc->lowfreq_avail) {
6421                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
6422                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
6423                 } else {
6424                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
6425                 }
6426         }
6427
6428         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
6429                 if (INTEL_INFO(dev)->gen < 4 ||
6430                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
6431                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
6432                 else
6433                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
6434         } else
6435                 pipeconf |= PIPECONF_PROGRESSIVE;
6436
6437         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
6438                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
6439
6440         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
6441         POSTING_READ(PIPECONF(intel_crtc->pipe));
6442 }
6443
6444 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
6445                                    struct intel_crtc_state *crtc_state)
6446 {
6447         struct drm_device *dev = crtc->base.dev;
6448         struct drm_i915_private *dev_priv = dev->dev_private;
6449         int refclk, num_connectors = 0;
6450         intel_clock_t clock, reduced_clock;
6451         bool ok, has_reduced_clock = false;
6452         bool is_lvds = false, is_dsi = false;
6453         struct intel_encoder *encoder;
6454         const intel_limit_t *limit;
6455
6456         for_each_intel_encoder(dev, encoder) {
6457                 if (encoder->new_crtc != crtc)
6458                         continue;
6459
6460                 switch (encoder->type) {
6461                 case INTEL_OUTPUT_LVDS:
6462                         is_lvds = true;
6463                         break;
6464                 case INTEL_OUTPUT_DSI:
6465                         is_dsi = true;
6466                         break;
6467                 default:
6468                         break;
6469                 }
6470
6471                 num_connectors++;
6472         }
6473
6474         if (is_dsi)
6475                 return 0;
6476
6477         if (!crtc_state->clock_set) {
6478                 refclk = i9xx_get_refclk(crtc, num_connectors);
6479
6480                 /*
6481                  * Returns a set of divisors for the desired target clock with
6482                  * the given refclk, or FALSE.  The returned values represent
6483                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
6484                  * 2) / p1 / p2.
6485                  */
6486                 limit = intel_limit(crtc, refclk);
6487                 ok = dev_priv->display.find_dpll(limit, crtc,
6488                                                  crtc_state->port_clock,
6489                                                  refclk, NULL, &clock);
6490                 if (!ok) {
6491                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
6492                         return -EINVAL;
6493                 }
6494
6495                 if (is_lvds && dev_priv->lvds_downclock_avail) {
6496                         /*
6497                          * Ensure we match the reduced clock's P to the target
6498                          * clock.  If the clocks don't match, we can't switch
6499                          * the display clock by using the FP0/FP1. In such case
6500                          * we will disable the LVDS downclock feature.
6501                          */
6502                         has_reduced_clock =
6503                                 dev_priv->display.find_dpll(limit, crtc,
6504                                                             dev_priv->lvds_downclock,
6505                                                             refclk, &clock,
6506                                                             &reduced_clock);
6507                 }
6508                 /* Compat-code for transition, will disappear. */
6509                 crtc_state->dpll.n = clock.n;
6510                 crtc_state->dpll.m1 = clock.m1;
6511                 crtc_state->dpll.m2 = clock.m2;
6512                 crtc_state->dpll.p1 = clock.p1;
6513                 crtc_state->dpll.p2 = clock.p2;
6514         }
6515
6516         if (IS_GEN2(dev)) {
6517                 i8xx_update_pll(crtc, crtc_state,
6518                                 has_reduced_clock ? &reduced_clock : NULL,
6519                                 num_connectors);
6520         } else if (IS_CHERRYVIEW(dev)) {
6521                 chv_update_pll(crtc, crtc_state);
6522         } else if (IS_VALLEYVIEW(dev)) {
6523                 vlv_update_pll(crtc, crtc_state);
6524         } else {
6525                 i9xx_update_pll(crtc, crtc_state,
6526                                 has_reduced_clock ? &reduced_clock : NULL,
6527                                 num_connectors);
6528         }
6529
6530         return 0;
6531 }
6532
6533 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
6534                                  struct intel_crtc_state *pipe_config)
6535 {
6536         struct drm_device *dev = crtc->base.dev;
6537         struct drm_i915_private *dev_priv = dev->dev_private;
6538         uint32_t tmp;
6539
6540         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
6541                 return;
6542
6543         tmp = I915_READ(PFIT_CONTROL);
6544         if (!(tmp & PFIT_ENABLE))
6545                 return;
6546
6547         /* Check whether the pfit is attached to our pipe. */
6548         if (INTEL_INFO(dev)->gen < 4) {
6549                 if (crtc->pipe != PIPE_B)
6550                         return;
6551         } else {
6552                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
6553                         return;
6554         }
6555
6556         pipe_config->gmch_pfit.control = tmp;
6557         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
6558         if (INTEL_INFO(dev)->gen < 5)
6559                 pipe_config->gmch_pfit.lvds_border_bits =
6560                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
6561 }
6562
6563 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
6564                                struct intel_crtc_state *pipe_config)
6565 {
6566         struct drm_device *dev = crtc->base.dev;
6567         struct drm_i915_private *dev_priv = dev->dev_private;
6568         int pipe = pipe_config->cpu_transcoder;
6569         intel_clock_t clock;
6570         u32 mdiv;
6571         int refclk = 100000;
6572
6573         /* In case of MIPI DPLL will not even be used */
6574         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
6575                 return;
6576
6577         mutex_lock(&dev_priv->dpio_lock);
6578         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
6579         mutex_unlock(&dev_priv->dpio_lock);
6580
6581         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
6582         clock.m2 = mdiv & DPIO_M2DIV_MASK;
6583         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
6584         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
6585         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
6586
6587         vlv_clock(refclk, &clock);
6588
6589         /* clock.dot is the fast clock */
6590         pipe_config->port_clock = clock.dot / 5;
6591 }
6592
6593 static void
6594 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
6595                               struct intel_initial_plane_config *plane_config)
6596 {
6597         struct drm_device *dev = crtc->base.dev;
6598         struct drm_i915_private *dev_priv = dev->dev_private;
6599         u32 val, base, offset;
6600         int pipe = crtc->pipe, plane = crtc->plane;
6601         int fourcc, pixel_format;
6602         int aligned_height;
6603         struct drm_framebuffer *fb;
6604         struct intel_framebuffer *intel_fb;
6605
6606         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
6607         if (!intel_fb) {
6608                 DRM_DEBUG_KMS("failed to alloc fb\n");
6609                 return;
6610         }
6611
6612         fb = &intel_fb->base;
6613
6614         val = I915_READ(DSPCNTR(plane));
6615
6616         if (INTEL_INFO(dev)->gen >= 4)
6617                 if (val & DISPPLANE_TILED)
6618                         plane_config->tiling = I915_TILING_X;
6619
6620         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
6621         fourcc = i9xx_format_to_fourcc(pixel_format);
6622         fb->pixel_format = fourcc;
6623         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
6624
6625         if (INTEL_INFO(dev)->gen >= 4) {
6626                 if (plane_config->tiling)
6627                         offset = I915_READ(DSPTILEOFF(plane));
6628                 else
6629                         offset = I915_READ(DSPLINOFF(plane));
6630                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
6631         } else {
6632                 base = I915_READ(DSPADDR(plane));
6633         }
6634         plane_config->base = base;
6635
6636         val = I915_READ(PIPESRC(pipe));
6637         fb->width = ((val >> 16) & 0xfff) + 1;
6638         fb->height = ((val >> 0) & 0xfff) + 1;
6639
6640         val = I915_READ(DSPSTRIDE(pipe));
6641         fb->pitches[0] = val & 0xffffffc0;
6642
6643         aligned_height = intel_fb_align_height(dev, fb->height,
6644                                                plane_config->tiling);
6645
6646         plane_config->size = PAGE_ALIGN(fb->pitches[0] * aligned_height);
6647
6648         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
6649                       pipe_name(pipe), plane, fb->width, fb->height,
6650                       fb->bits_per_pixel, base, fb->pitches[0],
6651                       plane_config->size);
6652
6653         crtc->base.primary->fb = fb;
6654         update_state_fb(crtc->base.primary);
6655 }
6656
6657 static void chv_crtc_clock_get(struct intel_crtc *crtc,
6658                                struct intel_crtc_state *pipe_config)
6659 {
6660         struct drm_device *dev = crtc->base.dev;
6661         struct drm_i915_private *dev_priv = dev->dev_private;
6662         int pipe = pipe_config->cpu_transcoder;
6663         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6664         intel_clock_t clock;
6665         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
6666         int refclk = 100000;
6667
6668         mutex_lock(&dev_priv->dpio_lock);
6669         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
6670         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
6671         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
6672         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
6673         mutex_unlock(&dev_priv->dpio_lock);
6674
6675         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
6676         clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
6677         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
6678         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
6679         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
6680
6681         chv_clock(refclk, &clock);
6682
6683         /* clock.dot is the fast clock */
6684         pipe_config->port_clock = clock.dot / 5;
6685 }
6686
6687 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
6688                                  struct intel_crtc_state *pipe_config)
6689 {
6690         struct drm_device *dev = crtc->base.dev;
6691         struct drm_i915_private *dev_priv = dev->dev_private;
6692         uint32_t tmp;
6693
6694         if (!intel_display_power_is_enabled(dev_priv,
6695                                             POWER_DOMAIN_PIPE(crtc->pipe)))
6696                 return false;
6697
6698         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
6699         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
6700
6701         tmp = I915_READ(PIPECONF(crtc->pipe));
6702         if (!(tmp & PIPECONF_ENABLE))
6703                 return false;
6704
6705         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
6706                 switch (tmp & PIPECONF_BPC_MASK) {
6707                 case PIPECONF_6BPC:
6708                         pipe_config->pipe_bpp = 18;
6709                         break;
6710                 case PIPECONF_8BPC:
6711                         pipe_config->pipe_bpp = 24;
6712                         break;
6713                 case PIPECONF_10BPC:
6714                         pipe_config->pipe_bpp = 30;
6715                         break;
6716                 default:
6717                         break;
6718                 }
6719         }
6720
6721         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
6722                 pipe_config->limited_color_range = true;
6723
6724         if (INTEL_INFO(dev)->gen < 4)
6725                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
6726
6727         intel_get_pipe_timings(crtc, pipe_config);
6728
6729         i9xx_get_pfit_config(crtc, pipe_config);
6730
6731         if (INTEL_INFO(dev)->gen >= 4) {
6732                 tmp = I915_READ(DPLL_MD(crtc->pipe));
6733                 pipe_config->pixel_multiplier =
6734                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
6735                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
6736                 pipe_config->dpll_hw_state.dpll_md = tmp;
6737         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
6738                 tmp = I915_READ(DPLL(crtc->pipe));
6739                 pipe_config->pixel_multiplier =
6740                         ((tmp & SDVO_MULTIPLIER_MASK)
6741                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
6742         } else {
6743                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
6744                  * port and will be fixed up in the encoder->get_config
6745                  * function. */
6746                 pipe_config->pixel_multiplier = 1;
6747         }
6748         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
6749         if (!IS_VALLEYVIEW(dev)) {
6750                 /*
6751                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
6752                  * on 830. Filter it out here so that we don't
6753                  * report errors due to that.
6754                  */
6755                 if (IS_I830(dev))
6756                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
6757
6758                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
6759                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
6760         } else {
6761                 /* Mask out read-only status bits. */
6762                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
6763                                                      DPLL_PORTC_READY_MASK |
6764                                                      DPLL_PORTB_READY_MASK);
6765         }
6766
6767         if (IS_CHERRYVIEW(dev))
6768                 chv_crtc_clock_get(crtc, pipe_config);
6769         else if (IS_VALLEYVIEW(dev))
6770                 vlv_crtc_clock_get(crtc, pipe_config);
6771         else
6772                 i9xx_crtc_clock_get(crtc, pipe_config);
6773
6774         return true;
6775 }
6776
6777 static void ironlake_init_pch_refclk(struct drm_device *dev)
6778 {
6779         struct drm_i915_private *dev_priv = dev->dev_private;
6780         struct intel_encoder *encoder;
6781         u32 val, final;
6782         bool has_lvds = false;
6783         bool has_cpu_edp = false;
6784         bool has_panel = false;
6785         bool has_ck505 = false;
6786         bool can_ssc = false;
6787
6788         /* We need to take the global config into account */
6789         for_each_intel_encoder(dev, encoder) {
6790                 switch (encoder->type) {
6791                 case INTEL_OUTPUT_LVDS:
6792                         has_panel = true;
6793                         has_lvds = true;
6794                         break;
6795                 case INTEL_OUTPUT_EDP:
6796                         has_panel = true;
6797                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
6798                                 has_cpu_edp = true;
6799                         break;
6800                 default:
6801                         break;
6802                 }
6803         }
6804
6805         if (HAS_PCH_IBX(dev)) {
6806                 has_ck505 = dev_priv->vbt.display_clock_mode;
6807                 can_ssc = has_ck505;
6808         } else {
6809                 has_ck505 = false;
6810                 can_ssc = true;
6811         }
6812
6813         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
6814                       has_panel, has_lvds, has_ck505);
6815
6816         /* Ironlake: try to setup display ref clock before DPLL
6817          * enabling. This is only under driver's control after
6818          * PCH B stepping, previous chipset stepping should be
6819          * ignoring this setting.
6820          */
6821         val = I915_READ(PCH_DREF_CONTROL);
6822
6823         /* As we must carefully and slowly disable/enable each source in turn,
6824          * compute the final state we want first and check if we need to
6825          * make any changes at all.
6826          */
6827         final = val;
6828         final &= ~DREF_NONSPREAD_SOURCE_MASK;
6829         if (has_ck505)
6830                 final |= DREF_NONSPREAD_CK505_ENABLE;
6831         else
6832                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
6833
6834         final &= ~DREF_SSC_SOURCE_MASK;
6835         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6836         final &= ~DREF_SSC1_ENABLE;
6837
6838         if (has_panel) {
6839                 final |= DREF_SSC_SOURCE_ENABLE;
6840
6841                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
6842                         final |= DREF_SSC1_ENABLE;
6843
6844                 if (has_cpu_edp) {
6845                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
6846                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
6847                         else
6848                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
6849                 } else
6850                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6851         } else {
6852                 final |= DREF_SSC_SOURCE_DISABLE;
6853                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6854         }
6855
6856         if (final == val)
6857                 return;
6858
6859         /* Always enable nonspread source */
6860         val &= ~DREF_NONSPREAD_SOURCE_MASK;
6861
6862         if (has_ck505)
6863                 val |= DREF_NONSPREAD_CK505_ENABLE;
6864         else
6865                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
6866
6867         if (has_panel) {
6868                 val &= ~DREF_SSC_SOURCE_MASK;
6869                 val |= DREF_SSC_SOURCE_ENABLE;
6870
6871                 /* SSC must be turned on before enabling the CPU output  */
6872                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
6873                         DRM_DEBUG_KMS("Using SSC on panel\n");
6874                         val |= DREF_SSC1_ENABLE;
6875                 } else
6876                         val &= ~DREF_SSC1_ENABLE;
6877
6878                 /* Get SSC going before enabling the outputs */
6879                 I915_WRITE(PCH_DREF_CONTROL, val);
6880                 POSTING_READ(PCH_DREF_CONTROL);
6881                 udelay(200);
6882
6883                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6884
6885                 /* Enable CPU source on CPU attached eDP */
6886                 if (has_cpu_edp) {
6887                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
6888                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
6889                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
6890                         } else
6891                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
6892                 } else
6893                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6894
6895                 I915_WRITE(PCH_DREF_CONTROL, val);
6896                 POSTING_READ(PCH_DREF_CONTROL);
6897                 udelay(200);
6898         } else {
6899                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
6900
6901                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6902
6903                 /* Turn off CPU output */
6904                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6905
6906                 I915_WRITE(PCH_DREF_CONTROL, val);
6907                 POSTING_READ(PCH_DREF_CONTROL);
6908                 udelay(200);
6909
6910                 /* Turn off the SSC source */
6911                 val &= ~DREF_SSC_SOURCE_MASK;
6912                 val |= DREF_SSC_SOURCE_DISABLE;
6913
6914                 /* Turn off SSC1 */
6915                 val &= ~DREF_SSC1_ENABLE;
6916
6917                 I915_WRITE(PCH_DREF_CONTROL, val);
6918                 POSTING_READ(PCH_DREF_CONTROL);
6919                 udelay(200);
6920         }
6921
6922         BUG_ON(val != final);
6923 }
6924
6925 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
6926 {
6927         uint32_t tmp;
6928
6929         tmp = I915_READ(SOUTH_CHICKEN2);
6930         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
6931         I915_WRITE(SOUTH_CHICKEN2, tmp);
6932
6933         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
6934                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
6935                 DRM_ERROR("FDI mPHY reset assert timeout\n");
6936
6937         tmp = I915_READ(SOUTH_CHICKEN2);
6938         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
6939         I915_WRITE(SOUTH_CHICKEN2, tmp);
6940
6941         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
6942                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
6943                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
6944 }
6945
6946 /* WaMPhyProgramming:hsw */
6947 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
6948 {
6949         uint32_t tmp;
6950
6951         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
6952         tmp &= ~(0xFF << 24);
6953         tmp |= (0x12 << 24);
6954         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
6955
6956         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
6957         tmp |= (1 << 11);
6958         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
6959
6960         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
6961         tmp |= (1 << 11);
6962         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
6963
6964         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
6965         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
6966         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
6967
6968         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
6969         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
6970         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
6971
6972         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
6973         tmp &= ~(7 << 13);
6974         tmp |= (5 << 13);
6975         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
6976
6977         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
6978         tmp &= ~(7 << 13);
6979         tmp |= (5 << 13);
6980         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
6981
6982         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
6983         tmp &= ~0xFF;
6984         tmp |= 0x1C;
6985         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
6986
6987         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
6988         tmp &= ~0xFF;
6989         tmp |= 0x1C;
6990         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
6991
6992         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
6993         tmp &= ~(0xFF << 16);
6994         tmp |= (0x1C << 16);
6995         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
6996
6997         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
6998         tmp &= ~(0xFF << 16);
6999         tmp |= (0x1C << 16);
7000         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7001
7002         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7003         tmp |= (1 << 27);
7004         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7005
7006         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7007         tmp |= (1 << 27);
7008         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7009
7010         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7011         tmp &= ~(0xF << 28);
7012         tmp |= (4 << 28);
7013         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7014
7015         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7016         tmp &= ~(0xF << 28);
7017         tmp |= (4 << 28);
7018         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7019 }
7020
7021 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7022  * Programming" based on the parameters passed:
7023  * - Sequence to enable CLKOUT_DP
7024  * - Sequence to enable CLKOUT_DP without spread
7025  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7026  */
7027 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
7028                                  bool with_fdi)
7029 {
7030         struct drm_i915_private *dev_priv = dev->dev_private;
7031         uint32_t reg, tmp;
7032
7033         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7034                 with_spread = true;
7035         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
7036                  with_fdi, "LP PCH doesn't have FDI\n"))
7037                 with_fdi = false;
7038
7039         mutex_lock(&dev_priv->dpio_lock);
7040
7041         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7042         tmp &= ~SBI_SSCCTL_DISABLE;
7043         tmp |= SBI_SSCCTL_PATHALT;
7044         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7045
7046         udelay(24);
7047
7048         if (with_spread) {
7049                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7050                 tmp &= ~SBI_SSCCTL_PATHALT;
7051                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7052
7053                 if (with_fdi) {
7054                         lpt_reset_fdi_mphy(dev_priv);
7055                         lpt_program_fdi_mphy(dev_priv);
7056                 }
7057         }
7058
7059         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7060                SBI_GEN0 : SBI_DBUFF0;
7061         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7062         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7063         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7064
7065         mutex_unlock(&dev_priv->dpio_lock);
7066 }
7067
7068 /* Sequence to disable CLKOUT_DP */
7069 static void lpt_disable_clkout_dp(struct drm_device *dev)
7070 {
7071         struct drm_i915_private *dev_priv = dev->dev_private;
7072         uint32_t reg, tmp;
7073
7074         mutex_lock(&dev_priv->dpio_lock);
7075
7076         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7077                SBI_GEN0 : SBI_DBUFF0;
7078         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7079         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7080         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7081
7082         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7083         if (!(tmp & SBI_SSCCTL_DISABLE)) {
7084                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
7085                         tmp |= SBI_SSCCTL_PATHALT;
7086                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7087                         udelay(32);
7088                 }
7089                 tmp |= SBI_SSCCTL_DISABLE;
7090                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7091         }
7092
7093         mutex_unlock(&dev_priv->dpio_lock);
7094 }
7095
7096 static void lpt_init_pch_refclk(struct drm_device *dev)
7097 {
7098         struct intel_encoder *encoder;
7099         bool has_vga = false;
7100
7101         for_each_intel_encoder(dev, encoder) {
7102                 switch (encoder->type) {
7103                 case INTEL_OUTPUT_ANALOG:
7104                         has_vga = true;
7105                         break;
7106                 default:
7107                         break;
7108                 }
7109         }
7110
7111         if (has_vga)
7112                 lpt_enable_clkout_dp(dev, true, true);
7113         else
7114                 lpt_disable_clkout_dp(dev);
7115 }
7116
7117 /*
7118  * Initialize reference clocks when the driver loads
7119  */
7120 void intel_init_pch_refclk(struct drm_device *dev)
7121 {
7122         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
7123                 ironlake_init_pch_refclk(dev);
7124         else if (HAS_PCH_LPT(dev))
7125                 lpt_init_pch_refclk(dev);
7126 }
7127
7128 static int ironlake_get_refclk(struct drm_crtc *crtc)
7129 {
7130         struct drm_device *dev = crtc->dev;
7131         struct drm_i915_private *dev_priv = dev->dev_private;
7132         struct intel_encoder *encoder;
7133         int num_connectors = 0;
7134         bool is_lvds = false;
7135
7136         for_each_intel_encoder(dev, encoder) {
7137                 if (encoder->new_crtc != to_intel_crtc(crtc))
7138                         continue;
7139
7140                 switch (encoder->type) {
7141                 case INTEL_OUTPUT_LVDS:
7142                         is_lvds = true;
7143                         break;
7144                 default:
7145                         break;
7146                 }
7147                 num_connectors++;
7148         }
7149
7150         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7151                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
7152                               dev_priv->vbt.lvds_ssc_freq);
7153                 return dev_priv->vbt.lvds_ssc_freq;
7154         }
7155
7156         return 120000;
7157 }
7158
7159 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
7160 {
7161         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
7162         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7163         int pipe = intel_crtc->pipe;
7164         uint32_t val;
7165
7166         val = 0;
7167
7168         switch (intel_crtc->config->pipe_bpp) {
7169         case 18:
7170                 val |= PIPECONF_6BPC;
7171                 break;
7172         case 24:
7173                 val |= PIPECONF_8BPC;
7174                 break;
7175         case 30:
7176                 val |= PIPECONF_10BPC;
7177                 break;
7178         case 36:
7179                 val |= PIPECONF_12BPC;
7180                 break;
7181         default:
7182                 /* Case prevented by intel_choose_pipe_bpp_dither. */
7183                 BUG();
7184         }
7185
7186         if (intel_crtc->config->dither)
7187                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
7188
7189         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
7190                 val |= PIPECONF_INTERLACED_ILK;
7191         else
7192                 val |= PIPECONF_PROGRESSIVE;
7193
7194         if (intel_crtc->config->limited_color_range)
7195                 val |= PIPECONF_COLOR_RANGE_SELECT;
7196
7197         I915_WRITE(PIPECONF(pipe), val);
7198         POSTING_READ(PIPECONF(pipe));
7199 }
7200
7201 /*
7202  * Set up the pipe CSC unit.
7203  *
7204  * Currently only full range RGB to limited range RGB conversion
7205  * is supported, but eventually this should handle various
7206  * RGB<->YCbCr scenarios as well.
7207  */
7208 static void intel_set_pipe_csc(struct drm_crtc *crtc)
7209 {
7210         struct drm_device *dev = crtc->dev;
7211         struct drm_i915_private *dev_priv = dev->dev_private;
7212         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7213         int pipe = intel_crtc->pipe;
7214         uint16_t coeff = 0x7800; /* 1.0 */
7215
7216         /*
7217          * TODO: Check what kind of values actually come out of the pipe
7218          * with these coeff/postoff values and adjust to get the best
7219          * accuracy. Perhaps we even need to take the bpc value into
7220          * consideration.
7221          */
7222
7223         if (intel_crtc->config->limited_color_range)
7224                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
7225
7226         /*
7227          * GY/GU and RY/RU should be the other way around according
7228          * to BSpec, but reality doesn't agree. Just set them up in
7229          * a way that results in the correct picture.
7230          */
7231         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
7232         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
7233
7234         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
7235         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
7236
7237         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
7238         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
7239
7240         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
7241         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
7242         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
7243
7244         if (INTEL_INFO(dev)->gen > 6) {
7245                 uint16_t postoff = 0;
7246
7247                 if (intel_crtc->config->limited_color_range)
7248                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
7249
7250                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
7251                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
7252                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
7253
7254                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
7255         } else {
7256                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
7257
7258                 if (intel_crtc->config->limited_color_range)
7259                         mode |= CSC_BLACK_SCREEN_OFFSET;
7260
7261                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
7262         }
7263 }
7264
7265 static void haswell_set_pipeconf(struct drm_crtc *crtc)
7266 {
7267         struct drm_device *dev = crtc->dev;
7268         struct drm_i915_private *dev_priv = dev->dev_private;
7269         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7270         enum pipe pipe = intel_crtc->pipe;
7271         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7272         uint32_t val;
7273
7274         val = 0;
7275
7276         if (IS_HASWELL(dev) && intel_crtc->config->dither)
7277                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
7278
7279         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
7280                 val |= PIPECONF_INTERLACED_ILK;
7281         else
7282                 val |= PIPECONF_PROGRESSIVE;
7283
7284         I915_WRITE(PIPECONF(cpu_transcoder), val);
7285         POSTING_READ(PIPECONF(cpu_transcoder));
7286
7287         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
7288         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
7289
7290         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
7291                 val = 0;
7292
7293                 switch (intel_crtc->config->pipe_bpp) {
7294                 case 18:
7295                         val |= PIPEMISC_DITHER_6_BPC;
7296                         break;
7297                 case 24:
7298                         val |= PIPEMISC_DITHER_8_BPC;
7299                         break;
7300                 case 30:
7301                         val |= PIPEMISC_DITHER_10_BPC;
7302                         break;
7303                 case 36:
7304                         val |= PIPEMISC_DITHER_12_BPC;
7305                         break;
7306                 default:
7307                         /* Case prevented by pipe_config_set_bpp. */
7308                         BUG();
7309                 }
7310
7311                 if (intel_crtc->config->dither)
7312                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
7313
7314                 I915_WRITE(PIPEMISC(pipe), val);
7315         }
7316 }
7317
7318 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
7319                                     struct intel_crtc_state *crtc_state,
7320                                     intel_clock_t *clock,
7321                                     bool *has_reduced_clock,
7322                                     intel_clock_t *reduced_clock)
7323 {
7324         struct drm_device *dev = crtc->dev;
7325         struct drm_i915_private *dev_priv = dev->dev_private;
7326         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7327         int refclk;
7328         const intel_limit_t *limit;
7329         bool ret, is_lvds = false;
7330
7331         is_lvds = intel_pipe_will_have_type(intel_crtc, INTEL_OUTPUT_LVDS);
7332
7333         refclk = ironlake_get_refclk(crtc);
7334
7335         /*
7336          * Returns a set of divisors for the desired target clock with the given
7337          * refclk, or FALSE.  The returned values represent the clock equation:
7338          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
7339          */
7340         limit = intel_limit(intel_crtc, refclk);
7341         ret = dev_priv->display.find_dpll(limit, intel_crtc,
7342                                           crtc_state->port_clock,
7343                                           refclk, NULL, clock);
7344         if (!ret)
7345                 return false;
7346
7347         if (is_lvds && dev_priv->lvds_downclock_avail) {
7348                 /*
7349                  * Ensure we match the reduced clock's P to the target clock.
7350                  * If the clocks don't match, we can't switch the display clock
7351                  * by using the FP0/FP1. In such case we will disable the LVDS
7352                  * downclock feature.
7353                 */
7354                 *has_reduced_clock =
7355                         dev_priv->display.find_dpll(limit, intel_crtc,
7356                                                     dev_priv->lvds_downclock,
7357                                                     refclk, clock,
7358                                                     reduced_clock);
7359         }
7360
7361         return true;
7362 }
7363
7364 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
7365 {
7366         /*
7367          * Account for spread spectrum to avoid
7368          * oversubscribing the link. Max center spread
7369          * is 2.5%; use 5% for safety's sake.
7370          */
7371         u32 bps = target_clock * bpp * 21 / 20;
7372         return DIV_ROUND_UP(bps, link_bw * 8);
7373 }
7374
7375 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
7376 {
7377         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
7378 }
7379
7380 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
7381                                       struct intel_crtc_state *crtc_state,
7382                                       u32 *fp,
7383                                       intel_clock_t *reduced_clock, u32 *fp2)
7384 {
7385         struct drm_crtc *crtc = &intel_crtc->base;
7386         struct drm_device *dev = crtc->dev;
7387         struct drm_i915_private *dev_priv = dev->dev_private;
7388         struct intel_encoder *intel_encoder;
7389         uint32_t dpll;
7390         int factor, num_connectors = 0;
7391         bool is_lvds = false, is_sdvo = false;
7392
7393         for_each_intel_encoder(dev, intel_encoder) {
7394                 if (intel_encoder->new_crtc != to_intel_crtc(crtc))
7395                         continue;
7396
7397                 switch (intel_encoder->type) {
7398                 case INTEL_OUTPUT_LVDS:
7399                         is_lvds = true;
7400                         break;
7401                 case INTEL_OUTPUT_SDVO:
7402                 case INTEL_OUTPUT_HDMI:
7403                         is_sdvo = true;
7404                         break;
7405                 default:
7406                         break;
7407                 }
7408
7409                 num_connectors++;
7410         }
7411
7412         /* Enable autotuning of the PLL clock (if permissible) */
7413         factor = 21;
7414         if (is_lvds) {
7415                 if ((intel_panel_use_ssc(dev_priv) &&
7416                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
7417                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
7418                         factor = 25;
7419         } else if (crtc_state->sdvo_tv_clock)
7420                 factor = 20;
7421
7422         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
7423                 *fp |= FP_CB_TUNE;
7424
7425         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
7426                 *fp2 |= FP_CB_TUNE;
7427
7428         dpll = 0;
7429
7430         if (is_lvds)
7431                 dpll |= DPLLB_MODE_LVDS;
7432         else
7433                 dpll |= DPLLB_MODE_DAC_SERIAL;
7434
7435         dpll |= (crtc_state->pixel_multiplier - 1)
7436                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
7437
7438         if (is_sdvo)
7439                 dpll |= DPLL_SDVO_HIGH_SPEED;
7440         if (crtc_state->has_dp_encoder)
7441                 dpll |= DPLL_SDVO_HIGH_SPEED;
7442
7443         /* compute bitmask from p1 value */
7444         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7445         /* also FPA1 */
7446         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7447
7448         switch (crtc_state->dpll.p2) {
7449         case 5:
7450                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7451                 break;
7452         case 7:
7453                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7454                 break;
7455         case 10:
7456                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7457                 break;
7458         case 14:
7459                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7460                 break;
7461         }
7462
7463         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7464                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7465         else
7466                 dpll |= PLL_REF_INPUT_DREFCLK;
7467
7468         return dpll | DPLL_VCO_ENABLE;
7469 }
7470
7471 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
7472                                        struct intel_crtc_state *crtc_state)
7473 {
7474         struct drm_device *dev = crtc->base.dev;
7475         intel_clock_t clock, reduced_clock;
7476         u32 dpll = 0, fp = 0, fp2 = 0;
7477         bool ok, has_reduced_clock = false;
7478         bool is_lvds = false;
7479         struct intel_shared_dpll *pll;
7480
7481         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
7482
7483         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
7484              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
7485
7486         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
7487                                      &has_reduced_clock, &reduced_clock);
7488         if (!ok && !crtc_state->clock_set) {
7489                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7490                 return -EINVAL;
7491         }
7492         /* Compat-code for transition, will disappear. */
7493         if (!crtc_state->clock_set) {
7494                 crtc_state->dpll.n = clock.n;
7495                 crtc_state->dpll.m1 = clock.m1;
7496                 crtc_state->dpll.m2 = clock.m2;
7497                 crtc_state->dpll.p1 = clock.p1;
7498                 crtc_state->dpll.p2 = clock.p2;
7499         }
7500
7501         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
7502         if (crtc_state->has_pch_encoder) {
7503                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7504                 if (has_reduced_clock)
7505                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
7506
7507                 dpll = ironlake_compute_dpll(crtc, crtc_state,
7508                                              &fp, &reduced_clock,
7509                                              has_reduced_clock ? &fp2 : NULL);
7510
7511                 crtc_state->dpll_hw_state.dpll = dpll;
7512                 crtc_state->dpll_hw_state.fp0 = fp;
7513                 if (has_reduced_clock)
7514                         crtc_state->dpll_hw_state.fp1 = fp2;
7515                 else
7516                         crtc_state->dpll_hw_state.fp1 = fp;
7517
7518                 pll = intel_get_shared_dpll(crtc, crtc_state);
7519                 if (pll == NULL) {
7520                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
7521                                          pipe_name(crtc->pipe));
7522                         return -EINVAL;
7523                 }
7524         }
7525
7526         if (is_lvds && has_reduced_clock && i915.powersave)
7527                 crtc->lowfreq_avail = true;
7528         else
7529                 crtc->lowfreq_avail = false;
7530
7531         return 0;
7532 }
7533
7534 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
7535                                          struct intel_link_m_n *m_n)
7536 {
7537         struct drm_device *dev = crtc->base.dev;
7538         struct drm_i915_private *dev_priv = dev->dev_private;
7539         enum pipe pipe = crtc->pipe;
7540
7541         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
7542         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
7543         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
7544                 & ~TU_SIZE_MASK;
7545         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
7546         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
7547                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7548 }
7549
7550 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
7551                                          enum transcoder transcoder,
7552                                          struct intel_link_m_n *m_n,
7553                                          struct intel_link_m_n *m2_n2)
7554 {
7555         struct drm_device *dev = crtc->base.dev;
7556         struct drm_i915_private *dev_priv = dev->dev_private;
7557         enum pipe pipe = crtc->pipe;
7558
7559         if (INTEL_INFO(dev)->gen >= 5) {
7560                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
7561                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
7562                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
7563                         & ~TU_SIZE_MASK;
7564                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
7565                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
7566                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7567                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
7568                  * gen < 8) and if DRRS is supported (to make sure the
7569                  * registers are not unnecessarily read).
7570                  */
7571                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
7572                         crtc->config->has_drrs) {
7573                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
7574                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
7575                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
7576                                         & ~TU_SIZE_MASK;
7577                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
7578                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
7579                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7580                 }
7581         } else {
7582                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
7583                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
7584                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
7585                         & ~TU_SIZE_MASK;
7586                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
7587                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
7588                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7589         }
7590 }
7591
7592 void intel_dp_get_m_n(struct intel_crtc *crtc,
7593                       struct intel_crtc_state *pipe_config)
7594 {
7595         if (pipe_config->has_pch_encoder)
7596                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
7597         else
7598                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7599                                              &pipe_config->dp_m_n,
7600                                              &pipe_config->dp_m2_n2);
7601 }
7602
7603 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
7604                                         struct intel_crtc_state *pipe_config)
7605 {
7606         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7607                                      &pipe_config->fdi_m_n, NULL);
7608 }
7609
7610 static void skylake_get_pfit_config(struct intel_crtc *crtc,
7611                                     struct intel_crtc_state *pipe_config)
7612 {
7613         struct drm_device *dev = crtc->base.dev;
7614         struct drm_i915_private *dev_priv = dev->dev_private;
7615         uint32_t tmp;
7616
7617         tmp = I915_READ(PS_CTL(crtc->pipe));
7618
7619         if (tmp & PS_ENABLE) {
7620                 pipe_config->pch_pfit.enabled = true;
7621                 pipe_config->pch_pfit.pos = I915_READ(PS_WIN_POS(crtc->pipe));
7622                 pipe_config->pch_pfit.size = I915_READ(PS_WIN_SZ(crtc->pipe));
7623         }
7624 }
7625
7626 static void
7627 skylake_get_initial_plane_config(struct intel_crtc *crtc,
7628                                  struct intel_initial_plane_config *plane_config)
7629 {
7630         struct drm_device *dev = crtc->base.dev;
7631         struct drm_i915_private *dev_priv = dev->dev_private;
7632         u32 val, base, offset, stride_mult;
7633         int pipe = crtc->pipe;
7634         int fourcc, pixel_format;
7635         int aligned_height;
7636         struct drm_framebuffer *fb;
7637         struct intel_framebuffer *intel_fb;
7638
7639         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7640         if (!intel_fb) {
7641                 DRM_DEBUG_KMS("failed to alloc fb\n");
7642                 return;
7643         }
7644
7645         fb = &intel_fb->base;
7646
7647         val = I915_READ(PLANE_CTL(pipe, 0));
7648         if (val & PLANE_CTL_TILED_MASK)
7649                 plane_config->tiling = I915_TILING_X;
7650
7651         pixel_format = val & PLANE_CTL_FORMAT_MASK;
7652         fourcc = skl_format_to_fourcc(pixel_format,
7653                                       val & PLANE_CTL_ORDER_RGBX,
7654                                       val & PLANE_CTL_ALPHA_MASK);
7655         fb->pixel_format = fourcc;
7656         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7657
7658         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
7659         plane_config->base = base;
7660
7661         offset = I915_READ(PLANE_OFFSET(pipe, 0));
7662
7663         val = I915_READ(PLANE_SIZE(pipe, 0));
7664         fb->height = ((val >> 16) & 0xfff) + 1;
7665         fb->width = ((val >> 0) & 0x1fff) + 1;
7666
7667         val = I915_READ(PLANE_STRIDE(pipe, 0));
7668         switch (plane_config->tiling) {
7669         case I915_TILING_NONE:
7670                 stride_mult = 64;
7671                 break;
7672         case I915_TILING_X:
7673                 stride_mult = 512;
7674                 break;
7675         default:
7676                 MISSING_CASE(plane_config->tiling);
7677                 goto error;
7678         }
7679         fb->pitches[0] = (val & 0x3ff) * stride_mult;
7680
7681         aligned_height = intel_fb_align_height(dev, fb->height,
7682                                                plane_config->tiling);
7683
7684         plane_config->size = ALIGN(fb->pitches[0] * aligned_height, PAGE_SIZE);
7685
7686         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7687                       pipe_name(pipe), fb->width, fb->height,
7688                       fb->bits_per_pixel, base, fb->pitches[0],
7689                       plane_config->size);
7690
7691         crtc->base.primary->fb = fb;
7692         update_state_fb(crtc->base.primary);
7693         return;
7694
7695 error:
7696         kfree(fb);
7697 }
7698
7699 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
7700                                      struct intel_crtc_state *pipe_config)
7701 {
7702         struct drm_device *dev = crtc->base.dev;
7703         struct drm_i915_private *dev_priv = dev->dev_private;
7704         uint32_t tmp;
7705
7706         tmp = I915_READ(PF_CTL(crtc->pipe));
7707
7708         if (tmp & PF_ENABLE) {
7709                 pipe_config->pch_pfit.enabled = true;
7710                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
7711                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
7712
7713                 /* We currently do not free assignements of panel fitters on
7714                  * ivb/hsw (since we don't use the higher upscaling modes which
7715                  * differentiates them) so just WARN about this case for now. */
7716                 if (IS_GEN7(dev)) {
7717                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
7718                                 PF_PIPE_SEL_IVB(crtc->pipe));
7719                 }
7720         }
7721 }
7722
7723 static void
7724 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
7725                                   struct intel_initial_plane_config *plane_config)
7726 {
7727         struct drm_device *dev = crtc->base.dev;
7728         struct drm_i915_private *dev_priv = dev->dev_private;
7729         u32 val, base, offset;
7730         int pipe = crtc->pipe;
7731         int fourcc, pixel_format;
7732         int aligned_height;
7733         struct drm_framebuffer *fb;
7734         struct intel_framebuffer *intel_fb;
7735
7736         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7737         if (!intel_fb) {
7738                 DRM_DEBUG_KMS("failed to alloc fb\n");
7739                 return;
7740         }
7741
7742         fb = &intel_fb->base;
7743
7744         val = I915_READ(DSPCNTR(pipe));
7745
7746         if (INTEL_INFO(dev)->gen >= 4)
7747                 if (val & DISPPLANE_TILED)
7748                         plane_config->tiling = I915_TILING_X;
7749
7750         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7751         fourcc = i9xx_format_to_fourcc(pixel_format);
7752         fb->pixel_format = fourcc;
7753         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7754
7755         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
7756         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
7757                 offset = I915_READ(DSPOFFSET(pipe));
7758         } else {
7759                 if (plane_config->tiling)
7760                         offset = I915_READ(DSPTILEOFF(pipe));
7761                 else
7762                         offset = I915_READ(DSPLINOFF(pipe));
7763         }
7764         plane_config->base = base;
7765
7766         val = I915_READ(PIPESRC(pipe));
7767         fb->width = ((val >> 16) & 0xfff) + 1;
7768         fb->height = ((val >> 0) & 0xfff) + 1;
7769
7770         val = I915_READ(DSPSTRIDE(pipe));
7771         fb->pitches[0] = val & 0xffffffc0;
7772
7773         aligned_height = intel_fb_align_height(dev, fb->height,
7774                                                plane_config->tiling);
7775
7776         plane_config->size = PAGE_ALIGN(fb->pitches[0] * aligned_height);
7777
7778         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7779                       pipe_name(pipe), fb->width, fb->height,
7780                       fb->bits_per_pixel, base, fb->pitches[0],
7781                       plane_config->size);
7782
7783         crtc->base.primary->fb = fb;
7784         update_state_fb(crtc->base.primary);
7785 }
7786
7787 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
7788                                      struct intel_crtc_state *pipe_config)
7789 {
7790         struct drm_device *dev = crtc->base.dev;
7791         struct drm_i915_private *dev_priv = dev->dev_private;
7792         uint32_t tmp;
7793
7794         if (!intel_display_power_is_enabled(dev_priv,
7795                                             POWER_DOMAIN_PIPE(crtc->pipe)))
7796                 return false;
7797
7798         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7799         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7800
7801         tmp = I915_READ(PIPECONF(crtc->pipe));
7802         if (!(tmp & PIPECONF_ENABLE))
7803                 return false;
7804
7805         switch (tmp & PIPECONF_BPC_MASK) {
7806         case PIPECONF_6BPC:
7807                 pipe_config->pipe_bpp = 18;
7808                 break;
7809         case PIPECONF_8BPC:
7810                 pipe_config->pipe_bpp = 24;
7811                 break;
7812         case PIPECONF_10BPC:
7813                 pipe_config->pipe_bpp = 30;
7814                 break;
7815         case PIPECONF_12BPC:
7816                 pipe_config->pipe_bpp = 36;
7817                 break;
7818         default:
7819                 break;
7820         }
7821
7822         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
7823                 pipe_config->limited_color_range = true;
7824
7825         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
7826                 struct intel_shared_dpll *pll;
7827
7828                 pipe_config->has_pch_encoder = true;
7829
7830                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
7831                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
7832                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
7833
7834                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
7835
7836                 if (HAS_PCH_IBX(dev_priv->dev)) {
7837                         pipe_config->shared_dpll =
7838                                 (enum intel_dpll_id) crtc->pipe;
7839                 } else {
7840                         tmp = I915_READ(PCH_DPLL_SEL);
7841                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
7842                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
7843                         else
7844                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
7845                 }
7846
7847                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
7848
7849                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
7850                                            &pipe_config->dpll_hw_state));
7851
7852                 tmp = pipe_config->dpll_hw_state.dpll;
7853                 pipe_config->pixel_multiplier =
7854                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
7855                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
7856
7857                 ironlake_pch_clock_get(crtc, pipe_config);
7858         } else {
7859                 pipe_config->pixel_multiplier = 1;
7860         }
7861
7862         intel_get_pipe_timings(crtc, pipe_config);
7863
7864         ironlake_get_pfit_config(crtc, pipe_config);
7865
7866         return true;
7867 }
7868
7869 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
7870 {
7871         struct drm_device *dev = dev_priv->dev;
7872         struct intel_crtc *crtc;
7873
7874         for_each_intel_crtc(dev, crtc)
7875                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
7876                      pipe_name(crtc->pipe));
7877
7878         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
7879         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
7880         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
7881         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
7882         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
7883         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
7884              "CPU PWM1 enabled\n");
7885         if (IS_HASWELL(dev))
7886                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
7887                      "CPU PWM2 enabled\n");
7888         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
7889              "PCH PWM1 enabled\n");
7890         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
7891              "Utility pin enabled\n");
7892         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
7893
7894         /*
7895          * In theory we can still leave IRQs enabled, as long as only the HPD
7896          * interrupts remain enabled. We used to check for that, but since it's
7897          * gen-specific and since we only disable LCPLL after we fully disable
7898          * the interrupts, the check below should be enough.
7899          */
7900         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
7901 }
7902
7903 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
7904 {
7905         struct drm_device *dev = dev_priv->dev;
7906
7907         if (IS_HASWELL(dev))
7908                 return I915_READ(D_COMP_HSW);
7909         else
7910                 return I915_READ(D_COMP_BDW);
7911 }
7912
7913 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
7914 {
7915         struct drm_device *dev = dev_priv->dev;
7916
7917         if (IS_HASWELL(dev)) {
7918                 mutex_lock(&dev_priv->rps.hw_lock);
7919                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
7920                                             val))
7921                         DRM_ERROR("Failed to write to D_COMP\n");
7922                 mutex_unlock(&dev_priv->rps.hw_lock);
7923         } else {
7924                 I915_WRITE(D_COMP_BDW, val);
7925                 POSTING_READ(D_COMP_BDW);
7926         }
7927 }
7928
7929 /*
7930  * This function implements pieces of two sequences from BSpec:
7931  * - Sequence for display software to disable LCPLL
7932  * - Sequence for display software to allow package C8+
7933  * The steps implemented here are just the steps that actually touch the LCPLL
7934  * register. Callers should take care of disabling all the display engine
7935  * functions, doing the mode unset, fixing interrupts, etc.
7936  */
7937 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
7938                               bool switch_to_fclk, bool allow_power_down)
7939 {
7940         uint32_t val;
7941
7942         assert_can_disable_lcpll(dev_priv);
7943
7944         val = I915_READ(LCPLL_CTL);
7945
7946         if (switch_to_fclk) {
7947                 val |= LCPLL_CD_SOURCE_FCLK;
7948                 I915_WRITE(LCPLL_CTL, val);
7949
7950                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
7951                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
7952                         DRM_ERROR("Switching to FCLK failed\n");
7953
7954                 val = I915_READ(LCPLL_CTL);
7955         }
7956
7957         val |= LCPLL_PLL_DISABLE;
7958         I915_WRITE(LCPLL_CTL, val);
7959         POSTING_READ(LCPLL_CTL);
7960
7961         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
7962                 DRM_ERROR("LCPLL still locked\n");
7963
7964         val = hsw_read_dcomp(dev_priv);
7965         val |= D_COMP_COMP_DISABLE;
7966         hsw_write_dcomp(dev_priv, val);
7967         ndelay(100);
7968
7969         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
7970                      1))
7971                 DRM_ERROR("D_COMP RCOMP still in progress\n");
7972
7973         if (allow_power_down) {
7974                 val = I915_READ(LCPLL_CTL);
7975                 val |= LCPLL_POWER_DOWN_ALLOW;
7976                 I915_WRITE(LCPLL_CTL, val);
7977                 POSTING_READ(LCPLL_CTL);
7978         }
7979 }
7980
7981 /*
7982  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
7983  * source.
7984  */
7985 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
7986 {
7987         uint32_t val;
7988
7989         val = I915_READ(LCPLL_CTL);
7990
7991         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
7992                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
7993                 return;
7994
7995         /*
7996          * Make sure we're not on PC8 state before disabling PC8, otherwise
7997          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
7998          */
7999         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8000
8001         if (val & LCPLL_POWER_DOWN_ALLOW) {
8002                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8003                 I915_WRITE(LCPLL_CTL, val);
8004                 POSTING_READ(LCPLL_CTL);
8005         }
8006
8007         val = hsw_read_dcomp(dev_priv);
8008         val |= D_COMP_COMP_FORCE;
8009         val &= ~D_COMP_COMP_DISABLE;
8010         hsw_write_dcomp(dev_priv, val);
8011
8012         val = I915_READ(LCPLL_CTL);
8013         val &= ~LCPLL_PLL_DISABLE;
8014         I915_WRITE(LCPLL_CTL, val);
8015
8016         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
8017                 DRM_ERROR("LCPLL not locked yet\n");
8018
8019         if (val & LCPLL_CD_SOURCE_FCLK) {
8020                 val = I915_READ(LCPLL_CTL);
8021                 val &= ~LCPLL_CD_SOURCE_FCLK;
8022                 I915_WRITE(LCPLL_CTL, val);
8023
8024                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
8025                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8026                         DRM_ERROR("Switching back to LCPLL failed\n");
8027         }
8028
8029         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8030 }
8031
8032 /*
8033  * Package states C8 and deeper are really deep PC states that can only be
8034  * reached when all the devices on the system allow it, so even if the graphics
8035  * device allows PC8+, it doesn't mean the system will actually get to these
8036  * states. Our driver only allows PC8+ when going into runtime PM.
8037  *
8038  * The requirements for PC8+ are that all the outputs are disabled, the power
8039  * well is disabled and most interrupts are disabled, and these are also
8040  * requirements for runtime PM. When these conditions are met, we manually do
8041  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8042  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8043  * hang the machine.
8044  *
8045  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8046  * the state of some registers, so when we come back from PC8+ we need to
8047  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8048  * need to take care of the registers kept by RC6. Notice that this happens even
8049  * if we don't put the device in PCI D3 state (which is what currently happens
8050  * because of the runtime PM support).
8051  *
8052  * For more, read "Display Sequences for Package C8" on the hardware
8053  * documentation.
8054  */
8055 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8056 {
8057         struct drm_device *dev = dev_priv->dev;
8058         uint32_t val;
8059
8060         DRM_DEBUG_KMS("Enabling package C8+\n");
8061
8062         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
8063                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8064                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8065                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8066         }
8067
8068         lpt_disable_clkout_dp(dev);
8069         hsw_disable_lcpll(dev_priv, true, true);
8070 }
8071
8072 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8073 {
8074         struct drm_device *dev = dev_priv->dev;
8075         uint32_t val;
8076
8077         DRM_DEBUG_KMS("Disabling package C8+\n");
8078
8079         hsw_restore_lcpll(dev_priv);
8080         lpt_init_pch_refclk(dev);
8081
8082         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
8083                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8084                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
8085                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8086         }
8087
8088         intel_prepare_ddi(dev);
8089 }
8090
8091 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
8092                                       struct intel_crtc_state *crtc_state)
8093 {
8094         if (!intel_ddi_pll_select(crtc, crtc_state))
8095                 return -EINVAL;
8096
8097         crtc->lowfreq_avail = false;
8098
8099         return 0;
8100 }
8101
8102 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
8103                                 enum port port,
8104                                 struct intel_crtc_state *pipe_config)
8105 {
8106         u32 temp, dpll_ctl1;
8107
8108         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
8109         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
8110
8111         switch (pipe_config->ddi_pll_sel) {
8112         case SKL_DPLL0:
8113                 /*
8114                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
8115                  * of the shared DPLL framework and thus needs to be read out
8116                  * separately
8117                  */
8118                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
8119                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
8120                 break;
8121         case SKL_DPLL1:
8122                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
8123                 break;
8124         case SKL_DPLL2:
8125                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
8126                 break;
8127         case SKL_DPLL3:
8128                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
8129                 break;
8130         }
8131 }
8132
8133 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
8134                                 enum port port,
8135                                 struct intel_crtc_state *pipe_config)
8136 {
8137         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
8138
8139         switch (pipe_config->ddi_pll_sel) {
8140         case PORT_CLK_SEL_WRPLL1:
8141                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
8142                 break;
8143         case PORT_CLK_SEL_WRPLL2:
8144                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
8145                 break;
8146         }
8147 }
8148
8149 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
8150                                        struct intel_crtc_state *pipe_config)
8151 {
8152         struct drm_device *dev = crtc->base.dev;
8153         struct drm_i915_private *dev_priv = dev->dev_private;
8154         struct intel_shared_dpll *pll;
8155         enum port port;
8156         uint32_t tmp;
8157
8158         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
8159
8160         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
8161
8162         if (IS_SKYLAKE(dev))
8163                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
8164         else
8165                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
8166
8167         if (pipe_config->shared_dpll >= 0) {
8168                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
8169
8170                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
8171                                            &pipe_config->dpll_hw_state));
8172         }
8173
8174         /*
8175          * Haswell has only FDI/PCH transcoder A. It is which is connected to
8176          * DDI E. So just check whether this pipe is wired to DDI E and whether
8177          * the PCH transcoder is on.
8178          */
8179         if (INTEL_INFO(dev)->gen < 9 &&
8180             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
8181                 pipe_config->has_pch_encoder = true;
8182
8183                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
8184                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8185                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8186
8187                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8188         }
8189 }
8190
8191 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
8192                                     struct intel_crtc_state *pipe_config)
8193 {
8194         struct drm_device *dev = crtc->base.dev;
8195         struct drm_i915_private *dev_priv = dev->dev_private;
8196         enum intel_display_power_domain pfit_domain;
8197         uint32_t tmp;
8198
8199         if (!intel_display_power_is_enabled(dev_priv,
8200                                          POWER_DOMAIN_PIPE(crtc->pipe)))
8201                 return false;
8202
8203         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8204         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8205
8206         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
8207         if (tmp & TRANS_DDI_FUNC_ENABLE) {
8208                 enum pipe trans_edp_pipe;
8209                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
8210                 default:
8211                         WARN(1, "unknown pipe linked to edp transcoder\n");
8212                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
8213                 case TRANS_DDI_EDP_INPUT_A_ON:
8214                         trans_edp_pipe = PIPE_A;
8215                         break;
8216                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
8217                         trans_edp_pipe = PIPE_B;
8218                         break;
8219                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
8220                         trans_edp_pipe = PIPE_C;
8221                         break;
8222                 }
8223
8224                 if (trans_edp_pipe == crtc->pipe)
8225                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
8226         }
8227
8228         if (!intel_display_power_is_enabled(dev_priv,
8229                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
8230                 return false;
8231
8232         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
8233         if (!(tmp & PIPECONF_ENABLE))
8234                 return false;
8235
8236         haswell_get_ddi_port_state(crtc, pipe_config);
8237
8238         intel_get_pipe_timings(crtc, pipe_config);
8239
8240         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
8241         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
8242                 if (IS_SKYLAKE(dev))
8243                         skylake_get_pfit_config(crtc, pipe_config);
8244                 else
8245                         ironlake_get_pfit_config(crtc, pipe_config);
8246         }
8247
8248         if (IS_HASWELL(dev))
8249                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
8250                         (I915_READ(IPS_CTL) & IPS_ENABLE);
8251
8252         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
8253                 pipe_config->pixel_multiplier =
8254                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
8255         } else {
8256                 pipe_config->pixel_multiplier = 1;
8257         }
8258
8259         return true;
8260 }
8261
8262 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
8263 {
8264         struct drm_device *dev = crtc->dev;
8265         struct drm_i915_private *dev_priv = dev->dev_private;
8266         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8267         uint32_t cntl = 0, size = 0;
8268
8269         if (base) {
8270                 unsigned int width = intel_crtc->cursor_width;
8271                 unsigned int height = intel_crtc->cursor_height;
8272                 unsigned int stride = roundup_pow_of_two(width) * 4;
8273
8274                 switch (stride) {
8275                 default:
8276                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
8277                                   width, stride);
8278                         stride = 256;
8279                         /* fallthrough */
8280                 case 256:
8281                 case 512:
8282                 case 1024:
8283                 case 2048:
8284                         break;
8285                 }
8286
8287                 cntl |= CURSOR_ENABLE |
8288                         CURSOR_GAMMA_ENABLE |
8289                         CURSOR_FORMAT_ARGB |
8290                         CURSOR_STRIDE(stride);
8291
8292                 size = (height << 12) | width;
8293         }
8294
8295         if (intel_crtc->cursor_cntl != 0 &&
8296             (intel_crtc->cursor_base != base ||
8297              intel_crtc->cursor_size != size ||
8298              intel_crtc->cursor_cntl != cntl)) {
8299                 /* On these chipsets we can only modify the base/size/stride
8300                  * whilst the cursor is disabled.
8301                  */
8302                 I915_WRITE(_CURACNTR, 0);
8303                 POSTING_READ(_CURACNTR);
8304                 intel_crtc->cursor_cntl = 0;
8305         }
8306
8307         if (intel_crtc->cursor_base != base) {
8308                 I915_WRITE(_CURABASE, base);
8309                 intel_crtc->cursor_base = base;
8310         }
8311
8312         if (intel_crtc->cursor_size != size) {
8313                 I915_WRITE(CURSIZE, size);
8314                 intel_crtc->cursor_size = size;
8315         }
8316
8317         if (intel_crtc->cursor_cntl != cntl) {
8318                 I915_WRITE(_CURACNTR, cntl);
8319                 POSTING_READ(_CURACNTR);
8320                 intel_crtc->cursor_cntl = cntl;
8321         }
8322 }
8323
8324 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
8325 {
8326         struct drm_device *dev = crtc->dev;
8327         struct drm_i915_private *dev_priv = dev->dev_private;
8328         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8329         int pipe = intel_crtc->pipe;
8330         uint32_t cntl;
8331
8332         cntl = 0;
8333         if (base) {
8334                 cntl = MCURSOR_GAMMA_ENABLE;
8335                 switch (intel_crtc->cursor_width) {
8336                         case 64:
8337                                 cntl |= CURSOR_MODE_64_ARGB_AX;
8338                                 break;
8339                         case 128:
8340                                 cntl |= CURSOR_MODE_128_ARGB_AX;
8341                                 break;
8342                         case 256:
8343                                 cntl |= CURSOR_MODE_256_ARGB_AX;
8344                                 break;
8345                         default:
8346                                 MISSING_CASE(intel_crtc->cursor_width);
8347                                 return;
8348                 }
8349                 cntl |= pipe << 28; /* Connect to correct pipe */
8350
8351                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
8352                         cntl |= CURSOR_PIPE_CSC_ENABLE;
8353         }
8354
8355         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
8356                 cntl |= CURSOR_ROTATE_180;
8357
8358         if (intel_crtc->cursor_cntl != cntl) {
8359                 I915_WRITE(CURCNTR(pipe), cntl);
8360                 POSTING_READ(CURCNTR(pipe));
8361                 intel_crtc->cursor_cntl = cntl;
8362         }
8363
8364         /* and commit changes on next vblank */
8365         I915_WRITE(CURBASE(pipe), base);
8366         POSTING_READ(CURBASE(pipe));
8367
8368         intel_crtc->cursor_base = base;
8369 }
8370
8371 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
8372 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
8373                                      bool on)
8374 {
8375         struct drm_device *dev = crtc->dev;
8376         struct drm_i915_private *dev_priv = dev->dev_private;
8377         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8378         int pipe = intel_crtc->pipe;
8379         int x = crtc->cursor_x;
8380         int y = crtc->cursor_y;
8381         u32 base = 0, pos = 0;
8382
8383         if (on)
8384                 base = intel_crtc->cursor_addr;
8385
8386         if (x >= intel_crtc->config->pipe_src_w)
8387                 base = 0;
8388
8389         if (y >= intel_crtc->config->pipe_src_h)
8390                 base = 0;
8391
8392         if (x < 0) {
8393                 if (x + intel_crtc->cursor_width <= 0)
8394                         base = 0;
8395
8396                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
8397                 x = -x;
8398         }
8399         pos |= x << CURSOR_X_SHIFT;
8400
8401         if (y < 0) {
8402                 if (y + intel_crtc->cursor_height <= 0)
8403                         base = 0;
8404
8405                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
8406                 y = -y;
8407         }
8408         pos |= y << CURSOR_Y_SHIFT;
8409
8410         if (base == 0 && intel_crtc->cursor_base == 0)
8411                 return;
8412
8413         I915_WRITE(CURPOS(pipe), pos);
8414
8415         /* ILK+ do this automagically */
8416         if (HAS_GMCH_DISPLAY(dev) &&
8417             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
8418                 base += (intel_crtc->cursor_height *
8419                         intel_crtc->cursor_width - 1) * 4;
8420         }
8421
8422         if (IS_845G(dev) || IS_I865G(dev))
8423                 i845_update_cursor(crtc, base);
8424         else
8425                 i9xx_update_cursor(crtc, base);
8426 }
8427
8428 static bool cursor_size_ok(struct drm_device *dev,
8429                            uint32_t width, uint32_t height)
8430 {
8431         if (width == 0 || height == 0)
8432                 return false;
8433
8434         /*
8435          * 845g/865g are special in that they are only limited by
8436          * the width of their cursors, the height is arbitrary up to
8437          * the precision of the register. Everything else requires
8438          * square cursors, limited to a few power-of-two sizes.
8439          */
8440         if (IS_845G(dev) || IS_I865G(dev)) {
8441                 if ((width & 63) != 0)
8442                         return false;
8443
8444                 if (width > (IS_845G(dev) ? 64 : 512))
8445                         return false;
8446
8447                 if (height > 1023)
8448                         return false;
8449         } else {
8450                 switch (width | height) {
8451                 case 256:
8452                 case 128:
8453                         if (IS_GEN2(dev))
8454                                 return false;
8455                 case 64:
8456                         break;
8457                 default:
8458                         return false;
8459                 }
8460         }
8461
8462         return true;
8463 }
8464
8465 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
8466                                  u16 *blue, uint32_t start, uint32_t size)
8467 {
8468         int end = (start + size > 256) ? 256 : start + size, i;
8469         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8470
8471         for (i = start; i < end; i++) {
8472                 intel_crtc->lut_r[i] = red[i] >> 8;
8473                 intel_crtc->lut_g[i] = green[i] >> 8;
8474                 intel_crtc->lut_b[i] = blue[i] >> 8;
8475         }
8476
8477         intel_crtc_load_lut(crtc);
8478 }
8479
8480 /* VESA 640x480x72Hz mode to set on the pipe */
8481 static struct drm_display_mode load_detect_mode = {
8482         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
8483                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
8484 };
8485
8486 struct drm_framebuffer *
8487 __intel_framebuffer_create(struct drm_device *dev,
8488                            struct drm_mode_fb_cmd2 *mode_cmd,
8489                            struct drm_i915_gem_object *obj)
8490 {
8491         struct intel_framebuffer *intel_fb;
8492         int ret;
8493
8494         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8495         if (!intel_fb) {
8496                 drm_gem_object_unreference(&obj->base);
8497                 return ERR_PTR(-ENOMEM);
8498         }
8499
8500         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
8501         if (ret)
8502                 goto err;
8503
8504         return &intel_fb->base;
8505 err:
8506         drm_gem_object_unreference(&obj->base);
8507         kfree(intel_fb);
8508
8509         return ERR_PTR(ret);
8510 }
8511
8512 static struct drm_framebuffer *
8513 intel_framebuffer_create(struct drm_device *dev,
8514                          struct drm_mode_fb_cmd2 *mode_cmd,
8515                          struct drm_i915_gem_object *obj)
8516 {
8517         struct drm_framebuffer *fb;
8518         int ret;
8519
8520         ret = i915_mutex_lock_interruptible(dev);
8521         if (ret)
8522                 return ERR_PTR(ret);
8523         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
8524         mutex_unlock(&dev->struct_mutex);
8525
8526         return fb;
8527 }
8528
8529 static u32
8530 intel_framebuffer_pitch_for_width(int width, int bpp)
8531 {
8532         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
8533         return ALIGN(pitch, 64);
8534 }
8535
8536 static u32
8537 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
8538 {
8539         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
8540         return PAGE_ALIGN(pitch * mode->vdisplay);
8541 }
8542
8543 static struct drm_framebuffer *
8544 intel_framebuffer_create_for_mode(struct drm_device *dev,
8545                                   struct drm_display_mode *mode,
8546                                   int depth, int bpp)
8547 {
8548         struct drm_i915_gem_object *obj;
8549         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
8550
8551         obj = i915_gem_alloc_object(dev,
8552                                     intel_framebuffer_size_for_mode(mode, bpp));
8553         if (obj == NULL)
8554                 return ERR_PTR(-ENOMEM);
8555
8556         mode_cmd.width = mode->hdisplay;
8557         mode_cmd.height = mode->vdisplay;
8558         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
8559                                                                 bpp);
8560         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
8561
8562         return intel_framebuffer_create(dev, &mode_cmd, obj);
8563 }
8564
8565 static struct drm_framebuffer *
8566 mode_fits_in_fbdev(struct drm_device *dev,
8567                    struct drm_display_mode *mode)
8568 {
8569 #ifdef CONFIG_DRM_I915_FBDEV
8570         struct drm_i915_private *dev_priv = dev->dev_private;
8571         struct drm_i915_gem_object *obj;
8572         struct drm_framebuffer *fb;
8573
8574         if (!dev_priv->fbdev)
8575                 return NULL;
8576
8577         if (!dev_priv->fbdev->fb)
8578                 return NULL;
8579
8580         obj = dev_priv->fbdev->fb->obj;
8581         BUG_ON(!obj);
8582
8583         fb = &dev_priv->fbdev->fb->base;
8584         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
8585                                                                fb->bits_per_pixel))
8586                 return NULL;
8587
8588         if (obj->base.size < mode->vdisplay * fb->pitches[0])
8589                 return NULL;
8590
8591         return fb;
8592 #else
8593         return NULL;
8594 #endif
8595 }
8596
8597 bool intel_get_load_detect_pipe(struct drm_connector *connector,
8598                                 struct drm_display_mode *mode,
8599                                 struct intel_load_detect_pipe *old,
8600                                 struct drm_modeset_acquire_ctx *ctx)
8601 {
8602         struct intel_crtc *intel_crtc;
8603         struct intel_encoder *intel_encoder =
8604                 intel_attached_encoder(connector);
8605         struct drm_crtc *possible_crtc;
8606         struct drm_encoder *encoder = &intel_encoder->base;
8607         struct drm_crtc *crtc = NULL;
8608         struct drm_device *dev = encoder->dev;
8609         struct drm_framebuffer *fb;
8610         struct drm_mode_config *config = &dev->mode_config;
8611         int ret, i = -1;
8612
8613         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8614                       connector->base.id, connector->name,
8615                       encoder->base.id, encoder->name);
8616
8617 retry:
8618         ret = drm_modeset_lock(&config->connection_mutex, ctx);
8619         if (ret)
8620                 goto fail_unlock;
8621
8622         /*
8623          * Algorithm gets a little messy:
8624          *
8625          *   - if the connector already has an assigned crtc, use it (but make
8626          *     sure it's on first)
8627          *
8628          *   - try to find the first unused crtc that can drive this connector,
8629          *     and use that if we find one
8630          */
8631
8632         /* See if we already have a CRTC for this connector */
8633         if (encoder->crtc) {
8634                 crtc = encoder->crtc;
8635
8636                 ret = drm_modeset_lock(&crtc->mutex, ctx);
8637                 if (ret)
8638                         goto fail_unlock;
8639                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
8640                 if (ret)
8641                         goto fail_unlock;
8642
8643                 old->dpms_mode = connector->dpms;
8644                 old->load_detect_temp = false;
8645
8646                 /* Make sure the crtc and connector are running */
8647                 if (connector->dpms != DRM_MODE_DPMS_ON)
8648                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
8649
8650                 return true;
8651         }
8652
8653         /* Find an unused one (if possible) */
8654         for_each_crtc(dev, possible_crtc) {
8655                 i++;
8656                 if (!(encoder->possible_crtcs & (1 << i)))
8657                         continue;
8658                 if (possible_crtc->enabled)
8659                         continue;
8660                 /* This can occur when applying the pipe A quirk on resume. */
8661                 if (to_intel_crtc(possible_crtc)->new_enabled)
8662                         continue;
8663
8664                 crtc = possible_crtc;
8665                 break;
8666         }
8667
8668         /*
8669          * If we didn't find an unused CRTC, don't use any.
8670          */
8671         if (!crtc) {
8672                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
8673                 goto fail_unlock;
8674         }
8675
8676         ret = drm_modeset_lock(&crtc->mutex, ctx);
8677         if (ret)
8678                 goto fail_unlock;
8679         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
8680         if (ret)
8681                 goto fail_unlock;
8682         intel_encoder->new_crtc = to_intel_crtc(crtc);
8683         to_intel_connector(connector)->new_encoder = intel_encoder;
8684
8685         intel_crtc = to_intel_crtc(crtc);
8686         intel_crtc->new_enabled = true;
8687         intel_crtc->new_config = intel_crtc->config;
8688         old->dpms_mode = connector->dpms;
8689         old->load_detect_temp = true;
8690         old->release_fb = NULL;
8691
8692         if (!mode)
8693                 mode = &load_detect_mode;
8694
8695         /* We need a framebuffer large enough to accommodate all accesses
8696          * that the plane may generate whilst we perform load detection.
8697          * We can not rely on the fbcon either being present (we get called
8698          * during its initialisation to detect all boot displays, or it may
8699          * not even exist) or that it is large enough to satisfy the
8700          * requested mode.
8701          */
8702         fb = mode_fits_in_fbdev(dev, mode);
8703         if (fb == NULL) {
8704                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
8705                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
8706                 old->release_fb = fb;
8707         } else
8708                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
8709         if (IS_ERR(fb)) {
8710                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
8711                 goto fail;
8712         }
8713
8714         if (intel_set_mode(crtc, mode, 0, 0, fb)) {
8715                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
8716                 if (old->release_fb)
8717                         old->release_fb->funcs->destroy(old->release_fb);
8718                 goto fail;
8719         }
8720
8721         /* let the connector get through one full cycle before testing */
8722         intel_wait_for_vblank(dev, intel_crtc->pipe);
8723         return true;
8724
8725  fail:
8726         intel_crtc->new_enabled = crtc->enabled;
8727         if (intel_crtc->new_enabled)
8728                 intel_crtc->new_config = intel_crtc->config;
8729         else
8730                 intel_crtc->new_config = NULL;
8731 fail_unlock:
8732         if (ret == -EDEADLK) {
8733                 drm_modeset_backoff(ctx);
8734                 goto retry;
8735         }
8736
8737         return false;
8738 }
8739
8740 void intel_release_load_detect_pipe(struct drm_connector *connector,
8741                                     struct intel_load_detect_pipe *old)
8742 {
8743         struct intel_encoder *intel_encoder =
8744                 intel_attached_encoder(connector);
8745         struct drm_encoder *encoder = &intel_encoder->base;
8746         struct drm_crtc *crtc = encoder->crtc;
8747         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8748
8749         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8750                       connector->base.id, connector->name,
8751                       encoder->base.id, encoder->name);
8752
8753         if (old->load_detect_temp) {
8754                 to_intel_connector(connector)->new_encoder = NULL;
8755                 intel_encoder->new_crtc = NULL;
8756                 intel_crtc->new_enabled = false;
8757                 intel_crtc->new_config = NULL;
8758                 intel_set_mode(crtc, NULL, 0, 0, NULL);
8759
8760                 if (old->release_fb) {
8761                         drm_framebuffer_unregister_private(old->release_fb);
8762                         drm_framebuffer_unreference(old->release_fb);
8763                 }
8764
8765                 return;
8766         }
8767
8768         /* Switch crtc and encoder back off if necessary */
8769         if (old->dpms_mode != DRM_MODE_DPMS_ON)
8770                 connector->funcs->dpms(connector, old->dpms_mode);
8771 }
8772
8773 static int i9xx_pll_refclk(struct drm_device *dev,
8774                            const struct intel_crtc_state *pipe_config)
8775 {
8776         struct drm_i915_private *dev_priv = dev->dev_private;
8777         u32 dpll = pipe_config->dpll_hw_state.dpll;
8778
8779         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
8780                 return dev_priv->vbt.lvds_ssc_freq;
8781         else if (HAS_PCH_SPLIT(dev))
8782                 return 120000;
8783         else if (!IS_GEN2(dev))
8784                 return 96000;
8785         else
8786                 return 48000;
8787 }
8788
8789 /* Returns the clock of the currently programmed mode of the given pipe. */
8790 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
8791                                 struct intel_crtc_state *pipe_config)
8792 {
8793         struct drm_device *dev = crtc->base.dev;
8794         struct drm_i915_private *dev_priv = dev->dev_private;
8795         int pipe = pipe_config->cpu_transcoder;
8796         u32 dpll = pipe_config->dpll_hw_state.dpll;
8797         u32 fp;
8798         intel_clock_t clock;
8799         int refclk = i9xx_pll_refclk(dev, pipe_config);
8800
8801         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
8802                 fp = pipe_config->dpll_hw_state.fp0;
8803         else
8804                 fp = pipe_config->dpll_hw_state.fp1;
8805
8806         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
8807         if (IS_PINEVIEW(dev)) {
8808                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
8809                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
8810         } else {
8811                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
8812                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
8813         }
8814
8815         if (!IS_GEN2(dev)) {
8816                 if (IS_PINEVIEW(dev))
8817                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
8818                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
8819                 else
8820                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
8821                                DPLL_FPA01_P1_POST_DIV_SHIFT);
8822
8823                 switch (dpll & DPLL_MODE_MASK) {
8824                 case DPLLB_MODE_DAC_SERIAL:
8825                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
8826                                 5 : 10;
8827                         break;
8828                 case DPLLB_MODE_LVDS:
8829                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
8830                                 7 : 14;
8831                         break;
8832                 default:
8833                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
8834                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
8835                         return;
8836                 }
8837
8838                 if (IS_PINEVIEW(dev))
8839                         pineview_clock(refclk, &clock);
8840                 else
8841                         i9xx_clock(refclk, &clock);
8842         } else {
8843                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
8844                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
8845
8846                 if (is_lvds) {
8847                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
8848                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
8849
8850                         if (lvds & LVDS_CLKB_POWER_UP)
8851                                 clock.p2 = 7;
8852                         else
8853                                 clock.p2 = 14;
8854                 } else {
8855                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
8856                                 clock.p1 = 2;
8857                         else {
8858                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
8859                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
8860                         }
8861                         if (dpll & PLL_P2_DIVIDE_BY_4)
8862                                 clock.p2 = 4;
8863                         else
8864                                 clock.p2 = 2;
8865                 }
8866
8867                 i9xx_clock(refclk, &clock);
8868         }
8869
8870         /*
8871          * This value includes pixel_multiplier. We will use
8872          * port_clock to compute adjusted_mode.crtc_clock in the
8873          * encoder's get_config() function.
8874          */
8875         pipe_config->port_clock = clock.dot;
8876 }
8877
8878 int intel_dotclock_calculate(int link_freq,
8879                              const struct intel_link_m_n *m_n)
8880 {
8881         /*
8882          * The calculation for the data clock is:
8883          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
8884          * But we want to avoid losing precison if possible, so:
8885          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
8886          *
8887          * and the link clock is simpler:
8888          * link_clock = (m * link_clock) / n
8889          */
8890
8891         if (!m_n->link_n)
8892                 return 0;
8893
8894         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
8895 }
8896
8897 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
8898                                    struct intel_crtc_state *pipe_config)
8899 {
8900         struct drm_device *dev = crtc->base.dev;
8901
8902         /* read out port_clock from the DPLL */
8903         i9xx_crtc_clock_get(crtc, pipe_config);
8904
8905         /*
8906          * This value does not include pixel_multiplier.
8907          * We will check that port_clock and adjusted_mode.crtc_clock
8908          * agree once we know their relationship in the encoder's
8909          * get_config() function.
8910          */
8911         pipe_config->base.adjusted_mode.crtc_clock =
8912                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
8913                                          &pipe_config->fdi_m_n);
8914 }
8915
8916 /** Returns the currently programmed mode of the given pipe. */
8917 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
8918                                              struct drm_crtc *crtc)
8919 {
8920         struct drm_i915_private *dev_priv = dev->dev_private;
8921         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8922         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8923         struct drm_display_mode *mode;
8924         struct intel_crtc_state pipe_config;
8925         int htot = I915_READ(HTOTAL(cpu_transcoder));
8926         int hsync = I915_READ(HSYNC(cpu_transcoder));
8927         int vtot = I915_READ(VTOTAL(cpu_transcoder));
8928         int vsync = I915_READ(VSYNC(cpu_transcoder));
8929         enum pipe pipe = intel_crtc->pipe;
8930
8931         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
8932         if (!mode)
8933                 return NULL;
8934
8935         /*
8936          * Construct a pipe_config sufficient for getting the clock info
8937          * back out of crtc_clock_get.
8938          *
8939          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
8940          * to use a real value here instead.
8941          */
8942         pipe_config.cpu_transcoder = (enum transcoder) pipe;
8943         pipe_config.pixel_multiplier = 1;
8944         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
8945         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
8946         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
8947         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
8948
8949         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
8950         mode->hdisplay = (htot & 0xffff) + 1;
8951         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
8952         mode->hsync_start = (hsync & 0xffff) + 1;
8953         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
8954         mode->vdisplay = (vtot & 0xffff) + 1;
8955         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
8956         mode->vsync_start = (vsync & 0xffff) + 1;
8957         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
8958
8959         drm_mode_set_name(mode);
8960
8961         return mode;
8962 }
8963
8964 static void intel_decrease_pllclock(struct drm_crtc *crtc)
8965 {
8966         struct drm_device *dev = crtc->dev;
8967         struct drm_i915_private *dev_priv = dev->dev_private;
8968         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8969
8970         if (!HAS_GMCH_DISPLAY(dev))
8971                 return;
8972
8973         if (!dev_priv->lvds_downclock_avail)
8974                 return;
8975
8976         /*
8977          * Since this is called by a timer, we should never get here in
8978          * the manual case.
8979          */
8980         if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
8981                 int pipe = intel_crtc->pipe;
8982                 int dpll_reg = DPLL(pipe);
8983                 int dpll;
8984
8985                 DRM_DEBUG_DRIVER("downclocking LVDS\n");
8986
8987                 assert_panel_unlocked(dev_priv, pipe);
8988
8989                 dpll = I915_READ(dpll_reg);
8990                 dpll |= DISPLAY_RATE_SELECT_FPA1;
8991                 I915_WRITE(dpll_reg, dpll);
8992                 intel_wait_for_vblank(dev, pipe);
8993                 dpll = I915_READ(dpll_reg);
8994                 if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
8995                         DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
8996         }
8997
8998 }
8999
9000 void intel_mark_busy(struct drm_device *dev)
9001 {
9002         struct drm_i915_private *dev_priv = dev->dev_private;
9003
9004         if (dev_priv->mm.busy)
9005                 return;
9006
9007         intel_runtime_pm_get(dev_priv);
9008         i915_update_gfx_val(dev_priv);
9009         dev_priv->mm.busy = true;
9010 }
9011
9012 void intel_mark_idle(struct drm_device *dev)
9013 {
9014         struct drm_i915_private *dev_priv = dev->dev_private;
9015         struct drm_crtc *crtc;
9016
9017         if (!dev_priv->mm.busy)
9018                 return;
9019
9020         dev_priv->mm.busy = false;
9021
9022         if (!i915.powersave)
9023                 goto out;
9024
9025         for_each_crtc(dev, crtc) {
9026                 if (!crtc->primary->fb)
9027                         continue;
9028
9029                 intel_decrease_pllclock(crtc);
9030         }
9031
9032         if (INTEL_INFO(dev)->gen >= 6)
9033                 gen6_rps_idle(dev->dev_private);
9034
9035 out:
9036         intel_runtime_pm_put(dev_priv);
9037 }
9038
9039 static void intel_crtc_set_state(struct intel_crtc *crtc,
9040                                  struct intel_crtc_state *crtc_state)
9041 {
9042         kfree(crtc->config);
9043         crtc->config = crtc_state;
9044         crtc->base.state = &crtc_state->base;
9045 }
9046
9047 static void intel_crtc_destroy(struct drm_crtc *crtc)
9048 {
9049         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9050         struct drm_device *dev = crtc->dev;
9051         struct intel_unpin_work *work;
9052
9053         spin_lock_irq(&dev->event_lock);
9054         work = intel_crtc->unpin_work;
9055         intel_crtc->unpin_work = NULL;
9056         spin_unlock_irq(&dev->event_lock);
9057
9058         if (work) {
9059                 cancel_work_sync(&work->work);
9060                 kfree(work);
9061         }
9062
9063         intel_crtc_set_state(intel_crtc, NULL);
9064         drm_crtc_cleanup(crtc);
9065
9066         kfree(intel_crtc);
9067 }
9068
9069 static void intel_unpin_work_fn(struct work_struct *__work)
9070 {
9071         struct intel_unpin_work *work =
9072                 container_of(__work, struct intel_unpin_work, work);
9073         struct drm_device *dev = work->crtc->dev;
9074         enum pipe pipe = to_intel_crtc(work->crtc)->pipe;
9075
9076         mutex_lock(&dev->struct_mutex);
9077         intel_unpin_fb_obj(intel_fb_obj(work->old_fb));
9078         drm_gem_object_unreference(&work->pending_flip_obj->base);
9079         drm_framebuffer_unreference(work->old_fb);
9080
9081         intel_fbc_update(dev);
9082
9083         if (work->flip_queued_req)
9084                 i915_gem_request_assign(&work->flip_queued_req, NULL);
9085         mutex_unlock(&dev->struct_mutex);
9086
9087         intel_frontbuffer_flip_complete(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
9088
9089         BUG_ON(atomic_read(&to_intel_crtc(work->crtc)->unpin_work_count) == 0);
9090         atomic_dec(&to_intel_crtc(work->crtc)->unpin_work_count);
9091
9092         kfree(work);
9093 }
9094
9095 static void do_intel_finish_page_flip(struct drm_device *dev,
9096                                       struct drm_crtc *crtc)
9097 {
9098         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9099         struct intel_unpin_work *work;
9100         unsigned long flags;
9101
9102         /* Ignore early vblank irqs */
9103         if (intel_crtc == NULL)
9104                 return;
9105
9106         /*
9107          * This is called both by irq handlers and the reset code (to complete
9108          * lost pageflips) so needs the full irqsave spinlocks.
9109          */
9110         spin_lock_irqsave(&dev->event_lock, flags);
9111         work = intel_crtc->unpin_work;
9112
9113         /* Ensure we don't miss a work->pending update ... */
9114         smp_rmb();
9115
9116         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
9117                 spin_unlock_irqrestore(&dev->event_lock, flags);
9118                 return;
9119         }
9120
9121         page_flip_completed(intel_crtc);
9122
9123         spin_unlock_irqrestore(&dev->event_lock, flags);
9124 }
9125
9126 void intel_finish_page_flip(struct drm_device *dev, int pipe)
9127 {
9128         struct drm_i915_private *dev_priv = dev->dev_private;
9129         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
9130
9131         do_intel_finish_page_flip(dev, crtc);
9132 }
9133
9134 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
9135 {
9136         struct drm_i915_private *dev_priv = dev->dev_private;
9137         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
9138
9139         do_intel_finish_page_flip(dev, crtc);
9140 }
9141
9142 /* Is 'a' after or equal to 'b'? */
9143 static bool g4x_flip_count_after_eq(u32 a, u32 b)
9144 {
9145         return !((a - b) & 0x80000000);
9146 }
9147
9148 static bool page_flip_finished(struct intel_crtc *crtc)
9149 {
9150         struct drm_device *dev = crtc->base.dev;
9151         struct drm_i915_private *dev_priv = dev->dev_private;
9152
9153         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
9154             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
9155                 return true;
9156
9157         /*
9158          * The relevant registers doen't exist on pre-ctg.
9159          * As the flip done interrupt doesn't trigger for mmio
9160          * flips on gmch platforms, a flip count check isn't
9161          * really needed there. But since ctg has the registers,
9162          * include it in the check anyway.
9163          */
9164         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
9165                 return true;
9166
9167         /*
9168          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
9169          * used the same base address. In that case the mmio flip might
9170          * have completed, but the CS hasn't even executed the flip yet.
9171          *
9172          * A flip count check isn't enough as the CS might have updated
9173          * the base address just after start of vblank, but before we
9174          * managed to process the interrupt. This means we'd complete the
9175          * CS flip too soon.
9176          *
9177          * Combining both checks should get us a good enough result. It may
9178          * still happen that the CS flip has been executed, but has not
9179          * yet actually completed. But in case the base address is the same
9180          * anyway, we don't really care.
9181          */
9182         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
9183                 crtc->unpin_work->gtt_offset &&
9184                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
9185                                     crtc->unpin_work->flip_count);
9186 }
9187
9188 void intel_prepare_page_flip(struct drm_device *dev, int plane)
9189 {
9190         struct drm_i915_private *dev_priv = dev->dev_private;
9191         struct intel_crtc *intel_crtc =
9192                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
9193         unsigned long flags;
9194
9195
9196         /*
9197          * This is called both by irq handlers and the reset code (to complete
9198          * lost pageflips) so needs the full irqsave spinlocks.
9199          *
9200          * NB: An MMIO update of the plane base pointer will also
9201          * generate a page-flip completion irq, i.e. every modeset
9202          * is also accompanied by a spurious intel_prepare_page_flip().
9203          */
9204         spin_lock_irqsave(&dev->event_lock, flags);
9205         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
9206                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
9207         spin_unlock_irqrestore(&dev->event_lock, flags);
9208 }
9209
9210 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
9211 {
9212         /* Ensure that the work item is consistent when activating it ... */
9213         smp_wmb();
9214         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
9215         /* and that it is marked active as soon as the irq could fire. */
9216         smp_wmb();
9217 }
9218
9219 static int intel_gen2_queue_flip(struct drm_device *dev,
9220                                  struct drm_crtc *crtc,
9221                                  struct drm_framebuffer *fb,
9222                                  struct drm_i915_gem_object *obj,
9223                                  struct intel_engine_cs *ring,
9224                                  uint32_t flags)
9225 {
9226         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9227         u32 flip_mask;
9228         int ret;
9229
9230         ret = intel_ring_begin(ring, 6);
9231         if (ret)
9232                 return ret;
9233
9234         /* Can't queue multiple flips, so wait for the previous
9235          * one to finish before executing the next.
9236          */
9237         if (intel_crtc->plane)
9238                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
9239         else
9240                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
9241         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
9242         intel_ring_emit(ring, MI_NOOP);
9243         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9244                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9245         intel_ring_emit(ring, fb->pitches[0]);
9246         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9247         intel_ring_emit(ring, 0); /* aux display base address, unused */
9248
9249         intel_mark_page_flip_active(intel_crtc);
9250         __intel_ring_advance(ring);
9251         return 0;
9252 }
9253
9254 static int intel_gen3_queue_flip(struct drm_device *dev,
9255                                  struct drm_crtc *crtc,
9256                                  struct drm_framebuffer *fb,
9257                                  struct drm_i915_gem_object *obj,
9258                                  struct intel_engine_cs *ring,
9259                                  uint32_t flags)
9260 {
9261         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9262         u32 flip_mask;
9263         int ret;
9264
9265         ret = intel_ring_begin(ring, 6);
9266         if (ret)
9267                 return ret;
9268
9269         if (intel_crtc->plane)
9270                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
9271         else
9272                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
9273         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
9274         intel_ring_emit(ring, MI_NOOP);
9275         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
9276                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9277         intel_ring_emit(ring, fb->pitches[0]);
9278         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9279         intel_ring_emit(ring, MI_NOOP);
9280
9281         intel_mark_page_flip_active(intel_crtc);
9282         __intel_ring_advance(ring);
9283         return 0;
9284 }
9285
9286 static int intel_gen4_queue_flip(struct drm_device *dev,
9287                                  struct drm_crtc *crtc,
9288                                  struct drm_framebuffer *fb,
9289                                  struct drm_i915_gem_object *obj,
9290                                  struct intel_engine_cs *ring,
9291                                  uint32_t flags)
9292 {
9293         struct drm_i915_private *dev_priv = dev->dev_private;
9294         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9295         uint32_t pf, pipesrc;
9296         int ret;
9297
9298         ret = intel_ring_begin(ring, 4);
9299         if (ret)
9300                 return ret;
9301
9302         /* i965+ uses the linear or tiled offsets from the
9303          * Display Registers (which do not change across a page-flip)
9304          * so we need only reprogram the base address.
9305          */
9306         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9307                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9308         intel_ring_emit(ring, fb->pitches[0]);
9309         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
9310                         obj->tiling_mode);
9311
9312         /* XXX Enabling the panel-fitter across page-flip is so far
9313          * untested on non-native modes, so ignore it for now.
9314          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
9315          */
9316         pf = 0;
9317         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9318         intel_ring_emit(ring, pf | pipesrc);
9319
9320         intel_mark_page_flip_active(intel_crtc);
9321         __intel_ring_advance(ring);
9322         return 0;
9323 }
9324
9325 static int intel_gen6_queue_flip(struct drm_device *dev,
9326                                  struct drm_crtc *crtc,
9327                                  struct drm_framebuffer *fb,
9328                                  struct drm_i915_gem_object *obj,
9329                                  struct intel_engine_cs *ring,
9330                                  uint32_t flags)
9331 {
9332         struct drm_i915_private *dev_priv = dev->dev_private;
9333         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9334         uint32_t pf, pipesrc;
9335         int ret;
9336
9337         ret = intel_ring_begin(ring, 4);
9338         if (ret)
9339                 return ret;
9340
9341         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9342                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9343         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
9344         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9345
9346         /* Contrary to the suggestions in the documentation,
9347          * "Enable Panel Fitter" does not seem to be required when page
9348          * flipping with a non-native mode, and worse causes a normal
9349          * modeset to fail.
9350          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
9351          */
9352         pf = 0;
9353         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9354         intel_ring_emit(ring, pf | pipesrc);
9355
9356         intel_mark_page_flip_active(intel_crtc);
9357         __intel_ring_advance(ring);
9358         return 0;
9359 }
9360
9361 static int intel_gen7_queue_flip(struct drm_device *dev,
9362                                  struct drm_crtc *crtc,
9363                                  struct drm_framebuffer *fb,
9364                                  struct drm_i915_gem_object *obj,
9365                                  struct intel_engine_cs *ring,
9366                                  uint32_t flags)
9367 {
9368         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9369         uint32_t plane_bit = 0;
9370         int len, ret;
9371
9372         switch (intel_crtc->plane) {
9373         case PLANE_A:
9374                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
9375                 break;
9376         case PLANE_B:
9377                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
9378                 break;
9379         case PLANE_C:
9380                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
9381                 break;
9382         default:
9383                 WARN_ONCE(1, "unknown plane in flip command\n");
9384                 return -ENODEV;
9385         }
9386
9387         len = 4;
9388         if (ring->id == RCS) {
9389                 len += 6;
9390                 /*
9391                  * On Gen 8, SRM is now taking an extra dword to accommodate
9392                  * 48bits addresses, and we need a NOOP for the batch size to
9393                  * stay even.
9394                  */
9395                 if (IS_GEN8(dev))
9396                         len += 2;
9397         }
9398
9399         /*
9400          * BSpec MI_DISPLAY_FLIP for IVB:
9401          * "The full packet must be contained within the same cache line."
9402          *
9403          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
9404          * cacheline, if we ever start emitting more commands before
9405          * the MI_DISPLAY_FLIP we may need to first emit everything else,
9406          * then do the cacheline alignment, and finally emit the
9407          * MI_DISPLAY_FLIP.
9408          */
9409         ret = intel_ring_cacheline_align(ring);
9410         if (ret)
9411                 return ret;
9412
9413         ret = intel_ring_begin(ring, len);
9414         if (ret)
9415                 return ret;
9416
9417         /* Unmask the flip-done completion message. Note that the bspec says that
9418          * we should do this for both the BCS and RCS, and that we must not unmask
9419          * more than one flip event at any time (or ensure that one flip message
9420          * can be sent by waiting for flip-done prior to queueing new flips).
9421          * Experimentation says that BCS works despite DERRMR masking all
9422          * flip-done completion events and that unmasking all planes at once
9423          * for the RCS also doesn't appear to drop events. Setting the DERRMR
9424          * to zero does lead to lockups within MI_DISPLAY_FLIP.
9425          */
9426         if (ring->id == RCS) {
9427                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
9428                 intel_ring_emit(ring, DERRMR);
9429                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
9430                                         DERRMR_PIPEB_PRI_FLIP_DONE |
9431                                         DERRMR_PIPEC_PRI_FLIP_DONE));
9432                 if (IS_GEN8(dev))
9433                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
9434                                               MI_SRM_LRM_GLOBAL_GTT);
9435                 else
9436                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
9437                                               MI_SRM_LRM_GLOBAL_GTT);
9438                 intel_ring_emit(ring, DERRMR);
9439                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
9440                 if (IS_GEN8(dev)) {
9441                         intel_ring_emit(ring, 0);
9442                         intel_ring_emit(ring, MI_NOOP);
9443                 }
9444         }
9445
9446         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
9447         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
9448         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9449         intel_ring_emit(ring, (MI_NOOP));
9450
9451         intel_mark_page_flip_active(intel_crtc);
9452         __intel_ring_advance(ring);
9453         return 0;
9454 }
9455
9456 static bool use_mmio_flip(struct intel_engine_cs *ring,
9457                           struct drm_i915_gem_object *obj)
9458 {
9459         /*
9460          * This is not being used for older platforms, because
9461          * non-availability of flip done interrupt forces us to use
9462          * CS flips. Older platforms derive flip done using some clever
9463          * tricks involving the flip_pending status bits and vblank irqs.
9464          * So using MMIO flips there would disrupt this mechanism.
9465          */
9466
9467         if (ring == NULL)
9468                 return true;
9469
9470         if (INTEL_INFO(ring->dev)->gen < 5)
9471                 return false;
9472
9473         if (i915.use_mmio_flip < 0)
9474                 return false;
9475         else if (i915.use_mmio_flip > 0)
9476                 return true;
9477         else if (i915.enable_execlists)
9478                 return true;
9479         else
9480                 return ring != i915_gem_request_get_ring(obj->last_read_req);
9481 }
9482
9483 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
9484 {
9485         struct drm_device *dev = intel_crtc->base.dev;
9486         struct drm_i915_private *dev_priv = dev->dev_private;
9487         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
9488         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
9489         struct drm_i915_gem_object *obj = intel_fb->obj;
9490         const enum pipe pipe = intel_crtc->pipe;
9491         u32 ctl, stride;
9492
9493         ctl = I915_READ(PLANE_CTL(pipe, 0));
9494         ctl &= ~PLANE_CTL_TILED_MASK;
9495         if (obj->tiling_mode == I915_TILING_X)
9496                 ctl |= PLANE_CTL_TILED_X;
9497
9498         /*
9499          * The stride is either expressed as a multiple of 64 bytes chunks for
9500          * linear buffers or in number of tiles for tiled buffers.
9501          */
9502         stride = fb->pitches[0] >> 6;
9503         if (obj->tiling_mode == I915_TILING_X)
9504                 stride = fb->pitches[0] >> 9; /* X tiles are 512 bytes wide */
9505
9506         /*
9507          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
9508          * PLANE_SURF updates, the update is then guaranteed to be atomic.
9509          */
9510         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
9511         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
9512
9513         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
9514         POSTING_READ(PLANE_SURF(pipe, 0));
9515 }
9516
9517 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
9518 {
9519         struct drm_device *dev = intel_crtc->base.dev;
9520         struct drm_i915_private *dev_priv = dev->dev_private;
9521         struct intel_framebuffer *intel_fb =
9522                 to_intel_framebuffer(intel_crtc->base.primary->fb);
9523         struct drm_i915_gem_object *obj = intel_fb->obj;
9524         u32 dspcntr;
9525         u32 reg;
9526
9527         reg = DSPCNTR(intel_crtc->plane);
9528         dspcntr = I915_READ(reg);
9529
9530         if (obj->tiling_mode != I915_TILING_NONE)
9531                 dspcntr |= DISPPLANE_TILED;
9532         else
9533                 dspcntr &= ~DISPPLANE_TILED;
9534
9535         I915_WRITE(reg, dspcntr);
9536
9537         I915_WRITE(DSPSURF(intel_crtc->plane),
9538                    intel_crtc->unpin_work->gtt_offset);
9539         POSTING_READ(DSPSURF(intel_crtc->plane));
9540
9541 }
9542
9543 /*
9544  * XXX: This is the temporary way to update the plane registers until we get
9545  * around to using the usual plane update functions for MMIO flips
9546  */
9547 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
9548 {
9549         struct drm_device *dev = intel_crtc->base.dev;
9550         bool atomic_update;
9551         u32 start_vbl_count;
9552
9553         intel_mark_page_flip_active(intel_crtc);
9554
9555         atomic_update = intel_pipe_update_start(intel_crtc, &start_vbl_count);
9556
9557         if (INTEL_INFO(dev)->gen >= 9)
9558                 skl_do_mmio_flip(intel_crtc);
9559         else
9560                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
9561                 ilk_do_mmio_flip(intel_crtc);
9562
9563         if (atomic_update)
9564                 intel_pipe_update_end(intel_crtc, start_vbl_count);
9565 }
9566
9567 static void intel_mmio_flip_work_func(struct work_struct *work)
9568 {
9569         struct intel_crtc *crtc =
9570                 container_of(work, struct intel_crtc, mmio_flip.work);
9571         struct intel_mmio_flip *mmio_flip;
9572
9573         mmio_flip = &crtc->mmio_flip;
9574         if (mmio_flip->req)
9575                 WARN_ON(__i915_wait_request(mmio_flip->req,
9576                                             crtc->reset_counter,
9577                                             false, NULL, NULL) != 0);
9578
9579         intel_do_mmio_flip(crtc);
9580         if (mmio_flip->req) {
9581                 mutex_lock(&crtc->base.dev->struct_mutex);
9582                 i915_gem_request_assign(&mmio_flip->req, NULL);
9583                 mutex_unlock(&crtc->base.dev->struct_mutex);
9584         }
9585 }
9586
9587 static int intel_queue_mmio_flip(struct drm_device *dev,
9588                                  struct drm_crtc *crtc,
9589                                  struct drm_framebuffer *fb,
9590                                  struct drm_i915_gem_object *obj,
9591                                  struct intel_engine_cs *ring,
9592                                  uint32_t flags)
9593 {
9594         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9595
9596         i915_gem_request_assign(&intel_crtc->mmio_flip.req,
9597                                 obj->last_write_req);
9598
9599         schedule_work(&intel_crtc->mmio_flip.work);
9600
9601         return 0;
9602 }
9603
9604 static int intel_gen9_queue_flip(struct drm_device *dev,
9605                                  struct drm_crtc *crtc,
9606                                  struct drm_framebuffer *fb,
9607                                  struct drm_i915_gem_object *obj,
9608                                  struct intel_engine_cs *ring,
9609                                  uint32_t flags)
9610 {
9611         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9612         uint32_t plane = 0, stride;
9613         int ret;
9614
9615         switch(intel_crtc->pipe) {
9616         case PIPE_A:
9617                 plane = MI_DISPLAY_FLIP_SKL_PLANE_1_A;
9618                 break;
9619         case PIPE_B:
9620                 plane = MI_DISPLAY_FLIP_SKL_PLANE_1_B;
9621                 break;
9622         case PIPE_C:
9623                 plane = MI_DISPLAY_FLIP_SKL_PLANE_1_C;
9624                 break;
9625         default:
9626                 WARN_ONCE(1, "unknown plane in flip command\n");
9627                 return -ENODEV;
9628         }
9629
9630         switch (obj->tiling_mode) {
9631         case I915_TILING_NONE:
9632                 stride = fb->pitches[0] >> 6;
9633                 break;
9634         case I915_TILING_X:
9635                 stride = fb->pitches[0] >> 9;
9636                 break;
9637         default:
9638                 WARN_ONCE(1, "unknown tiling in flip command\n");
9639                 return -ENODEV;
9640         }
9641
9642         ret = intel_ring_begin(ring, 10);
9643         if (ret)
9644                 return ret;
9645
9646         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
9647         intel_ring_emit(ring, DERRMR);
9648         intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
9649                                 DERRMR_PIPEB_PRI_FLIP_DONE |
9650                                 DERRMR_PIPEC_PRI_FLIP_DONE));
9651         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
9652                               MI_SRM_LRM_GLOBAL_GTT);
9653         intel_ring_emit(ring, DERRMR);
9654         intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
9655         intel_ring_emit(ring, 0);
9656
9657         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane);
9658         intel_ring_emit(ring, stride << 6 | obj->tiling_mode);
9659         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9660
9661         intel_mark_page_flip_active(intel_crtc);
9662         __intel_ring_advance(ring);
9663
9664         return 0;
9665 }
9666
9667 static int intel_default_queue_flip(struct drm_device *dev,
9668                                     struct drm_crtc *crtc,
9669                                     struct drm_framebuffer *fb,
9670                                     struct drm_i915_gem_object *obj,
9671                                     struct intel_engine_cs *ring,
9672                                     uint32_t flags)
9673 {
9674         return -ENODEV;
9675 }
9676
9677 static bool __intel_pageflip_stall_check(struct drm_device *dev,
9678                                          struct drm_crtc *crtc)
9679 {
9680         struct drm_i915_private *dev_priv = dev->dev_private;
9681         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9682         struct intel_unpin_work *work = intel_crtc->unpin_work;
9683         u32 addr;
9684
9685         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
9686                 return true;
9687
9688         if (!work->enable_stall_check)
9689                 return false;
9690
9691         if (work->flip_ready_vblank == 0) {
9692                 if (work->flip_queued_req &&
9693                     !i915_gem_request_completed(work->flip_queued_req, true))
9694                         return false;
9695
9696                 work->flip_ready_vblank = drm_vblank_count(dev, intel_crtc->pipe);
9697         }
9698
9699         if (drm_vblank_count(dev, intel_crtc->pipe) - work->flip_ready_vblank < 3)
9700                 return false;
9701
9702         /* Potential stall - if we see that the flip has happened,
9703          * assume a missed interrupt. */
9704         if (INTEL_INFO(dev)->gen >= 4)
9705                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
9706         else
9707                 addr = I915_READ(DSPADDR(intel_crtc->plane));
9708
9709         /* There is a potential issue here with a false positive after a flip
9710          * to the same address. We could address this by checking for a
9711          * non-incrementing frame counter.
9712          */
9713         return addr == work->gtt_offset;
9714 }
9715
9716 void intel_check_page_flip(struct drm_device *dev, int pipe)
9717 {
9718         struct drm_i915_private *dev_priv = dev->dev_private;
9719         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
9720         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9721
9722         WARN_ON(!in_irq());
9723
9724         if (crtc == NULL)
9725                 return;
9726
9727         spin_lock(&dev->event_lock);
9728         if (intel_crtc->unpin_work && __intel_pageflip_stall_check(dev, crtc)) {
9729                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
9730                          intel_crtc->unpin_work->flip_queued_vblank, drm_vblank_count(dev, pipe));
9731                 page_flip_completed(intel_crtc);
9732         }
9733         spin_unlock(&dev->event_lock);
9734 }
9735
9736 static int intel_crtc_page_flip(struct drm_crtc *crtc,
9737                                 struct drm_framebuffer *fb,
9738                                 struct drm_pending_vblank_event *event,
9739                                 uint32_t page_flip_flags)
9740 {
9741         struct drm_device *dev = crtc->dev;
9742         struct drm_i915_private *dev_priv = dev->dev_private;
9743         struct drm_framebuffer *old_fb = crtc->primary->fb;
9744         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9745         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9746         struct drm_plane *primary = crtc->primary;
9747         enum pipe pipe = intel_crtc->pipe;
9748         struct intel_unpin_work *work;
9749         struct intel_engine_cs *ring;
9750         int ret;
9751
9752         /*
9753          * drm_mode_page_flip_ioctl() should already catch this, but double
9754          * check to be safe.  In the future we may enable pageflipping from
9755          * a disabled primary plane.
9756          */
9757         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
9758                 return -EBUSY;
9759
9760         /* Can't change pixel format via MI display flips. */
9761         if (fb->pixel_format != crtc->primary->fb->pixel_format)
9762                 return -EINVAL;
9763
9764         /*
9765          * TILEOFF/LINOFF registers can't be changed via MI display flips.
9766          * Note that pitch changes could also affect these register.
9767          */
9768         if (INTEL_INFO(dev)->gen > 3 &&
9769             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
9770              fb->pitches[0] != crtc->primary->fb->pitches[0]))
9771                 return -EINVAL;
9772
9773         if (i915_terminally_wedged(&dev_priv->gpu_error))
9774                 goto out_hang;
9775
9776         work = kzalloc(sizeof(*work), GFP_KERNEL);
9777         if (work == NULL)
9778                 return -ENOMEM;
9779
9780         work->event = event;
9781         work->crtc = crtc;
9782         work->old_fb = old_fb;
9783         INIT_WORK(&work->work, intel_unpin_work_fn);
9784
9785         ret = drm_crtc_vblank_get(crtc);
9786         if (ret)
9787                 goto free_work;
9788
9789         /* We borrow the event spin lock for protecting unpin_work */
9790         spin_lock_irq(&dev->event_lock);
9791         if (intel_crtc->unpin_work) {
9792                 /* Before declaring the flip queue wedged, check if
9793                  * the hardware completed the operation behind our backs.
9794                  */
9795                 if (__intel_pageflip_stall_check(dev, crtc)) {
9796                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
9797                         page_flip_completed(intel_crtc);
9798                 } else {
9799                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
9800                         spin_unlock_irq(&dev->event_lock);
9801
9802                         drm_crtc_vblank_put(crtc);
9803                         kfree(work);
9804                         return -EBUSY;
9805                 }
9806         }
9807         intel_crtc->unpin_work = work;
9808         spin_unlock_irq(&dev->event_lock);
9809
9810         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
9811                 flush_workqueue(dev_priv->wq);
9812
9813         ret = i915_mutex_lock_interruptible(dev);
9814         if (ret)
9815                 goto cleanup;
9816
9817         /* Reference the objects for the scheduled work. */
9818         drm_framebuffer_reference(work->old_fb);
9819         drm_gem_object_reference(&obj->base);
9820
9821         crtc->primary->fb = fb;
9822         update_state_fb(crtc->primary);
9823
9824         work->pending_flip_obj = obj;
9825
9826         atomic_inc(&intel_crtc->unpin_work_count);
9827         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
9828
9829         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
9830                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
9831
9832         if (IS_VALLEYVIEW(dev)) {
9833                 ring = &dev_priv->ring[BCS];
9834                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
9835                         /* vlv: DISPLAY_FLIP fails to change tiling */
9836                         ring = NULL;
9837         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
9838                 ring = &dev_priv->ring[BCS];
9839         } else if (INTEL_INFO(dev)->gen >= 7) {
9840                 ring = i915_gem_request_get_ring(obj->last_read_req);
9841                 if (ring == NULL || ring->id != RCS)
9842                         ring = &dev_priv->ring[BCS];
9843         } else {
9844                 ring = &dev_priv->ring[RCS];
9845         }
9846
9847         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb, ring);
9848         if (ret)
9849                 goto cleanup_pending;
9850
9851         work->gtt_offset =
9852                 i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset;
9853
9854         if (use_mmio_flip(ring, obj)) {
9855                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
9856                                             page_flip_flags);
9857                 if (ret)
9858                         goto cleanup_unpin;
9859
9860                 i915_gem_request_assign(&work->flip_queued_req,
9861                                         obj->last_write_req);
9862         } else {
9863                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, ring,
9864                                                    page_flip_flags);
9865                 if (ret)
9866                         goto cleanup_unpin;
9867
9868                 i915_gem_request_assign(&work->flip_queued_req,
9869                                         intel_ring_get_request(ring));
9870         }
9871
9872         work->flip_queued_vblank = drm_vblank_count(dev, intel_crtc->pipe);
9873         work->enable_stall_check = true;
9874
9875         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
9876                           INTEL_FRONTBUFFER_PRIMARY(pipe));
9877
9878         intel_fbc_disable(dev);
9879         intel_frontbuffer_flip_prepare(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
9880         mutex_unlock(&dev->struct_mutex);
9881
9882         trace_i915_flip_request(intel_crtc->plane, obj);
9883
9884         return 0;
9885
9886 cleanup_unpin:
9887         intel_unpin_fb_obj(obj);
9888 cleanup_pending:
9889         atomic_dec(&intel_crtc->unpin_work_count);
9890         crtc->primary->fb = old_fb;
9891         update_state_fb(crtc->primary);
9892         drm_framebuffer_unreference(work->old_fb);
9893         drm_gem_object_unreference(&obj->base);
9894         mutex_unlock(&dev->struct_mutex);
9895
9896 cleanup:
9897         spin_lock_irq(&dev->event_lock);
9898         intel_crtc->unpin_work = NULL;
9899         spin_unlock_irq(&dev->event_lock);
9900
9901         drm_crtc_vblank_put(crtc);
9902 free_work:
9903         kfree(work);
9904
9905         if (ret == -EIO) {
9906 out_hang:
9907                 ret = intel_plane_restore(primary);
9908                 if (ret == 0 && event) {
9909                         spin_lock_irq(&dev->event_lock);
9910                         drm_send_vblank_event(dev, pipe, event);
9911                         spin_unlock_irq(&dev->event_lock);
9912                 }
9913         }
9914         return ret;
9915 }
9916
9917 static struct drm_crtc_helper_funcs intel_helper_funcs = {
9918         .mode_set_base_atomic = intel_pipe_set_base_atomic,
9919         .load_lut = intel_crtc_load_lut,
9920         .atomic_begin = intel_begin_crtc_commit,
9921         .atomic_flush = intel_finish_crtc_commit,
9922 };
9923
9924 /**
9925  * intel_modeset_update_staged_output_state
9926  *
9927  * Updates the staged output configuration state, e.g. after we've read out the
9928  * current hw state.
9929  */
9930 static void intel_modeset_update_staged_output_state(struct drm_device *dev)
9931 {
9932         struct intel_crtc *crtc;
9933         struct intel_encoder *encoder;
9934         struct intel_connector *connector;
9935
9936         list_for_each_entry(connector, &dev->mode_config.connector_list,
9937                             base.head) {
9938                 connector->new_encoder =
9939                         to_intel_encoder(connector->base.encoder);
9940         }
9941
9942         for_each_intel_encoder(dev, encoder) {
9943                 encoder->new_crtc =
9944                         to_intel_crtc(encoder->base.crtc);
9945         }
9946
9947         for_each_intel_crtc(dev, crtc) {
9948                 crtc->new_enabled = crtc->base.enabled;
9949
9950                 if (crtc->new_enabled)
9951                         crtc->new_config = crtc->config;
9952                 else
9953                         crtc->new_config = NULL;
9954         }
9955 }
9956
9957 /**
9958  * intel_modeset_commit_output_state
9959  *
9960  * This function copies the stage display pipe configuration to the real one.
9961  */
9962 static void intel_modeset_commit_output_state(struct drm_device *dev)
9963 {
9964         struct intel_crtc *crtc;
9965         struct intel_encoder *encoder;
9966         struct intel_connector *connector;
9967
9968         list_for_each_entry(connector, &dev->mode_config.connector_list,
9969                             base.head) {
9970                 connector->base.encoder = &connector->new_encoder->base;
9971         }
9972
9973         for_each_intel_encoder(dev, encoder) {
9974                 encoder->base.crtc = &encoder->new_crtc->base;
9975         }
9976
9977         for_each_intel_crtc(dev, crtc) {
9978                 crtc->base.enabled = crtc->new_enabled;
9979         }
9980 }
9981
9982 static void
9983 connected_sink_compute_bpp(struct intel_connector *connector,
9984                            struct intel_crtc_state *pipe_config)
9985 {
9986         int bpp = pipe_config->pipe_bpp;
9987
9988         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
9989                 connector->base.base.id,
9990                 connector->base.name);
9991
9992         /* Don't use an invalid EDID bpc value */
9993         if (connector->base.display_info.bpc &&
9994             connector->base.display_info.bpc * 3 < bpp) {
9995                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
9996                               bpp, connector->base.display_info.bpc*3);
9997                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
9998         }
9999
10000         /* Clamp bpp to 8 on screens without EDID 1.4 */
10001         if (connector->base.display_info.bpc == 0 && bpp > 24) {
10002                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10003                               bpp);
10004                 pipe_config->pipe_bpp = 24;
10005         }
10006 }
10007
10008 static int
10009 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10010                           struct drm_framebuffer *fb,
10011                           struct intel_crtc_state *pipe_config)
10012 {
10013         struct drm_device *dev = crtc->base.dev;
10014         struct intel_connector *connector;
10015         int bpp;
10016
10017         switch (fb->pixel_format) {
10018         case DRM_FORMAT_C8:
10019                 bpp = 8*3; /* since we go through a colormap */
10020                 break;
10021         case DRM_FORMAT_XRGB1555:
10022         case DRM_FORMAT_ARGB1555:
10023                 /* checked in intel_framebuffer_init already */
10024                 if (WARN_ON(INTEL_INFO(dev)->gen > 3))
10025                         return -EINVAL;
10026         case DRM_FORMAT_RGB565:
10027                 bpp = 6*3; /* min is 18bpp */
10028                 break;
10029         case DRM_FORMAT_XBGR8888:
10030         case DRM_FORMAT_ABGR8888:
10031                 /* checked in intel_framebuffer_init already */
10032                 if (WARN_ON(INTEL_INFO(dev)->gen < 4))
10033                         return -EINVAL;
10034         case DRM_FORMAT_XRGB8888:
10035         case DRM_FORMAT_ARGB8888:
10036                 bpp = 8*3;
10037                 break;
10038         case DRM_FORMAT_XRGB2101010:
10039         case DRM_FORMAT_ARGB2101010:
10040         case DRM_FORMAT_XBGR2101010:
10041         case DRM_FORMAT_ABGR2101010:
10042                 /* checked in intel_framebuffer_init already */
10043                 if (WARN_ON(INTEL_INFO(dev)->gen < 4))
10044                         return -EINVAL;
10045                 bpp = 10*3;
10046                 break;
10047         /* TODO: gen4+ supports 16 bpc floating point, too. */
10048         default:
10049                 DRM_DEBUG_KMS("unsupported depth\n");
10050                 return -EINVAL;
10051         }
10052
10053         pipe_config->pipe_bpp = bpp;
10054
10055         /* Clamp display bpp to EDID value */
10056         list_for_each_entry(connector, &dev->mode_config.connector_list,
10057                             base.head) {
10058                 if (!connector->new_encoder ||
10059                     connector->new_encoder->new_crtc != crtc)
10060                         continue;
10061
10062                 connected_sink_compute_bpp(connector, pipe_config);
10063         }
10064
10065         return bpp;
10066 }
10067
10068 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10069 {
10070         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10071                         "type: 0x%x flags: 0x%x\n",
10072                 mode->crtc_clock,
10073                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10074                 mode->crtc_hsync_end, mode->crtc_htotal,
10075                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10076                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10077 }
10078
10079 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10080                                    struct intel_crtc_state *pipe_config,
10081                                    const char *context)
10082 {
10083         DRM_DEBUG_KMS("[CRTC:%d]%s config for pipe %c\n", crtc->base.base.id,
10084                       context, pipe_name(crtc->pipe));
10085
10086         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
10087         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
10088                       pipe_config->pipe_bpp, pipe_config->dither);
10089         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10090                       pipe_config->has_pch_encoder,
10091                       pipe_config->fdi_lanes,
10092                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
10093                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
10094                       pipe_config->fdi_m_n.tu);
10095         DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10096                       pipe_config->has_dp_encoder,
10097                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
10098                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
10099                       pipe_config->dp_m_n.tu);
10100
10101         DRM_DEBUG_KMS("dp: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
10102                       pipe_config->has_dp_encoder,
10103                       pipe_config->dp_m2_n2.gmch_m,
10104                       pipe_config->dp_m2_n2.gmch_n,
10105                       pipe_config->dp_m2_n2.link_m,
10106                       pipe_config->dp_m2_n2.link_n,
10107                       pipe_config->dp_m2_n2.tu);
10108
10109         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10110                       pipe_config->has_audio,
10111                       pipe_config->has_infoframe);
10112
10113         DRM_DEBUG_KMS("requested mode:\n");
10114         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10115         DRM_DEBUG_KMS("adjusted mode:\n");
10116         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10117         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10118         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
10119         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
10120                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
10121         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10122                       pipe_config->gmch_pfit.control,
10123                       pipe_config->gmch_pfit.pgm_ratios,
10124                       pipe_config->gmch_pfit.lvds_border_bits);
10125         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10126                       pipe_config->pch_pfit.pos,
10127                       pipe_config->pch_pfit.size,
10128                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
10129         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
10130         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
10131 }
10132
10133 static bool encoders_cloneable(const struct intel_encoder *a,
10134                                const struct intel_encoder *b)
10135 {
10136         /* masks could be asymmetric, so check both ways */
10137         return a == b || (a->cloneable & (1 << b->type) &&
10138                           b->cloneable & (1 << a->type));
10139 }
10140
10141 static bool check_single_encoder_cloning(struct intel_crtc *crtc,
10142                                          struct intel_encoder *encoder)
10143 {
10144         struct drm_device *dev = crtc->base.dev;
10145         struct intel_encoder *source_encoder;
10146
10147         for_each_intel_encoder(dev, source_encoder) {
10148                 if (source_encoder->new_crtc != crtc)
10149                         continue;
10150
10151                 if (!encoders_cloneable(encoder, source_encoder))
10152                         return false;
10153         }
10154
10155         return true;
10156 }
10157
10158 static bool check_encoder_cloning(struct intel_crtc *crtc)
10159 {
10160         struct drm_device *dev = crtc->base.dev;
10161         struct intel_encoder *encoder;
10162
10163         for_each_intel_encoder(dev, encoder) {
10164                 if (encoder->new_crtc != crtc)
10165                         continue;
10166
10167                 if (!check_single_encoder_cloning(crtc, encoder))
10168                         return false;
10169         }
10170
10171         return true;
10172 }
10173
10174 static bool check_digital_port_conflicts(struct drm_device *dev)
10175 {
10176         struct intel_connector *connector;
10177         unsigned int used_ports = 0;
10178
10179         /*
10180          * Walk the connector list instead of the encoder
10181          * list to detect the problem on ddi platforms
10182          * where there's just one encoder per digital port.
10183          */
10184         list_for_each_entry(connector,
10185                             &dev->mode_config.connector_list, base.head) {
10186                 struct intel_encoder *encoder = connector->new_encoder;
10187
10188                 if (!encoder)
10189                         continue;
10190
10191                 WARN_ON(!encoder->new_crtc);
10192
10193                 switch (encoder->type) {
10194                         unsigned int port_mask;
10195                 case INTEL_OUTPUT_UNKNOWN:
10196                         if (WARN_ON(!HAS_DDI(dev)))
10197                                 break;
10198                 case INTEL_OUTPUT_DISPLAYPORT:
10199                 case INTEL_OUTPUT_HDMI:
10200                 case INTEL_OUTPUT_EDP:
10201                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
10202
10203                         /* the same port mustn't appear more than once */
10204                         if (used_ports & port_mask)
10205                                 return false;
10206
10207                         used_ports |= port_mask;
10208                 default:
10209                         break;
10210                 }
10211         }
10212
10213         return true;
10214 }
10215
10216 static struct intel_crtc_state *
10217 intel_modeset_pipe_config(struct drm_crtc *crtc,
10218                           struct drm_framebuffer *fb,
10219                           struct drm_display_mode *mode)
10220 {
10221         struct drm_device *dev = crtc->dev;
10222         struct intel_encoder *encoder;
10223         struct intel_crtc_state *pipe_config;
10224         int plane_bpp, ret = -EINVAL;
10225         bool retry = true;
10226
10227         if (!check_encoder_cloning(to_intel_crtc(crtc))) {
10228                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10229                 return ERR_PTR(-EINVAL);
10230         }
10231
10232         if (!check_digital_port_conflicts(dev)) {
10233                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
10234                 return ERR_PTR(-EINVAL);
10235         }
10236
10237         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10238         if (!pipe_config)
10239                 return ERR_PTR(-ENOMEM);
10240
10241         drm_mode_copy(&pipe_config->base.adjusted_mode, mode);
10242         drm_mode_copy(&pipe_config->base.mode, mode);
10243
10244         pipe_config->cpu_transcoder =
10245                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10246         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
10247
10248         /*
10249          * Sanitize sync polarity flags based on requested ones. If neither
10250          * positive or negative polarity is requested, treat this as meaning
10251          * negative polarity.
10252          */
10253         if (!(pipe_config->base.adjusted_mode.flags &
10254               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10255                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10256
10257         if (!(pipe_config->base.adjusted_mode.flags &
10258               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10259                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10260
10261         /* Compute a starting value for pipe_config->pipe_bpp taking the source
10262          * plane pixel format and any sink constraints into account. Returns the
10263          * source plane bpp so that dithering can be selected on mismatches
10264          * after encoders and crtc also have had their say. */
10265         plane_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10266                                               fb, pipe_config);
10267         if (plane_bpp < 0)
10268                 goto fail;
10269
10270         /*
10271          * Determine the real pipe dimensions. Note that stereo modes can
10272          * increase the actual pipe size due to the frame doubling and
10273          * insertion of additional space for blanks between the frame. This
10274          * is stored in the crtc timings. We use the requested mode to do this
10275          * computation to clearly distinguish it from the adjusted mode, which
10276          * can be changed by the connectors in the below retry loop.
10277          */
10278         drm_crtc_get_hv_timing(&pipe_config->base.mode,
10279                                &pipe_config->pipe_src_w,
10280                                &pipe_config->pipe_src_h);
10281
10282 encoder_retry:
10283         /* Ensure the port clock defaults are reset when retrying. */
10284         pipe_config->port_clock = 0;
10285         pipe_config->pixel_multiplier = 1;
10286
10287         /* Fill in default crtc timings, allow encoders to overwrite them. */
10288         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10289                               CRTC_STEREO_DOUBLE);
10290
10291         /* Pass our mode to the connectors and the CRTC to give them a chance to
10292          * adjust it according to limitations or connector properties, and also
10293          * a chance to reject the mode entirely.
10294          */
10295         for_each_intel_encoder(dev, encoder) {
10296
10297                 if (&encoder->new_crtc->base != crtc)
10298                         continue;
10299
10300                 if (!(encoder->compute_config(encoder, pipe_config))) {
10301                         DRM_DEBUG_KMS("Encoder config failure\n");
10302                         goto fail;
10303                 }
10304         }
10305
10306         /* Set default port clock if not overwritten by the encoder. Needs to be
10307          * done afterwards in case the encoder adjusts the mode. */
10308         if (!pipe_config->port_clock)
10309                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
10310                         * pipe_config->pixel_multiplier;
10311
10312         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
10313         if (ret < 0) {
10314                 DRM_DEBUG_KMS("CRTC fixup failed\n");
10315                 goto fail;
10316         }
10317
10318         if (ret == RETRY) {
10319                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
10320                         ret = -EINVAL;
10321                         goto fail;
10322                 }
10323
10324                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
10325                 retry = false;
10326                 goto encoder_retry;
10327         }
10328
10329         pipe_config->dither = pipe_config->pipe_bpp != plane_bpp;
10330         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
10331                       plane_bpp, pipe_config->pipe_bpp, pipe_config->dither);
10332
10333         return pipe_config;
10334 fail:
10335         kfree(pipe_config);
10336         return ERR_PTR(ret);
10337 }
10338
10339 /* Computes which crtcs are affected and sets the relevant bits in the mask. For
10340  * simplicity we use the crtc's pipe number (because it's easier to obtain). */
10341 static void
10342 intel_modeset_affected_pipes(struct drm_crtc *crtc, unsigned *modeset_pipes,
10343                              unsigned *prepare_pipes, unsigned *disable_pipes)
10344 {
10345         struct intel_crtc *intel_crtc;
10346         struct drm_device *dev = crtc->dev;
10347         struct intel_encoder *encoder;
10348         struct intel_connector *connector;
10349         struct drm_crtc *tmp_crtc;
10350
10351         *disable_pipes = *modeset_pipes = *prepare_pipes = 0;
10352
10353         /* Check which crtcs have changed outputs connected to them, these need
10354          * to be part of the prepare_pipes mask. We don't (yet) support global
10355          * modeset across multiple crtcs, so modeset_pipes will only have one
10356          * bit set at most. */
10357         list_for_each_entry(connector, &dev->mode_config.connector_list,
10358                             base.head) {
10359                 if (connector->base.encoder == &connector->new_encoder->base)
10360                         continue;
10361
10362                 if (connector->base.encoder) {
10363                         tmp_crtc = connector->base.encoder->crtc;
10364
10365                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
10366                 }
10367
10368                 if (connector->new_encoder)
10369                         *prepare_pipes |=
10370                                 1 << connector->new_encoder->new_crtc->pipe;
10371         }
10372
10373         for_each_intel_encoder(dev, encoder) {
10374                 if (encoder->base.crtc == &encoder->new_crtc->base)
10375                         continue;
10376
10377                 if (encoder->base.crtc) {
10378                         tmp_crtc = encoder->base.crtc;
10379
10380                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
10381                 }
10382
10383                 if (encoder->new_crtc)
10384                         *prepare_pipes |= 1 << encoder->new_crtc->pipe;
10385         }
10386
10387         /* Check for pipes that will be enabled/disabled ... */
10388         for_each_intel_crtc(dev, intel_crtc) {
10389                 if (intel_crtc->base.enabled == intel_crtc->new_enabled)
10390                         continue;
10391
10392                 if (!intel_crtc->new_enabled)
10393                         *disable_pipes |= 1 << intel_crtc->pipe;
10394                 else
10395                         *prepare_pipes |= 1 << intel_crtc->pipe;
10396         }
10397
10398
10399         /* set_mode is also used to update properties on life display pipes. */
10400         intel_crtc = to_intel_crtc(crtc);
10401         if (intel_crtc->new_enabled)
10402                 *prepare_pipes |= 1 << intel_crtc->pipe;
10403
10404         /*
10405          * For simplicity do a full modeset on any pipe where the output routing
10406          * changed. We could be more clever, but that would require us to be
10407          * more careful with calling the relevant encoder->mode_set functions.
10408          */
10409         if (*prepare_pipes)
10410                 *modeset_pipes = *prepare_pipes;
10411
10412         /* ... and mask these out. */
10413         *modeset_pipes &= ~(*disable_pipes);
10414         *prepare_pipes &= ~(*disable_pipes);
10415
10416         /*
10417          * HACK: We don't (yet) fully support global modesets. intel_set_config
10418          * obies this rule, but the modeset restore mode of
10419          * intel_modeset_setup_hw_state does not.
10420          */
10421         *modeset_pipes &= 1 << intel_crtc->pipe;
10422         *prepare_pipes &= 1 << intel_crtc->pipe;
10423
10424         DRM_DEBUG_KMS("set mode pipe masks: modeset: %x, prepare: %x, disable: %x\n",
10425                       *modeset_pipes, *prepare_pipes, *disable_pipes);
10426 }
10427
10428 static bool intel_crtc_in_use(struct drm_crtc *crtc)
10429 {
10430         struct drm_encoder *encoder;
10431         struct drm_device *dev = crtc->dev;
10432
10433         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
10434                 if (encoder->crtc == crtc)
10435                         return true;
10436
10437         return false;
10438 }
10439
10440 static void
10441 intel_modeset_update_state(struct drm_device *dev, unsigned prepare_pipes)
10442 {
10443         struct drm_i915_private *dev_priv = dev->dev_private;
10444         struct intel_encoder *intel_encoder;
10445         struct intel_crtc *intel_crtc;
10446         struct drm_connector *connector;
10447
10448         intel_shared_dpll_commit(dev_priv);
10449
10450         for_each_intel_encoder(dev, intel_encoder) {
10451                 if (!intel_encoder->base.crtc)
10452                         continue;
10453
10454                 intel_crtc = to_intel_crtc(intel_encoder->base.crtc);
10455
10456                 if (prepare_pipes & (1 << intel_crtc->pipe))
10457                         intel_encoder->connectors_active = false;
10458         }
10459
10460         intel_modeset_commit_output_state(dev);
10461
10462         /* Double check state. */
10463         for_each_intel_crtc(dev, intel_crtc) {
10464                 WARN_ON(intel_crtc->base.enabled != intel_crtc_in_use(&intel_crtc->base));
10465                 WARN_ON(intel_crtc->new_config &&
10466                         intel_crtc->new_config != intel_crtc->config);
10467                 WARN_ON(intel_crtc->base.enabled != !!intel_crtc->new_config);
10468         }
10469
10470         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
10471                 if (!connector->encoder || !connector->encoder->crtc)
10472                         continue;
10473
10474                 intel_crtc = to_intel_crtc(connector->encoder->crtc);
10475
10476                 if (prepare_pipes & (1 << intel_crtc->pipe)) {
10477                         struct drm_property *dpms_property =
10478                                 dev->mode_config.dpms_property;
10479
10480                         connector->dpms = DRM_MODE_DPMS_ON;
10481                         drm_object_property_set_value(&connector->base,
10482                                                          dpms_property,
10483                                                          DRM_MODE_DPMS_ON);
10484
10485                         intel_encoder = to_intel_encoder(connector->encoder);
10486                         intel_encoder->connectors_active = true;
10487                 }
10488         }
10489
10490 }
10491
10492 static bool intel_fuzzy_clock_check(int clock1, int clock2)
10493 {
10494         int diff;
10495
10496         if (clock1 == clock2)
10497                 return true;
10498
10499         if (!clock1 || !clock2)
10500                 return false;
10501
10502         diff = abs(clock1 - clock2);
10503
10504         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
10505                 return true;
10506
10507         return false;
10508 }
10509
10510 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
10511         list_for_each_entry((intel_crtc), \
10512                             &(dev)->mode_config.crtc_list, \
10513                             base.head) \
10514                 if (mask & (1 <<(intel_crtc)->pipe))
10515
10516 static bool
10517 intel_pipe_config_compare(struct drm_device *dev,
10518                           struct intel_crtc_state *current_config,
10519                           struct intel_crtc_state *pipe_config)
10520 {
10521 #define PIPE_CONF_CHECK_X(name) \
10522         if (current_config->name != pipe_config->name) { \
10523                 DRM_ERROR("mismatch in " #name " " \
10524                           "(expected 0x%08x, found 0x%08x)\n", \
10525                           current_config->name, \
10526                           pipe_config->name); \
10527                 return false; \
10528         }
10529
10530 #define PIPE_CONF_CHECK_I(name) \
10531         if (current_config->name != pipe_config->name) { \
10532                 DRM_ERROR("mismatch in " #name " " \
10533                           "(expected %i, found %i)\n", \
10534                           current_config->name, \
10535                           pipe_config->name); \
10536                 return false; \
10537         }
10538
10539 /* This is required for BDW+ where there is only one set of registers for
10540  * switching between high and low RR.
10541  * This macro can be used whenever a comparison has to be made between one
10542  * hw state and multiple sw state variables.
10543  */
10544 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
10545         if ((current_config->name != pipe_config->name) && \
10546                 (current_config->alt_name != pipe_config->name)) { \
10547                         DRM_ERROR("mismatch in " #name " " \
10548                                   "(expected %i or %i, found %i)\n", \
10549                                   current_config->name, \
10550                                   current_config->alt_name, \
10551                                   pipe_config->name); \
10552                         return false; \
10553         }
10554
10555 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
10556         if ((current_config->name ^ pipe_config->name) & (mask)) { \
10557                 DRM_ERROR("mismatch in " #name "(" #mask ") "      \
10558                           "(expected %i, found %i)\n", \
10559                           current_config->name & (mask), \
10560                           pipe_config->name & (mask)); \
10561                 return false; \
10562         }
10563
10564 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
10565         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
10566                 DRM_ERROR("mismatch in " #name " " \
10567                           "(expected %i, found %i)\n", \
10568                           current_config->name, \
10569                           pipe_config->name); \
10570                 return false; \
10571         }
10572
10573 #define PIPE_CONF_QUIRK(quirk)  \
10574         ((current_config->quirks | pipe_config->quirks) & (quirk))
10575
10576         PIPE_CONF_CHECK_I(cpu_transcoder);
10577
10578         PIPE_CONF_CHECK_I(has_pch_encoder);
10579         PIPE_CONF_CHECK_I(fdi_lanes);
10580         PIPE_CONF_CHECK_I(fdi_m_n.gmch_m);
10581         PIPE_CONF_CHECK_I(fdi_m_n.gmch_n);
10582         PIPE_CONF_CHECK_I(fdi_m_n.link_m);
10583         PIPE_CONF_CHECK_I(fdi_m_n.link_n);
10584         PIPE_CONF_CHECK_I(fdi_m_n.tu);
10585
10586         PIPE_CONF_CHECK_I(has_dp_encoder);
10587
10588         if (INTEL_INFO(dev)->gen < 8) {
10589                 PIPE_CONF_CHECK_I(dp_m_n.gmch_m);
10590                 PIPE_CONF_CHECK_I(dp_m_n.gmch_n);
10591                 PIPE_CONF_CHECK_I(dp_m_n.link_m);
10592                 PIPE_CONF_CHECK_I(dp_m_n.link_n);
10593                 PIPE_CONF_CHECK_I(dp_m_n.tu);
10594
10595                 if (current_config->has_drrs) {
10596                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_m);
10597                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_n);
10598                         PIPE_CONF_CHECK_I(dp_m2_n2.link_m);
10599                         PIPE_CONF_CHECK_I(dp_m2_n2.link_n);
10600                         PIPE_CONF_CHECK_I(dp_m2_n2.tu);
10601                 }
10602         } else {
10603                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_m, dp_m2_n2.gmch_m);
10604                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_n, dp_m2_n2.gmch_n);
10605                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_m, dp_m2_n2.link_m);
10606                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_n, dp_m2_n2.link_n);
10607                 PIPE_CONF_CHECK_I_ALT(dp_m_n.tu, dp_m2_n2.tu);
10608         }
10609
10610         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
10611         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
10612         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
10613         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
10614         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
10615         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
10616
10617         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
10618         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
10619         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
10620         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
10621         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
10622         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
10623
10624         PIPE_CONF_CHECK_I(pixel_multiplier);
10625         PIPE_CONF_CHECK_I(has_hdmi_sink);
10626         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
10627             IS_VALLEYVIEW(dev))
10628                 PIPE_CONF_CHECK_I(limited_color_range);
10629         PIPE_CONF_CHECK_I(has_infoframe);
10630
10631         PIPE_CONF_CHECK_I(has_audio);
10632
10633         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10634                               DRM_MODE_FLAG_INTERLACE);
10635
10636         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
10637                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10638                                       DRM_MODE_FLAG_PHSYNC);
10639                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10640                                       DRM_MODE_FLAG_NHSYNC);
10641                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10642                                       DRM_MODE_FLAG_PVSYNC);
10643                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10644                                       DRM_MODE_FLAG_NVSYNC);
10645         }
10646
10647         PIPE_CONF_CHECK_I(pipe_src_w);
10648         PIPE_CONF_CHECK_I(pipe_src_h);
10649
10650         /*
10651          * FIXME: BIOS likes to set up a cloned config with lvds+external
10652          * screen. Since we don't yet re-compute the pipe config when moving
10653          * just the lvds port away to another pipe the sw tracking won't match.
10654          *
10655          * Proper atomic modesets with recomputed global state will fix this.
10656          * Until then just don't check gmch state for inherited modes.
10657          */
10658         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
10659                 PIPE_CONF_CHECK_I(gmch_pfit.control);
10660                 /* pfit ratios are autocomputed by the hw on gen4+ */
10661                 if (INTEL_INFO(dev)->gen < 4)
10662                         PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
10663                 PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
10664         }
10665
10666         PIPE_CONF_CHECK_I(pch_pfit.enabled);
10667         if (current_config->pch_pfit.enabled) {
10668                 PIPE_CONF_CHECK_I(pch_pfit.pos);
10669                 PIPE_CONF_CHECK_I(pch_pfit.size);
10670         }
10671
10672         /* BDW+ don't expose a synchronous way to read the state */
10673         if (IS_HASWELL(dev))
10674                 PIPE_CONF_CHECK_I(ips_enabled);
10675
10676         PIPE_CONF_CHECK_I(double_wide);
10677
10678         PIPE_CONF_CHECK_X(ddi_pll_sel);
10679
10680         PIPE_CONF_CHECK_I(shared_dpll);
10681         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
10682         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
10683         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
10684         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
10685         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
10686         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
10687         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
10688         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
10689
10690         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
10691                 PIPE_CONF_CHECK_I(pipe_bpp);
10692
10693         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
10694         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
10695
10696 #undef PIPE_CONF_CHECK_X
10697 #undef PIPE_CONF_CHECK_I
10698 #undef PIPE_CONF_CHECK_I_ALT
10699 #undef PIPE_CONF_CHECK_FLAGS
10700 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
10701 #undef PIPE_CONF_QUIRK
10702
10703         return true;
10704 }
10705
10706 static void check_wm_state(struct drm_device *dev)
10707 {
10708         struct drm_i915_private *dev_priv = dev->dev_private;
10709         struct skl_ddb_allocation hw_ddb, *sw_ddb;
10710         struct intel_crtc *intel_crtc;
10711         int plane;
10712
10713         if (INTEL_INFO(dev)->gen < 9)
10714                 return;
10715
10716         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
10717         sw_ddb = &dev_priv->wm.skl_hw.ddb;
10718
10719         for_each_intel_crtc(dev, intel_crtc) {
10720                 struct skl_ddb_entry *hw_entry, *sw_entry;
10721                 const enum pipe pipe = intel_crtc->pipe;
10722
10723                 if (!intel_crtc->active)
10724                         continue;
10725
10726                 /* planes */
10727                 for_each_plane(pipe, plane) {
10728                         hw_entry = &hw_ddb.plane[pipe][plane];
10729                         sw_entry = &sw_ddb->plane[pipe][plane];
10730
10731                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
10732                                 continue;
10733
10734                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
10735                                   "(expected (%u,%u), found (%u,%u))\n",
10736                                   pipe_name(pipe), plane + 1,
10737                                   sw_entry->start, sw_entry->end,
10738                                   hw_entry->start, hw_entry->end);
10739                 }
10740
10741                 /* cursor */
10742                 hw_entry = &hw_ddb.cursor[pipe];
10743                 sw_entry = &sw_ddb->cursor[pipe];
10744
10745                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
10746                         continue;
10747
10748                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
10749                           "(expected (%u,%u), found (%u,%u))\n",
10750                           pipe_name(pipe),
10751                           sw_entry->start, sw_entry->end,
10752                           hw_entry->start, hw_entry->end);
10753         }
10754 }
10755
10756 static void
10757 check_connector_state(struct drm_device *dev)
10758 {
10759         struct intel_connector *connector;
10760
10761         list_for_each_entry(connector, &dev->mode_config.connector_list,
10762                             base.head) {
10763                 /* This also checks the encoder/connector hw state with the
10764                  * ->get_hw_state callbacks. */
10765                 intel_connector_check_state(connector);
10766
10767                 I915_STATE_WARN(&connector->new_encoder->base != connector->base.encoder,
10768                      "connector's staged encoder doesn't match current encoder\n");
10769         }
10770 }
10771
10772 static void
10773 check_encoder_state(struct drm_device *dev)
10774 {
10775         struct intel_encoder *encoder;
10776         struct intel_connector *connector;
10777
10778         for_each_intel_encoder(dev, encoder) {
10779                 bool enabled = false;
10780                 bool active = false;
10781                 enum pipe pipe, tracked_pipe;
10782
10783                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
10784                               encoder->base.base.id,
10785                               encoder->base.name);
10786
10787                 I915_STATE_WARN(&encoder->new_crtc->base != encoder->base.crtc,
10788                      "encoder's stage crtc doesn't match current crtc\n");
10789                 I915_STATE_WARN(encoder->connectors_active && !encoder->base.crtc,
10790                      "encoder's active_connectors set, but no crtc\n");
10791
10792                 list_for_each_entry(connector, &dev->mode_config.connector_list,
10793                                     base.head) {
10794                         if (connector->base.encoder != &encoder->base)
10795                                 continue;
10796                         enabled = true;
10797                         if (connector->base.dpms != DRM_MODE_DPMS_OFF)
10798                                 active = true;
10799                 }
10800                 /*
10801                  * for MST connectors if we unplug the connector is gone
10802                  * away but the encoder is still connected to a crtc
10803                  * until a modeset happens in response to the hotplug.
10804                  */
10805                 if (!enabled && encoder->base.encoder_type == DRM_MODE_ENCODER_DPMST)
10806                         continue;
10807
10808                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
10809                      "encoder's enabled state mismatch "
10810                      "(expected %i, found %i)\n",
10811                      !!encoder->base.crtc, enabled);
10812                 I915_STATE_WARN(active && !encoder->base.crtc,
10813                      "active encoder with no crtc\n");
10814
10815                 I915_STATE_WARN(encoder->connectors_active != active,
10816                      "encoder's computed active state doesn't match tracked active state "
10817                      "(expected %i, found %i)\n", active, encoder->connectors_active);
10818
10819                 active = encoder->get_hw_state(encoder, &pipe);
10820                 I915_STATE_WARN(active != encoder->connectors_active,
10821                      "encoder's hw state doesn't match sw tracking "
10822                      "(expected %i, found %i)\n",
10823                      encoder->connectors_active, active);
10824
10825                 if (!encoder->base.crtc)
10826                         continue;
10827
10828                 tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
10829                 I915_STATE_WARN(active && pipe != tracked_pipe,
10830                      "active encoder's pipe doesn't match"
10831                      "(expected %i, found %i)\n",
10832                      tracked_pipe, pipe);
10833
10834         }
10835 }
10836
10837 static void
10838 check_crtc_state(struct drm_device *dev)
10839 {
10840         struct drm_i915_private *dev_priv = dev->dev_private;
10841         struct intel_crtc *crtc;
10842         struct intel_encoder *encoder;
10843         struct intel_crtc_state pipe_config;
10844
10845         for_each_intel_crtc(dev, crtc) {
10846                 bool enabled = false;
10847                 bool active = false;
10848
10849                 memset(&pipe_config, 0, sizeof(pipe_config));
10850
10851                 DRM_DEBUG_KMS("[CRTC:%d]\n",
10852                               crtc->base.base.id);
10853
10854                 I915_STATE_WARN(crtc->active && !crtc->base.enabled,
10855                      "active crtc, but not enabled in sw tracking\n");
10856
10857                 for_each_intel_encoder(dev, encoder) {
10858                         if (encoder->base.crtc != &crtc->base)
10859                                 continue;
10860                         enabled = true;
10861                         if (encoder->connectors_active)
10862                                 active = true;
10863                 }
10864
10865                 I915_STATE_WARN(active != crtc->active,
10866                      "crtc's computed active state doesn't match tracked active state "
10867                      "(expected %i, found %i)\n", active, crtc->active);
10868                 I915_STATE_WARN(enabled != crtc->base.enabled,
10869                      "crtc's computed enabled state doesn't match tracked enabled state "
10870                      "(expected %i, found %i)\n", enabled, crtc->base.enabled);
10871
10872                 active = dev_priv->display.get_pipe_config(crtc,
10873                                                            &pipe_config);
10874
10875                 /* hw state is inconsistent with the pipe quirk */
10876                 if ((crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
10877                     (crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
10878                         active = crtc->active;
10879
10880                 for_each_intel_encoder(dev, encoder) {
10881                         enum pipe pipe;
10882                         if (encoder->base.crtc != &crtc->base)
10883                                 continue;
10884                         if (encoder->get_hw_state(encoder, &pipe))
10885                                 encoder->get_config(encoder, &pipe_config);
10886                 }
10887
10888                 I915_STATE_WARN(crtc->active != active,
10889                      "crtc active state doesn't match with hw state "
10890                      "(expected %i, found %i)\n", crtc->active, active);
10891
10892                 if (active &&
10893                     !intel_pipe_config_compare(dev, crtc->config, &pipe_config)) {
10894                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
10895                         intel_dump_pipe_config(crtc, &pipe_config,
10896                                                "[hw state]");
10897                         intel_dump_pipe_config(crtc, crtc->config,
10898                                                "[sw state]");
10899                 }
10900         }
10901 }
10902
10903 static void
10904 check_shared_dpll_state(struct drm_device *dev)
10905 {
10906         struct drm_i915_private *dev_priv = dev->dev_private;
10907         struct intel_crtc *crtc;
10908         struct intel_dpll_hw_state dpll_hw_state;
10909         int i;
10910
10911         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
10912                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
10913                 int enabled_crtcs = 0, active_crtcs = 0;
10914                 bool active;
10915
10916                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
10917
10918                 DRM_DEBUG_KMS("%s\n", pll->name);
10919
10920                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
10921
10922                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
10923                      "more active pll users than references: %i vs %i\n",
10924                      pll->active, hweight32(pll->config.crtc_mask));
10925                 I915_STATE_WARN(pll->active && !pll->on,
10926                      "pll in active use but not on in sw tracking\n");
10927                 I915_STATE_WARN(pll->on && !pll->active,
10928                      "pll in on but not on in use in sw tracking\n");
10929                 I915_STATE_WARN(pll->on != active,
10930                      "pll on state mismatch (expected %i, found %i)\n",
10931                      pll->on, active);
10932
10933                 for_each_intel_crtc(dev, crtc) {
10934                         if (crtc->base.enabled && intel_crtc_to_shared_dpll(crtc) == pll)
10935                                 enabled_crtcs++;
10936                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
10937                                 active_crtcs++;
10938                 }
10939                 I915_STATE_WARN(pll->active != active_crtcs,
10940                      "pll active crtcs mismatch (expected %i, found %i)\n",
10941                      pll->active, active_crtcs);
10942                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
10943                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
10944                      hweight32(pll->config.crtc_mask), enabled_crtcs);
10945
10946                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
10947                                        sizeof(dpll_hw_state)),
10948                      "pll hw state mismatch\n");
10949         }
10950 }
10951
10952 void
10953 intel_modeset_check_state(struct drm_device *dev)
10954 {
10955         check_wm_state(dev);
10956         check_connector_state(dev);
10957         check_encoder_state(dev);
10958         check_crtc_state(dev);
10959         check_shared_dpll_state(dev);
10960 }
10961
10962 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
10963                                      int dotclock)
10964 {
10965         /*
10966          * FDI already provided one idea for the dotclock.
10967          * Yell if the encoder disagrees.
10968          */
10969         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
10970              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
10971              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
10972 }
10973
10974 static void update_scanline_offset(struct intel_crtc *crtc)
10975 {
10976         struct drm_device *dev = crtc->base.dev;
10977
10978         /*
10979          * The scanline counter increments at the leading edge of hsync.
10980          *
10981          * On most platforms it starts counting from vtotal-1 on the
10982          * first active line. That means the scanline counter value is
10983          * always one less than what we would expect. Ie. just after
10984          * start of vblank, which also occurs at start of hsync (on the
10985          * last active line), the scanline counter will read vblank_start-1.
10986          *
10987          * On gen2 the scanline counter starts counting from 1 instead
10988          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
10989          * to keep the value positive), instead of adding one.
10990          *
10991          * On HSW+ the behaviour of the scanline counter depends on the output
10992          * type. For DP ports it behaves like most other platforms, but on HDMI
10993          * there's an extra 1 line difference. So we need to add two instead of
10994          * one to the value.
10995          */
10996         if (IS_GEN2(dev)) {
10997                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
10998                 int vtotal;
10999
11000                 vtotal = mode->crtc_vtotal;
11001                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
11002                         vtotal /= 2;
11003
11004                 crtc->scanline_offset = vtotal - 1;
11005         } else if (HAS_DDI(dev) &&
11006                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
11007                 crtc->scanline_offset = 2;
11008         } else
11009                 crtc->scanline_offset = 1;
11010 }
11011
11012 static struct intel_crtc_state *
11013 intel_modeset_compute_config(struct drm_crtc *crtc,
11014                              struct drm_display_mode *mode,
11015                              struct drm_framebuffer *fb,
11016                              unsigned *modeset_pipes,
11017                              unsigned *prepare_pipes,
11018                              unsigned *disable_pipes)
11019 {
11020         struct intel_crtc_state *pipe_config = NULL;
11021
11022         intel_modeset_affected_pipes(crtc, modeset_pipes,
11023                                      prepare_pipes, disable_pipes);
11024
11025         if ((*modeset_pipes) == 0)
11026                 goto out;
11027
11028         /*
11029          * Note this needs changes when we start tracking multiple modes
11030          * and crtcs.  At that point we'll need to compute the whole config
11031          * (i.e. one pipe_config for each crtc) rather than just the one
11032          * for this crtc.
11033          */
11034         pipe_config = intel_modeset_pipe_config(crtc, fb, mode);
11035         if (IS_ERR(pipe_config)) {
11036                 goto out;
11037         }
11038         intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
11039                                "[modeset]");
11040
11041 out:
11042         return pipe_config;
11043 }
11044
11045 static int __intel_set_mode_setup_plls(struct drm_device *dev,
11046                                        unsigned modeset_pipes,
11047                                        unsigned disable_pipes)
11048 {
11049         struct drm_i915_private *dev_priv = to_i915(dev);
11050         unsigned clear_pipes = modeset_pipes | disable_pipes;
11051         struct intel_crtc *intel_crtc;
11052         int ret = 0;
11053
11054         if (!dev_priv->display.crtc_compute_clock)
11055                 return 0;
11056
11057         ret = intel_shared_dpll_start_config(dev_priv, clear_pipes);
11058         if (ret)
11059                 goto done;
11060
11061         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
11062                 struct intel_crtc_state *state = intel_crtc->new_config;
11063                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11064                                                            state);
11065                 if (ret) {
11066                         intel_shared_dpll_abort_config(dev_priv);
11067                         goto done;
11068                 }
11069         }
11070
11071 done:
11072         return ret;
11073 }
11074
11075 static int __intel_set_mode(struct drm_crtc *crtc,
11076                             struct drm_display_mode *mode,
11077                             int x, int y, struct drm_framebuffer *fb,
11078                             struct intel_crtc_state *pipe_config,
11079                             unsigned modeset_pipes,
11080                             unsigned prepare_pipes,
11081                             unsigned disable_pipes)
11082 {
11083         struct drm_device *dev = crtc->dev;
11084         struct drm_i915_private *dev_priv = dev->dev_private;
11085         struct drm_display_mode *saved_mode;
11086         struct intel_crtc *intel_crtc;
11087         int ret = 0;
11088
11089         saved_mode = kmalloc(sizeof(*saved_mode), GFP_KERNEL);
11090         if (!saved_mode)
11091                 return -ENOMEM;
11092
11093         *saved_mode = crtc->mode;
11094
11095         if (modeset_pipes)
11096                 to_intel_crtc(crtc)->new_config = pipe_config;
11097
11098         /*
11099          * See if the config requires any additional preparation, e.g.
11100          * to adjust global state with pipes off.  We need to do this
11101          * here so we can get the modeset_pipe updated config for the new
11102          * mode set on this crtc.  For other crtcs we need to use the
11103          * adjusted_mode bits in the crtc directly.
11104          */
11105         if (IS_VALLEYVIEW(dev)) {
11106                 valleyview_modeset_global_pipes(dev, &prepare_pipes);
11107
11108                 /* may have added more to prepare_pipes than we should */
11109                 prepare_pipes &= ~disable_pipes;
11110         }
11111
11112         ret = __intel_set_mode_setup_plls(dev, modeset_pipes, disable_pipes);
11113         if (ret)
11114                 goto done;
11115
11116         for_each_intel_crtc_masked(dev, disable_pipes, intel_crtc)
11117                 intel_crtc_disable(&intel_crtc->base);
11118
11119         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
11120                 if (intel_crtc->base.enabled)
11121                         dev_priv->display.crtc_disable(&intel_crtc->base);
11122         }
11123
11124         /* crtc->mode is already used by the ->mode_set callbacks, hence we need
11125          * to set it here already despite that we pass it down the callchain.
11126          *
11127          * Note we'll need to fix this up when we start tracking multiple
11128          * pipes; here we assume a single modeset_pipe and only track the
11129          * single crtc and mode.
11130          */
11131         if (modeset_pipes) {
11132                 crtc->mode = *mode;
11133                 /* mode_set/enable/disable functions rely on a correct pipe
11134                  * config. */
11135                 intel_crtc_set_state(to_intel_crtc(crtc), pipe_config);
11136
11137                 /*
11138                  * Calculate and store various constants which
11139                  * are later needed by vblank and swap-completion
11140                  * timestamping. They are derived from true hwmode.
11141                  */
11142                 drm_calc_timestamping_constants(crtc,
11143                                                 &pipe_config->base.adjusted_mode);
11144         }
11145
11146         /* Only after disabling all output pipelines that will be changed can we
11147          * update the the output configuration. */
11148         intel_modeset_update_state(dev, prepare_pipes);
11149
11150         modeset_update_crtc_power_domains(dev);
11151
11152         /* Set up the DPLL and any encoders state that needs to adjust or depend
11153          * on the DPLL.
11154          */
11155         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
11156                 struct drm_plane *primary = intel_crtc->base.primary;
11157                 int vdisplay, hdisplay;
11158
11159                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
11160                 ret = primary->funcs->update_plane(primary, &intel_crtc->base,
11161                                                    fb, 0, 0,
11162                                                    hdisplay, vdisplay,
11163                                                    x << 16, y << 16,
11164                                                    hdisplay << 16, vdisplay << 16);
11165         }
11166
11167         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
11168         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
11169                 update_scanline_offset(intel_crtc);
11170
11171                 dev_priv->display.crtc_enable(&intel_crtc->base);
11172         }
11173
11174         /* FIXME: add subpixel order */
11175 done:
11176         if (ret && crtc->enabled)
11177                 crtc->mode = *saved_mode;
11178
11179         kfree(saved_mode);
11180         return ret;
11181 }
11182
11183 static int intel_set_mode_pipes(struct drm_crtc *crtc,
11184                                 struct drm_display_mode *mode,
11185                                 int x, int y, struct drm_framebuffer *fb,
11186                                 struct intel_crtc_state *pipe_config,
11187                                 unsigned modeset_pipes,
11188                                 unsigned prepare_pipes,
11189                                 unsigned disable_pipes)
11190 {
11191         int ret;
11192
11193         ret = __intel_set_mode(crtc, mode, x, y, fb, pipe_config, modeset_pipes,
11194                                prepare_pipes, disable_pipes);
11195
11196         if (ret == 0)
11197                 intel_modeset_check_state(crtc->dev);
11198
11199         return ret;
11200 }
11201
11202 static int intel_set_mode(struct drm_crtc *crtc,
11203                           struct drm_display_mode *mode,
11204                           int x, int y, struct drm_framebuffer *fb)
11205 {
11206         struct intel_crtc_state *pipe_config;
11207         unsigned modeset_pipes, prepare_pipes, disable_pipes;
11208
11209         pipe_config = intel_modeset_compute_config(crtc, mode, fb,
11210                                                    &modeset_pipes,
11211                                                    &prepare_pipes,
11212                                                    &disable_pipes);
11213
11214         if (IS_ERR(pipe_config))
11215                 return PTR_ERR(pipe_config);
11216
11217         return intel_set_mode_pipes(crtc, mode, x, y, fb, pipe_config,
11218                                     modeset_pipes, prepare_pipes,
11219                                     disable_pipes);
11220 }
11221
11222 void intel_crtc_restore_mode(struct drm_crtc *crtc)
11223 {
11224         intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y, crtc->primary->fb);
11225 }
11226
11227 #undef for_each_intel_crtc_masked
11228
11229 static void intel_set_config_free(struct intel_set_config *config)
11230 {
11231         if (!config)
11232                 return;
11233
11234         kfree(config->save_connector_encoders);
11235         kfree(config->save_encoder_crtcs);
11236         kfree(config->save_crtc_enabled);
11237         kfree(config);
11238 }
11239
11240 static int intel_set_config_save_state(struct drm_device *dev,
11241                                        struct intel_set_config *config)
11242 {
11243         struct drm_crtc *crtc;
11244         struct drm_encoder *encoder;
11245         struct drm_connector *connector;
11246         int count;
11247
11248         config->save_crtc_enabled =
11249                 kcalloc(dev->mode_config.num_crtc,
11250                         sizeof(bool), GFP_KERNEL);
11251         if (!config->save_crtc_enabled)
11252                 return -ENOMEM;
11253
11254         config->save_encoder_crtcs =
11255                 kcalloc(dev->mode_config.num_encoder,
11256                         sizeof(struct drm_crtc *), GFP_KERNEL);
11257         if (!config->save_encoder_crtcs)
11258                 return -ENOMEM;
11259
11260         config->save_connector_encoders =
11261                 kcalloc(dev->mode_config.num_connector,
11262                         sizeof(struct drm_encoder *), GFP_KERNEL);
11263         if (!config->save_connector_encoders)
11264                 return -ENOMEM;
11265
11266         /* Copy data. Note that driver private data is not affected.
11267          * Should anything bad happen only the expected state is
11268          * restored, not the drivers personal bookkeeping.
11269          */
11270         count = 0;
11271         for_each_crtc(dev, crtc) {
11272                 config->save_crtc_enabled[count++] = crtc->enabled;
11273         }
11274
11275         count = 0;
11276         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
11277                 config->save_encoder_crtcs[count++] = encoder->crtc;
11278         }
11279
11280         count = 0;
11281         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
11282                 config->save_connector_encoders[count++] = connector->encoder;
11283         }
11284
11285         return 0;
11286 }
11287
11288 static void intel_set_config_restore_state(struct drm_device *dev,
11289                                            struct intel_set_config *config)
11290 {
11291         struct intel_crtc *crtc;
11292         struct intel_encoder *encoder;
11293         struct intel_connector *connector;
11294         int count;
11295
11296         count = 0;
11297         for_each_intel_crtc(dev, crtc) {
11298                 crtc->new_enabled = config->save_crtc_enabled[count++];
11299
11300                 if (crtc->new_enabled)
11301                         crtc->new_config = crtc->config;
11302                 else
11303                         crtc->new_config = NULL;
11304         }
11305
11306         count = 0;
11307         for_each_intel_encoder(dev, encoder) {
11308                 encoder->new_crtc =
11309                         to_intel_crtc(config->save_encoder_crtcs[count++]);
11310         }
11311
11312         count = 0;
11313         list_for_each_entry(connector, &dev->mode_config.connector_list, base.head) {
11314                 connector->new_encoder =
11315                         to_intel_encoder(config->save_connector_encoders[count++]);
11316         }
11317 }
11318
11319 static bool
11320 is_crtc_connector_off(struct drm_mode_set *set)
11321 {
11322         int i;
11323
11324         if (set->num_connectors == 0)
11325                 return false;
11326
11327         if (WARN_ON(set->connectors == NULL))
11328                 return false;
11329
11330         for (i = 0; i < set->num_connectors; i++)
11331                 if (set->connectors[i]->encoder &&
11332                     set->connectors[i]->encoder->crtc == set->crtc &&
11333                     set->connectors[i]->dpms != DRM_MODE_DPMS_ON)
11334                         return true;
11335
11336         return false;
11337 }
11338
11339 static void
11340 intel_set_config_compute_mode_changes(struct drm_mode_set *set,
11341                                       struct intel_set_config *config)
11342 {
11343
11344         /* We should be able to check here if the fb has the same properties
11345          * and then just flip_or_move it */
11346         if (is_crtc_connector_off(set)) {
11347                 config->mode_changed = true;
11348         } else if (set->crtc->primary->fb != set->fb) {
11349                 /*
11350                  * If we have no fb, we can only flip as long as the crtc is
11351                  * active, otherwise we need a full mode set.  The crtc may
11352                  * be active if we've only disabled the primary plane, or
11353                  * in fastboot situations.
11354                  */
11355                 if (set->crtc->primary->fb == NULL) {
11356                         struct intel_crtc *intel_crtc =
11357                                 to_intel_crtc(set->crtc);
11358
11359                         if (intel_crtc->active) {
11360                                 DRM_DEBUG_KMS("crtc has no fb, will flip\n");
11361                                 config->fb_changed = true;
11362                         } else {
11363                                 DRM_DEBUG_KMS("inactive crtc, full mode set\n");
11364                                 config->mode_changed = true;
11365                         }
11366                 } else if (set->fb == NULL) {
11367                         config->mode_changed = true;
11368                 } else if (set->fb->pixel_format !=
11369                            set->crtc->primary->fb->pixel_format) {
11370                         config->mode_changed = true;
11371                 } else {
11372                         config->fb_changed = true;
11373                 }
11374         }
11375
11376         if (set->fb && (set->x != set->crtc->x || set->y != set->crtc->y))
11377                 config->fb_changed = true;
11378
11379         if (set->mode && !drm_mode_equal(set->mode, &set->crtc->mode)) {
11380                 DRM_DEBUG_KMS("modes are different, full mode set\n");
11381                 drm_mode_debug_printmodeline(&set->crtc->mode);
11382                 drm_mode_debug_printmodeline(set->mode);
11383                 config->mode_changed = true;
11384         }
11385
11386         DRM_DEBUG_KMS("computed changes for [CRTC:%d], mode_changed=%d, fb_changed=%d\n",
11387                         set->crtc->base.id, config->mode_changed, config->fb_changed);
11388 }
11389
11390 static int
11391 intel_modeset_stage_output_state(struct drm_device *dev,
11392                                  struct drm_mode_set *set,
11393                                  struct intel_set_config *config)
11394 {
11395         struct intel_connector *connector;
11396         struct intel_encoder *encoder;
11397         struct intel_crtc *crtc;
11398         int ro;
11399
11400         /* The upper layers ensure that we either disable a crtc or have a list
11401          * of connectors. For paranoia, double-check this. */
11402         WARN_ON(!set->fb && (set->num_connectors != 0));
11403         WARN_ON(set->fb && (set->num_connectors == 0));
11404
11405         list_for_each_entry(connector, &dev->mode_config.connector_list,
11406                             base.head) {
11407                 /* Otherwise traverse passed in connector list and get encoders
11408                  * for them. */
11409                 for (ro = 0; ro < set->num_connectors; ro++) {
11410                         if (set->connectors[ro] == &connector->base) {
11411                                 connector->new_encoder = intel_find_encoder(connector, to_intel_crtc(set->crtc)->pipe);
11412                                 break;
11413                         }
11414                 }
11415
11416                 /* If we disable the crtc, disable all its connectors. Also, if
11417                  * the connector is on the changing crtc but not on the new
11418                  * connector list, disable it. */
11419                 if ((!set->fb || ro == set->num_connectors) &&
11420                     connector->base.encoder &&
11421                     connector->base.encoder->crtc == set->crtc) {
11422                         connector->new_encoder = NULL;
11423
11424                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
11425                                 connector->base.base.id,
11426                                 connector->base.name);
11427                 }
11428
11429
11430                 if (&connector->new_encoder->base != connector->base.encoder) {
11431                         DRM_DEBUG_KMS("encoder changed, full mode switch\n");
11432                         config->mode_changed = true;
11433                 }
11434         }
11435         /* connector->new_encoder is now updated for all connectors. */
11436
11437         /* Update crtc of enabled connectors. */
11438         list_for_each_entry(connector, &dev->mode_config.connector_list,
11439                             base.head) {
11440                 struct drm_crtc *new_crtc;
11441
11442                 if (!connector->new_encoder)
11443                         continue;
11444
11445                 new_crtc = connector->new_encoder->base.crtc;
11446
11447                 for (ro = 0; ro < set->num_connectors; ro++) {
11448                         if (set->connectors[ro] == &connector->base)
11449                                 new_crtc = set->crtc;
11450                 }
11451
11452                 /* Make sure the new CRTC will work with the encoder */
11453                 if (!drm_encoder_crtc_ok(&connector->new_encoder->base,
11454                                          new_crtc)) {
11455                         return -EINVAL;
11456                 }
11457                 connector->new_encoder->new_crtc = to_intel_crtc(new_crtc);
11458
11459                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
11460                         connector->base.base.id,
11461                         connector->base.name,
11462                         new_crtc->base.id);
11463         }
11464
11465         /* Check for any encoders that needs to be disabled. */
11466         for_each_intel_encoder(dev, encoder) {
11467                 int num_connectors = 0;
11468                 list_for_each_entry(connector,
11469                                     &dev->mode_config.connector_list,
11470                                     base.head) {
11471                         if (connector->new_encoder == encoder) {
11472                                 WARN_ON(!connector->new_encoder->new_crtc);
11473                                 num_connectors++;
11474                         }
11475                 }
11476
11477                 if (num_connectors == 0)
11478                         encoder->new_crtc = NULL;
11479                 else if (num_connectors > 1)
11480                         return -EINVAL;
11481
11482                 /* Only now check for crtc changes so we don't miss encoders
11483                  * that will be disabled. */
11484                 if (&encoder->new_crtc->base != encoder->base.crtc) {
11485                         DRM_DEBUG_KMS("crtc changed, full mode switch\n");
11486                         config->mode_changed = true;
11487                 }
11488         }
11489         /* Now we've also updated encoder->new_crtc for all encoders. */
11490         list_for_each_entry(connector, &dev->mode_config.connector_list,
11491                             base.head) {
11492                 if (connector->new_encoder)
11493                         if (connector->new_encoder != connector->encoder)
11494                                 connector->encoder = connector->new_encoder;
11495         }
11496         for_each_intel_crtc(dev, crtc) {
11497                 crtc->new_enabled = false;
11498
11499                 for_each_intel_encoder(dev, encoder) {
11500                         if (encoder->new_crtc == crtc) {
11501                                 crtc->new_enabled = true;
11502                                 break;
11503                         }
11504                 }
11505
11506                 if (crtc->new_enabled != crtc->base.enabled) {
11507                         DRM_DEBUG_KMS("crtc %sabled, full mode switch\n",
11508                                       crtc->new_enabled ? "en" : "dis");
11509                         config->mode_changed = true;
11510                 }
11511
11512                 if (crtc->new_enabled)
11513                         crtc->new_config = crtc->config;
11514                 else
11515                         crtc->new_config = NULL;
11516         }
11517
11518         return 0;
11519 }
11520
11521 static void disable_crtc_nofb(struct intel_crtc *crtc)
11522 {
11523         struct drm_device *dev = crtc->base.dev;
11524         struct intel_encoder *encoder;
11525         struct intel_connector *connector;
11526
11527         DRM_DEBUG_KMS("Trying to restore without FB -> disabling pipe %c\n",
11528                       pipe_name(crtc->pipe));
11529
11530         list_for_each_entry(connector, &dev->mode_config.connector_list, base.head) {
11531                 if (connector->new_encoder &&
11532                     connector->new_encoder->new_crtc == crtc)
11533                         connector->new_encoder = NULL;
11534         }
11535
11536         for_each_intel_encoder(dev, encoder) {
11537                 if (encoder->new_crtc == crtc)
11538                         encoder->new_crtc = NULL;
11539         }
11540
11541         crtc->new_enabled = false;
11542         crtc->new_config = NULL;
11543 }
11544
11545 static int intel_crtc_set_config(struct drm_mode_set *set)
11546 {
11547         struct drm_device *dev;
11548         struct drm_mode_set save_set;
11549         struct intel_set_config *config;
11550         struct intel_crtc_state *pipe_config;
11551         unsigned modeset_pipes, prepare_pipes, disable_pipes;
11552         int ret;
11553
11554         BUG_ON(!set);
11555         BUG_ON(!set->crtc);
11556         BUG_ON(!set->crtc->helper_private);
11557
11558         /* Enforce sane interface api - has been abused by the fb helper. */
11559         BUG_ON(!set->mode && set->fb);
11560         BUG_ON(set->fb && set->num_connectors == 0);
11561
11562         if (set->fb) {
11563                 DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
11564                                 set->crtc->base.id, set->fb->base.id,
11565                                 (int)set->num_connectors, set->x, set->y);
11566         } else {
11567                 DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
11568         }
11569
11570         dev = set->crtc->dev;
11571
11572         ret = -ENOMEM;
11573         config = kzalloc(sizeof(*config), GFP_KERNEL);
11574         if (!config)
11575                 goto out_config;
11576
11577         ret = intel_set_config_save_state(dev, config);
11578         if (ret)
11579                 goto out_config;
11580
11581         save_set.crtc = set->crtc;
11582         save_set.mode = &set->crtc->mode;
11583         save_set.x = set->crtc->x;
11584         save_set.y = set->crtc->y;
11585         save_set.fb = set->crtc->primary->fb;
11586
11587         /* Compute whether we need a full modeset, only an fb base update or no
11588          * change at all. In the future we might also check whether only the
11589          * mode changed, e.g. for LVDS where we only change the panel fitter in
11590          * such cases. */
11591         intel_set_config_compute_mode_changes(set, config);
11592
11593         ret = intel_modeset_stage_output_state(dev, set, config);
11594         if (ret)
11595                 goto fail;
11596
11597         pipe_config = intel_modeset_compute_config(set->crtc, set->mode,
11598                                                    set->fb,
11599                                                    &modeset_pipes,
11600                                                    &prepare_pipes,
11601                                                    &disable_pipes);
11602         if (IS_ERR(pipe_config)) {
11603                 ret = PTR_ERR(pipe_config);
11604                 goto fail;
11605         } else if (pipe_config) {
11606                 if (pipe_config->has_audio !=
11607                     to_intel_crtc(set->crtc)->config->has_audio)
11608                         config->mode_changed = true;
11609
11610                 /*
11611                  * Note we have an issue here with infoframes: current code
11612                  * only updates them on the full mode set path per hw
11613                  * requirements.  So here we should be checking for any
11614                  * required changes and forcing a mode set.
11615                  */
11616         }
11617
11618         /* set_mode will free it in the mode_changed case */
11619         if (!config->mode_changed)
11620                 kfree(pipe_config);
11621
11622         intel_update_pipe_size(to_intel_crtc(set->crtc));
11623
11624         if (config->mode_changed) {
11625                 ret = intel_set_mode_pipes(set->crtc, set->mode,
11626                                            set->x, set->y, set->fb, pipe_config,
11627                                            modeset_pipes, prepare_pipes,
11628                                            disable_pipes);
11629         } else if (config->fb_changed) {
11630                 struct intel_crtc *intel_crtc = to_intel_crtc(set->crtc);
11631                 struct drm_plane *primary = set->crtc->primary;
11632                 int vdisplay, hdisplay;
11633
11634                 drm_crtc_get_hv_timing(set->mode, &hdisplay, &vdisplay);
11635                 ret = primary->funcs->update_plane(primary, set->crtc, set->fb,
11636                                                    0, 0, hdisplay, vdisplay,
11637                                                    set->x << 16, set->y << 16,
11638                                                    hdisplay << 16, vdisplay << 16);
11639
11640                 /*
11641                  * We need to make sure the primary plane is re-enabled if it
11642                  * has previously been turned off.
11643                  */
11644                 if (!intel_crtc->primary_enabled && ret == 0) {
11645                         WARN_ON(!intel_crtc->active);
11646                         intel_enable_primary_hw_plane(set->crtc->primary, set->crtc);
11647                 }
11648
11649                 /*
11650                  * In the fastboot case this may be our only check of the
11651                  * state after boot.  It would be better to only do it on
11652                  * the first update, but we don't have a nice way of doing that
11653                  * (and really, set_config isn't used much for high freq page
11654                  * flipping, so increasing its cost here shouldn't be a big
11655                  * deal).
11656                  */
11657                 if (i915.fastboot && ret == 0)
11658                         intel_modeset_check_state(set->crtc->dev);
11659         }
11660
11661         if (ret) {
11662                 DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
11663                               set->crtc->base.id, ret);
11664 fail:
11665                 intel_set_config_restore_state(dev, config);
11666
11667                 /*
11668                  * HACK: if the pipe was on, but we didn't have a framebuffer,
11669                  * force the pipe off to avoid oopsing in the modeset code
11670                  * due to fb==NULL. This should only happen during boot since
11671                  * we don't yet reconstruct the FB from the hardware state.
11672                  */
11673                 if (to_intel_crtc(save_set.crtc)->new_enabled && !save_set.fb)
11674                         disable_crtc_nofb(to_intel_crtc(save_set.crtc));
11675
11676                 /* Try to restore the config */
11677                 if (config->mode_changed &&
11678                     intel_set_mode(save_set.crtc, save_set.mode,
11679                                    save_set.x, save_set.y, save_set.fb))
11680                         DRM_ERROR("failed to restore config after modeset failure\n");
11681         }
11682
11683 out_config:
11684         intel_set_config_free(config);
11685         return ret;
11686 }
11687
11688 static const struct drm_crtc_funcs intel_crtc_funcs = {
11689         .gamma_set = intel_crtc_gamma_set,
11690         .set_config = intel_crtc_set_config,
11691         .destroy = intel_crtc_destroy,
11692         .page_flip = intel_crtc_page_flip,
11693         .atomic_duplicate_state = intel_crtc_duplicate_state,
11694         .atomic_destroy_state = intel_crtc_destroy_state,
11695 };
11696
11697 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
11698                                       struct intel_shared_dpll *pll,
11699                                       struct intel_dpll_hw_state *hw_state)
11700 {
11701         uint32_t val;
11702
11703         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
11704                 return false;
11705
11706         val = I915_READ(PCH_DPLL(pll->id));
11707         hw_state->dpll = val;
11708         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
11709         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
11710
11711         return val & DPLL_VCO_ENABLE;
11712 }
11713
11714 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
11715                                   struct intel_shared_dpll *pll)
11716 {
11717         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
11718         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
11719 }
11720
11721 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
11722                                 struct intel_shared_dpll *pll)
11723 {
11724         /* PCH refclock must be enabled first */
11725         ibx_assert_pch_refclk_enabled(dev_priv);
11726
11727         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
11728
11729         /* Wait for the clocks to stabilize. */
11730         POSTING_READ(PCH_DPLL(pll->id));
11731         udelay(150);
11732
11733         /* The pixel multiplier can only be updated once the
11734          * DPLL is enabled and the clocks are stable.
11735          *
11736          * So write it again.
11737          */
11738         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
11739         POSTING_READ(PCH_DPLL(pll->id));
11740         udelay(200);
11741 }
11742
11743 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
11744                                  struct intel_shared_dpll *pll)
11745 {
11746         struct drm_device *dev = dev_priv->dev;
11747         struct intel_crtc *crtc;
11748
11749         /* Make sure no transcoder isn't still depending on us. */
11750         for_each_intel_crtc(dev, crtc) {
11751                 if (intel_crtc_to_shared_dpll(crtc) == pll)
11752                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
11753         }
11754
11755         I915_WRITE(PCH_DPLL(pll->id), 0);
11756         POSTING_READ(PCH_DPLL(pll->id));
11757         udelay(200);
11758 }
11759
11760 static char *ibx_pch_dpll_names[] = {
11761         "PCH DPLL A",
11762         "PCH DPLL B",
11763 };
11764
11765 static void ibx_pch_dpll_init(struct drm_device *dev)
11766 {
11767         struct drm_i915_private *dev_priv = dev->dev_private;
11768         int i;
11769
11770         dev_priv->num_shared_dpll = 2;
11771
11772         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
11773                 dev_priv->shared_dplls[i].id = i;
11774                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
11775                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
11776                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
11777                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
11778                 dev_priv->shared_dplls[i].get_hw_state =
11779                         ibx_pch_dpll_get_hw_state;
11780         }
11781 }
11782
11783 static void intel_shared_dpll_init(struct drm_device *dev)
11784 {
11785         struct drm_i915_private *dev_priv = dev->dev_private;
11786
11787         if (HAS_DDI(dev))
11788                 intel_ddi_pll_init(dev);
11789         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
11790                 ibx_pch_dpll_init(dev);
11791         else
11792                 dev_priv->num_shared_dpll = 0;
11793
11794         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
11795 }
11796
11797 /**
11798  * intel_prepare_plane_fb - Prepare fb for usage on plane
11799  * @plane: drm plane to prepare for
11800  * @fb: framebuffer to prepare for presentation
11801  *
11802  * Prepares a framebuffer for usage on a display plane.  Generally this
11803  * involves pinning the underlying object and updating the frontbuffer tracking
11804  * bits.  Some older platforms need special physical address handling for
11805  * cursor planes.
11806  *
11807  * Returns 0 on success, negative error code on failure.
11808  */
11809 int
11810 intel_prepare_plane_fb(struct drm_plane *plane,
11811                        struct drm_framebuffer *fb)
11812 {
11813         struct drm_device *dev = plane->dev;
11814         struct intel_plane *intel_plane = to_intel_plane(plane);
11815         enum pipe pipe = intel_plane->pipe;
11816         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11817         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
11818         unsigned frontbuffer_bits = 0;
11819         int ret = 0;
11820
11821         if (!obj)
11822                 return 0;
11823
11824         switch (plane->type) {
11825         case DRM_PLANE_TYPE_PRIMARY:
11826                 frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(pipe);
11827                 break;
11828         case DRM_PLANE_TYPE_CURSOR:
11829                 frontbuffer_bits = INTEL_FRONTBUFFER_CURSOR(pipe);
11830                 break;
11831         case DRM_PLANE_TYPE_OVERLAY:
11832                 frontbuffer_bits = INTEL_FRONTBUFFER_SPRITE(pipe);
11833                 break;
11834         }
11835
11836         mutex_lock(&dev->struct_mutex);
11837
11838         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11839             INTEL_INFO(dev)->cursor_needs_physical) {
11840                 int align = IS_I830(dev) ? 16 * 1024 : 256;
11841                 ret = i915_gem_object_attach_phys(obj, align);
11842                 if (ret)
11843                         DRM_DEBUG_KMS("failed to attach phys object\n");
11844         } else {
11845                 ret = intel_pin_and_fence_fb_obj(plane, fb, NULL);
11846         }
11847
11848         if (ret == 0)
11849                 i915_gem_track_fb(old_obj, obj, frontbuffer_bits);
11850
11851         mutex_unlock(&dev->struct_mutex);
11852
11853         return ret;
11854 }
11855
11856 /**
11857  * intel_cleanup_plane_fb - Cleans up an fb after plane use
11858  * @plane: drm plane to clean up for
11859  * @fb: old framebuffer that was on plane
11860  *
11861  * Cleans up a framebuffer that has just been removed from a plane.
11862  */
11863 void
11864 intel_cleanup_plane_fb(struct drm_plane *plane,
11865                        struct drm_framebuffer *fb)
11866 {
11867         struct drm_device *dev = plane->dev;
11868         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11869
11870         if (WARN_ON(!obj))
11871                 return;
11872
11873         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
11874             !INTEL_INFO(dev)->cursor_needs_physical) {
11875                 mutex_lock(&dev->struct_mutex);
11876                 intel_unpin_fb_obj(obj);
11877                 mutex_unlock(&dev->struct_mutex);
11878         }
11879 }
11880
11881 static int
11882 intel_check_primary_plane(struct drm_plane *plane,
11883                           struct intel_plane_state *state)
11884 {
11885         struct drm_device *dev = plane->dev;
11886         struct drm_i915_private *dev_priv = dev->dev_private;
11887         struct drm_crtc *crtc = state->base.crtc;
11888         struct intel_crtc *intel_crtc;
11889         struct drm_framebuffer *fb = state->base.fb;
11890         struct drm_rect *dest = &state->dst;
11891         struct drm_rect *src = &state->src;
11892         const struct drm_rect *clip = &state->clip;
11893         int ret;
11894
11895         crtc = crtc ? crtc : plane->crtc;
11896         intel_crtc = to_intel_crtc(crtc);
11897
11898         ret = drm_plane_helper_check_update(plane, crtc, fb,
11899                                             src, dest, clip,
11900                                             DRM_PLANE_HELPER_NO_SCALING,
11901                                             DRM_PLANE_HELPER_NO_SCALING,
11902                                             false, true, &state->visible);
11903         if (ret)
11904                 return ret;
11905
11906         if (intel_crtc->active) {
11907                 intel_crtc->atomic.wait_for_flips = true;
11908
11909                 /*
11910                  * FBC does not work on some platforms for rotated
11911                  * planes, so disable it when rotation is not 0 and
11912                  * update it when rotation is set back to 0.
11913                  *
11914                  * FIXME: This is redundant with the fbc update done in
11915                  * the primary plane enable function except that that
11916                  * one is done too late. We eventually need to unify
11917                  * this.
11918                  */
11919                 if (intel_crtc->primary_enabled &&
11920                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11921                     dev_priv->fbc.plane == intel_crtc->plane &&
11922                     state->base.rotation != BIT(DRM_ROTATE_0)) {
11923                         intel_crtc->atomic.disable_fbc = true;
11924                 }
11925
11926                 if (state->visible) {
11927                         /*
11928                          * BDW signals flip done immediately if the plane
11929                          * is disabled, even if the plane enable is already
11930                          * armed to occur at the next vblank :(
11931                          */
11932                         if (IS_BROADWELL(dev) && !intel_crtc->primary_enabled)
11933                                 intel_crtc->atomic.wait_vblank = true;
11934                 }
11935
11936                 intel_crtc->atomic.fb_bits |=
11937                         INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
11938
11939                 intel_crtc->atomic.update_fbc = true;
11940         }
11941
11942         return 0;
11943 }
11944
11945 static void
11946 intel_commit_primary_plane(struct drm_plane *plane,
11947                            struct intel_plane_state *state)
11948 {
11949         struct drm_crtc *crtc = state->base.crtc;
11950         struct drm_framebuffer *fb = state->base.fb;
11951         struct drm_device *dev = plane->dev;
11952         struct drm_i915_private *dev_priv = dev->dev_private;
11953         struct intel_crtc *intel_crtc;
11954         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11955         struct intel_plane *intel_plane = to_intel_plane(plane);
11956         struct drm_rect *src = &state->src;
11957
11958         crtc = crtc ? crtc : plane->crtc;
11959         intel_crtc = to_intel_crtc(crtc);
11960
11961         plane->fb = fb;
11962         crtc->x = src->x1 >> 16;
11963         crtc->y = src->y1 >> 16;
11964
11965         intel_plane->obj = obj;
11966
11967         if (intel_crtc->active) {
11968                 if (state->visible) {
11969                         /* FIXME: kill this fastboot hack */
11970                         intel_update_pipe_size(intel_crtc);
11971
11972                         intel_crtc->primary_enabled = true;
11973
11974                         dev_priv->display.update_primary_plane(crtc, plane->fb,
11975                                         crtc->x, crtc->y);
11976                 } else {
11977                         /*
11978                          * If clipping results in a non-visible primary plane,
11979                          * we'll disable the primary plane.  Note that this is
11980                          * a bit different than what happens if userspace
11981                          * explicitly disables the plane by passing fb=0
11982                          * because plane->fb still gets set and pinned.
11983                          */
11984                         intel_disable_primary_hw_plane(plane, crtc);
11985                 }
11986         }
11987 }
11988
11989 static void intel_begin_crtc_commit(struct drm_crtc *crtc)
11990 {
11991         struct drm_device *dev = crtc->dev;
11992         struct drm_i915_private *dev_priv = dev->dev_private;
11993         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11994         struct intel_plane *intel_plane;
11995         struct drm_plane *p;
11996         unsigned fb_bits = 0;
11997
11998         /* Track fb's for any planes being disabled */
11999         list_for_each_entry(p, &dev->mode_config.plane_list, head) {
12000                 intel_plane = to_intel_plane(p);
12001
12002                 if (intel_crtc->atomic.disabled_planes &
12003                     (1 << drm_plane_index(p))) {
12004                         switch (p->type) {
12005                         case DRM_PLANE_TYPE_PRIMARY:
12006                                 fb_bits = INTEL_FRONTBUFFER_PRIMARY(intel_plane->pipe);
12007                                 break;
12008                         case DRM_PLANE_TYPE_CURSOR:
12009                                 fb_bits = INTEL_FRONTBUFFER_CURSOR(intel_plane->pipe);
12010                                 break;
12011                         case DRM_PLANE_TYPE_OVERLAY:
12012                                 fb_bits = INTEL_FRONTBUFFER_SPRITE(intel_plane->pipe);
12013                                 break;
12014                         }
12015
12016                         mutex_lock(&dev->struct_mutex);
12017                         i915_gem_track_fb(intel_fb_obj(p->fb), NULL, fb_bits);
12018                         mutex_unlock(&dev->struct_mutex);
12019                 }
12020         }
12021
12022         if (intel_crtc->atomic.wait_for_flips)
12023                 intel_crtc_wait_for_pending_flips(crtc);
12024
12025         if (intel_crtc->atomic.disable_fbc)
12026                 intel_fbc_disable(dev);
12027
12028         if (intel_crtc->atomic.pre_disable_primary)
12029                 intel_pre_disable_primary(crtc);
12030
12031         if (intel_crtc->atomic.update_wm)
12032                 intel_update_watermarks(crtc);
12033
12034         intel_runtime_pm_get(dev_priv);
12035
12036         /* Perform vblank evasion around commit operation */
12037         if (intel_crtc->active)
12038                 intel_crtc->atomic.evade =
12039                         intel_pipe_update_start(intel_crtc,
12040                                                 &intel_crtc->atomic.start_vbl_count);
12041 }
12042
12043 static void intel_finish_crtc_commit(struct drm_crtc *crtc)
12044 {
12045         struct drm_device *dev = crtc->dev;
12046         struct drm_i915_private *dev_priv = dev->dev_private;
12047         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12048         struct drm_plane *p;
12049
12050         if (intel_crtc->atomic.evade)
12051                 intel_pipe_update_end(intel_crtc,
12052                                       intel_crtc->atomic.start_vbl_count);
12053
12054         intel_runtime_pm_put(dev_priv);
12055
12056         if (intel_crtc->atomic.wait_vblank)
12057                 intel_wait_for_vblank(dev, intel_crtc->pipe);
12058
12059         intel_frontbuffer_flip(dev, intel_crtc->atomic.fb_bits);
12060
12061         if (intel_crtc->atomic.update_fbc) {
12062                 mutex_lock(&dev->struct_mutex);
12063                 intel_fbc_update(dev);
12064                 mutex_unlock(&dev->struct_mutex);
12065         }
12066
12067         if (intel_crtc->atomic.post_enable_primary)
12068                 intel_post_enable_primary(crtc);
12069
12070         drm_for_each_legacy_plane(p, &dev->mode_config.plane_list)
12071                 if (intel_crtc->atomic.update_sprite_watermarks & drm_plane_index(p))
12072                         intel_update_sprite_watermarks(p, crtc, 0, 0, 0,
12073                                                        false, false);
12074
12075         memset(&intel_crtc->atomic, 0, sizeof(intel_crtc->atomic));
12076 }
12077
12078 /**
12079  * intel_plane_destroy - destroy a plane
12080  * @plane: plane to destroy
12081  *
12082  * Common destruction function for all types of planes (primary, cursor,
12083  * sprite).
12084  */
12085 void intel_plane_destroy(struct drm_plane *plane)
12086 {
12087         struct intel_plane *intel_plane = to_intel_plane(plane);
12088         drm_plane_cleanup(plane);
12089         kfree(intel_plane);
12090 }
12091
12092 const struct drm_plane_funcs intel_plane_funcs = {
12093         .update_plane = drm_atomic_helper_update_plane,
12094         .disable_plane = drm_atomic_helper_disable_plane,
12095         .destroy = intel_plane_destroy,
12096         .set_property = drm_atomic_helper_plane_set_property,
12097         .atomic_get_property = intel_plane_atomic_get_property,
12098         .atomic_set_property = intel_plane_atomic_set_property,
12099         .atomic_duplicate_state = intel_plane_duplicate_state,
12100         .atomic_destroy_state = intel_plane_destroy_state,
12101
12102 };
12103
12104 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
12105                                                     int pipe)
12106 {
12107         struct intel_plane *primary;
12108         struct intel_plane_state *state;
12109         const uint32_t *intel_primary_formats;
12110         int num_formats;
12111
12112         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
12113         if (primary == NULL)
12114                 return NULL;
12115
12116         state = intel_create_plane_state(&primary->base);
12117         if (!state) {
12118                 kfree(primary);
12119                 return NULL;
12120         }
12121         primary->base.state = &state->base;
12122
12123         primary->can_scale = false;
12124         primary->max_downscale = 1;
12125         primary->pipe = pipe;
12126         primary->plane = pipe;
12127         primary->check_plane = intel_check_primary_plane;
12128         primary->commit_plane = intel_commit_primary_plane;
12129         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
12130                 primary->plane = !pipe;
12131
12132         if (INTEL_INFO(dev)->gen <= 3) {
12133                 intel_primary_formats = intel_primary_formats_gen2;
12134                 num_formats = ARRAY_SIZE(intel_primary_formats_gen2);
12135         } else {
12136                 intel_primary_formats = intel_primary_formats_gen4;
12137                 num_formats = ARRAY_SIZE(intel_primary_formats_gen4);
12138         }
12139
12140         drm_universal_plane_init(dev, &primary->base, 0,
12141                                  &intel_plane_funcs,
12142                                  intel_primary_formats, num_formats,
12143                                  DRM_PLANE_TYPE_PRIMARY);
12144
12145         if (INTEL_INFO(dev)->gen >= 4) {
12146                 if (!dev->mode_config.rotation_property)
12147                         dev->mode_config.rotation_property =
12148                                 drm_mode_create_rotation_property(dev,
12149                                                         BIT(DRM_ROTATE_0) |
12150                                                         BIT(DRM_ROTATE_180));
12151                 if (dev->mode_config.rotation_property)
12152                         drm_object_attach_property(&primary->base.base,
12153                                 dev->mode_config.rotation_property,
12154                                 state->base.rotation);
12155         }
12156
12157         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
12158
12159         return &primary->base;
12160 }
12161
12162 static int
12163 intel_check_cursor_plane(struct drm_plane *plane,
12164                          struct intel_plane_state *state)
12165 {
12166         struct drm_crtc *crtc = state->base.crtc;
12167         struct drm_device *dev = plane->dev;
12168         struct drm_framebuffer *fb = state->base.fb;
12169         struct drm_rect *dest = &state->dst;
12170         struct drm_rect *src = &state->src;
12171         const struct drm_rect *clip = &state->clip;
12172         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12173         struct intel_crtc *intel_crtc;
12174         unsigned stride;
12175         int ret;
12176
12177         crtc = crtc ? crtc : plane->crtc;
12178         intel_crtc = to_intel_crtc(crtc);
12179
12180         ret = drm_plane_helper_check_update(plane, crtc, fb,
12181                                             src, dest, clip,
12182                                             DRM_PLANE_HELPER_NO_SCALING,
12183                                             DRM_PLANE_HELPER_NO_SCALING,
12184                                             true, true, &state->visible);
12185         if (ret)
12186                 return ret;
12187
12188
12189         /* if we want to turn off the cursor ignore width and height */
12190         if (!obj)
12191                 goto finish;
12192
12193         /* Check for which cursor types we support */
12194         if (!cursor_size_ok(dev, state->base.crtc_w, state->base.crtc_h)) {
12195                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
12196                           state->base.crtc_w, state->base.crtc_h);
12197                 return -EINVAL;
12198         }
12199
12200         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
12201         if (obj->base.size < stride * state->base.crtc_h) {
12202                 DRM_DEBUG_KMS("buffer is too small\n");
12203                 return -ENOMEM;
12204         }
12205
12206         if (fb == crtc->cursor->fb)
12207                 return 0;
12208
12209         /* we only need to pin inside GTT if cursor is non-phy */
12210         mutex_lock(&dev->struct_mutex);
12211         if (!INTEL_INFO(dev)->cursor_needs_physical && obj->tiling_mode) {
12212                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
12213                 ret = -EINVAL;
12214         }
12215         mutex_unlock(&dev->struct_mutex);
12216
12217 finish:
12218         if (intel_crtc->active) {
12219                 if (intel_crtc->cursor_width != state->base.crtc_w)
12220                         intel_crtc->atomic.update_wm = true;
12221
12222                 intel_crtc->atomic.fb_bits |=
12223                         INTEL_FRONTBUFFER_CURSOR(intel_crtc->pipe);
12224         }
12225
12226         return ret;
12227 }
12228
12229 static void
12230 intel_commit_cursor_plane(struct drm_plane *plane,
12231                           struct intel_plane_state *state)
12232 {
12233         struct drm_crtc *crtc = state->base.crtc;
12234         struct drm_device *dev = plane->dev;
12235         struct intel_crtc *intel_crtc;
12236         struct intel_plane *intel_plane = to_intel_plane(plane);
12237         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
12238         uint32_t addr;
12239
12240         crtc = crtc ? crtc : plane->crtc;
12241         intel_crtc = to_intel_crtc(crtc);
12242
12243         plane->fb = state->base.fb;
12244         crtc->cursor_x = state->base.crtc_x;
12245         crtc->cursor_y = state->base.crtc_y;
12246
12247         intel_plane->obj = obj;
12248
12249         if (intel_crtc->cursor_bo == obj)
12250                 goto update;
12251
12252         if (!obj)
12253                 addr = 0;
12254         else if (!INTEL_INFO(dev)->cursor_needs_physical)
12255                 addr = i915_gem_obj_ggtt_offset(obj);
12256         else
12257                 addr = obj->phys_handle->busaddr;
12258
12259         intel_crtc->cursor_addr = addr;
12260         intel_crtc->cursor_bo = obj;
12261 update:
12262         intel_crtc->cursor_width = state->base.crtc_w;
12263         intel_crtc->cursor_height = state->base.crtc_h;
12264
12265         if (intel_crtc->active)
12266                 intel_crtc_update_cursor(crtc, state->visible);
12267 }
12268
12269 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
12270                                                    int pipe)
12271 {
12272         struct intel_plane *cursor;
12273         struct intel_plane_state *state;
12274
12275         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
12276         if (cursor == NULL)
12277                 return NULL;
12278
12279         state = intel_create_plane_state(&cursor->base);
12280         if (!state) {
12281                 kfree(cursor);
12282                 return NULL;
12283         }
12284         cursor->base.state = &state->base;
12285
12286         cursor->can_scale = false;
12287         cursor->max_downscale = 1;
12288         cursor->pipe = pipe;
12289         cursor->plane = pipe;
12290         cursor->check_plane = intel_check_cursor_plane;
12291         cursor->commit_plane = intel_commit_cursor_plane;
12292
12293         drm_universal_plane_init(dev, &cursor->base, 0,
12294                                  &intel_plane_funcs,
12295                                  intel_cursor_formats,
12296                                  ARRAY_SIZE(intel_cursor_formats),
12297                                  DRM_PLANE_TYPE_CURSOR);
12298
12299         if (INTEL_INFO(dev)->gen >= 4) {
12300                 if (!dev->mode_config.rotation_property)
12301                         dev->mode_config.rotation_property =
12302                                 drm_mode_create_rotation_property(dev,
12303                                                         BIT(DRM_ROTATE_0) |
12304                                                         BIT(DRM_ROTATE_180));
12305                 if (dev->mode_config.rotation_property)
12306                         drm_object_attach_property(&cursor->base.base,
12307                                 dev->mode_config.rotation_property,
12308                                 state->base.rotation);
12309         }
12310
12311         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
12312
12313         return &cursor->base;
12314 }
12315
12316 static void intel_crtc_init(struct drm_device *dev, int pipe)
12317 {
12318         struct drm_i915_private *dev_priv = dev->dev_private;
12319         struct intel_crtc *intel_crtc;
12320         struct intel_crtc_state *crtc_state = NULL;
12321         struct drm_plane *primary = NULL;
12322         struct drm_plane *cursor = NULL;
12323         int i, ret;
12324
12325         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
12326         if (intel_crtc == NULL)
12327                 return;
12328
12329         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
12330         if (!crtc_state)
12331                 goto fail;
12332         intel_crtc_set_state(intel_crtc, crtc_state);
12333
12334         primary = intel_primary_plane_create(dev, pipe);
12335         if (!primary)
12336                 goto fail;
12337
12338         cursor = intel_cursor_plane_create(dev, pipe);
12339         if (!cursor)
12340                 goto fail;
12341
12342         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
12343                                         cursor, &intel_crtc_funcs);
12344         if (ret)
12345                 goto fail;
12346
12347         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
12348         for (i = 0; i < 256; i++) {
12349                 intel_crtc->lut_r[i] = i;
12350                 intel_crtc->lut_g[i] = i;
12351                 intel_crtc->lut_b[i] = i;
12352         }
12353
12354         /*
12355          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
12356          * is hooked to pipe B. Hence we want plane A feeding pipe B.
12357          */
12358         intel_crtc->pipe = pipe;
12359         intel_crtc->plane = pipe;
12360         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
12361                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
12362                 intel_crtc->plane = !pipe;
12363         }
12364
12365         intel_crtc->cursor_base = ~0;
12366         intel_crtc->cursor_cntl = ~0;
12367         intel_crtc->cursor_size = ~0;
12368
12369         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
12370                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
12371         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
12372         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
12373
12374         INIT_WORK(&intel_crtc->mmio_flip.work, intel_mmio_flip_work_func);
12375
12376         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
12377
12378         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
12379         return;
12380
12381 fail:
12382         if (primary)
12383                 drm_plane_cleanup(primary);
12384         if (cursor)
12385                 drm_plane_cleanup(cursor);
12386         kfree(crtc_state);
12387         kfree(intel_crtc);
12388 }
12389
12390 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
12391 {
12392         struct drm_encoder *encoder = connector->base.encoder;
12393         struct drm_device *dev = connector->base.dev;
12394
12395         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
12396
12397         if (!encoder || WARN_ON(!encoder->crtc))
12398                 return INVALID_PIPE;
12399
12400         return to_intel_crtc(encoder->crtc)->pipe;
12401 }
12402
12403 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
12404                                 struct drm_file *file)
12405 {
12406         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
12407         struct drm_crtc *drmmode_crtc;
12408         struct intel_crtc *crtc;
12409
12410         if (!drm_core_check_feature(dev, DRIVER_MODESET))
12411                 return -ENODEV;
12412
12413         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
12414
12415         if (!drmmode_crtc) {
12416                 DRM_ERROR("no such CRTC id\n");
12417                 return -ENOENT;
12418         }
12419
12420         crtc = to_intel_crtc(drmmode_crtc);
12421         pipe_from_crtc_id->pipe = crtc->pipe;
12422
12423         return 0;
12424 }
12425
12426 static int intel_encoder_clones(struct intel_encoder *encoder)
12427 {
12428         struct drm_device *dev = encoder->base.dev;
12429         struct intel_encoder *source_encoder;
12430         int index_mask = 0;
12431         int entry = 0;
12432
12433         for_each_intel_encoder(dev, source_encoder) {
12434                 if (encoders_cloneable(encoder, source_encoder))
12435                         index_mask |= (1 << entry);
12436
12437                 entry++;
12438         }
12439
12440         return index_mask;
12441 }
12442
12443 static bool has_edp_a(struct drm_device *dev)
12444 {
12445         struct drm_i915_private *dev_priv = dev->dev_private;
12446
12447         if (!IS_MOBILE(dev))
12448                 return false;
12449
12450         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
12451                 return false;
12452
12453         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
12454                 return false;
12455
12456         return true;
12457 }
12458
12459 static bool intel_crt_present(struct drm_device *dev)
12460 {
12461         struct drm_i915_private *dev_priv = dev->dev_private;
12462
12463         if (INTEL_INFO(dev)->gen >= 9)
12464                 return false;
12465
12466         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
12467                 return false;
12468
12469         if (IS_CHERRYVIEW(dev))
12470                 return false;
12471
12472         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
12473                 return false;
12474
12475         return true;
12476 }
12477
12478 static void intel_setup_outputs(struct drm_device *dev)
12479 {
12480         struct drm_i915_private *dev_priv = dev->dev_private;
12481         struct intel_encoder *encoder;
12482         struct drm_connector *connector;
12483         bool dpd_is_edp = false;
12484
12485         intel_lvds_init(dev);
12486
12487         if (intel_crt_present(dev))
12488                 intel_crt_init(dev);
12489
12490         if (HAS_DDI(dev)) {
12491                 int found;
12492
12493                 /* Haswell uses DDI functions to detect digital outputs */
12494                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
12495                 /* DDI A only supports eDP */
12496                 if (found)
12497                         intel_ddi_init(dev, PORT_A);
12498
12499                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
12500                  * register */
12501                 found = I915_READ(SFUSE_STRAP);
12502
12503                 if (found & SFUSE_STRAP_DDIB_DETECTED)
12504                         intel_ddi_init(dev, PORT_B);
12505                 if (found & SFUSE_STRAP_DDIC_DETECTED)
12506                         intel_ddi_init(dev, PORT_C);
12507                 if (found & SFUSE_STRAP_DDID_DETECTED)
12508                         intel_ddi_init(dev, PORT_D);
12509         } else if (HAS_PCH_SPLIT(dev)) {
12510                 int found;
12511                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
12512
12513                 if (has_edp_a(dev))
12514                         intel_dp_init(dev, DP_A, PORT_A);
12515
12516                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
12517                         /* PCH SDVOB multiplex with HDMIB */
12518                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
12519                         if (!found)
12520                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
12521                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
12522                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
12523                 }
12524
12525                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
12526                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
12527
12528                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
12529                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
12530
12531                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
12532                         intel_dp_init(dev, PCH_DP_C, PORT_C);
12533
12534                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
12535                         intel_dp_init(dev, PCH_DP_D, PORT_D);
12536         } else if (IS_VALLEYVIEW(dev)) {
12537                 /*
12538                  * The DP_DETECTED bit is the latched state of the DDC
12539                  * SDA pin at boot. However since eDP doesn't require DDC
12540                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
12541                  * eDP ports may have been muxed to an alternate function.
12542                  * Thus we can't rely on the DP_DETECTED bit alone to detect
12543                  * eDP ports. Consult the VBT as well as DP_DETECTED to
12544                  * detect eDP ports.
12545                  */
12546                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
12547                     !intel_dp_is_edp(dev, PORT_B))
12548                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
12549                                         PORT_B);
12550                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
12551                     intel_dp_is_edp(dev, PORT_B))
12552                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
12553
12554                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
12555                     !intel_dp_is_edp(dev, PORT_C))
12556                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
12557                                         PORT_C);
12558                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
12559                     intel_dp_is_edp(dev, PORT_C))
12560                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
12561
12562                 if (IS_CHERRYVIEW(dev)) {
12563                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
12564                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
12565                                                 PORT_D);
12566                         /* eDP not supported on port D, so don't check VBT */
12567                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
12568                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
12569                 }
12570
12571                 intel_dsi_init(dev);
12572         } else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
12573                 bool found = false;
12574
12575                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
12576                         DRM_DEBUG_KMS("probing SDVOB\n");
12577                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
12578                         if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
12579                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
12580                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
12581                         }
12582
12583                         if (!found && SUPPORTS_INTEGRATED_DP(dev))
12584                                 intel_dp_init(dev, DP_B, PORT_B);
12585                 }
12586
12587                 /* Before G4X SDVOC doesn't have its own detect register */
12588
12589                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
12590                         DRM_DEBUG_KMS("probing SDVOC\n");
12591                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
12592                 }
12593
12594                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
12595
12596                         if (SUPPORTS_INTEGRATED_HDMI(dev)) {
12597                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
12598                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
12599                         }
12600                         if (SUPPORTS_INTEGRATED_DP(dev))
12601                                 intel_dp_init(dev, DP_C, PORT_C);
12602                 }
12603
12604                 if (SUPPORTS_INTEGRATED_DP(dev) &&
12605                     (I915_READ(DP_D) & DP_DETECTED))
12606                         intel_dp_init(dev, DP_D, PORT_D);
12607         } else if (IS_GEN2(dev))
12608                 intel_dvo_init(dev);
12609
12610         if (SUPPORTS_TV(dev))
12611                 intel_tv_init(dev);
12612
12613         /*
12614          * FIXME:  We don't have full atomic support yet, but we want to be
12615          * able to enable/test plane updates via the atomic interface in the
12616          * meantime.  However as soon as we flip DRIVER_ATOMIC on, the DRM core
12617          * will take some atomic codepaths to lookup properties during
12618          * drmModeGetConnector() that unconditionally dereference
12619          * connector->state.
12620          *
12621          * We create a dummy connector state here for each connector to ensure
12622          * the DRM core doesn't try to dereference a NULL connector->state.
12623          * The actual connector properties will never be updated or contain
12624          * useful information, but since we're doing this specifically for
12625          * testing/debug of the plane operations (and only when a specific
12626          * kernel module option is given), that shouldn't really matter.
12627          *
12628          * Once atomic support for crtc's + connectors lands, this loop should
12629          * be removed since we'll be setting up real connector state, which
12630          * will contain Intel-specific properties.
12631          */
12632         if (drm_core_check_feature(dev, DRIVER_ATOMIC)) {
12633                 list_for_each_entry(connector,
12634                                     &dev->mode_config.connector_list,
12635                                     head) {
12636                         if (!WARN_ON(connector->state)) {
12637                                 connector->state =
12638                                         kzalloc(sizeof(*connector->state),
12639                                                 GFP_KERNEL);
12640                         }
12641                 }
12642         }
12643
12644         intel_psr_init(dev);
12645
12646         for_each_intel_encoder(dev, encoder) {
12647                 encoder->base.possible_crtcs = encoder->crtc_mask;
12648                 encoder->base.possible_clones =
12649                         intel_encoder_clones(encoder);
12650         }
12651
12652         intel_init_pch_refclk(dev);
12653
12654         drm_helper_move_panel_connectors_to_head(dev);
12655 }
12656
12657 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
12658 {
12659         struct drm_device *dev = fb->dev;
12660         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
12661
12662         drm_framebuffer_cleanup(fb);
12663         mutex_lock(&dev->struct_mutex);
12664         WARN_ON(!intel_fb->obj->framebuffer_references--);
12665         drm_gem_object_unreference(&intel_fb->obj->base);
12666         mutex_unlock(&dev->struct_mutex);
12667         kfree(intel_fb);
12668 }
12669
12670 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
12671                                                 struct drm_file *file,
12672                                                 unsigned int *handle)
12673 {
12674         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
12675         struct drm_i915_gem_object *obj = intel_fb->obj;
12676
12677         return drm_gem_handle_create(file, &obj->base, handle);
12678 }
12679
12680 static const struct drm_framebuffer_funcs intel_fb_funcs = {
12681         .destroy = intel_user_framebuffer_destroy,
12682         .create_handle = intel_user_framebuffer_create_handle,
12683 };
12684
12685 static int intel_framebuffer_init(struct drm_device *dev,
12686                                   struct intel_framebuffer *intel_fb,
12687                                   struct drm_mode_fb_cmd2 *mode_cmd,
12688                                   struct drm_i915_gem_object *obj)
12689 {
12690         int aligned_height;
12691         int pitch_limit;
12692         int ret;
12693
12694         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
12695
12696         if (obj->tiling_mode == I915_TILING_Y) {
12697                 DRM_DEBUG("hardware does not support tiling Y\n");
12698                 return -EINVAL;
12699         }
12700
12701         if (mode_cmd->pitches[0] & 63) {
12702                 DRM_DEBUG("pitch (%d) must be at least 64 byte aligned\n",
12703                           mode_cmd->pitches[0]);
12704                 return -EINVAL;
12705         }
12706
12707         if (INTEL_INFO(dev)->gen >= 5 && !IS_VALLEYVIEW(dev)) {
12708                 pitch_limit = 32*1024;
12709         } else if (INTEL_INFO(dev)->gen >= 4) {
12710                 if (obj->tiling_mode)
12711                         pitch_limit = 16*1024;
12712                 else
12713                         pitch_limit = 32*1024;
12714         } else if (INTEL_INFO(dev)->gen >= 3) {
12715                 if (obj->tiling_mode)
12716                         pitch_limit = 8*1024;
12717                 else
12718                         pitch_limit = 16*1024;
12719         } else
12720                 /* XXX DSPC is limited to 4k tiled */
12721                 pitch_limit = 8*1024;
12722
12723         if (mode_cmd->pitches[0] > pitch_limit) {
12724                 DRM_DEBUG("%s pitch (%d) must be at less than %d\n",
12725                           obj->tiling_mode ? "tiled" : "linear",
12726                           mode_cmd->pitches[0], pitch_limit);
12727                 return -EINVAL;
12728         }
12729
12730         if (obj->tiling_mode != I915_TILING_NONE &&
12731             mode_cmd->pitches[0] != obj->stride) {
12732                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
12733                           mode_cmd->pitches[0], obj->stride);
12734                 return -EINVAL;
12735         }
12736
12737         /* Reject formats not supported by any plane early. */
12738         switch (mode_cmd->pixel_format) {
12739         case DRM_FORMAT_C8:
12740         case DRM_FORMAT_RGB565:
12741         case DRM_FORMAT_XRGB8888:
12742         case DRM_FORMAT_ARGB8888:
12743                 break;
12744         case DRM_FORMAT_XRGB1555:
12745         case DRM_FORMAT_ARGB1555:
12746                 if (INTEL_INFO(dev)->gen > 3) {
12747                         DRM_DEBUG("unsupported pixel format: %s\n",
12748                                   drm_get_format_name(mode_cmd->pixel_format));
12749                         return -EINVAL;
12750                 }
12751                 break;
12752         case DRM_FORMAT_XBGR8888:
12753         case DRM_FORMAT_ABGR8888:
12754         case DRM_FORMAT_XRGB2101010:
12755         case DRM_FORMAT_ARGB2101010:
12756         case DRM_FORMAT_XBGR2101010:
12757         case DRM_FORMAT_ABGR2101010:
12758                 if (INTEL_INFO(dev)->gen < 4) {
12759                         DRM_DEBUG("unsupported pixel format: %s\n",
12760                                   drm_get_format_name(mode_cmd->pixel_format));
12761                         return -EINVAL;
12762                 }
12763                 break;
12764         case DRM_FORMAT_YUYV:
12765         case DRM_FORMAT_UYVY:
12766         case DRM_FORMAT_YVYU:
12767         case DRM_FORMAT_VYUY:
12768                 if (INTEL_INFO(dev)->gen < 5) {
12769                         DRM_DEBUG("unsupported pixel format: %s\n",
12770                                   drm_get_format_name(mode_cmd->pixel_format));
12771                         return -EINVAL;
12772                 }
12773                 break;
12774         default:
12775                 DRM_DEBUG("unsupported pixel format: %s\n",
12776                           drm_get_format_name(mode_cmd->pixel_format));
12777                 return -EINVAL;
12778         }
12779
12780         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
12781         if (mode_cmd->offsets[0] != 0)
12782                 return -EINVAL;
12783
12784         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
12785                                                obj->tiling_mode);
12786         /* FIXME drm helper for size checks (especially planar formats)? */
12787         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
12788                 return -EINVAL;
12789
12790         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
12791         intel_fb->obj = obj;
12792         intel_fb->obj->framebuffer_references++;
12793
12794         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
12795         if (ret) {
12796                 DRM_ERROR("framebuffer init failed %d\n", ret);
12797                 return ret;
12798         }
12799
12800         return 0;
12801 }
12802
12803 static struct drm_framebuffer *
12804 intel_user_framebuffer_create(struct drm_device *dev,
12805                               struct drm_file *filp,
12806                               struct drm_mode_fb_cmd2 *mode_cmd)
12807 {
12808         struct drm_i915_gem_object *obj;
12809
12810         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
12811                                                 mode_cmd->handles[0]));
12812         if (&obj->base == NULL)
12813                 return ERR_PTR(-ENOENT);
12814
12815         return intel_framebuffer_create(dev, mode_cmd, obj);
12816 }
12817
12818 #ifndef CONFIG_DRM_I915_FBDEV
12819 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
12820 {
12821 }
12822 #endif
12823
12824 static const struct drm_mode_config_funcs intel_mode_funcs = {
12825         .fb_create = intel_user_framebuffer_create,
12826         .output_poll_changed = intel_fbdev_output_poll_changed,
12827         .atomic_check = intel_atomic_check,
12828         .atomic_commit = intel_atomic_commit,
12829 };
12830
12831 /* Set up chip specific display functions */
12832 static void intel_init_display(struct drm_device *dev)
12833 {
12834         struct drm_i915_private *dev_priv = dev->dev_private;
12835
12836         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
12837                 dev_priv->display.find_dpll = g4x_find_best_dpll;
12838         else if (IS_CHERRYVIEW(dev))
12839                 dev_priv->display.find_dpll = chv_find_best_dpll;
12840         else if (IS_VALLEYVIEW(dev))
12841                 dev_priv->display.find_dpll = vlv_find_best_dpll;
12842         else if (IS_PINEVIEW(dev))
12843                 dev_priv->display.find_dpll = pnv_find_best_dpll;
12844         else
12845                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
12846
12847         if (INTEL_INFO(dev)->gen >= 9) {
12848                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
12849                 dev_priv->display.get_initial_plane_config =
12850                         skylake_get_initial_plane_config;
12851                 dev_priv->display.crtc_compute_clock =
12852                         haswell_crtc_compute_clock;
12853                 dev_priv->display.crtc_enable = haswell_crtc_enable;
12854                 dev_priv->display.crtc_disable = haswell_crtc_disable;
12855                 dev_priv->display.off = ironlake_crtc_off;
12856                 dev_priv->display.update_primary_plane =
12857                         skylake_update_primary_plane;
12858         } else if (HAS_DDI(dev)) {
12859                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
12860                 dev_priv->display.get_initial_plane_config =
12861                         ironlake_get_initial_plane_config;
12862                 dev_priv->display.crtc_compute_clock =
12863                         haswell_crtc_compute_clock;
12864                 dev_priv->display.crtc_enable = haswell_crtc_enable;
12865                 dev_priv->display.crtc_disable = haswell_crtc_disable;
12866                 dev_priv->display.off = ironlake_crtc_off;
12867                 dev_priv->display.update_primary_plane =
12868                         ironlake_update_primary_plane;
12869         } else if (HAS_PCH_SPLIT(dev)) {
12870                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
12871                 dev_priv->display.get_initial_plane_config =
12872                         ironlake_get_initial_plane_config;
12873                 dev_priv->display.crtc_compute_clock =
12874                         ironlake_crtc_compute_clock;
12875                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
12876                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
12877                 dev_priv->display.off = ironlake_crtc_off;
12878                 dev_priv->display.update_primary_plane =
12879                         ironlake_update_primary_plane;
12880         } else if (IS_VALLEYVIEW(dev)) {
12881                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
12882                 dev_priv->display.get_initial_plane_config =
12883                         i9xx_get_initial_plane_config;
12884                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
12885                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
12886                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
12887                 dev_priv->display.off = i9xx_crtc_off;
12888                 dev_priv->display.update_primary_plane =
12889                         i9xx_update_primary_plane;
12890         } else {
12891                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
12892                 dev_priv->display.get_initial_plane_config =
12893                         i9xx_get_initial_plane_config;
12894                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
12895                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
12896                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
12897                 dev_priv->display.off = i9xx_crtc_off;
12898                 dev_priv->display.update_primary_plane =
12899                         i9xx_update_primary_plane;
12900         }
12901
12902         /* Returns the core display clock speed */
12903         if (IS_VALLEYVIEW(dev))
12904                 dev_priv->display.get_display_clock_speed =
12905                         valleyview_get_display_clock_speed;
12906         else if (IS_I945G(dev) || (IS_G33(dev) && !IS_PINEVIEW_M(dev)))
12907                 dev_priv->display.get_display_clock_speed =
12908                         i945_get_display_clock_speed;
12909         else if (IS_I915G(dev))
12910                 dev_priv->display.get_display_clock_speed =
12911                         i915_get_display_clock_speed;
12912         else if (IS_I945GM(dev) || IS_845G(dev))
12913                 dev_priv->display.get_display_clock_speed =
12914                         i9xx_misc_get_display_clock_speed;
12915         else if (IS_PINEVIEW(dev))
12916                 dev_priv->display.get_display_clock_speed =
12917                         pnv_get_display_clock_speed;
12918         else if (IS_I915GM(dev))
12919                 dev_priv->display.get_display_clock_speed =
12920                         i915gm_get_display_clock_speed;
12921         else if (IS_I865G(dev))
12922                 dev_priv->display.get_display_clock_speed =
12923                         i865_get_display_clock_speed;
12924         else if (IS_I85X(dev))
12925                 dev_priv->display.get_display_clock_speed =
12926                         i855_get_display_clock_speed;
12927         else /* 852, 830 */
12928                 dev_priv->display.get_display_clock_speed =
12929                         i830_get_display_clock_speed;
12930
12931         if (IS_GEN5(dev)) {
12932                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
12933         } else if (IS_GEN6(dev)) {
12934                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
12935         } else if (IS_IVYBRIDGE(dev)) {
12936                 /* FIXME: detect B0+ stepping and use auto training */
12937                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
12938                 dev_priv->display.modeset_global_resources =
12939                         ivb_modeset_global_resources;
12940         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
12941                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
12942         } else if (IS_VALLEYVIEW(dev)) {
12943                 dev_priv->display.modeset_global_resources =
12944                         valleyview_modeset_global_resources;
12945         }
12946
12947         /* Default just returns -ENODEV to indicate unsupported */
12948         dev_priv->display.queue_flip = intel_default_queue_flip;
12949
12950         switch (INTEL_INFO(dev)->gen) {
12951         case 2:
12952                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
12953                 break;
12954
12955         case 3:
12956                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
12957                 break;
12958
12959         case 4:
12960         case 5:
12961                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
12962                 break;
12963
12964         case 6:
12965                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
12966                 break;
12967         case 7:
12968         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
12969                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
12970                 break;
12971         case 9:
12972                 dev_priv->display.queue_flip = intel_gen9_queue_flip;
12973                 break;
12974         }
12975
12976         intel_panel_init_backlight_funcs(dev);
12977
12978         mutex_init(&dev_priv->pps_mutex);
12979 }
12980
12981 /*
12982  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
12983  * resume, or other times.  This quirk makes sure that's the case for
12984  * affected systems.
12985  */
12986 static void quirk_pipea_force(struct drm_device *dev)
12987 {
12988         struct drm_i915_private *dev_priv = dev->dev_private;
12989
12990         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
12991         DRM_INFO("applying pipe a force quirk\n");
12992 }
12993
12994 static void quirk_pipeb_force(struct drm_device *dev)
12995 {
12996         struct drm_i915_private *dev_priv = dev->dev_private;
12997
12998         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
12999         DRM_INFO("applying pipe b force quirk\n");
13000 }
13001
13002 /*
13003  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
13004  */
13005 static void quirk_ssc_force_disable(struct drm_device *dev)
13006 {
13007         struct drm_i915_private *dev_priv = dev->dev_private;
13008         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
13009         DRM_INFO("applying lvds SSC disable quirk\n");
13010 }
13011
13012 /*
13013  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
13014  * brightness value
13015  */
13016 static void quirk_invert_brightness(struct drm_device *dev)
13017 {
13018         struct drm_i915_private *dev_priv = dev->dev_private;
13019         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
13020         DRM_INFO("applying inverted panel brightness quirk\n");
13021 }
13022
13023 /* Some VBT's incorrectly indicate no backlight is present */
13024 static void quirk_backlight_present(struct drm_device *dev)
13025 {
13026         struct drm_i915_private *dev_priv = dev->dev_private;
13027         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
13028         DRM_INFO("applying backlight present quirk\n");
13029 }
13030
13031 struct intel_quirk {
13032         int device;
13033         int subsystem_vendor;
13034         int subsystem_device;
13035         void (*hook)(struct drm_device *dev);
13036 };
13037
13038 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
13039 struct intel_dmi_quirk {
13040         void (*hook)(struct drm_device *dev);
13041         const struct dmi_system_id (*dmi_id_list)[];
13042 };
13043
13044 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
13045 {
13046         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
13047         return 1;
13048 }
13049
13050 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
13051         {
13052                 .dmi_id_list = &(const struct dmi_system_id[]) {
13053                         {
13054                                 .callback = intel_dmi_reverse_brightness,
13055                                 .ident = "NCR Corporation",
13056                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
13057                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
13058                                 },
13059                         },
13060                         { }  /* terminating entry */
13061                 },
13062                 .hook = quirk_invert_brightness,
13063         },
13064 };
13065
13066 static struct intel_quirk intel_quirks[] = {
13067         /* HP Mini needs pipe A force quirk (LP: #322104) */
13068         { 0x27ae, 0x103c, 0x361a, quirk_pipea_force },
13069
13070         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
13071         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
13072
13073         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
13074         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
13075
13076         /* 830 needs to leave pipe A & dpll A up */
13077         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
13078
13079         /* 830 needs to leave pipe B & dpll B up */
13080         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
13081
13082         /* Lenovo U160 cannot use SSC on LVDS */
13083         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
13084
13085         /* Sony Vaio Y cannot use SSC on LVDS */
13086         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
13087
13088         /* Acer Aspire 5734Z must invert backlight brightness */
13089         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
13090
13091         /* Acer/eMachines G725 */
13092         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
13093
13094         /* Acer/eMachines e725 */
13095         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
13096
13097         /* Acer/Packard Bell NCL20 */
13098         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
13099
13100         /* Acer Aspire 4736Z */
13101         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
13102
13103         /* Acer Aspire 5336 */
13104         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
13105
13106         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
13107         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
13108
13109         /* Acer C720 Chromebook (Core i3 4005U) */
13110         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
13111
13112         /* Apple Macbook 2,1 (Core 2 T7400) */
13113         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
13114
13115         /* Toshiba CB35 Chromebook (Celeron 2955U) */
13116         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
13117
13118         /* HP Chromebook 14 (Celeron 2955U) */
13119         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
13120 };
13121
13122 static void intel_init_quirks(struct drm_device *dev)
13123 {
13124         struct pci_dev *d = dev->pdev;
13125         int i;
13126
13127         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
13128                 struct intel_quirk *q = &intel_quirks[i];
13129
13130                 if (d->device == q->device &&
13131                     (d->subsystem_vendor == q->subsystem_vendor ||
13132                      q->subsystem_vendor == PCI_ANY_ID) &&
13133                     (d->subsystem_device == q->subsystem_device ||
13134                      q->subsystem_device == PCI_ANY_ID))
13135                         q->hook(dev);
13136         }
13137         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
13138                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
13139                         intel_dmi_quirks[i].hook(dev);
13140         }
13141 }
13142
13143 /* Disable the VGA plane that we never use */
13144 static void i915_disable_vga(struct drm_device *dev)
13145 {
13146         struct drm_i915_private *dev_priv = dev->dev_private;
13147         u8 sr1;
13148         u32 vga_reg = i915_vgacntrl_reg(dev);
13149
13150         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
13151         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
13152         outb(SR01, VGA_SR_INDEX);
13153         sr1 = inb(VGA_SR_DATA);
13154         outb(sr1 | 1<<5, VGA_SR_DATA);
13155         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
13156         udelay(300);
13157
13158         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
13159         POSTING_READ(vga_reg);
13160 }
13161
13162 void intel_modeset_init_hw(struct drm_device *dev)
13163 {
13164         intel_prepare_ddi(dev);
13165
13166         if (IS_VALLEYVIEW(dev))
13167                 vlv_update_cdclk(dev);
13168
13169         intel_init_clock_gating(dev);
13170
13171         intel_enable_gt_powersave(dev);
13172 }
13173
13174 void intel_modeset_init(struct drm_device *dev)
13175 {
13176         struct drm_i915_private *dev_priv = dev->dev_private;
13177         int sprite, ret;
13178         enum pipe pipe;
13179         struct intel_crtc *crtc;
13180
13181         drm_mode_config_init(dev);
13182
13183         dev->mode_config.min_width = 0;
13184         dev->mode_config.min_height = 0;
13185
13186         dev->mode_config.preferred_depth = 24;
13187         dev->mode_config.prefer_shadow = 1;
13188
13189         dev->mode_config.funcs = &intel_mode_funcs;
13190
13191         intel_init_quirks(dev);
13192
13193         intel_init_pm(dev);
13194
13195         if (INTEL_INFO(dev)->num_pipes == 0)
13196                 return;
13197
13198         intel_init_display(dev);
13199         intel_init_audio(dev);
13200
13201         if (IS_GEN2(dev)) {
13202                 dev->mode_config.max_width = 2048;
13203                 dev->mode_config.max_height = 2048;
13204         } else if (IS_GEN3(dev)) {
13205                 dev->mode_config.max_width = 4096;
13206                 dev->mode_config.max_height = 4096;
13207         } else {
13208                 dev->mode_config.max_width = 8192;
13209                 dev->mode_config.max_height = 8192;
13210         }
13211
13212         if (IS_845G(dev) || IS_I865G(dev)) {
13213                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
13214                 dev->mode_config.cursor_height = 1023;
13215         } else if (IS_GEN2(dev)) {
13216                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
13217                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
13218         } else {
13219                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
13220                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
13221         }
13222
13223         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
13224
13225         DRM_DEBUG_KMS("%d display pipe%s available.\n",
13226                       INTEL_INFO(dev)->num_pipes,
13227                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
13228
13229         for_each_pipe(dev_priv, pipe) {
13230                 intel_crtc_init(dev, pipe);
13231                 for_each_sprite(pipe, sprite) {
13232                         ret = intel_plane_init(dev, pipe, sprite);
13233                         if (ret)
13234                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
13235                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
13236                 }
13237         }
13238
13239         intel_init_dpio(dev);
13240
13241         intel_shared_dpll_init(dev);
13242
13243         /* Just disable it once at startup */
13244         i915_disable_vga(dev);
13245         intel_setup_outputs(dev);
13246
13247         /* Just in case the BIOS is doing something questionable. */
13248         intel_fbc_disable(dev);
13249
13250         drm_modeset_lock_all(dev);
13251         intel_modeset_setup_hw_state(dev, false);
13252         drm_modeset_unlock_all(dev);
13253
13254         for_each_intel_crtc(dev, crtc) {
13255                 if (!crtc->active)
13256                         continue;
13257
13258                 /*
13259                  * Note that reserving the BIOS fb up front prevents us
13260                  * from stuffing other stolen allocations like the ring
13261                  * on top.  This prevents some ugliness at boot time, and
13262                  * can even allow for smooth boot transitions if the BIOS
13263                  * fb is large enough for the active pipe configuration.
13264                  */
13265                 if (dev_priv->display.get_initial_plane_config) {
13266                         dev_priv->display.get_initial_plane_config(crtc,
13267                                                            &crtc->plane_config);
13268                         /*
13269                          * If the fb is shared between multiple heads, we'll
13270                          * just get the first one.
13271                          */
13272                         intel_find_plane_obj(crtc, &crtc->plane_config);
13273                 }
13274         }
13275 }
13276
13277 static void intel_enable_pipe_a(struct drm_device *dev)
13278 {
13279         struct intel_connector *connector;
13280         struct drm_connector *crt = NULL;
13281         struct intel_load_detect_pipe load_detect_temp;
13282         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
13283
13284         /* We can't just switch on the pipe A, we need to set things up with a
13285          * proper mode and output configuration. As a gross hack, enable pipe A
13286          * by enabling the load detect pipe once. */
13287         list_for_each_entry(connector,
13288                             &dev->mode_config.connector_list,
13289                             base.head) {
13290                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
13291                         crt = &connector->base;
13292                         break;
13293                 }
13294         }
13295
13296         if (!crt)
13297                 return;
13298
13299         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
13300                 intel_release_load_detect_pipe(crt, &load_detect_temp);
13301 }
13302
13303 static bool
13304 intel_check_plane_mapping(struct intel_crtc *crtc)
13305 {
13306         struct drm_device *dev = crtc->base.dev;
13307         struct drm_i915_private *dev_priv = dev->dev_private;
13308         u32 reg, val;
13309
13310         if (INTEL_INFO(dev)->num_pipes == 1)
13311                 return true;
13312
13313         reg = DSPCNTR(!crtc->plane);
13314         val = I915_READ(reg);
13315
13316         if ((val & DISPLAY_PLANE_ENABLE) &&
13317             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
13318                 return false;
13319
13320         return true;
13321 }
13322
13323 static void intel_sanitize_crtc(struct intel_crtc *crtc)
13324 {
13325         struct drm_device *dev = crtc->base.dev;
13326         struct drm_i915_private *dev_priv = dev->dev_private;
13327         u32 reg;
13328
13329         /* Clear any frame start delays used for debugging left by the BIOS */
13330         reg = PIPECONF(crtc->config->cpu_transcoder);
13331         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
13332
13333         /* restore vblank interrupts to correct state */
13334         if (crtc->active) {
13335                 update_scanline_offset(crtc);
13336                 drm_vblank_on(dev, crtc->pipe);
13337         } else
13338                 drm_vblank_off(dev, crtc->pipe);
13339
13340         /* We need to sanitize the plane -> pipe mapping first because this will
13341          * disable the crtc (and hence change the state) if it is wrong. Note
13342          * that gen4+ has a fixed plane -> pipe mapping.  */
13343         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
13344                 struct intel_connector *connector;
13345                 bool plane;
13346
13347                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
13348                               crtc->base.base.id);
13349
13350                 /* Pipe has the wrong plane attached and the plane is active.
13351                  * Temporarily change the plane mapping and disable everything
13352                  * ...  */
13353                 plane = crtc->plane;
13354                 crtc->plane = !plane;
13355                 crtc->primary_enabled = true;
13356                 dev_priv->display.crtc_disable(&crtc->base);
13357                 crtc->plane = plane;
13358
13359                 /* ... and break all links. */
13360                 list_for_each_entry(connector, &dev->mode_config.connector_list,
13361                                     base.head) {
13362                         if (connector->encoder->base.crtc != &crtc->base)
13363                                 continue;
13364
13365                         connector->base.dpms = DRM_MODE_DPMS_OFF;
13366                         connector->base.encoder = NULL;
13367                 }
13368                 /* multiple connectors may have the same encoder:
13369                  *  handle them and break crtc link separately */
13370                 list_for_each_entry(connector, &dev->mode_config.connector_list,
13371                                     base.head)
13372                         if (connector->encoder->base.crtc == &crtc->base) {
13373                                 connector->encoder->base.crtc = NULL;
13374                                 connector->encoder->connectors_active = false;
13375                         }
13376
13377                 WARN_ON(crtc->active);
13378                 crtc->base.enabled = false;
13379         }
13380
13381         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
13382             crtc->pipe == PIPE_A && !crtc->active) {
13383                 /* BIOS forgot to enable pipe A, this mostly happens after
13384                  * resume. Force-enable the pipe to fix this, the update_dpms
13385                  * call below we restore the pipe to the right state, but leave
13386                  * the required bits on. */
13387                 intel_enable_pipe_a(dev);
13388         }
13389
13390         /* Adjust the state of the output pipe according to whether we
13391          * have active connectors/encoders. */
13392         intel_crtc_update_dpms(&crtc->base);
13393
13394         if (crtc->active != crtc->base.enabled) {
13395                 struct intel_encoder *encoder;
13396
13397                 /* This can happen either due to bugs in the get_hw_state
13398                  * functions or because the pipe is force-enabled due to the
13399                  * pipe A quirk. */
13400                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
13401                               crtc->base.base.id,
13402                               crtc->base.enabled ? "enabled" : "disabled",
13403                               crtc->active ? "enabled" : "disabled");
13404
13405                 crtc->base.enabled = crtc->active;
13406
13407                 /* Because we only establish the connector -> encoder ->
13408                  * crtc links if something is active, this means the
13409                  * crtc is now deactivated. Break the links. connector
13410                  * -> encoder links are only establish when things are
13411                  *  actually up, hence no need to break them. */
13412                 WARN_ON(crtc->active);
13413
13414                 for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
13415                         WARN_ON(encoder->connectors_active);
13416                         encoder->base.crtc = NULL;
13417                 }
13418         }
13419
13420         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
13421                 /*
13422                  * We start out with underrun reporting disabled to avoid races.
13423                  * For correct bookkeeping mark this on active crtcs.
13424                  *
13425                  * Also on gmch platforms we dont have any hardware bits to
13426                  * disable the underrun reporting. Which means we need to start
13427                  * out with underrun reporting disabled also on inactive pipes,
13428                  * since otherwise we'll complain about the garbage we read when
13429                  * e.g. coming up after runtime pm.
13430                  *
13431                  * No protection against concurrent access is required - at
13432                  * worst a fifo underrun happens which also sets this to false.
13433                  */
13434                 crtc->cpu_fifo_underrun_disabled = true;
13435                 crtc->pch_fifo_underrun_disabled = true;
13436         }
13437 }
13438
13439 static void intel_sanitize_encoder(struct intel_encoder *encoder)
13440 {
13441         struct intel_connector *connector;
13442         struct drm_device *dev = encoder->base.dev;
13443
13444         /* We need to check both for a crtc link (meaning that the
13445          * encoder is active and trying to read from a pipe) and the
13446          * pipe itself being active. */
13447         bool has_active_crtc = encoder->base.crtc &&
13448                 to_intel_crtc(encoder->base.crtc)->active;
13449
13450         if (encoder->connectors_active && !has_active_crtc) {
13451                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
13452                               encoder->base.base.id,
13453                               encoder->base.name);
13454
13455                 /* Connector is active, but has no active pipe. This is
13456                  * fallout from our resume register restoring. Disable
13457                  * the encoder manually again. */
13458                 if (encoder->base.crtc) {
13459                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
13460                                       encoder->base.base.id,
13461                                       encoder->base.name);
13462                         encoder->disable(encoder);
13463                         if (encoder->post_disable)
13464                                 encoder->post_disable(encoder);
13465                 }
13466                 encoder->base.crtc = NULL;
13467                 encoder->connectors_active = false;
13468
13469                 /* Inconsistent output/port/pipe state happens presumably due to
13470                  * a bug in one of the get_hw_state functions. Or someplace else
13471                  * in our code, like the register restore mess on resume. Clamp
13472                  * things to off as a safer default. */
13473                 list_for_each_entry(connector,
13474                                     &dev->mode_config.connector_list,
13475                                     base.head) {
13476                         if (connector->encoder != encoder)
13477                                 continue;
13478                         connector->base.dpms = DRM_MODE_DPMS_OFF;
13479                         connector->base.encoder = NULL;
13480                 }
13481         }
13482         /* Enabled encoders without active connectors will be fixed in
13483          * the crtc fixup. */
13484 }
13485
13486 void i915_redisable_vga_power_on(struct drm_device *dev)
13487 {
13488         struct drm_i915_private *dev_priv = dev->dev_private;
13489         u32 vga_reg = i915_vgacntrl_reg(dev);
13490
13491         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
13492                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
13493                 i915_disable_vga(dev);
13494         }
13495 }
13496
13497 void i915_redisable_vga(struct drm_device *dev)
13498 {
13499         struct drm_i915_private *dev_priv = dev->dev_private;
13500
13501         /* This function can be called both from intel_modeset_setup_hw_state or
13502          * at a very early point in our resume sequence, where the power well
13503          * structures are not yet restored. Since this function is at a very
13504          * paranoid "someone might have enabled VGA while we were not looking"
13505          * level, just check if the power well is enabled instead of trying to
13506          * follow the "don't touch the power well if we don't need it" policy
13507          * the rest of the driver uses. */
13508         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
13509                 return;
13510
13511         i915_redisable_vga_power_on(dev);
13512 }
13513
13514 static bool primary_get_hw_state(struct intel_crtc *crtc)
13515 {
13516         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
13517
13518         if (!crtc->active)
13519                 return false;
13520
13521         return I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE;
13522 }
13523
13524 static void intel_modeset_readout_hw_state(struct drm_device *dev)
13525 {
13526         struct drm_i915_private *dev_priv = dev->dev_private;
13527         enum pipe pipe;
13528         struct intel_crtc *crtc;
13529         struct intel_encoder *encoder;
13530         struct intel_connector *connector;
13531         int i;
13532
13533         for_each_intel_crtc(dev, crtc) {
13534                 memset(crtc->config, 0, sizeof(*crtc->config));
13535
13536                 crtc->config->quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
13537
13538                 crtc->active = dev_priv->display.get_pipe_config(crtc,
13539                                                                  crtc->config);
13540
13541                 crtc->base.enabled = crtc->active;
13542                 crtc->primary_enabled = primary_get_hw_state(crtc);
13543
13544                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
13545                               crtc->base.base.id,
13546                               crtc->active ? "enabled" : "disabled");
13547         }
13548
13549         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13550                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
13551
13552                 pll->on = pll->get_hw_state(dev_priv, pll,
13553                                             &pll->config.hw_state);
13554                 pll->active = 0;
13555                 pll->config.crtc_mask = 0;
13556                 for_each_intel_crtc(dev, crtc) {
13557                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
13558                                 pll->active++;
13559                                 pll->config.crtc_mask |= 1 << crtc->pipe;
13560                         }
13561                 }
13562
13563                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
13564                               pll->name, pll->config.crtc_mask, pll->on);
13565
13566                 if (pll->config.crtc_mask)
13567                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
13568         }
13569
13570         for_each_intel_encoder(dev, encoder) {
13571                 pipe = 0;
13572
13573                 if (encoder->get_hw_state(encoder, &pipe)) {
13574                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
13575                         encoder->base.crtc = &crtc->base;
13576                         encoder->get_config(encoder, crtc->config);
13577                 } else {
13578                         encoder->base.crtc = NULL;
13579                 }
13580
13581                 encoder->connectors_active = false;
13582                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
13583                               encoder->base.base.id,
13584                               encoder->base.name,
13585                               encoder->base.crtc ? "enabled" : "disabled",
13586                               pipe_name(pipe));
13587         }
13588
13589         list_for_each_entry(connector, &dev->mode_config.connector_list,
13590                             base.head) {
13591                 if (connector->get_hw_state(connector)) {
13592                         connector->base.dpms = DRM_MODE_DPMS_ON;
13593                         connector->encoder->connectors_active = true;
13594                         connector->base.encoder = &connector->encoder->base;
13595                 } else {
13596                         connector->base.dpms = DRM_MODE_DPMS_OFF;
13597                         connector->base.encoder = NULL;
13598                 }
13599                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
13600                               connector->base.base.id,
13601                               connector->base.name,
13602                               connector->base.encoder ? "enabled" : "disabled");
13603         }
13604 }
13605
13606 /* Scan out the current hw modeset state, sanitizes it and maps it into the drm
13607  * and i915 state tracking structures. */
13608 void intel_modeset_setup_hw_state(struct drm_device *dev,
13609                                   bool force_restore)
13610 {
13611         struct drm_i915_private *dev_priv = dev->dev_private;
13612         enum pipe pipe;
13613         struct intel_crtc *crtc;
13614         struct intel_encoder *encoder;
13615         int i;
13616
13617         intel_modeset_readout_hw_state(dev);
13618
13619         /*
13620          * Now that we have the config, copy it to each CRTC struct
13621          * Note that this could go away if we move to using crtc_config
13622          * checking everywhere.
13623          */
13624         for_each_intel_crtc(dev, crtc) {
13625                 if (crtc->active && i915.fastboot) {
13626                         intel_mode_from_pipe_config(&crtc->base.mode,
13627                                                     crtc->config);
13628                         DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
13629                                       crtc->base.base.id);
13630                         drm_mode_debug_printmodeline(&crtc->base.mode);
13631                 }
13632         }
13633
13634         /* HW state is read out, now we need to sanitize this mess. */
13635         for_each_intel_encoder(dev, encoder) {
13636                 intel_sanitize_encoder(encoder);
13637         }
13638
13639         for_each_pipe(dev_priv, pipe) {
13640                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
13641                 intel_sanitize_crtc(crtc);
13642                 intel_dump_pipe_config(crtc, crtc->config,
13643                                        "[setup_hw_state]");
13644         }
13645
13646         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13647                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
13648
13649                 if (!pll->on || pll->active)
13650                         continue;
13651
13652                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
13653
13654                 pll->disable(dev_priv, pll);
13655                 pll->on = false;
13656         }
13657
13658         if (IS_GEN9(dev))
13659                 skl_wm_get_hw_state(dev);
13660         else if (HAS_PCH_SPLIT(dev))
13661                 ilk_wm_get_hw_state(dev);
13662
13663         if (force_restore) {
13664                 i915_redisable_vga(dev);
13665
13666                 /*
13667                  * We need to use raw interfaces for restoring state to avoid
13668                  * checking (bogus) intermediate states.
13669                  */
13670                 for_each_pipe(dev_priv, pipe) {
13671                         struct drm_crtc *crtc =
13672                                 dev_priv->pipe_to_crtc_mapping[pipe];
13673
13674                         intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y,
13675                                        crtc->primary->fb);
13676                 }
13677         } else {
13678                 intel_modeset_update_staged_output_state(dev);
13679         }
13680
13681         intel_modeset_check_state(dev);
13682 }
13683
13684 void intel_modeset_gem_init(struct drm_device *dev)
13685 {
13686         struct drm_i915_private *dev_priv = dev->dev_private;
13687         struct drm_crtc *c;
13688         struct drm_i915_gem_object *obj;
13689
13690         mutex_lock(&dev->struct_mutex);
13691         intel_init_gt_powersave(dev);
13692         mutex_unlock(&dev->struct_mutex);
13693
13694         /*
13695          * There may be no VBT; and if the BIOS enabled SSC we can
13696          * just keep using it to avoid unnecessary flicker.  Whereas if the
13697          * BIOS isn't using it, don't assume it will work even if the VBT
13698          * indicates as much.
13699          */
13700         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13701                 dev_priv->vbt.lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
13702                                                 DREF_SSC1_ENABLE);
13703
13704         intel_modeset_init_hw(dev);
13705
13706         intel_setup_overlay(dev);
13707
13708         /*
13709          * Make sure any fbs we allocated at startup are properly
13710          * pinned & fenced.  When we do the allocation it's too early
13711          * for this.
13712          */
13713         mutex_lock(&dev->struct_mutex);
13714         for_each_crtc(dev, c) {
13715                 obj = intel_fb_obj(c->primary->fb);
13716                 if (obj == NULL)
13717                         continue;
13718
13719                 if (intel_pin_and_fence_fb_obj(c->primary,
13720                                                c->primary->fb,
13721                                                NULL)) {
13722                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
13723                                   to_intel_crtc(c)->pipe);
13724                         drm_framebuffer_unreference(c->primary->fb);
13725                         c->primary->fb = NULL;
13726                         update_state_fb(c->primary);
13727                 }
13728         }
13729         mutex_unlock(&dev->struct_mutex);
13730
13731         intel_backlight_register(dev);
13732 }
13733
13734 void intel_connector_unregister(struct intel_connector *intel_connector)
13735 {
13736         struct drm_connector *connector = &intel_connector->base;
13737
13738         intel_panel_destroy_backlight(connector);
13739         drm_connector_unregister(connector);
13740 }
13741
13742 void intel_modeset_cleanup(struct drm_device *dev)
13743 {
13744         struct drm_i915_private *dev_priv = dev->dev_private;
13745         struct drm_connector *connector;
13746
13747         intel_disable_gt_powersave(dev);
13748
13749         intel_backlight_unregister(dev);
13750
13751         /*
13752          * Interrupts and polling as the first thing to avoid creating havoc.
13753          * Too much stuff here (turning of connectors, ...) would
13754          * experience fancy races otherwise.
13755          */
13756         intel_irq_uninstall(dev_priv);
13757
13758         /*
13759          * Due to the hpd irq storm handling the hotplug work can re-arm the
13760          * poll handlers. Hence disable polling after hpd handling is shut down.
13761          */
13762         drm_kms_helper_poll_fini(dev);
13763
13764         mutex_lock(&dev->struct_mutex);
13765
13766         intel_unregister_dsm_handler();
13767
13768         intel_fbc_disable(dev);
13769
13770         ironlake_teardown_rc6(dev);
13771
13772         mutex_unlock(&dev->struct_mutex);
13773
13774         /* flush any delayed tasks or pending work */
13775         flush_scheduled_work();
13776
13777         /* destroy the backlight and sysfs files before encoders/connectors */
13778         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
13779                 struct intel_connector *intel_connector;
13780
13781                 intel_connector = to_intel_connector(connector);
13782                 intel_connector->unregister(intel_connector);
13783         }
13784
13785         drm_mode_config_cleanup(dev);
13786
13787         intel_cleanup_overlay(dev);
13788
13789         mutex_lock(&dev->struct_mutex);
13790         intel_cleanup_gt_powersave(dev);
13791         mutex_unlock(&dev->struct_mutex);
13792 }
13793
13794 /*
13795  * Return which encoder is currently attached for connector.
13796  */
13797 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
13798 {
13799         return &intel_attached_encoder(connector)->base;
13800 }
13801
13802 void intel_connector_attach_encoder(struct intel_connector *connector,
13803                                     struct intel_encoder *encoder)
13804 {
13805         connector->encoder = encoder;
13806         drm_mode_connector_attach_encoder(&connector->base,
13807                                           &encoder->base);
13808 }
13809
13810 /*
13811  * set vga decode state - true == enable VGA decode
13812  */
13813 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
13814 {
13815         struct drm_i915_private *dev_priv = dev->dev_private;
13816         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
13817         u16 gmch_ctrl;
13818
13819         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
13820                 DRM_ERROR("failed to read control word\n");
13821                 return -EIO;
13822         }
13823
13824         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
13825                 return 0;
13826
13827         if (state)
13828                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
13829         else
13830                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
13831
13832         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
13833                 DRM_ERROR("failed to write control word\n");
13834                 return -EIO;
13835         }
13836
13837         return 0;
13838 }
13839
13840 struct intel_display_error_state {
13841
13842         u32 power_well_driver;
13843
13844         int num_transcoders;
13845
13846         struct intel_cursor_error_state {
13847                 u32 control;
13848                 u32 position;
13849                 u32 base;
13850                 u32 size;
13851         } cursor[I915_MAX_PIPES];
13852
13853         struct intel_pipe_error_state {
13854                 bool power_domain_on;
13855                 u32 source;
13856                 u32 stat;
13857         } pipe[I915_MAX_PIPES];
13858
13859         struct intel_plane_error_state {
13860                 u32 control;
13861                 u32 stride;
13862                 u32 size;
13863                 u32 pos;
13864                 u32 addr;
13865                 u32 surface;
13866                 u32 tile_offset;
13867         } plane[I915_MAX_PIPES];
13868
13869         struct intel_transcoder_error_state {
13870                 bool power_domain_on;
13871                 enum transcoder cpu_transcoder;
13872
13873                 u32 conf;
13874
13875                 u32 htotal;
13876                 u32 hblank;
13877                 u32 hsync;
13878                 u32 vtotal;
13879                 u32 vblank;
13880                 u32 vsync;
13881         } transcoder[4];
13882 };
13883
13884 struct intel_display_error_state *
13885 intel_display_capture_error_state(struct drm_device *dev)
13886 {
13887         struct drm_i915_private *dev_priv = dev->dev_private;
13888         struct intel_display_error_state *error;
13889         int transcoders[] = {
13890                 TRANSCODER_A,
13891                 TRANSCODER_B,
13892                 TRANSCODER_C,
13893                 TRANSCODER_EDP,
13894         };
13895         int i;
13896
13897         if (INTEL_INFO(dev)->num_pipes == 0)
13898                 return NULL;
13899
13900         error = kzalloc(sizeof(*error), GFP_ATOMIC);
13901         if (error == NULL)
13902                 return NULL;
13903
13904         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
13905                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
13906
13907         for_each_pipe(dev_priv, i) {
13908                 error->pipe[i].power_domain_on =
13909                         __intel_display_power_is_enabled(dev_priv,
13910                                                          POWER_DOMAIN_PIPE(i));
13911                 if (!error->pipe[i].power_domain_on)
13912                         continue;
13913
13914                 error->cursor[i].control = I915_READ(CURCNTR(i));
13915                 error->cursor[i].position = I915_READ(CURPOS(i));
13916                 error->cursor[i].base = I915_READ(CURBASE(i));
13917
13918                 error->plane[i].control = I915_READ(DSPCNTR(i));
13919                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
13920                 if (INTEL_INFO(dev)->gen <= 3) {
13921                         error->plane[i].size = I915_READ(DSPSIZE(i));
13922                         error->plane[i].pos = I915_READ(DSPPOS(i));
13923                 }
13924                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
13925                         error->plane[i].addr = I915_READ(DSPADDR(i));
13926                 if (INTEL_INFO(dev)->gen >= 4) {
13927                         error->plane[i].surface = I915_READ(DSPSURF(i));
13928                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
13929                 }
13930
13931                 error->pipe[i].source = I915_READ(PIPESRC(i));
13932
13933                 if (HAS_GMCH_DISPLAY(dev))
13934                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
13935         }
13936
13937         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
13938         if (HAS_DDI(dev_priv->dev))
13939                 error->num_transcoders++; /* Account for eDP. */
13940
13941         for (i = 0; i < error->num_transcoders; i++) {
13942                 enum transcoder cpu_transcoder = transcoders[i];
13943
13944                 error->transcoder[i].power_domain_on =
13945                         __intel_display_power_is_enabled(dev_priv,
13946                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
13947                 if (!error->transcoder[i].power_domain_on)
13948                         continue;
13949
13950                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
13951
13952                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
13953                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
13954                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
13955                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
13956                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
13957                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
13958                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
13959         }
13960
13961         return error;
13962 }
13963
13964 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
13965
13966 void
13967 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
13968                                 struct drm_device *dev,
13969                                 struct intel_display_error_state *error)
13970 {
13971         struct drm_i915_private *dev_priv = dev->dev_private;
13972         int i;
13973
13974         if (!error)
13975                 return;
13976
13977         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
13978         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
13979                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
13980                            error->power_well_driver);
13981         for_each_pipe(dev_priv, i) {
13982                 err_printf(m, "Pipe [%d]:\n", i);
13983                 err_printf(m, "  Power: %s\n",
13984                            error->pipe[i].power_domain_on ? "on" : "off");
13985                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
13986                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
13987
13988                 err_printf(m, "Plane [%d]:\n", i);
13989                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
13990                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
13991                 if (INTEL_INFO(dev)->gen <= 3) {
13992                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
13993                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
13994                 }
13995                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
13996                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
13997                 if (INTEL_INFO(dev)->gen >= 4) {
13998                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
13999                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
14000                 }
14001
14002                 err_printf(m, "Cursor [%d]:\n", i);
14003                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
14004                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
14005                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
14006         }
14007
14008         for (i = 0; i < error->num_transcoders; i++) {
14009                 err_printf(m, "CPU transcoder: %c\n",
14010                            transcoder_name(error->transcoder[i].cpu_transcoder));
14011                 err_printf(m, "  Power: %s\n",
14012                            error->transcoder[i].power_domain_on ? "on" : "off");
14013                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
14014                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
14015                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
14016                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
14017                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
14018                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
14019                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
14020         }
14021 }
14022
14023 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
14024 {
14025         struct intel_crtc *crtc;
14026
14027         for_each_intel_crtc(dev, crtc) {
14028                 struct intel_unpin_work *work;
14029
14030                 spin_lock_irq(&dev->event_lock);
14031
14032                 work = crtc->unpin_work;
14033
14034                 if (work && work->event &&
14035                     work->event->base.file_priv == file) {
14036                         kfree(work->event);
14037                         work->event = NULL;
14038                 }
14039
14040                 spin_unlock_irq(&dev->event_lock);
14041         }
14042 }