Merge tag 'drm-intel-next-fixes-2015-09-02' into drm-intel-next-queued
[linux-2.6-block.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include <drm/drm_atomic.h>
41 #include <drm/drm_atomic_helper.h>
42 #include <drm/drm_dp_helper.h>
43 #include <drm/drm_crtc_helper.h>
44 #include <drm/drm_plane_helper.h>
45 #include <drm/drm_rect.h>
46 #include <linux/dma_remapping.h>
47
48 /* Primary plane formats for gen <= 3 */
49 static const uint32_t i8xx_primary_formats[] = {
50         DRM_FORMAT_C8,
51         DRM_FORMAT_RGB565,
52         DRM_FORMAT_XRGB1555,
53         DRM_FORMAT_XRGB8888,
54 };
55
56 /* Primary plane formats for gen >= 4 */
57 static const uint32_t i965_primary_formats[] = {
58         DRM_FORMAT_C8,
59         DRM_FORMAT_RGB565,
60         DRM_FORMAT_XRGB8888,
61         DRM_FORMAT_XBGR8888,
62         DRM_FORMAT_XRGB2101010,
63         DRM_FORMAT_XBGR2101010,
64 };
65
66 static const uint32_t skl_primary_formats[] = {
67         DRM_FORMAT_C8,
68         DRM_FORMAT_RGB565,
69         DRM_FORMAT_XRGB8888,
70         DRM_FORMAT_XBGR8888,
71         DRM_FORMAT_ARGB8888,
72         DRM_FORMAT_ABGR8888,
73         DRM_FORMAT_XRGB2101010,
74         DRM_FORMAT_XBGR2101010,
75 };
76
77 /* Cursor formats */
78 static const uint32_t intel_cursor_formats[] = {
79         DRM_FORMAT_ARGB8888,
80 };
81
82 static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
83
84 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
85                                 struct intel_crtc_state *pipe_config);
86 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
87                                    struct intel_crtc_state *pipe_config);
88
89 static int intel_framebuffer_init(struct drm_device *dev,
90                                   struct intel_framebuffer *ifb,
91                                   struct drm_mode_fb_cmd2 *mode_cmd,
92                                   struct drm_i915_gem_object *obj);
93 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
94 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
95 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
96                                          struct intel_link_m_n *m_n,
97                                          struct intel_link_m_n *m2_n2);
98 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
99 static void haswell_set_pipeconf(struct drm_crtc *crtc);
100 static void intel_set_pipe_csc(struct drm_crtc *crtc);
101 static void vlv_prepare_pll(struct intel_crtc *crtc,
102                             const struct intel_crtc_state *pipe_config);
103 static void chv_prepare_pll(struct intel_crtc *crtc,
104                             const struct intel_crtc_state *pipe_config);
105 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
106 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
107 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
108         struct intel_crtc_state *crtc_state);
109 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
110                            int num_connectors);
111 static void intel_modeset_setup_hw_state(struct drm_device *dev);
112
113 typedef struct {
114         int     min, max;
115 } intel_range_t;
116
117 typedef struct {
118         int     dot_limit;
119         int     p2_slow, p2_fast;
120 } intel_p2_t;
121
122 typedef struct intel_limit intel_limit_t;
123 struct intel_limit {
124         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
125         intel_p2_t          p2;
126 };
127
128 int
129 intel_pch_rawclk(struct drm_device *dev)
130 {
131         struct drm_i915_private *dev_priv = dev->dev_private;
132
133         WARN_ON(!HAS_PCH_SPLIT(dev));
134
135         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
136 }
137
138 /* hrawclock is 1/4 the FSB frequency */
139 int intel_hrawclk(struct drm_device *dev)
140 {
141         struct drm_i915_private *dev_priv = dev->dev_private;
142         uint32_t clkcfg;
143
144         /* There is no CLKCFG reg in Valleyview. VLV hrawclk is 200 MHz */
145         if (IS_VALLEYVIEW(dev))
146                 return 200;
147
148         clkcfg = I915_READ(CLKCFG);
149         switch (clkcfg & CLKCFG_FSB_MASK) {
150         case CLKCFG_FSB_400:
151                 return 100;
152         case CLKCFG_FSB_533:
153                 return 133;
154         case CLKCFG_FSB_667:
155                 return 166;
156         case CLKCFG_FSB_800:
157                 return 200;
158         case CLKCFG_FSB_1067:
159                 return 266;
160         case CLKCFG_FSB_1333:
161                 return 333;
162         /* these two are just a guess; one of them might be right */
163         case CLKCFG_FSB_1600:
164         case CLKCFG_FSB_1600_ALT:
165                 return 400;
166         default:
167                 return 133;
168         }
169 }
170
171 static inline u32 /* units of 100MHz */
172 intel_fdi_link_freq(struct drm_device *dev)
173 {
174         if (IS_GEN5(dev)) {
175                 struct drm_i915_private *dev_priv = dev->dev_private;
176                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
177         } else
178                 return 27;
179 }
180
181 static const intel_limit_t intel_limits_i8xx_dac = {
182         .dot = { .min = 25000, .max = 350000 },
183         .vco = { .min = 908000, .max = 1512000 },
184         .n = { .min = 2, .max = 16 },
185         .m = { .min = 96, .max = 140 },
186         .m1 = { .min = 18, .max = 26 },
187         .m2 = { .min = 6, .max = 16 },
188         .p = { .min = 4, .max = 128 },
189         .p1 = { .min = 2, .max = 33 },
190         .p2 = { .dot_limit = 165000,
191                 .p2_slow = 4, .p2_fast = 2 },
192 };
193
194 static const intel_limit_t intel_limits_i8xx_dvo = {
195         .dot = { .min = 25000, .max = 350000 },
196         .vco = { .min = 908000, .max = 1512000 },
197         .n = { .min = 2, .max = 16 },
198         .m = { .min = 96, .max = 140 },
199         .m1 = { .min = 18, .max = 26 },
200         .m2 = { .min = 6, .max = 16 },
201         .p = { .min = 4, .max = 128 },
202         .p1 = { .min = 2, .max = 33 },
203         .p2 = { .dot_limit = 165000,
204                 .p2_slow = 4, .p2_fast = 4 },
205 };
206
207 static const intel_limit_t intel_limits_i8xx_lvds = {
208         .dot = { .min = 25000, .max = 350000 },
209         .vco = { .min = 908000, .max = 1512000 },
210         .n = { .min = 2, .max = 16 },
211         .m = { .min = 96, .max = 140 },
212         .m1 = { .min = 18, .max = 26 },
213         .m2 = { .min = 6, .max = 16 },
214         .p = { .min = 4, .max = 128 },
215         .p1 = { .min = 1, .max = 6 },
216         .p2 = { .dot_limit = 165000,
217                 .p2_slow = 14, .p2_fast = 7 },
218 };
219
220 static const intel_limit_t intel_limits_i9xx_sdvo = {
221         .dot = { .min = 20000, .max = 400000 },
222         .vco = { .min = 1400000, .max = 2800000 },
223         .n = { .min = 1, .max = 6 },
224         .m = { .min = 70, .max = 120 },
225         .m1 = { .min = 8, .max = 18 },
226         .m2 = { .min = 3, .max = 7 },
227         .p = { .min = 5, .max = 80 },
228         .p1 = { .min = 1, .max = 8 },
229         .p2 = { .dot_limit = 200000,
230                 .p2_slow = 10, .p2_fast = 5 },
231 };
232
233 static const intel_limit_t intel_limits_i9xx_lvds = {
234         .dot = { .min = 20000, .max = 400000 },
235         .vco = { .min = 1400000, .max = 2800000 },
236         .n = { .min = 1, .max = 6 },
237         .m = { .min = 70, .max = 120 },
238         .m1 = { .min = 8, .max = 18 },
239         .m2 = { .min = 3, .max = 7 },
240         .p = { .min = 7, .max = 98 },
241         .p1 = { .min = 1, .max = 8 },
242         .p2 = { .dot_limit = 112000,
243                 .p2_slow = 14, .p2_fast = 7 },
244 };
245
246
247 static const intel_limit_t intel_limits_g4x_sdvo = {
248         .dot = { .min = 25000, .max = 270000 },
249         .vco = { .min = 1750000, .max = 3500000},
250         .n = { .min = 1, .max = 4 },
251         .m = { .min = 104, .max = 138 },
252         .m1 = { .min = 17, .max = 23 },
253         .m2 = { .min = 5, .max = 11 },
254         .p = { .min = 10, .max = 30 },
255         .p1 = { .min = 1, .max = 3},
256         .p2 = { .dot_limit = 270000,
257                 .p2_slow = 10,
258                 .p2_fast = 10
259         },
260 };
261
262 static const intel_limit_t intel_limits_g4x_hdmi = {
263         .dot = { .min = 22000, .max = 400000 },
264         .vco = { .min = 1750000, .max = 3500000},
265         .n = { .min = 1, .max = 4 },
266         .m = { .min = 104, .max = 138 },
267         .m1 = { .min = 16, .max = 23 },
268         .m2 = { .min = 5, .max = 11 },
269         .p = { .min = 5, .max = 80 },
270         .p1 = { .min = 1, .max = 8},
271         .p2 = { .dot_limit = 165000,
272                 .p2_slow = 10, .p2_fast = 5 },
273 };
274
275 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
276         .dot = { .min = 20000, .max = 115000 },
277         .vco = { .min = 1750000, .max = 3500000 },
278         .n = { .min = 1, .max = 3 },
279         .m = { .min = 104, .max = 138 },
280         .m1 = { .min = 17, .max = 23 },
281         .m2 = { .min = 5, .max = 11 },
282         .p = { .min = 28, .max = 112 },
283         .p1 = { .min = 2, .max = 8 },
284         .p2 = { .dot_limit = 0,
285                 .p2_slow = 14, .p2_fast = 14
286         },
287 };
288
289 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
290         .dot = { .min = 80000, .max = 224000 },
291         .vco = { .min = 1750000, .max = 3500000 },
292         .n = { .min = 1, .max = 3 },
293         .m = { .min = 104, .max = 138 },
294         .m1 = { .min = 17, .max = 23 },
295         .m2 = { .min = 5, .max = 11 },
296         .p = { .min = 14, .max = 42 },
297         .p1 = { .min = 2, .max = 6 },
298         .p2 = { .dot_limit = 0,
299                 .p2_slow = 7, .p2_fast = 7
300         },
301 };
302
303 static const intel_limit_t intel_limits_pineview_sdvo = {
304         .dot = { .min = 20000, .max = 400000},
305         .vco = { .min = 1700000, .max = 3500000 },
306         /* Pineview's Ncounter is a ring counter */
307         .n = { .min = 3, .max = 6 },
308         .m = { .min = 2, .max = 256 },
309         /* Pineview only has one combined m divider, which we treat as m2. */
310         .m1 = { .min = 0, .max = 0 },
311         .m2 = { .min = 0, .max = 254 },
312         .p = { .min = 5, .max = 80 },
313         .p1 = { .min = 1, .max = 8 },
314         .p2 = { .dot_limit = 200000,
315                 .p2_slow = 10, .p2_fast = 5 },
316 };
317
318 static const intel_limit_t intel_limits_pineview_lvds = {
319         .dot = { .min = 20000, .max = 400000 },
320         .vco = { .min = 1700000, .max = 3500000 },
321         .n = { .min = 3, .max = 6 },
322         .m = { .min = 2, .max = 256 },
323         .m1 = { .min = 0, .max = 0 },
324         .m2 = { .min = 0, .max = 254 },
325         .p = { .min = 7, .max = 112 },
326         .p1 = { .min = 1, .max = 8 },
327         .p2 = { .dot_limit = 112000,
328                 .p2_slow = 14, .p2_fast = 14 },
329 };
330
331 /* Ironlake / Sandybridge
332  *
333  * We calculate clock using (register_value + 2) for N/M1/M2, so here
334  * the range value for them is (actual_value - 2).
335  */
336 static const intel_limit_t intel_limits_ironlake_dac = {
337         .dot = { .min = 25000, .max = 350000 },
338         .vco = { .min = 1760000, .max = 3510000 },
339         .n = { .min = 1, .max = 5 },
340         .m = { .min = 79, .max = 127 },
341         .m1 = { .min = 12, .max = 22 },
342         .m2 = { .min = 5, .max = 9 },
343         .p = { .min = 5, .max = 80 },
344         .p1 = { .min = 1, .max = 8 },
345         .p2 = { .dot_limit = 225000,
346                 .p2_slow = 10, .p2_fast = 5 },
347 };
348
349 static const intel_limit_t intel_limits_ironlake_single_lvds = {
350         .dot = { .min = 25000, .max = 350000 },
351         .vco = { .min = 1760000, .max = 3510000 },
352         .n = { .min = 1, .max = 3 },
353         .m = { .min = 79, .max = 118 },
354         .m1 = { .min = 12, .max = 22 },
355         .m2 = { .min = 5, .max = 9 },
356         .p = { .min = 28, .max = 112 },
357         .p1 = { .min = 2, .max = 8 },
358         .p2 = { .dot_limit = 225000,
359                 .p2_slow = 14, .p2_fast = 14 },
360 };
361
362 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
363         .dot = { .min = 25000, .max = 350000 },
364         .vco = { .min = 1760000, .max = 3510000 },
365         .n = { .min = 1, .max = 3 },
366         .m = { .min = 79, .max = 127 },
367         .m1 = { .min = 12, .max = 22 },
368         .m2 = { .min = 5, .max = 9 },
369         .p = { .min = 14, .max = 56 },
370         .p1 = { .min = 2, .max = 8 },
371         .p2 = { .dot_limit = 225000,
372                 .p2_slow = 7, .p2_fast = 7 },
373 };
374
375 /* LVDS 100mhz refclk limits. */
376 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
377         .dot = { .min = 25000, .max = 350000 },
378         .vco = { .min = 1760000, .max = 3510000 },
379         .n = { .min = 1, .max = 2 },
380         .m = { .min = 79, .max = 126 },
381         .m1 = { .min = 12, .max = 22 },
382         .m2 = { .min = 5, .max = 9 },
383         .p = { .min = 28, .max = 112 },
384         .p1 = { .min = 2, .max = 8 },
385         .p2 = { .dot_limit = 225000,
386                 .p2_slow = 14, .p2_fast = 14 },
387 };
388
389 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
390         .dot = { .min = 25000, .max = 350000 },
391         .vco = { .min = 1760000, .max = 3510000 },
392         .n = { .min = 1, .max = 3 },
393         .m = { .min = 79, .max = 126 },
394         .m1 = { .min = 12, .max = 22 },
395         .m2 = { .min = 5, .max = 9 },
396         .p = { .min = 14, .max = 42 },
397         .p1 = { .min = 2, .max = 6 },
398         .p2 = { .dot_limit = 225000,
399                 .p2_slow = 7, .p2_fast = 7 },
400 };
401
402 static const intel_limit_t intel_limits_vlv = {
403          /*
404           * These are the data rate limits (measured in fast clocks)
405           * since those are the strictest limits we have. The fast
406           * clock and actual rate limits are more relaxed, so checking
407           * them would make no difference.
408           */
409         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
410         .vco = { .min = 4000000, .max = 6000000 },
411         .n = { .min = 1, .max = 7 },
412         .m1 = { .min = 2, .max = 3 },
413         .m2 = { .min = 11, .max = 156 },
414         .p1 = { .min = 2, .max = 3 },
415         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
416 };
417
418 static const intel_limit_t intel_limits_chv = {
419         /*
420          * These are the data rate limits (measured in fast clocks)
421          * since those are the strictest limits we have.  The fast
422          * clock and actual rate limits are more relaxed, so checking
423          * them would make no difference.
424          */
425         .dot = { .min = 25000 * 5, .max = 540000 * 5},
426         .vco = { .min = 4800000, .max = 6480000 },
427         .n = { .min = 1, .max = 1 },
428         .m1 = { .min = 2, .max = 2 },
429         .m2 = { .min = 24 << 22, .max = 175 << 22 },
430         .p1 = { .min = 2, .max = 4 },
431         .p2 = { .p2_slow = 1, .p2_fast = 14 },
432 };
433
434 static const intel_limit_t intel_limits_bxt = {
435         /* FIXME: find real dot limits */
436         .dot = { .min = 0, .max = INT_MAX },
437         .vco = { .min = 4800000, .max = 6700000 },
438         .n = { .min = 1, .max = 1 },
439         .m1 = { .min = 2, .max = 2 },
440         /* FIXME: find real m2 limits */
441         .m2 = { .min = 2 << 22, .max = 255 << 22 },
442         .p1 = { .min = 2, .max = 4 },
443         .p2 = { .p2_slow = 1, .p2_fast = 20 },
444 };
445
446 static bool
447 needs_modeset(struct drm_crtc_state *state)
448 {
449         return drm_atomic_crtc_needs_modeset(state);
450 }
451
452 /**
453  * Returns whether any output on the specified pipe is of the specified type
454  */
455 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
456 {
457         struct drm_device *dev = crtc->base.dev;
458         struct intel_encoder *encoder;
459
460         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
461                 if (encoder->type == type)
462                         return true;
463
464         return false;
465 }
466
467 /**
468  * Returns whether any output on the specified pipe will have the specified
469  * type after a staged modeset is complete, i.e., the same as
470  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
471  * encoder->crtc.
472  */
473 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
474                                       int type)
475 {
476         struct drm_atomic_state *state = crtc_state->base.state;
477         struct drm_connector *connector;
478         struct drm_connector_state *connector_state;
479         struct intel_encoder *encoder;
480         int i, num_connectors = 0;
481
482         for_each_connector_in_state(state, connector, connector_state, i) {
483                 if (connector_state->crtc != crtc_state->base.crtc)
484                         continue;
485
486                 num_connectors++;
487
488                 encoder = to_intel_encoder(connector_state->best_encoder);
489                 if (encoder->type == type)
490                         return true;
491         }
492
493         WARN_ON(num_connectors == 0);
494
495         return false;
496 }
497
498 static const intel_limit_t *
499 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
500 {
501         struct drm_device *dev = crtc_state->base.crtc->dev;
502         const intel_limit_t *limit;
503
504         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
505                 if (intel_is_dual_link_lvds(dev)) {
506                         if (refclk == 100000)
507                                 limit = &intel_limits_ironlake_dual_lvds_100m;
508                         else
509                                 limit = &intel_limits_ironlake_dual_lvds;
510                 } else {
511                         if (refclk == 100000)
512                                 limit = &intel_limits_ironlake_single_lvds_100m;
513                         else
514                                 limit = &intel_limits_ironlake_single_lvds;
515                 }
516         } else
517                 limit = &intel_limits_ironlake_dac;
518
519         return limit;
520 }
521
522 static const intel_limit_t *
523 intel_g4x_limit(struct intel_crtc_state *crtc_state)
524 {
525         struct drm_device *dev = crtc_state->base.crtc->dev;
526         const intel_limit_t *limit;
527
528         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
529                 if (intel_is_dual_link_lvds(dev))
530                         limit = &intel_limits_g4x_dual_channel_lvds;
531                 else
532                         limit = &intel_limits_g4x_single_channel_lvds;
533         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
534                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
535                 limit = &intel_limits_g4x_hdmi;
536         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
537                 limit = &intel_limits_g4x_sdvo;
538         } else /* The option is for other outputs */
539                 limit = &intel_limits_i9xx_sdvo;
540
541         return limit;
542 }
543
544 static const intel_limit_t *
545 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
546 {
547         struct drm_device *dev = crtc_state->base.crtc->dev;
548         const intel_limit_t *limit;
549
550         if (IS_BROXTON(dev))
551                 limit = &intel_limits_bxt;
552         else if (HAS_PCH_SPLIT(dev))
553                 limit = intel_ironlake_limit(crtc_state, refclk);
554         else if (IS_G4X(dev)) {
555                 limit = intel_g4x_limit(crtc_state);
556         } else if (IS_PINEVIEW(dev)) {
557                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
558                         limit = &intel_limits_pineview_lvds;
559                 else
560                         limit = &intel_limits_pineview_sdvo;
561         } else if (IS_CHERRYVIEW(dev)) {
562                 limit = &intel_limits_chv;
563         } else if (IS_VALLEYVIEW(dev)) {
564                 limit = &intel_limits_vlv;
565         } else if (!IS_GEN2(dev)) {
566                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
567                         limit = &intel_limits_i9xx_lvds;
568                 else
569                         limit = &intel_limits_i9xx_sdvo;
570         } else {
571                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
572                         limit = &intel_limits_i8xx_lvds;
573                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
574                         limit = &intel_limits_i8xx_dvo;
575                 else
576                         limit = &intel_limits_i8xx_dac;
577         }
578         return limit;
579 }
580
581 /*
582  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
583  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
584  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
585  * The helpers' return value is the rate of the clock that is fed to the
586  * display engine's pipe which can be the above fast dot clock rate or a
587  * divided-down version of it.
588  */
589 /* m1 is reserved as 0 in Pineview, n is a ring counter */
590 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
591 {
592         clock->m = clock->m2 + 2;
593         clock->p = clock->p1 * clock->p2;
594         if (WARN_ON(clock->n == 0 || clock->p == 0))
595                 return 0;
596         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
597         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
598
599         return clock->dot;
600 }
601
602 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
603 {
604         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
605 }
606
607 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
608 {
609         clock->m = i9xx_dpll_compute_m(clock);
610         clock->p = clock->p1 * clock->p2;
611         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
612                 return 0;
613         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
614         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
615
616         return clock->dot;
617 }
618
619 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
620 {
621         clock->m = clock->m1 * clock->m2;
622         clock->p = clock->p1 * clock->p2;
623         if (WARN_ON(clock->n == 0 || clock->p == 0))
624                 return 0;
625         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
626         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
627
628         return clock->dot / 5;
629 }
630
631 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
632 {
633         clock->m = clock->m1 * clock->m2;
634         clock->p = clock->p1 * clock->p2;
635         if (WARN_ON(clock->n == 0 || clock->p == 0))
636                 return 0;
637         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
638                         clock->n << 22);
639         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
640
641         return clock->dot / 5;
642 }
643
644 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
645 /**
646  * Returns whether the given set of divisors are valid for a given refclk with
647  * the given connectors.
648  */
649
650 static bool intel_PLL_is_valid(struct drm_device *dev,
651                                const intel_limit_t *limit,
652                                const intel_clock_t *clock)
653 {
654         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
655                 INTELPllInvalid("n out of range\n");
656         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
657                 INTELPllInvalid("p1 out of range\n");
658         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
659                 INTELPllInvalid("m2 out of range\n");
660         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
661                 INTELPllInvalid("m1 out of range\n");
662
663         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) && !IS_BROXTON(dev))
664                 if (clock->m1 <= clock->m2)
665                         INTELPllInvalid("m1 <= m2\n");
666
667         if (!IS_VALLEYVIEW(dev) && !IS_BROXTON(dev)) {
668                 if (clock->p < limit->p.min || limit->p.max < clock->p)
669                         INTELPllInvalid("p out of range\n");
670                 if (clock->m < limit->m.min || limit->m.max < clock->m)
671                         INTELPllInvalid("m out of range\n");
672         }
673
674         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
675                 INTELPllInvalid("vco out of range\n");
676         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
677          * connector, etc., rather than just a single range.
678          */
679         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
680                 INTELPllInvalid("dot out of range\n");
681
682         return true;
683 }
684
685 static int
686 i9xx_select_p2_div(const intel_limit_t *limit,
687                    const struct intel_crtc_state *crtc_state,
688                    int target)
689 {
690         struct drm_device *dev = crtc_state->base.crtc->dev;
691
692         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
693                 /*
694                  * For LVDS just rely on its current settings for dual-channel.
695                  * We haven't figured out how to reliably set up different
696                  * single/dual channel state, if we even can.
697                  */
698                 if (intel_is_dual_link_lvds(dev))
699                         return limit->p2.p2_fast;
700                 else
701                         return limit->p2.p2_slow;
702         } else {
703                 if (target < limit->p2.dot_limit)
704                         return limit->p2.p2_slow;
705                 else
706                         return limit->p2.p2_fast;
707         }
708 }
709
710 static bool
711 i9xx_find_best_dpll(const intel_limit_t *limit,
712                     struct intel_crtc_state *crtc_state,
713                     int target, int refclk, intel_clock_t *match_clock,
714                     intel_clock_t *best_clock)
715 {
716         struct drm_device *dev = crtc_state->base.crtc->dev;
717         intel_clock_t clock;
718         int err = target;
719
720         memset(best_clock, 0, sizeof(*best_clock));
721
722         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
723
724         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
725              clock.m1++) {
726                 for (clock.m2 = limit->m2.min;
727                      clock.m2 <= limit->m2.max; clock.m2++) {
728                         if (clock.m2 >= clock.m1)
729                                 break;
730                         for (clock.n = limit->n.min;
731                              clock.n <= limit->n.max; clock.n++) {
732                                 for (clock.p1 = limit->p1.min;
733                                         clock.p1 <= limit->p1.max; clock.p1++) {
734                                         int this_err;
735
736                                         i9xx_calc_dpll_params(refclk, &clock);
737                                         if (!intel_PLL_is_valid(dev, limit,
738                                                                 &clock))
739                                                 continue;
740                                         if (match_clock &&
741                                             clock.p != match_clock->p)
742                                                 continue;
743
744                                         this_err = abs(clock.dot - target);
745                                         if (this_err < err) {
746                                                 *best_clock = clock;
747                                                 err = this_err;
748                                         }
749                                 }
750                         }
751                 }
752         }
753
754         return (err != target);
755 }
756
757 static bool
758 pnv_find_best_dpll(const intel_limit_t *limit,
759                    struct intel_crtc_state *crtc_state,
760                    int target, int refclk, intel_clock_t *match_clock,
761                    intel_clock_t *best_clock)
762 {
763         struct drm_device *dev = crtc_state->base.crtc->dev;
764         intel_clock_t clock;
765         int err = target;
766
767         memset(best_clock, 0, sizeof(*best_clock));
768
769         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
770
771         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
772              clock.m1++) {
773                 for (clock.m2 = limit->m2.min;
774                      clock.m2 <= limit->m2.max; clock.m2++) {
775                         for (clock.n = limit->n.min;
776                              clock.n <= limit->n.max; clock.n++) {
777                                 for (clock.p1 = limit->p1.min;
778                                         clock.p1 <= limit->p1.max; clock.p1++) {
779                                         int this_err;
780
781                                         pnv_calc_dpll_params(refclk, &clock);
782                                         if (!intel_PLL_is_valid(dev, limit,
783                                                                 &clock))
784                                                 continue;
785                                         if (match_clock &&
786                                             clock.p != match_clock->p)
787                                                 continue;
788
789                                         this_err = abs(clock.dot - target);
790                                         if (this_err < err) {
791                                                 *best_clock = clock;
792                                                 err = this_err;
793                                         }
794                                 }
795                         }
796                 }
797         }
798
799         return (err != target);
800 }
801
802 static bool
803 g4x_find_best_dpll(const intel_limit_t *limit,
804                    struct intel_crtc_state *crtc_state,
805                    int target, int refclk, intel_clock_t *match_clock,
806                    intel_clock_t *best_clock)
807 {
808         struct drm_device *dev = crtc_state->base.crtc->dev;
809         intel_clock_t clock;
810         int max_n;
811         bool found = false;
812         /* approximately equals target * 0.00585 */
813         int err_most = (target >> 8) + (target >> 9);
814
815         memset(best_clock, 0, sizeof(*best_clock));
816
817         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
818
819         max_n = limit->n.max;
820         /* based on hardware requirement, prefer smaller n to precision */
821         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
822                 /* based on hardware requirement, prefere larger m1,m2 */
823                 for (clock.m1 = limit->m1.max;
824                      clock.m1 >= limit->m1.min; clock.m1--) {
825                         for (clock.m2 = limit->m2.max;
826                              clock.m2 >= limit->m2.min; clock.m2--) {
827                                 for (clock.p1 = limit->p1.max;
828                                      clock.p1 >= limit->p1.min; clock.p1--) {
829                                         int this_err;
830
831                                         i9xx_calc_dpll_params(refclk, &clock);
832                                         if (!intel_PLL_is_valid(dev, limit,
833                                                                 &clock))
834                                                 continue;
835
836                                         this_err = abs(clock.dot - target);
837                                         if (this_err < err_most) {
838                                                 *best_clock = clock;
839                                                 err_most = this_err;
840                                                 max_n = clock.n;
841                                                 found = true;
842                                         }
843                                 }
844                         }
845                 }
846         }
847         return found;
848 }
849
850 /*
851  * Check if the calculated PLL configuration is more optimal compared to the
852  * best configuration and error found so far. Return the calculated error.
853  */
854 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
855                                const intel_clock_t *calculated_clock,
856                                const intel_clock_t *best_clock,
857                                unsigned int best_error_ppm,
858                                unsigned int *error_ppm)
859 {
860         /*
861          * For CHV ignore the error and consider only the P value.
862          * Prefer a bigger P value based on HW requirements.
863          */
864         if (IS_CHERRYVIEW(dev)) {
865                 *error_ppm = 0;
866
867                 return calculated_clock->p > best_clock->p;
868         }
869
870         if (WARN_ON_ONCE(!target_freq))
871                 return false;
872
873         *error_ppm = div_u64(1000000ULL *
874                                 abs(target_freq - calculated_clock->dot),
875                              target_freq);
876         /*
877          * Prefer a better P value over a better (smaller) error if the error
878          * is small. Ensure this preference for future configurations too by
879          * setting the error to 0.
880          */
881         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
882                 *error_ppm = 0;
883
884                 return true;
885         }
886
887         return *error_ppm + 10 < best_error_ppm;
888 }
889
890 static bool
891 vlv_find_best_dpll(const intel_limit_t *limit,
892                    struct intel_crtc_state *crtc_state,
893                    int target, int refclk, intel_clock_t *match_clock,
894                    intel_clock_t *best_clock)
895 {
896         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
897         struct drm_device *dev = crtc->base.dev;
898         intel_clock_t clock;
899         unsigned int bestppm = 1000000;
900         /* min update 19.2 MHz */
901         int max_n = min(limit->n.max, refclk / 19200);
902         bool found = false;
903
904         target *= 5; /* fast clock */
905
906         memset(best_clock, 0, sizeof(*best_clock));
907
908         /* based on hardware requirement, prefer smaller n to precision */
909         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
910                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
911                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
912                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
913                                 clock.p = clock.p1 * clock.p2;
914                                 /* based on hardware requirement, prefer bigger m1,m2 values */
915                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
916                                         unsigned int ppm;
917
918                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
919                                                                      refclk * clock.m1);
920
921                                         vlv_calc_dpll_params(refclk, &clock);
922
923                                         if (!intel_PLL_is_valid(dev, limit,
924                                                                 &clock))
925                                                 continue;
926
927                                         if (!vlv_PLL_is_optimal(dev, target,
928                                                                 &clock,
929                                                                 best_clock,
930                                                                 bestppm, &ppm))
931                                                 continue;
932
933                                         *best_clock = clock;
934                                         bestppm = ppm;
935                                         found = true;
936                                 }
937                         }
938                 }
939         }
940
941         return found;
942 }
943
944 static bool
945 chv_find_best_dpll(const intel_limit_t *limit,
946                    struct intel_crtc_state *crtc_state,
947                    int target, int refclk, intel_clock_t *match_clock,
948                    intel_clock_t *best_clock)
949 {
950         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
951         struct drm_device *dev = crtc->base.dev;
952         unsigned int best_error_ppm;
953         intel_clock_t clock;
954         uint64_t m2;
955         int found = false;
956
957         memset(best_clock, 0, sizeof(*best_clock));
958         best_error_ppm = 1000000;
959
960         /*
961          * Based on hardware doc, the n always set to 1, and m1 always
962          * set to 2.  If requires to support 200Mhz refclk, we need to
963          * revisit this because n may not 1 anymore.
964          */
965         clock.n = 1, clock.m1 = 2;
966         target *= 5;    /* fast clock */
967
968         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
969                 for (clock.p2 = limit->p2.p2_fast;
970                                 clock.p2 >= limit->p2.p2_slow;
971                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
972                         unsigned int error_ppm;
973
974                         clock.p = clock.p1 * clock.p2;
975
976                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
977                                         clock.n) << 22, refclk * clock.m1);
978
979                         if (m2 > INT_MAX/clock.m1)
980                                 continue;
981
982                         clock.m2 = m2;
983
984                         chv_calc_dpll_params(refclk, &clock);
985
986                         if (!intel_PLL_is_valid(dev, limit, &clock))
987                                 continue;
988
989                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
990                                                 best_error_ppm, &error_ppm))
991                                 continue;
992
993                         *best_clock = clock;
994                         best_error_ppm = error_ppm;
995                         found = true;
996                 }
997         }
998
999         return found;
1000 }
1001
1002 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1003                         intel_clock_t *best_clock)
1004 {
1005         int refclk = i9xx_get_refclk(crtc_state, 0);
1006
1007         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
1008                                   target_clock, refclk, NULL, best_clock);
1009 }
1010
1011 bool intel_crtc_active(struct drm_crtc *crtc)
1012 {
1013         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1014
1015         /* Be paranoid as we can arrive here with only partial
1016          * state retrieved from the hardware during setup.
1017          *
1018          * We can ditch the adjusted_mode.crtc_clock check as soon
1019          * as Haswell has gained clock readout/fastboot support.
1020          *
1021          * We can ditch the crtc->primary->fb check as soon as we can
1022          * properly reconstruct framebuffers.
1023          *
1024          * FIXME: The intel_crtc->active here should be switched to
1025          * crtc->state->active once we have proper CRTC states wired up
1026          * for atomic.
1027          */
1028         return intel_crtc->active && crtc->primary->state->fb &&
1029                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1030 }
1031
1032 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1033                                              enum pipe pipe)
1034 {
1035         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1036         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1037
1038         return intel_crtc->config->cpu_transcoder;
1039 }
1040
1041 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1042 {
1043         struct drm_i915_private *dev_priv = dev->dev_private;
1044         u32 reg = PIPEDSL(pipe);
1045         u32 line1, line2;
1046         u32 line_mask;
1047
1048         if (IS_GEN2(dev))
1049                 line_mask = DSL_LINEMASK_GEN2;
1050         else
1051                 line_mask = DSL_LINEMASK_GEN3;
1052
1053         line1 = I915_READ(reg) & line_mask;
1054         msleep(5);
1055         line2 = I915_READ(reg) & line_mask;
1056
1057         return line1 == line2;
1058 }
1059
1060 /*
1061  * intel_wait_for_pipe_off - wait for pipe to turn off
1062  * @crtc: crtc whose pipe to wait for
1063  *
1064  * After disabling a pipe, we can't wait for vblank in the usual way,
1065  * spinning on the vblank interrupt status bit, since we won't actually
1066  * see an interrupt when the pipe is disabled.
1067  *
1068  * On Gen4 and above:
1069  *   wait for the pipe register state bit to turn off
1070  *
1071  * Otherwise:
1072  *   wait for the display line value to settle (it usually
1073  *   ends up stopping at the start of the next frame).
1074  *
1075  */
1076 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1077 {
1078         struct drm_device *dev = crtc->base.dev;
1079         struct drm_i915_private *dev_priv = dev->dev_private;
1080         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1081         enum pipe pipe = crtc->pipe;
1082
1083         if (INTEL_INFO(dev)->gen >= 4) {
1084                 int reg = PIPECONF(cpu_transcoder);
1085
1086                 /* Wait for the Pipe State to go off */
1087                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1088                              100))
1089                         WARN(1, "pipe_off wait timed out\n");
1090         } else {
1091                 /* Wait for the display line to settle */
1092                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1093                         WARN(1, "pipe_off wait timed out\n");
1094         }
1095 }
1096
1097 static const char *state_string(bool enabled)
1098 {
1099         return enabled ? "on" : "off";
1100 }
1101
1102 /* Only for pre-ILK configs */
1103 void assert_pll(struct drm_i915_private *dev_priv,
1104                 enum pipe pipe, bool state)
1105 {
1106         int reg;
1107         u32 val;
1108         bool cur_state;
1109
1110         reg = DPLL(pipe);
1111         val = I915_READ(reg);
1112         cur_state = !!(val & DPLL_VCO_ENABLE);
1113         I915_STATE_WARN(cur_state != state,
1114              "PLL state assertion failure (expected %s, current %s)\n",
1115              state_string(state), state_string(cur_state));
1116 }
1117
1118 /* XXX: the dsi pll is shared between MIPI DSI ports */
1119 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1120 {
1121         u32 val;
1122         bool cur_state;
1123
1124         mutex_lock(&dev_priv->sb_lock);
1125         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1126         mutex_unlock(&dev_priv->sb_lock);
1127
1128         cur_state = val & DSI_PLL_VCO_EN;
1129         I915_STATE_WARN(cur_state != state,
1130              "DSI PLL state assertion failure (expected %s, current %s)\n",
1131              state_string(state), state_string(cur_state));
1132 }
1133 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1134 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1135
1136 struct intel_shared_dpll *
1137 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1138 {
1139         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1140
1141         if (crtc->config->shared_dpll < 0)
1142                 return NULL;
1143
1144         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1145 }
1146
1147 /* For ILK+ */
1148 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1149                         struct intel_shared_dpll *pll,
1150                         bool state)
1151 {
1152         bool cur_state;
1153         struct intel_dpll_hw_state hw_state;
1154
1155         if (WARN (!pll,
1156                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1157                 return;
1158
1159         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1160         I915_STATE_WARN(cur_state != state,
1161              "%s assertion failure (expected %s, current %s)\n",
1162              pll->name, state_string(state), state_string(cur_state));
1163 }
1164
1165 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1166                           enum pipe pipe, bool state)
1167 {
1168         int reg;
1169         u32 val;
1170         bool cur_state;
1171         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1172                                                                       pipe);
1173
1174         if (HAS_DDI(dev_priv->dev)) {
1175                 /* DDI does not have a specific FDI_TX register */
1176                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1177                 val = I915_READ(reg);
1178                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1179         } else {
1180                 reg = FDI_TX_CTL(pipe);
1181                 val = I915_READ(reg);
1182                 cur_state = !!(val & FDI_TX_ENABLE);
1183         }
1184         I915_STATE_WARN(cur_state != state,
1185              "FDI TX state assertion failure (expected %s, current %s)\n",
1186              state_string(state), state_string(cur_state));
1187 }
1188 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1189 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1190
1191 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1192                           enum pipe pipe, bool state)
1193 {
1194         int reg;
1195         u32 val;
1196         bool cur_state;
1197
1198         reg = FDI_RX_CTL(pipe);
1199         val = I915_READ(reg);
1200         cur_state = !!(val & FDI_RX_ENABLE);
1201         I915_STATE_WARN(cur_state != state,
1202              "FDI RX state assertion failure (expected %s, current %s)\n",
1203              state_string(state), state_string(cur_state));
1204 }
1205 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1206 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1207
1208 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1209                                       enum pipe pipe)
1210 {
1211         int reg;
1212         u32 val;
1213
1214         /* ILK FDI PLL is always enabled */
1215         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1216                 return;
1217
1218         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1219         if (HAS_DDI(dev_priv->dev))
1220                 return;
1221
1222         reg = FDI_TX_CTL(pipe);
1223         val = I915_READ(reg);
1224         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1225 }
1226
1227 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1228                        enum pipe pipe, bool state)
1229 {
1230         int reg;
1231         u32 val;
1232         bool cur_state;
1233
1234         reg = FDI_RX_CTL(pipe);
1235         val = I915_READ(reg);
1236         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1237         I915_STATE_WARN(cur_state != state,
1238              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1239              state_string(state), state_string(cur_state));
1240 }
1241
1242 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1243                            enum pipe pipe)
1244 {
1245         struct drm_device *dev = dev_priv->dev;
1246         int pp_reg;
1247         u32 val;
1248         enum pipe panel_pipe = PIPE_A;
1249         bool locked = true;
1250
1251         if (WARN_ON(HAS_DDI(dev)))
1252                 return;
1253
1254         if (HAS_PCH_SPLIT(dev)) {
1255                 u32 port_sel;
1256
1257                 pp_reg = PCH_PP_CONTROL;
1258                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1259
1260                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1261                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1262                         panel_pipe = PIPE_B;
1263                 /* XXX: else fix for eDP */
1264         } else if (IS_VALLEYVIEW(dev)) {
1265                 /* presumably write lock depends on pipe, not port select */
1266                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1267                 panel_pipe = pipe;
1268         } else {
1269                 pp_reg = PP_CONTROL;
1270                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1271                         panel_pipe = PIPE_B;
1272         }
1273
1274         val = I915_READ(pp_reg);
1275         if (!(val & PANEL_POWER_ON) ||
1276             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1277                 locked = false;
1278
1279         I915_STATE_WARN(panel_pipe == pipe && locked,
1280              "panel assertion failure, pipe %c regs locked\n",
1281              pipe_name(pipe));
1282 }
1283
1284 static void assert_cursor(struct drm_i915_private *dev_priv,
1285                           enum pipe pipe, bool state)
1286 {
1287         struct drm_device *dev = dev_priv->dev;
1288         bool cur_state;
1289
1290         if (IS_845G(dev) || IS_I865G(dev))
1291                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1292         else
1293                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1294
1295         I915_STATE_WARN(cur_state != state,
1296              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1297              pipe_name(pipe), state_string(state), state_string(cur_state));
1298 }
1299 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1300 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1301
1302 void assert_pipe(struct drm_i915_private *dev_priv,
1303                  enum pipe pipe, bool state)
1304 {
1305         int reg;
1306         u32 val;
1307         bool cur_state;
1308         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1309                                                                       pipe);
1310
1311         /* if we need the pipe quirk it must be always on */
1312         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1313             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1314                 state = true;
1315
1316         if (!intel_display_power_is_enabled(dev_priv,
1317                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1318                 cur_state = false;
1319         } else {
1320                 reg = PIPECONF(cpu_transcoder);
1321                 val = I915_READ(reg);
1322                 cur_state = !!(val & PIPECONF_ENABLE);
1323         }
1324
1325         I915_STATE_WARN(cur_state != state,
1326              "pipe %c assertion failure (expected %s, current %s)\n",
1327              pipe_name(pipe), state_string(state), state_string(cur_state));
1328 }
1329
1330 static void assert_plane(struct drm_i915_private *dev_priv,
1331                          enum plane plane, bool state)
1332 {
1333         int reg;
1334         u32 val;
1335         bool cur_state;
1336
1337         reg = DSPCNTR(plane);
1338         val = I915_READ(reg);
1339         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1340         I915_STATE_WARN(cur_state != state,
1341              "plane %c assertion failure (expected %s, current %s)\n",
1342              plane_name(plane), state_string(state), state_string(cur_state));
1343 }
1344
1345 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1346 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1347
1348 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1349                                    enum pipe pipe)
1350 {
1351         struct drm_device *dev = dev_priv->dev;
1352         int reg, i;
1353         u32 val;
1354         int cur_pipe;
1355
1356         /* Primary planes are fixed to pipes on gen4+ */
1357         if (INTEL_INFO(dev)->gen >= 4) {
1358                 reg = DSPCNTR(pipe);
1359                 val = I915_READ(reg);
1360                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1361                      "plane %c assertion failure, should be disabled but not\n",
1362                      plane_name(pipe));
1363                 return;
1364         }
1365
1366         /* Need to check both planes against the pipe */
1367         for_each_pipe(dev_priv, i) {
1368                 reg = DSPCNTR(i);
1369                 val = I915_READ(reg);
1370                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1371                         DISPPLANE_SEL_PIPE_SHIFT;
1372                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1373                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1374                      plane_name(i), pipe_name(pipe));
1375         }
1376 }
1377
1378 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1379                                     enum pipe pipe)
1380 {
1381         struct drm_device *dev = dev_priv->dev;
1382         int reg, sprite;
1383         u32 val;
1384
1385         if (INTEL_INFO(dev)->gen >= 9) {
1386                 for_each_sprite(dev_priv, pipe, sprite) {
1387                         val = I915_READ(PLANE_CTL(pipe, sprite));
1388                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1389                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1390                              sprite, pipe_name(pipe));
1391                 }
1392         } else if (IS_VALLEYVIEW(dev)) {
1393                 for_each_sprite(dev_priv, pipe, sprite) {
1394                         reg = SPCNTR(pipe, sprite);
1395                         val = I915_READ(reg);
1396                         I915_STATE_WARN(val & SP_ENABLE,
1397                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1398                              sprite_name(pipe, sprite), pipe_name(pipe));
1399                 }
1400         } else if (INTEL_INFO(dev)->gen >= 7) {
1401                 reg = SPRCTL(pipe);
1402                 val = I915_READ(reg);
1403                 I915_STATE_WARN(val & SPRITE_ENABLE,
1404                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1405                      plane_name(pipe), pipe_name(pipe));
1406         } else if (INTEL_INFO(dev)->gen >= 5) {
1407                 reg = DVSCNTR(pipe);
1408                 val = I915_READ(reg);
1409                 I915_STATE_WARN(val & DVS_ENABLE,
1410                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1411                      plane_name(pipe), pipe_name(pipe));
1412         }
1413 }
1414
1415 static void assert_vblank_disabled(struct drm_crtc *crtc)
1416 {
1417         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1418                 drm_crtc_vblank_put(crtc);
1419 }
1420
1421 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1422 {
1423         u32 val;
1424         bool enabled;
1425
1426         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1427
1428         val = I915_READ(PCH_DREF_CONTROL);
1429         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1430                             DREF_SUPERSPREAD_SOURCE_MASK));
1431         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1432 }
1433
1434 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1435                                            enum pipe pipe)
1436 {
1437         int reg;
1438         u32 val;
1439         bool enabled;
1440
1441         reg = PCH_TRANSCONF(pipe);
1442         val = I915_READ(reg);
1443         enabled = !!(val & TRANS_ENABLE);
1444         I915_STATE_WARN(enabled,
1445              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1446              pipe_name(pipe));
1447 }
1448
1449 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1450                             enum pipe pipe, u32 port_sel, u32 val)
1451 {
1452         if ((val & DP_PORT_EN) == 0)
1453                 return false;
1454
1455         if (HAS_PCH_CPT(dev_priv->dev)) {
1456                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1457                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1458                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1459                         return false;
1460         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1461                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1462                         return false;
1463         } else {
1464                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1465                         return false;
1466         }
1467         return true;
1468 }
1469
1470 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1471                               enum pipe pipe, u32 val)
1472 {
1473         if ((val & SDVO_ENABLE) == 0)
1474                 return false;
1475
1476         if (HAS_PCH_CPT(dev_priv->dev)) {
1477                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1478                         return false;
1479         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1480                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1481                         return false;
1482         } else {
1483                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1484                         return false;
1485         }
1486         return true;
1487 }
1488
1489 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1490                               enum pipe pipe, u32 val)
1491 {
1492         if ((val & LVDS_PORT_EN) == 0)
1493                 return false;
1494
1495         if (HAS_PCH_CPT(dev_priv->dev)) {
1496                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1497                         return false;
1498         } else {
1499                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1500                         return false;
1501         }
1502         return true;
1503 }
1504
1505 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1506                               enum pipe pipe, u32 val)
1507 {
1508         if ((val & ADPA_DAC_ENABLE) == 0)
1509                 return false;
1510         if (HAS_PCH_CPT(dev_priv->dev)) {
1511                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1512                         return false;
1513         } else {
1514                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1515                         return false;
1516         }
1517         return true;
1518 }
1519
1520 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1521                                    enum pipe pipe, int reg, u32 port_sel)
1522 {
1523         u32 val = I915_READ(reg);
1524         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1525              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1526              reg, pipe_name(pipe));
1527
1528         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1529              && (val & DP_PIPEB_SELECT),
1530              "IBX PCH dp port still using transcoder B\n");
1531 }
1532
1533 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1534                                      enum pipe pipe, int reg)
1535 {
1536         u32 val = I915_READ(reg);
1537         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1538              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1539              reg, pipe_name(pipe));
1540
1541         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1542              && (val & SDVO_PIPE_B_SELECT),
1543              "IBX PCH hdmi port still using transcoder B\n");
1544 }
1545
1546 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1547                                       enum pipe pipe)
1548 {
1549         int reg;
1550         u32 val;
1551
1552         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1553         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1554         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1555
1556         reg = PCH_ADPA;
1557         val = I915_READ(reg);
1558         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1559              "PCH VGA enabled on transcoder %c, should be disabled\n",
1560              pipe_name(pipe));
1561
1562         reg = PCH_LVDS;
1563         val = I915_READ(reg);
1564         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1565              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1566              pipe_name(pipe));
1567
1568         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1569         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1570         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1571 }
1572
1573 static void vlv_enable_pll(struct intel_crtc *crtc,
1574                            const struct intel_crtc_state *pipe_config)
1575 {
1576         struct drm_device *dev = crtc->base.dev;
1577         struct drm_i915_private *dev_priv = dev->dev_private;
1578         int reg = DPLL(crtc->pipe);
1579         u32 dpll = pipe_config->dpll_hw_state.dpll;
1580
1581         assert_pipe_disabled(dev_priv, crtc->pipe);
1582
1583         /* No really, not for ILK+ */
1584         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1585
1586         /* PLL is protected by panel, make sure we can write it */
1587         if (IS_MOBILE(dev_priv->dev))
1588                 assert_panel_unlocked(dev_priv, crtc->pipe);
1589
1590         I915_WRITE(reg, dpll);
1591         POSTING_READ(reg);
1592         udelay(150);
1593
1594         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1595                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1596
1597         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1598         POSTING_READ(DPLL_MD(crtc->pipe));
1599
1600         /* We do this three times for luck */
1601         I915_WRITE(reg, dpll);
1602         POSTING_READ(reg);
1603         udelay(150); /* wait for warmup */
1604         I915_WRITE(reg, dpll);
1605         POSTING_READ(reg);
1606         udelay(150); /* wait for warmup */
1607         I915_WRITE(reg, dpll);
1608         POSTING_READ(reg);
1609         udelay(150); /* wait for warmup */
1610 }
1611
1612 static void chv_enable_pll(struct intel_crtc *crtc,
1613                            const struct intel_crtc_state *pipe_config)
1614 {
1615         struct drm_device *dev = crtc->base.dev;
1616         struct drm_i915_private *dev_priv = dev->dev_private;
1617         int pipe = crtc->pipe;
1618         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1619         u32 tmp;
1620
1621         assert_pipe_disabled(dev_priv, crtc->pipe);
1622
1623         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1624
1625         mutex_lock(&dev_priv->sb_lock);
1626
1627         /* Enable back the 10bit clock to display controller */
1628         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1629         tmp |= DPIO_DCLKP_EN;
1630         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1631
1632         mutex_unlock(&dev_priv->sb_lock);
1633
1634         /*
1635          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1636          */
1637         udelay(1);
1638
1639         /* Enable PLL */
1640         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1641
1642         /* Check PLL is locked */
1643         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1644                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1645
1646         /* not sure when this should be written */
1647         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1648         POSTING_READ(DPLL_MD(pipe));
1649 }
1650
1651 static int intel_num_dvo_pipes(struct drm_device *dev)
1652 {
1653         struct intel_crtc *crtc;
1654         int count = 0;
1655
1656         for_each_intel_crtc(dev, crtc)
1657                 count += crtc->base.state->active &&
1658                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1659
1660         return count;
1661 }
1662
1663 static void i9xx_enable_pll(struct intel_crtc *crtc)
1664 {
1665         struct drm_device *dev = crtc->base.dev;
1666         struct drm_i915_private *dev_priv = dev->dev_private;
1667         int reg = DPLL(crtc->pipe);
1668         u32 dpll = crtc->config->dpll_hw_state.dpll;
1669
1670         assert_pipe_disabled(dev_priv, crtc->pipe);
1671
1672         /* No really, not for ILK+ */
1673         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1674
1675         /* PLL is protected by panel, make sure we can write it */
1676         if (IS_MOBILE(dev) && !IS_I830(dev))
1677                 assert_panel_unlocked(dev_priv, crtc->pipe);
1678
1679         /* Enable DVO 2x clock on both PLLs if necessary */
1680         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1681                 /*
1682                  * It appears to be important that we don't enable this
1683                  * for the current pipe before otherwise configuring the
1684                  * PLL. No idea how this should be handled if multiple
1685                  * DVO outputs are enabled simultaneosly.
1686                  */
1687                 dpll |= DPLL_DVO_2X_MODE;
1688                 I915_WRITE(DPLL(!crtc->pipe),
1689                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1690         }
1691
1692         /* Wait for the clocks to stabilize. */
1693         POSTING_READ(reg);
1694         udelay(150);
1695
1696         if (INTEL_INFO(dev)->gen >= 4) {
1697                 I915_WRITE(DPLL_MD(crtc->pipe),
1698                            crtc->config->dpll_hw_state.dpll_md);
1699         } else {
1700                 /* The pixel multiplier can only be updated once the
1701                  * DPLL is enabled and the clocks are stable.
1702                  *
1703                  * So write it again.
1704                  */
1705                 I915_WRITE(reg, dpll);
1706         }
1707
1708         /* We do this three times for luck */
1709         I915_WRITE(reg, dpll);
1710         POSTING_READ(reg);
1711         udelay(150); /* wait for warmup */
1712         I915_WRITE(reg, dpll);
1713         POSTING_READ(reg);
1714         udelay(150); /* wait for warmup */
1715         I915_WRITE(reg, dpll);
1716         POSTING_READ(reg);
1717         udelay(150); /* wait for warmup */
1718 }
1719
1720 /**
1721  * i9xx_disable_pll - disable a PLL
1722  * @dev_priv: i915 private structure
1723  * @pipe: pipe PLL to disable
1724  *
1725  * Disable the PLL for @pipe, making sure the pipe is off first.
1726  *
1727  * Note!  This is for pre-ILK only.
1728  */
1729 static void i9xx_disable_pll(struct intel_crtc *crtc)
1730 {
1731         struct drm_device *dev = crtc->base.dev;
1732         struct drm_i915_private *dev_priv = dev->dev_private;
1733         enum pipe pipe = crtc->pipe;
1734
1735         /* Disable DVO 2x clock on both PLLs if necessary */
1736         if (IS_I830(dev) &&
1737             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1738             !intel_num_dvo_pipes(dev)) {
1739                 I915_WRITE(DPLL(PIPE_B),
1740                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1741                 I915_WRITE(DPLL(PIPE_A),
1742                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1743         }
1744
1745         /* Don't disable pipe or pipe PLLs if needed */
1746         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1747             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1748                 return;
1749
1750         /* Make sure the pipe isn't still relying on us */
1751         assert_pipe_disabled(dev_priv, pipe);
1752
1753         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1754         POSTING_READ(DPLL(pipe));
1755 }
1756
1757 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1758 {
1759         u32 val;
1760
1761         /* Make sure the pipe isn't still relying on us */
1762         assert_pipe_disabled(dev_priv, pipe);
1763
1764         /*
1765          * Leave integrated clock source and reference clock enabled for pipe B.
1766          * The latter is needed for VGA hotplug / manual detection.
1767          */
1768         val = DPLL_VGA_MODE_DIS;
1769         if (pipe == PIPE_B)
1770                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1771         I915_WRITE(DPLL(pipe), val);
1772         POSTING_READ(DPLL(pipe));
1773
1774 }
1775
1776 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1777 {
1778         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1779         u32 val;
1780
1781         /* Make sure the pipe isn't still relying on us */
1782         assert_pipe_disabled(dev_priv, pipe);
1783
1784         /* Set PLL en = 0 */
1785         val = DPLL_SSC_REF_CLK_CHV |
1786                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1787         if (pipe != PIPE_A)
1788                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1789         I915_WRITE(DPLL(pipe), val);
1790         POSTING_READ(DPLL(pipe));
1791
1792         mutex_lock(&dev_priv->sb_lock);
1793
1794         /* Disable 10bit clock to display controller */
1795         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1796         val &= ~DPIO_DCLKP_EN;
1797         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1798
1799         mutex_unlock(&dev_priv->sb_lock);
1800 }
1801
1802 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1803                          struct intel_digital_port *dport,
1804                          unsigned int expected_mask)
1805 {
1806         u32 port_mask;
1807         int dpll_reg;
1808
1809         switch (dport->port) {
1810         case PORT_B:
1811                 port_mask = DPLL_PORTB_READY_MASK;
1812                 dpll_reg = DPLL(0);
1813                 break;
1814         case PORT_C:
1815                 port_mask = DPLL_PORTC_READY_MASK;
1816                 dpll_reg = DPLL(0);
1817                 expected_mask <<= 4;
1818                 break;
1819         case PORT_D:
1820                 port_mask = DPLL_PORTD_READY_MASK;
1821                 dpll_reg = DPIO_PHY_STATUS;
1822                 break;
1823         default:
1824                 BUG();
1825         }
1826
1827         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1828                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1829                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1830 }
1831
1832 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1833 {
1834         struct drm_device *dev = crtc->base.dev;
1835         struct drm_i915_private *dev_priv = dev->dev_private;
1836         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1837
1838         if (WARN_ON(pll == NULL))
1839                 return;
1840
1841         WARN_ON(!pll->config.crtc_mask);
1842         if (pll->active == 0) {
1843                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1844                 WARN_ON(pll->on);
1845                 assert_shared_dpll_disabled(dev_priv, pll);
1846
1847                 pll->mode_set(dev_priv, pll);
1848         }
1849 }
1850
1851 /**
1852  * intel_enable_shared_dpll - enable PCH PLL
1853  * @dev_priv: i915 private structure
1854  * @pipe: pipe PLL to enable
1855  *
1856  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1857  * drives the transcoder clock.
1858  */
1859 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1860 {
1861         struct drm_device *dev = crtc->base.dev;
1862         struct drm_i915_private *dev_priv = dev->dev_private;
1863         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1864
1865         if (WARN_ON(pll == NULL))
1866                 return;
1867
1868         if (WARN_ON(pll->config.crtc_mask == 0))
1869                 return;
1870
1871         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1872                       pll->name, pll->active, pll->on,
1873                       crtc->base.base.id);
1874
1875         if (pll->active++) {
1876                 WARN_ON(!pll->on);
1877                 assert_shared_dpll_enabled(dev_priv, pll);
1878                 return;
1879         }
1880         WARN_ON(pll->on);
1881
1882         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1883
1884         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1885         pll->enable(dev_priv, pll);
1886         pll->on = true;
1887 }
1888
1889 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1890 {
1891         struct drm_device *dev = crtc->base.dev;
1892         struct drm_i915_private *dev_priv = dev->dev_private;
1893         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1894
1895         /* PCH only available on ILK+ */
1896         if (INTEL_INFO(dev)->gen < 5)
1897                 return;
1898
1899         if (pll == NULL)
1900                 return;
1901
1902         if (WARN_ON(!(pll->config.crtc_mask & (1 << drm_crtc_index(&crtc->base)))))
1903                 return;
1904
1905         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1906                       pll->name, pll->active, pll->on,
1907                       crtc->base.base.id);
1908
1909         if (WARN_ON(pll->active == 0)) {
1910                 assert_shared_dpll_disabled(dev_priv, pll);
1911                 return;
1912         }
1913
1914         assert_shared_dpll_enabled(dev_priv, pll);
1915         WARN_ON(!pll->on);
1916         if (--pll->active)
1917                 return;
1918
1919         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1920         pll->disable(dev_priv, pll);
1921         pll->on = false;
1922
1923         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1924 }
1925
1926 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1927                                            enum pipe pipe)
1928 {
1929         struct drm_device *dev = dev_priv->dev;
1930         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1931         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1932         uint32_t reg, val, pipeconf_val;
1933
1934         /* PCH only available on ILK+ */
1935         BUG_ON(!HAS_PCH_SPLIT(dev));
1936
1937         /* Make sure PCH DPLL is enabled */
1938         assert_shared_dpll_enabled(dev_priv,
1939                                    intel_crtc_to_shared_dpll(intel_crtc));
1940
1941         /* FDI must be feeding us bits for PCH ports */
1942         assert_fdi_tx_enabled(dev_priv, pipe);
1943         assert_fdi_rx_enabled(dev_priv, pipe);
1944
1945         if (HAS_PCH_CPT(dev)) {
1946                 /* Workaround: Set the timing override bit before enabling the
1947                  * pch transcoder. */
1948                 reg = TRANS_CHICKEN2(pipe);
1949                 val = I915_READ(reg);
1950                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1951                 I915_WRITE(reg, val);
1952         }
1953
1954         reg = PCH_TRANSCONF(pipe);
1955         val = I915_READ(reg);
1956         pipeconf_val = I915_READ(PIPECONF(pipe));
1957
1958         if (HAS_PCH_IBX(dev_priv->dev)) {
1959                 /*
1960                  * Make the BPC in transcoder be consistent with
1961                  * that in pipeconf reg. For HDMI we must use 8bpc
1962                  * here for both 8bpc and 12bpc.
1963                  */
1964                 val &= ~PIPECONF_BPC_MASK;
1965                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1966                         val |= PIPECONF_8BPC;
1967                 else
1968                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1969         }
1970
1971         val &= ~TRANS_INTERLACE_MASK;
1972         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1973                 if (HAS_PCH_IBX(dev_priv->dev) &&
1974                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1975                         val |= TRANS_LEGACY_INTERLACED_ILK;
1976                 else
1977                         val |= TRANS_INTERLACED;
1978         else
1979                 val |= TRANS_PROGRESSIVE;
1980
1981         I915_WRITE(reg, val | TRANS_ENABLE);
1982         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1983                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1984 }
1985
1986 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1987                                       enum transcoder cpu_transcoder)
1988 {
1989         u32 val, pipeconf_val;
1990
1991         /* PCH only available on ILK+ */
1992         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
1993
1994         /* FDI must be feeding us bits for PCH ports */
1995         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1996         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1997
1998         /* Workaround: set timing override bit. */
1999         val = I915_READ(_TRANSA_CHICKEN2);
2000         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2001         I915_WRITE(_TRANSA_CHICKEN2, val);
2002
2003         val = TRANS_ENABLE;
2004         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2005
2006         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2007             PIPECONF_INTERLACED_ILK)
2008                 val |= TRANS_INTERLACED;
2009         else
2010                 val |= TRANS_PROGRESSIVE;
2011
2012         I915_WRITE(LPT_TRANSCONF, val);
2013         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2014                 DRM_ERROR("Failed to enable PCH transcoder\n");
2015 }
2016
2017 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2018                                             enum pipe pipe)
2019 {
2020         struct drm_device *dev = dev_priv->dev;
2021         uint32_t reg, val;
2022
2023         /* FDI relies on the transcoder */
2024         assert_fdi_tx_disabled(dev_priv, pipe);
2025         assert_fdi_rx_disabled(dev_priv, pipe);
2026
2027         /* Ports must be off as well */
2028         assert_pch_ports_disabled(dev_priv, pipe);
2029
2030         reg = PCH_TRANSCONF(pipe);
2031         val = I915_READ(reg);
2032         val &= ~TRANS_ENABLE;
2033         I915_WRITE(reg, val);
2034         /* wait for PCH transcoder off, transcoder state */
2035         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2036                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2037
2038         if (!HAS_PCH_IBX(dev)) {
2039                 /* Workaround: Clear the timing override chicken bit again. */
2040                 reg = TRANS_CHICKEN2(pipe);
2041                 val = I915_READ(reg);
2042                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2043                 I915_WRITE(reg, val);
2044         }
2045 }
2046
2047 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2048 {
2049         u32 val;
2050
2051         val = I915_READ(LPT_TRANSCONF);
2052         val &= ~TRANS_ENABLE;
2053         I915_WRITE(LPT_TRANSCONF, val);
2054         /* wait for PCH transcoder off, transcoder state */
2055         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2056                 DRM_ERROR("Failed to disable PCH transcoder\n");
2057
2058         /* Workaround: clear timing override bit. */
2059         val = I915_READ(_TRANSA_CHICKEN2);
2060         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2061         I915_WRITE(_TRANSA_CHICKEN2, val);
2062 }
2063
2064 /**
2065  * intel_enable_pipe - enable a pipe, asserting requirements
2066  * @crtc: crtc responsible for the pipe
2067  *
2068  * Enable @crtc's pipe, making sure that various hardware specific requirements
2069  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2070  */
2071 static void intel_enable_pipe(struct intel_crtc *crtc)
2072 {
2073         struct drm_device *dev = crtc->base.dev;
2074         struct drm_i915_private *dev_priv = dev->dev_private;
2075         enum pipe pipe = crtc->pipe;
2076         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2077                                                                       pipe);
2078         enum pipe pch_transcoder;
2079         int reg;
2080         u32 val;
2081
2082         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
2083
2084         assert_planes_disabled(dev_priv, pipe);
2085         assert_cursor_disabled(dev_priv, pipe);
2086         assert_sprites_disabled(dev_priv, pipe);
2087
2088         if (HAS_PCH_LPT(dev_priv->dev))
2089                 pch_transcoder = TRANSCODER_A;
2090         else
2091                 pch_transcoder = pipe;
2092
2093         /*
2094          * A pipe without a PLL won't actually be able to drive bits from
2095          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2096          * need the check.
2097          */
2098         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2099                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2100                         assert_dsi_pll_enabled(dev_priv);
2101                 else
2102                         assert_pll_enabled(dev_priv, pipe);
2103         else {
2104                 if (crtc->config->has_pch_encoder) {
2105                         /* if driving the PCH, we need FDI enabled */
2106                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2107                         assert_fdi_tx_pll_enabled(dev_priv,
2108                                                   (enum pipe) cpu_transcoder);
2109                 }
2110                 /* FIXME: assert CPU port conditions for SNB+ */
2111         }
2112
2113         reg = PIPECONF(cpu_transcoder);
2114         val = I915_READ(reg);
2115         if (val & PIPECONF_ENABLE) {
2116                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2117                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2118                 return;
2119         }
2120
2121         I915_WRITE(reg, val | PIPECONF_ENABLE);
2122         POSTING_READ(reg);
2123 }
2124
2125 /**
2126  * intel_disable_pipe - disable a pipe, asserting requirements
2127  * @crtc: crtc whose pipes is to be disabled
2128  *
2129  * Disable the pipe of @crtc, making sure that various hardware
2130  * specific requirements are met, if applicable, e.g. plane
2131  * disabled, panel fitter off, etc.
2132  *
2133  * Will wait until the pipe has shut down before returning.
2134  */
2135 static void intel_disable_pipe(struct intel_crtc *crtc)
2136 {
2137         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2138         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2139         enum pipe pipe = crtc->pipe;
2140         int reg;
2141         u32 val;
2142
2143         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2144
2145         /*
2146          * Make sure planes won't keep trying to pump pixels to us,
2147          * or we might hang the display.
2148          */
2149         assert_planes_disabled(dev_priv, pipe);
2150         assert_cursor_disabled(dev_priv, pipe);
2151         assert_sprites_disabled(dev_priv, pipe);
2152
2153         reg = PIPECONF(cpu_transcoder);
2154         val = I915_READ(reg);
2155         if ((val & PIPECONF_ENABLE) == 0)
2156                 return;
2157
2158         /*
2159          * Double wide has implications for planes
2160          * so best keep it disabled when not needed.
2161          */
2162         if (crtc->config->double_wide)
2163                 val &= ~PIPECONF_DOUBLE_WIDE;
2164
2165         /* Don't disable pipe or pipe PLLs if needed */
2166         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2167             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2168                 val &= ~PIPECONF_ENABLE;
2169
2170         I915_WRITE(reg, val);
2171         if ((val & PIPECONF_ENABLE) == 0)
2172                 intel_wait_for_pipe_off(crtc);
2173 }
2174
2175 static bool need_vtd_wa(struct drm_device *dev)
2176 {
2177 #ifdef CONFIG_INTEL_IOMMU
2178         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2179                 return true;
2180 #endif
2181         return false;
2182 }
2183
2184 unsigned int
2185 intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2186                   uint64_t fb_format_modifier)
2187 {
2188         unsigned int tile_height;
2189         uint32_t pixel_bytes;
2190
2191         switch (fb_format_modifier) {
2192         case DRM_FORMAT_MOD_NONE:
2193                 tile_height = 1;
2194                 break;
2195         case I915_FORMAT_MOD_X_TILED:
2196                 tile_height = IS_GEN2(dev) ? 16 : 8;
2197                 break;
2198         case I915_FORMAT_MOD_Y_TILED:
2199                 tile_height = 32;
2200                 break;
2201         case I915_FORMAT_MOD_Yf_TILED:
2202                 pixel_bytes = drm_format_plane_cpp(pixel_format, 0);
2203                 switch (pixel_bytes) {
2204                 default:
2205                 case 1:
2206                         tile_height = 64;
2207                         break;
2208                 case 2:
2209                 case 4:
2210                         tile_height = 32;
2211                         break;
2212                 case 8:
2213                         tile_height = 16;
2214                         break;
2215                 case 16:
2216                         WARN_ONCE(1,
2217                                   "128-bit pixels are not supported for display!");
2218                         tile_height = 16;
2219                         break;
2220                 }
2221                 break;
2222         default:
2223                 MISSING_CASE(fb_format_modifier);
2224                 tile_height = 1;
2225                 break;
2226         }
2227
2228         return tile_height;
2229 }
2230
2231 unsigned int
2232 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2233                       uint32_t pixel_format, uint64_t fb_format_modifier)
2234 {
2235         return ALIGN(height, intel_tile_height(dev, pixel_format,
2236                                                fb_format_modifier));
2237 }
2238
2239 static int
2240 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2241                         const struct drm_plane_state *plane_state)
2242 {
2243         struct intel_rotation_info *info = &view->rotation_info;
2244         unsigned int tile_height, tile_pitch;
2245
2246         *view = i915_ggtt_view_normal;
2247
2248         if (!plane_state)
2249                 return 0;
2250
2251         if (!intel_rotation_90_or_270(plane_state->rotation))
2252                 return 0;
2253
2254         *view = i915_ggtt_view_rotated;
2255
2256         info->height = fb->height;
2257         info->pixel_format = fb->pixel_format;
2258         info->pitch = fb->pitches[0];
2259         info->fb_modifier = fb->modifier[0];
2260
2261         tile_height = intel_tile_height(fb->dev, fb->pixel_format,
2262                                         fb->modifier[0]);
2263         tile_pitch = PAGE_SIZE / tile_height;
2264         info->width_pages = DIV_ROUND_UP(fb->pitches[0], tile_pitch);
2265         info->height_pages = DIV_ROUND_UP(fb->height, tile_height);
2266         info->size = info->width_pages * info->height_pages * PAGE_SIZE;
2267
2268         return 0;
2269 }
2270
2271 static unsigned int intel_linear_alignment(struct drm_i915_private *dev_priv)
2272 {
2273         if (INTEL_INFO(dev_priv)->gen >= 9)
2274                 return 256 * 1024;
2275         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2276                  IS_VALLEYVIEW(dev_priv))
2277                 return 128 * 1024;
2278         else if (INTEL_INFO(dev_priv)->gen >= 4)
2279                 return 4 * 1024;
2280         else
2281                 return 0;
2282 }
2283
2284 int
2285 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2286                            struct drm_framebuffer *fb,
2287                            const struct drm_plane_state *plane_state,
2288                            struct intel_engine_cs *pipelined,
2289                            struct drm_i915_gem_request **pipelined_request)
2290 {
2291         struct drm_device *dev = fb->dev;
2292         struct drm_i915_private *dev_priv = dev->dev_private;
2293         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2294         struct i915_ggtt_view view;
2295         u32 alignment;
2296         int ret;
2297
2298         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2299
2300         switch (fb->modifier[0]) {
2301         case DRM_FORMAT_MOD_NONE:
2302                 alignment = intel_linear_alignment(dev_priv);
2303                 break;
2304         case I915_FORMAT_MOD_X_TILED:
2305                 if (INTEL_INFO(dev)->gen >= 9)
2306                         alignment = 256 * 1024;
2307                 else {
2308                         /* pin() will align the object as required by fence */
2309                         alignment = 0;
2310                 }
2311                 break;
2312         case I915_FORMAT_MOD_Y_TILED:
2313         case I915_FORMAT_MOD_Yf_TILED:
2314                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2315                           "Y tiling bo slipped through, driver bug!\n"))
2316                         return -EINVAL;
2317                 alignment = 1 * 1024 * 1024;
2318                 break;
2319         default:
2320                 MISSING_CASE(fb->modifier[0]);
2321                 return -EINVAL;
2322         }
2323
2324         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2325         if (ret)
2326                 return ret;
2327
2328         /* Note that the w/a also requires 64 PTE of padding following the
2329          * bo. We currently fill all unused PTE with the shadow page and so
2330          * we should always have valid PTE following the scanout preventing
2331          * the VT-d warning.
2332          */
2333         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2334                 alignment = 256 * 1024;
2335
2336         /*
2337          * Global gtt pte registers are special registers which actually forward
2338          * writes to a chunk of system memory. Which means that there is no risk
2339          * that the register values disappear as soon as we call
2340          * intel_runtime_pm_put(), so it is correct to wrap only the
2341          * pin/unpin/fence and not more.
2342          */
2343         intel_runtime_pm_get(dev_priv);
2344
2345         dev_priv->mm.interruptible = false;
2346         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined,
2347                                                    pipelined_request, &view);
2348         if (ret)
2349                 goto err_interruptible;
2350
2351         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2352          * fence, whereas 965+ only requires a fence if using
2353          * framebuffer compression.  For simplicity, we always install
2354          * a fence as the cost is not that onerous.
2355          */
2356         ret = i915_gem_object_get_fence(obj);
2357         if (ret == -EDEADLK) {
2358                 /*
2359                  * -EDEADLK means there are no free fences
2360                  * no pending flips.
2361                  *
2362                  * This is propagated to atomic, but it uses
2363                  * -EDEADLK to force a locking recovery, so
2364                  * change the returned error to -EBUSY.
2365                  */
2366                 ret = -EBUSY;
2367                 goto err_unpin;
2368         } else if (ret)
2369                 goto err_unpin;
2370
2371         i915_gem_object_pin_fence(obj);
2372
2373         dev_priv->mm.interruptible = true;
2374         intel_runtime_pm_put(dev_priv);
2375         return 0;
2376
2377 err_unpin:
2378         i915_gem_object_unpin_from_display_plane(obj, &view);
2379 err_interruptible:
2380         dev_priv->mm.interruptible = true;
2381         intel_runtime_pm_put(dev_priv);
2382         return ret;
2383 }
2384
2385 static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2386                                const struct drm_plane_state *plane_state)
2387 {
2388         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2389         struct i915_ggtt_view view;
2390         int ret;
2391
2392         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2393
2394         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2395         WARN_ONCE(ret, "Couldn't get view from plane state!");
2396
2397         i915_gem_object_unpin_fence(obj);
2398         i915_gem_object_unpin_from_display_plane(obj, &view);
2399 }
2400
2401 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2402  * is assumed to be a power-of-two. */
2403 unsigned long intel_gen4_compute_page_offset(struct drm_i915_private *dev_priv,
2404                                              int *x, int *y,
2405                                              unsigned int tiling_mode,
2406                                              unsigned int cpp,
2407                                              unsigned int pitch)
2408 {
2409         if (tiling_mode != I915_TILING_NONE) {
2410                 unsigned int tile_rows, tiles;
2411
2412                 tile_rows = *y / 8;
2413                 *y %= 8;
2414
2415                 tiles = *x / (512/cpp);
2416                 *x %= 512/cpp;
2417
2418                 return tile_rows * pitch * 8 + tiles * 4096;
2419         } else {
2420                 unsigned int alignment = intel_linear_alignment(dev_priv) - 1;
2421                 unsigned int offset;
2422
2423                 offset = *y * pitch + *x * cpp;
2424                 *y = (offset & alignment) / pitch;
2425                 *x = ((offset & alignment) - *y * pitch) / cpp;
2426                 return offset & ~alignment;
2427         }
2428 }
2429
2430 static int i9xx_format_to_fourcc(int format)
2431 {
2432         switch (format) {
2433         case DISPPLANE_8BPP:
2434                 return DRM_FORMAT_C8;
2435         case DISPPLANE_BGRX555:
2436                 return DRM_FORMAT_XRGB1555;
2437         case DISPPLANE_BGRX565:
2438                 return DRM_FORMAT_RGB565;
2439         default:
2440         case DISPPLANE_BGRX888:
2441                 return DRM_FORMAT_XRGB8888;
2442         case DISPPLANE_RGBX888:
2443                 return DRM_FORMAT_XBGR8888;
2444         case DISPPLANE_BGRX101010:
2445                 return DRM_FORMAT_XRGB2101010;
2446         case DISPPLANE_RGBX101010:
2447                 return DRM_FORMAT_XBGR2101010;
2448         }
2449 }
2450
2451 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2452 {
2453         switch (format) {
2454         case PLANE_CTL_FORMAT_RGB_565:
2455                 return DRM_FORMAT_RGB565;
2456         default:
2457         case PLANE_CTL_FORMAT_XRGB_8888:
2458                 if (rgb_order) {
2459                         if (alpha)
2460                                 return DRM_FORMAT_ABGR8888;
2461                         else
2462                                 return DRM_FORMAT_XBGR8888;
2463                 } else {
2464                         if (alpha)
2465                                 return DRM_FORMAT_ARGB8888;
2466                         else
2467                                 return DRM_FORMAT_XRGB8888;
2468                 }
2469         case PLANE_CTL_FORMAT_XRGB_2101010:
2470                 if (rgb_order)
2471                         return DRM_FORMAT_XBGR2101010;
2472                 else
2473                         return DRM_FORMAT_XRGB2101010;
2474         }
2475 }
2476
2477 static bool
2478 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2479                               struct intel_initial_plane_config *plane_config)
2480 {
2481         struct drm_device *dev = crtc->base.dev;
2482         struct drm_i915_gem_object *obj = NULL;
2483         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2484         struct drm_framebuffer *fb = &plane_config->fb->base;
2485         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2486         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2487                                     PAGE_SIZE);
2488
2489         size_aligned -= base_aligned;
2490
2491         if (plane_config->size == 0)
2492                 return false;
2493
2494         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2495                                                              base_aligned,
2496                                                              base_aligned,
2497                                                              size_aligned);
2498         if (!obj)
2499                 return false;
2500
2501         obj->tiling_mode = plane_config->tiling;
2502         if (obj->tiling_mode == I915_TILING_X)
2503                 obj->stride = fb->pitches[0];
2504
2505         mode_cmd.pixel_format = fb->pixel_format;
2506         mode_cmd.width = fb->width;
2507         mode_cmd.height = fb->height;
2508         mode_cmd.pitches[0] = fb->pitches[0];
2509         mode_cmd.modifier[0] = fb->modifier[0];
2510         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2511
2512         mutex_lock(&dev->struct_mutex);
2513         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2514                                    &mode_cmd, obj)) {
2515                 DRM_DEBUG_KMS("intel fb init failed\n");
2516                 goto out_unref_obj;
2517         }
2518         mutex_unlock(&dev->struct_mutex);
2519
2520         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2521         return true;
2522
2523 out_unref_obj:
2524         drm_gem_object_unreference(&obj->base);
2525         mutex_unlock(&dev->struct_mutex);
2526         return false;
2527 }
2528
2529 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2530 static void
2531 update_state_fb(struct drm_plane *plane)
2532 {
2533         if (plane->fb == plane->state->fb)
2534                 return;
2535
2536         if (plane->state->fb)
2537                 drm_framebuffer_unreference(plane->state->fb);
2538         plane->state->fb = plane->fb;
2539         if (plane->state->fb)
2540                 drm_framebuffer_reference(plane->state->fb);
2541 }
2542
2543 static void
2544 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2545                              struct intel_initial_plane_config *plane_config)
2546 {
2547         struct drm_device *dev = intel_crtc->base.dev;
2548         struct drm_i915_private *dev_priv = dev->dev_private;
2549         struct drm_crtc *c;
2550         struct intel_crtc *i;
2551         struct drm_i915_gem_object *obj;
2552         struct drm_plane *primary = intel_crtc->base.primary;
2553         struct drm_plane_state *plane_state = primary->state;
2554         struct drm_framebuffer *fb;
2555
2556         if (!plane_config->fb)
2557                 return;
2558
2559         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2560                 fb = &plane_config->fb->base;
2561                 goto valid_fb;
2562         }
2563
2564         kfree(plane_config->fb);
2565
2566         /*
2567          * Failed to alloc the obj, check to see if we should share
2568          * an fb with another CRTC instead
2569          */
2570         for_each_crtc(dev, c) {
2571                 i = to_intel_crtc(c);
2572
2573                 if (c == &intel_crtc->base)
2574                         continue;
2575
2576                 if (!i->active)
2577                         continue;
2578
2579                 fb = c->primary->fb;
2580                 if (!fb)
2581                         continue;
2582
2583                 obj = intel_fb_obj(fb);
2584                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2585                         drm_framebuffer_reference(fb);
2586                         goto valid_fb;
2587                 }
2588         }
2589
2590         return;
2591
2592 valid_fb:
2593         plane_state->src_x = plane_state->src_y = 0;
2594         plane_state->src_w = fb->width << 16;
2595         plane_state->src_h = fb->height << 16;
2596
2597         plane_state->crtc_x = plane_state->src_y = 0;
2598         plane_state->crtc_w = fb->width;
2599         plane_state->crtc_h = fb->height;
2600
2601         obj = intel_fb_obj(fb);
2602         if (obj->tiling_mode != I915_TILING_NONE)
2603                 dev_priv->preserve_bios_swizzle = true;
2604
2605         drm_framebuffer_reference(fb);
2606         primary->fb = primary->state->fb = fb;
2607         primary->crtc = primary->state->crtc = &intel_crtc->base;
2608         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2609         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2610 }
2611
2612 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2613                                       struct drm_framebuffer *fb,
2614                                       int x, int y)
2615 {
2616         struct drm_device *dev = crtc->dev;
2617         struct drm_i915_private *dev_priv = dev->dev_private;
2618         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2619         struct drm_plane *primary = crtc->primary;
2620         bool visible = to_intel_plane_state(primary->state)->visible;
2621         struct drm_i915_gem_object *obj;
2622         int plane = intel_crtc->plane;
2623         unsigned long linear_offset;
2624         u32 dspcntr;
2625         u32 reg = DSPCNTR(plane);
2626         int pixel_size;
2627
2628         if (!visible || !fb) {
2629                 I915_WRITE(reg, 0);
2630                 if (INTEL_INFO(dev)->gen >= 4)
2631                         I915_WRITE(DSPSURF(plane), 0);
2632                 else
2633                         I915_WRITE(DSPADDR(plane), 0);
2634                 POSTING_READ(reg);
2635                 return;
2636         }
2637
2638         obj = intel_fb_obj(fb);
2639         if (WARN_ON(obj == NULL))
2640                 return;
2641
2642         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2643
2644         dspcntr = DISPPLANE_GAMMA_ENABLE;
2645
2646         dspcntr |= DISPLAY_PLANE_ENABLE;
2647
2648         if (INTEL_INFO(dev)->gen < 4) {
2649                 if (intel_crtc->pipe == PIPE_B)
2650                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2651
2652                 /* pipesrc and dspsize control the size that is scaled from,
2653                  * which should always be the user's requested size.
2654                  */
2655                 I915_WRITE(DSPSIZE(plane),
2656                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2657                            (intel_crtc->config->pipe_src_w - 1));
2658                 I915_WRITE(DSPPOS(plane), 0);
2659         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2660                 I915_WRITE(PRIMSIZE(plane),
2661                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2662                            (intel_crtc->config->pipe_src_w - 1));
2663                 I915_WRITE(PRIMPOS(plane), 0);
2664                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2665         }
2666
2667         switch (fb->pixel_format) {
2668         case DRM_FORMAT_C8:
2669                 dspcntr |= DISPPLANE_8BPP;
2670                 break;
2671         case DRM_FORMAT_XRGB1555:
2672                 dspcntr |= DISPPLANE_BGRX555;
2673                 break;
2674         case DRM_FORMAT_RGB565:
2675                 dspcntr |= DISPPLANE_BGRX565;
2676                 break;
2677         case DRM_FORMAT_XRGB8888:
2678                 dspcntr |= DISPPLANE_BGRX888;
2679                 break;
2680         case DRM_FORMAT_XBGR8888:
2681                 dspcntr |= DISPPLANE_RGBX888;
2682                 break;
2683         case DRM_FORMAT_XRGB2101010:
2684                 dspcntr |= DISPPLANE_BGRX101010;
2685                 break;
2686         case DRM_FORMAT_XBGR2101010:
2687                 dspcntr |= DISPPLANE_RGBX101010;
2688                 break;
2689         default:
2690                 BUG();
2691         }
2692
2693         if (INTEL_INFO(dev)->gen >= 4 &&
2694             obj->tiling_mode != I915_TILING_NONE)
2695                 dspcntr |= DISPPLANE_TILED;
2696
2697         if (IS_G4X(dev))
2698                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2699
2700         linear_offset = y * fb->pitches[0] + x * pixel_size;
2701
2702         if (INTEL_INFO(dev)->gen >= 4) {
2703                 intel_crtc->dspaddr_offset =
2704                         intel_gen4_compute_page_offset(dev_priv,
2705                                                        &x, &y, obj->tiling_mode,
2706                                                        pixel_size,
2707                                                        fb->pitches[0]);
2708                 linear_offset -= intel_crtc->dspaddr_offset;
2709         } else {
2710                 intel_crtc->dspaddr_offset = linear_offset;
2711         }
2712
2713         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2714                 dspcntr |= DISPPLANE_ROTATE_180;
2715
2716                 x += (intel_crtc->config->pipe_src_w - 1);
2717                 y += (intel_crtc->config->pipe_src_h - 1);
2718
2719                 /* Finding the last pixel of the last line of the display
2720                 data and adding to linear_offset*/
2721                 linear_offset +=
2722                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2723                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2724         }
2725
2726         I915_WRITE(reg, dspcntr);
2727
2728         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2729         if (INTEL_INFO(dev)->gen >= 4) {
2730                 I915_WRITE(DSPSURF(plane),
2731                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2732                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2733                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2734         } else
2735                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2736         POSTING_READ(reg);
2737 }
2738
2739 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2740                                           struct drm_framebuffer *fb,
2741                                           int x, int y)
2742 {
2743         struct drm_device *dev = crtc->dev;
2744         struct drm_i915_private *dev_priv = dev->dev_private;
2745         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2746         struct drm_plane *primary = crtc->primary;
2747         bool visible = to_intel_plane_state(primary->state)->visible;
2748         struct drm_i915_gem_object *obj;
2749         int plane = intel_crtc->plane;
2750         unsigned long linear_offset;
2751         u32 dspcntr;
2752         u32 reg = DSPCNTR(plane);
2753         int pixel_size;
2754
2755         if (!visible || !fb) {
2756                 I915_WRITE(reg, 0);
2757                 I915_WRITE(DSPSURF(plane), 0);
2758                 POSTING_READ(reg);
2759                 return;
2760         }
2761
2762         obj = intel_fb_obj(fb);
2763         if (WARN_ON(obj == NULL))
2764                 return;
2765
2766         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2767
2768         dspcntr = DISPPLANE_GAMMA_ENABLE;
2769
2770         dspcntr |= DISPLAY_PLANE_ENABLE;
2771
2772         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2773                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2774
2775         switch (fb->pixel_format) {
2776         case DRM_FORMAT_C8:
2777                 dspcntr |= DISPPLANE_8BPP;
2778                 break;
2779         case DRM_FORMAT_RGB565:
2780                 dspcntr |= DISPPLANE_BGRX565;
2781                 break;
2782         case DRM_FORMAT_XRGB8888:
2783                 dspcntr |= DISPPLANE_BGRX888;
2784                 break;
2785         case DRM_FORMAT_XBGR8888:
2786                 dspcntr |= DISPPLANE_RGBX888;
2787                 break;
2788         case DRM_FORMAT_XRGB2101010:
2789                 dspcntr |= DISPPLANE_BGRX101010;
2790                 break;
2791         case DRM_FORMAT_XBGR2101010:
2792                 dspcntr |= DISPPLANE_RGBX101010;
2793                 break;
2794         default:
2795                 BUG();
2796         }
2797
2798         if (obj->tiling_mode != I915_TILING_NONE)
2799                 dspcntr |= DISPPLANE_TILED;
2800
2801         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2802                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2803
2804         linear_offset = y * fb->pitches[0] + x * pixel_size;
2805         intel_crtc->dspaddr_offset =
2806                 intel_gen4_compute_page_offset(dev_priv,
2807                                                &x, &y, obj->tiling_mode,
2808                                                pixel_size,
2809                                                fb->pitches[0]);
2810         linear_offset -= intel_crtc->dspaddr_offset;
2811         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2812                 dspcntr |= DISPPLANE_ROTATE_180;
2813
2814                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2815                         x += (intel_crtc->config->pipe_src_w - 1);
2816                         y += (intel_crtc->config->pipe_src_h - 1);
2817
2818                         /* Finding the last pixel of the last line of the display
2819                         data and adding to linear_offset*/
2820                         linear_offset +=
2821                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2822                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2823                 }
2824         }
2825
2826         I915_WRITE(reg, dspcntr);
2827
2828         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2829         I915_WRITE(DSPSURF(plane),
2830                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2831         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2832                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2833         } else {
2834                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2835                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2836         }
2837         POSTING_READ(reg);
2838 }
2839
2840 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2841                               uint32_t pixel_format)
2842 {
2843         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2844
2845         /*
2846          * The stride is either expressed as a multiple of 64 bytes
2847          * chunks for linear buffers or in number of tiles for tiled
2848          * buffers.
2849          */
2850         switch (fb_modifier) {
2851         case DRM_FORMAT_MOD_NONE:
2852                 return 64;
2853         case I915_FORMAT_MOD_X_TILED:
2854                 if (INTEL_INFO(dev)->gen == 2)
2855                         return 128;
2856                 return 512;
2857         case I915_FORMAT_MOD_Y_TILED:
2858                 /* No need to check for old gens and Y tiling since this is
2859                  * about the display engine and those will be blocked before
2860                  * we get here.
2861                  */
2862                 return 128;
2863         case I915_FORMAT_MOD_Yf_TILED:
2864                 if (bits_per_pixel == 8)
2865                         return 64;
2866                 else
2867                         return 128;
2868         default:
2869                 MISSING_CASE(fb_modifier);
2870                 return 64;
2871         }
2872 }
2873
2874 unsigned long intel_plane_obj_offset(struct intel_plane *intel_plane,
2875                                      struct drm_i915_gem_object *obj)
2876 {
2877         const struct i915_ggtt_view *view = &i915_ggtt_view_normal;
2878
2879         if (intel_rotation_90_or_270(intel_plane->base.state->rotation))
2880                 view = &i915_ggtt_view_rotated;
2881
2882         return i915_gem_obj_ggtt_offset_view(obj, view);
2883 }
2884
2885 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2886 {
2887         struct drm_device *dev = intel_crtc->base.dev;
2888         struct drm_i915_private *dev_priv = dev->dev_private;
2889
2890         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2891         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2892         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2893 }
2894
2895 /*
2896  * This function detaches (aka. unbinds) unused scalers in hardware
2897  */
2898 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2899 {
2900         struct intel_crtc_scaler_state *scaler_state;
2901         int i;
2902
2903         scaler_state = &intel_crtc->config->scaler_state;
2904
2905         /* loop through and disable scalers that aren't in use */
2906         for (i = 0; i < intel_crtc->num_scalers; i++) {
2907                 if (!scaler_state->scalers[i].in_use)
2908                         skl_detach_scaler(intel_crtc, i);
2909         }
2910 }
2911
2912 u32 skl_plane_ctl_format(uint32_t pixel_format)
2913 {
2914         switch (pixel_format) {
2915         case DRM_FORMAT_C8:
2916                 return PLANE_CTL_FORMAT_INDEXED;
2917         case DRM_FORMAT_RGB565:
2918                 return PLANE_CTL_FORMAT_RGB_565;
2919         case DRM_FORMAT_XBGR8888:
2920                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2921         case DRM_FORMAT_XRGB8888:
2922                 return PLANE_CTL_FORMAT_XRGB_8888;
2923         /*
2924          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2925          * to be already pre-multiplied. We need to add a knob (or a different
2926          * DRM_FORMAT) for user-space to configure that.
2927          */
2928         case DRM_FORMAT_ABGR8888:
2929                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2930                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2931         case DRM_FORMAT_ARGB8888:
2932                 return PLANE_CTL_FORMAT_XRGB_8888 |
2933                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2934         case DRM_FORMAT_XRGB2101010:
2935                 return PLANE_CTL_FORMAT_XRGB_2101010;
2936         case DRM_FORMAT_XBGR2101010:
2937                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2938         case DRM_FORMAT_YUYV:
2939                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2940         case DRM_FORMAT_YVYU:
2941                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2942         case DRM_FORMAT_UYVY:
2943                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2944         case DRM_FORMAT_VYUY:
2945                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2946         default:
2947                 MISSING_CASE(pixel_format);
2948         }
2949
2950         return 0;
2951 }
2952
2953 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2954 {
2955         switch (fb_modifier) {
2956         case DRM_FORMAT_MOD_NONE:
2957                 break;
2958         case I915_FORMAT_MOD_X_TILED:
2959                 return PLANE_CTL_TILED_X;
2960         case I915_FORMAT_MOD_Y_TILED:
2961                 return PLANE_CTL_TILED_Y;
2962         case I915_FORMAT_MOD_Yf_TILED:
2963                 return PLANE_CTL_TILED_YF;
2964         default:
2965                 MISSING_CASE(fb_modifier);
2966         }
2967
2968         return 0;
2969 }
2970
2971 u32 skl_plane_ctl_rotation(unsigned int rotation)
2972 {
2973         switch (rotation) {
2974         case BIT(DRM_ROTATE_0):
2975                 break;
2976         /*
2977          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2978          * while i915 HW rotation is clockwise, thats why this swapping.
2979          */
2980         case BIT(DRM_ROTATE_90):
2981                 return PLANE_CTL_ROTATE_270;
2982         case BIT(DRM_ROTATE_180):
2983                 return PLANE_CTL_ROTATE_180;
2984         case BIT(DRM_ROTATE_270):
2985                 return PLANE_CTL_ROTATE_90;
2986         default:
2987                 MISSING_CASE(rotation);
2988         }
2989
2990         return 0;
2991 }
2992
2993 static void skylake_update_primary_plane(struct drm_crtc *crtc,
2994                                          struct drm_framebuffer *fb,
2995                                          int x, int y)
2996 {
2997         struct drm_device *dev = crtc->dev;
2998         struct drm_i915_private *dev_priv = dev->dev_private;
2999         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3000         struct drm_plane *plane = crtc->primary;
3001         bool visible = to_intel_plane_state(plane->state)->visible;
3002         struct drm_i915_gem_object *obj;
3003         int pipe = intel_crtc->pipe;
3004         u32 plane_ctl, stride_div, stride;
3005         u32 tile_height, plane_offset, plane_size;
3006         unsigned int rotation;
3007         int x_offset, y_offset;
3008         unsigned long surf_addr;
3009         struct intel_crtc_state *crtc_state = intel_crtc->config;
3010         struct intel_plane_state *plane_state;
3011         int src_x = 0, src_y = 0, src_w = 0, src_h = 0;
3012         int dst_x = 0, dst_y = 0, dst_w = 0, dst_h = 0;
3013         int scaler_id = -1;
3014
3015         plane_state = to_intel_plane_state(plane->state);
3016
3017         if (!visible || !fb) {
3018                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
3019                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
3020                 POSTING_READ(PLANE_CTL(pipe, 0));
3021                 return;
3022         }
3023
3024         plane_ctl = PLANE_CTL_ENABLE |
3025                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3026                     PLANE_CTL_PIPE_CSC_ENABLE;
3027
3028         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3029         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3030         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3031
3032         rotation = plane->state->rotation;
3033         plane_ctl |= skl_plane_ctl_rotation(rotation);
3034
3035         obj = intel_fb_obj(fb);
3036         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3037                                                fb->pixel_format);
3038         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj);
3039
3040         /*
3041          * FIXME: intel_plane_state->src, dst aren't set when transitional
3042          * update_plane helpers are called from legacy paths.
3043          * Once full atomic crtc is available, below check can be avoided.
3044          */
3045         if (drm_rect_width(&plane_state->src)) {
3046                 scaler_id = plane_state->scaler_id;
3047                 src_x = plane_state->src.x1 >> 16;
3048                 src_y = plane_state->src.y1 >> 16;
3049                 src_w = drm_rect_width(&plane_state->src) >> 16;
3050                 src_h = drm_rect_height(&plane_state->src) >> 16;
3051                 dst_x = plane_state->dst.x1;
3052                 dst_y = plane_state->dst.y1;
3053                 dst_w = drm_rect_width(&plane_state->dst);
3054                 dst_h = drm_rect_height(&plane_state->dst);
3055
3056                 WARN_ON(x != src_x || y != src_y);
3057         } else {
3058                 src_w = intel_crtc->config->pipe_src_w;
3059                 src_h = intel_crtc->config->pipe_src_h;
3060         }
3061
3062         if (intel_rotation_90_or_270(rotation)) {
3063                 /* stride = Surface height in tiles */
3064                 tile_height = intel_tile_height(dev, fb->pixel_format,
3065                                                 fb->modifier[0]);
3066                 stride = DIV_ROUND_UP(fb->height, tile_height);
3067                 x_offset = stride * tile_height - y - src_h;
3068                 y_offset = x;
3069                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3070         } else {
3071                 stride = fb->pitches[0] / stride_div;
3072                 x_offset = x;
3073                 y_offset = y;
3074                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3075         }
3076         plane_offset = y_offset << 16 | x_offset;
3077
3078         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3079         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3080         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3081         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3082
3083         if (scaler_id >= 0) {
3084                 uint32_t ps_ctrl = 0;
3085
3086                 WARN_ON(!dst_w || !dst_h);
3087                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3088                         crtc_state->scaler_state.scalers[scaler_id].mode;
3089                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3090                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3091                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3092                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3093                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3094         } else {
3095                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3096         }
3097
3098         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3099
3100         POSTING_READ(PLANE_SURF(pipe, 0));
3101 }
3102
3103 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3104 static int
3105 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3106                            int x, int y, enum mode_set_atomic state)
3107 {
3108         struct drm_device *dev = crtc->dev;
3109         struct drm_i915_private *dev_priv = dev->dev_private;
3110
3111         if (dev_priv->fbc.disable_fbc)
3112                 dev_priv->fbc.disable_fbc(dev_priv);
3113
3114         dev_priv->display.update_primary_plane(crtc, fb, x, y);
3115
3116         return 0;
3117 }
3118
3119 static void intel_complete_page_flips(struct drm_device *dev)
3120 {
3121         struct drm_crtc *crtc;
3122
3123         for_each_crtc(dev, crtc) {
3124                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3125                 enum plane plane = intel_crtc->plane;
3126
3127                 intel_prepare_page_flip(dev, plane);
3128                 intel_finish_page_flip_plane(dev, plane);
3129         }
3130 }
3131
3132 static void intel_update_primary_planes(struct drm_device *dev)
3133 {
3134         struct drm_i915_private *dev_priv = dev->dev_private;
3135         struct drm_crtc *crtc;
3136
3137         for_each_crtc(dev, crtc) {
3138                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3139
3140                 drm_modeset_lock(&crtc->mutex, NULL);
3141                 /*
3142                  * FIXME: Once we have proper support for primary planes (and
3143                  * disabling them without disabling the entire crtc) allow again
3144                  * a NULL crtc->primary->fb.
3145                  */
3146                 if (intel_crtc->active && crtc->primary->fb)
3147                         dev_priv->display.update_primary_plane(crtc,
3148                                                                crtc->primary->fb,
3149                                                                crtc->x,
3150                                                                crtc->y);
3151                 drm_modeset_unlock(&crtc->mutex);
3152         }
3153 }
3154
3155 void intel_prepare_reset(struct drm_device *dev)
3156 {
3157         /* no reset support for gen2 */
3158         if (IS_GEN2(dev))
3159                 return;
3160
3161         /* reset doesn't touch the display */
3162         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3163                 return;
3164
3165         drm_modeset_lock_all(dev);
3166         /*
3167          * Disabling the crtcs gracefully seems nicer. Also the
3168          * g33 docs say we should at least disable all the planes.
3169          */
3170         intel_display_suspend(dev);
3171 }
3172
3173 void intel_finish_reset(struct drm_device *dev)
3174 {
3175         struct drm_i915_private *dev_priv = to_i915(dev);
3176
3177         /*
3178          * Flips in the rings will be nuked by the reset,
3179          * so complete all pending flips so that user space
3180          * will get its events and not get stuck.
3181          */
3182         intel_complete_page_flips(dev);
3183
3184         /* no reset support for gen2 */
3185         if (IS_GEN2(dev))
3186                 return;
3187
3188         /* reset doesn't touch the display */
3189         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3190                 /*
3191                  * Flips in the rings have been nuked by the reset,
3192                  * so update the base address of all primary
3193                  * planes to the the last fb to make sure we're
3194                  * showing the correct fb after a reset.
3195                  */
3196                 intel_update_primary_planes(dev);
3197                 return;
3198         }
3199
3200         /*
3201          * The display has been reset as well,
3202          * so need a full re-initialization.
3203          */
3204         intel_runtime_pm_disable_interrupts(dev_priv);
3205         intel_runtime_pm_enable_interrupts(dev_priv);
3206
3207         intel_modeset_init_hw(dev);
3208
3209         spin_lock_irq(&dev_priv->irq_lock);
3210         if (dev_priv->display.hpd_irq_setup)
3211                 dev_priv->display.hpd_irq_setup(dev);
3212         spin_unlock_irq(&dev_priv->irq_lock);
3213
3214         intel_display_resume(dev);
3215
3216         intel_hpd_init(dev_priv);
3217
3218         drm_modeset_unlock_all(dev);
3219 }
3220
3221 static void
3222 intel_finish_fb(struct drm_framebuffer *old_fb)
3223 {
3224         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3225         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
3226         bool was_interruptible = dev_priv->mm.interruptible;
3227         int ret;
3228
3229         /* Big Hammer, we also need to ensure that any pending
3230          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3231          * current scanout is retired before unpinning the old
3232          * framebuffer. Note that we rely on userspace rendering
3233          * into the buffer attached to the pipe they are waiting
3234          * on. If not, userspace generates a GPU hang with IPEHR
3235          * point to the MI_WAIT_FOR_EVENT.
3236          *
3237          * This should only fail upon a hung GPU, in which case we
3238          * can safely continue.
3239          */
3240         dev_priv->mm.interruptible = false;
3241         ret = i915_gem_object_wait_rendering(obj, true);
3242         dev_priv->mm.interruptible = was_interruptible;
3243
3244         WARN_ON(ret);
3245 }
3246
3247 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3248 {
3249         struct drm_device *dev = crtc->dev;
3250         struct drm_i915_private *dev_priv = dev->dev_private;
3251         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3252         bool pending;
3253
3254         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3255             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3256                 return false;
3257
3258         spin_lock_irq(&dev->event_lock);
3259         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3260         spin_unlock_irq(&dev->event_lock);
3261
3262         return pending;
3263 }
3264
3265 static void intel_update_pipe_size(struct intel_crtc *crtc)
3266 {
3267         struct drm_device *dev = crtc->base.dev;
3268         struct drm_i915_private *dev_priv = dev->dev_private;
3269         const struct drm_display_mode *adjusted_mode;
3270
3271         if (!i915.fastboot)
3272                 return;
3273
3274         /*
3275          * Update pipe size and adjust fitter if needed: the reason for this is
3276          * that in compute_mode_changes we check the native mode (not the pfit
3277          * mode) to see if we can flip rather than do a full mode set. In the
3278          * fastboot case, we'll flip, but if we don't update the pipesrc and
3279          * pfit state, we'll end up with a big fb scanned out into the wrong
3280          * sized surface.
3281          *
3282          * To fix this properly, we need to hoist the checks up into
3283          * compute_mode_changes (or above), check the actual pfit state and
3284          * whether the platform allows pfit disable with pipe active, and only
3285          * then update the pipesrc and pfit state, even on the flip path.
3286          */
3287
3288         adjusted_mode = &crtc->config->base.adjusted_mode;
3289
3290         I915_WRITE(PIPESRC(crtc->pipe),
3291                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3292                    (adjusted_mode->crtc_vdisplay - 1));
3293         if (!crtc->config->pch_pfit.enabled &&
3294             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3295              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3296                 I915_WRITE(PF_CTL(crtc->pipe), 0);
3297                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3298                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3299         }
3300         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3301         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3302 }
3303
3304 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3305 {
3306         struct drm_device *dev = crtc->dev;
3307         struct drm_i915_private *dev_priv = dev->dev_private;
3308         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3309         int pipe = intel_crtc->pipe;
3310         u32 reg, temp;
3311
3312         /* enable normal train */
3313         reg = FDI_TX_CTL(pipe);
3314         temp = I915_READ(reg);
3315         if (IS_IVYBRIDGE(dev)) {
3316                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3317                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3318         } else {
3319                 temp &= ~FDI_LINK_TRAIN_NONE;
3320                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3321         }
3322         I915_WRITE(reg, temp);
3323
3324         reg = FDI_RX_CTL(pipe);
3325         temp = I915_READ(reg);
3326         if (HAS_PCH_CPT(dev)) {
3327                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3328                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3329         } else {
3330                 temp &= ~FDI_LINK_TRAIN_NONE;
3331                 temp |= FDI_LINK_TRAIN_NONE;
3332         }
3333         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3334
3335         /* wait one idle pattern time */
3336         POSTING_READ(reg);
3337         udelay(1000);
3338
3339         /* IVB wants error correction enabled */
3340         if (IS_IVYBRIDGE(dev))
3341                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3342                            FDI_FE_ERRC_ENABLE);
3343 }
3344
3345 /* The FDI link training functions for ILK/Ibexpeak. */
3346 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3347 {
3348         struct drm_device *dev = crtc->dev;
3349         struct drm_i915_private *dev_priv = dev->dev_private;
3350         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3351         int pipe = intel_crtc->pipe;
3352         u32 reg, temp, tries;
3353
3354         /* FDI needs bits from pipe first */
3355         assert_pipe_enabled(dev_priv, pipe);
3356
3357         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3358            for train result */
3359         reg = FDI_RX_IMR(pipe);
3360         temp = I915_READ(reg);
3361         temp &= ~FDI_RX_SYMBOL_LOCK;
3362         temp &= ~FDI_RX_BIT_LOCK;
3363         I915_WRITE(reg, temp);
3364         I915_READ(reg);
3365         udelay(150);
3366
3367         /* enable CPU FDI TX and PCH FDI RX */
3368         reg = FDI_TX_CTL(pipe);
3369         temp = I915_READ(reg);
3370         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3371         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3372         temp &= ~FDI_LINK_TRAIN_NONE;
3373         temp |= FDI_LINK_TRAIN_PATTERN_1;
3374         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3375
3376         reg = FDI_RX_CTL(pipe);
3377         temp = I915_READ(reg);
3378         temp &= ~FDI_LINK_TRAIN_NONE;
3379         temp |= FDI_LINK_TRAIN_PATTERN_1;
3380         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3381
3382         POSTING_READ(reg);
3383         udelay(150);
3384
3385         /* Ironlake workaround, enable clock pointer after FDI enable*/
3386         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3387         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3388                    FDI_RX_PHASE_SYNC_POINTER_EN);
3389
3390         reg = FDI_RX_IIR(pipe);
3391         for (tries = 0; tries < 5; tries++) {
3392                 temp = I915_READ(reg);
3393                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3394
3395                 if ((temp & FDI_RX_BIT_LOCK)) {
3396                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3397                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3398                         break;
3399                 }
3400         }
3401         if (tries == 5)
3402                 DRM_ERROR("FDI train 1 fail!\n");
3403
3404         /* Train 2 */
3405         reg = FDI_TX_CTL(pipe);
3406         temp = I915_READ(reg);
3407         temp &= ~FDI_LINK_TRAIN_NONE;
3408         temp |= FDI_LINK_TRAIN_PATTERN_2;
3409         I915_WRITE(reg, temp);
3410
3411         reg = FDI_RX_CTL(pipe);
3412         temp = I915_READ(reg);
3413         temp &= ~FDI_LINK_TRAIN_NONE;
3414         temp |= FDI_LINK_TRAIN_PATTERN_2;
3415         I915_WRITE(reg, temp);
3416
3417         POSTING_READ(reg);
3418         udelay(150);
3419
3420         reg = FDI_RX_IIR(pipe);
3421         for (tries = 0; tries < 5; tries++) {
3422                 temp = I915_READ(reg);
3423                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3424
3425                 if (temp & FDI_RX_SYMBOL_LOCK) {
3426                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3427                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3428                         break;
3429                 }
3430         }
3431         if (tries == 5)
3432                 DRM_ERROR("FDI train 2 fail!\n");
3433
3434         DRM_DEBUG_KMS("FDI train done\n");
3435
3436 }
3437
3438 static const int snb_b_fdi_train_param[] = {
3439         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3440         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3441         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3442         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3443 };
3444
3445 /* The FDI link training functions for SNB/Cougarpoint. */
3446 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3447 {
3448         struct drm_device *dev = crtc->dev;
3449         struct drm_i915_private *dev_priv = dev->dev_private;
3450         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3451         int pipe = intel_crtc->pipe;
3452         u32 reg, temp, i, retry;
3453
3454         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3455            for train result */
3456         reg = FDI_RX_IMR(pipe);
3457         temp = I915_READ(reg);
3458         temp &= ~FDI_RX_SYMBOL_LOCK;
3459         temp &= ~FDI_RX_BIT_LOCK;
3460         I915_WRITE(reg, temp);
3461
3462         POSTING_READ(reg);
3463         udelay(150);
3464
3465         /* enable CPU FDI TX and PCH FDI RX */
3466         reg = FDI_TX_CTL(pipe);
3467         temp = I915_READ(reg);
3468         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3469         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3470         temp &= ~FDI_LINK_TRAIN_NONE;
3471         temp |= FDI_LINK_TRAIN_PATTERN_1;
3472         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3473         /* SNB-B */
3474         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3475         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3476
3477         I915_WRITE(FDI_RX_MISC(pipe),
3478                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3479
3480         reg = FDI_RX_CTL(pipe);
3481         temp = I915_READ(reg);
3482         if (HAS_PCH_CPT(dev)) {
3483                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3484                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3485         } else {
3486                 temp &= ~FDI_LINK_TRAIN_NONE;
3487                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3488         }
3489         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3490
3491         POSTING_READ(reg);
3492         udelay(150);
3493
3494         for (i = 0; i < 4; i++) {
3495                 reg = FDI_TX_CTL(pipe);
3496                 temp = I915_READ(reg);
3497                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3498                 temp |= snb_b_fdi_train_param[i];
3499                 I915_WRITE(reg, temp);
3500
3501                 POSTING_READ(reg);
3502                 udelay(500);
3503
3504                 for (retry = 0; retry < 5; retry++) {
3505                         reg = FDI_RX_IIR(pipe);
3506                         temp = I915_READ(reg);
3507                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3508                         if (temp & FDI_RX_BIT_LOCK) {
3509                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3510                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3511                                 break;
3512                         }
3513                         udelay(50);
3514                 }
3515                 if (retry < 5)
3516                         break;
3517         }
3518         if (i == 4)
3519                 DRM_ERROR("FDI train 1 fail!\n");
3520
3521         /* Train 2 */
3522         reg = FDI_TX_CTL(pipe);
3523         temp = I915_READ(reg);
3524         temp &= ~FDI_LINK_TRAIN_NONE;
3525         temp |= FDI_LINK_TRAIN_PATTERN_2;
3526         if (IS_GEN6(dev)) {
3527                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3528                 /* SNB-B */
3529                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3530         }
3531         I915_WRITE(reg, temp);
3532
3533         reg = FDI_RX_CTL(pipe);
3534         temp = I915_READ(reg);
3535         if (HAS_PCH_CPT(dev)) {
3536                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3537                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3538         } else {
3539                 temp &= ~FDI_LINK_TRAIN_NONE;
3540                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3541         }
3542         I915_WRITE(reg, temp);
3543
3544         POSTING_READ(reg);
3545         udelay(150);
3546
3547         for (i = 0; i < 4; i++) {
3548                 reg = FDI_TX_CTL(pipe);
3549                 temp = I915_READ(reg);
3550                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3551                 temp |= snb_b_fdi_train_param[i];
3552                 I915_WRITE(reg, temp);
3553
3554                 POSTING_READ(reg);
3555                 udelay(500);
3556
3557                 for (retry = 0; retry < 5; retry++) {
3558                         reg = FDI_RX_IIR(pipe);
3559                         temp = I915_READ(reg);
3560                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3561                         if (temp & FDI_RX_SYMBOL_LOCK) {
3562                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3563                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3564                                 break;
3565                         }
3566                         udelay(50);
3567                 }
3568                 if (retry < 5)
3569                         break;
3570         }
3571         if (i == 4)
3572                 DRM_ERROR("FDI train 2 fail!\n");
3573
3574         DRM_DEBUG_KMS("FDI train done.\n");
3575 }
3576
3577 /* Manual link training for Ivy Bridge A0 parts */
3578 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3579 {
3580         struct drm_device *dev = crtc->dev;
3581         struct drm_i915_private *dev_priv = dev->dev_private;
3582         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3583         int pipe = intel_crtc->pipe;
3584         u32 reg, temp, i, j;
3585
3586         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3587            for train result */
3588         reg = FDI_RX_IMR(pipe);
3589         temp = I915_READ(reg);
3590         temp &= ~FDI_RX_SYMBOL_LOCK;
3591         temp &= ~FDI_RX_BIT_LOCK;
3592         I915_WRITE(reg, temp);
3593
3594         POSTING_READ(reg);
3595         udelay(150);
3596
3597         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3598                       I915_READ(FDI_RX_IIR(pipe)));
3599
3600         /* Try each vswing and preemphasis setting twice before moving on */
3601         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3602                 /* disable first in case we need to retry */
3603                 reg = FDI_TX_CTL(pipe);
3604                 temp = I915_READ(reg);
3605                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3606                 temp &= ~FDI_TX_ENABLE;
3607                 I915_WRITE(reg, temp);
3608
3609                 reg = FDI_RX_CTL(pipe);
3610                 temp = I915_READ(reg);
3611                 temp &= ~FDI_LINK_TRAIN_AUTO;
3612                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3613                 temp &= ~FDI_RX_ENABLE;
3614                 I915_WRITE(reg, temp);
3615
3616                 /* enable CPU FDI TX and PCH FDI RX */
3617                 reg = FDI_TX_CTL(pipe);
3618                 temp = I915_READ(reg);
3619                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3620                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3621                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3622                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3623                 temp |= snb_b_fdi_train_param[j/2];
3624                 temp |= FDI_COMPOSITE_SYNC;
3625                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3626
3627                 I915_WRITE(FDI_RX_MISC(pipe),
3628                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3629
3630                 reg = FDI_RX_CTL(pipe);
3631                 temp = I915_READ(reg);
3632                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3633                 temp |= FDI_COMPOSITE_SYNC;
3634                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3635
3636                 POSTING_READ(reg);
3637                 udelay(1); /* should be 0.5us */
3638
3639                 for (i = 0; i < 4; i++) {
3640                         reg = FDI_RX_IIR(pipe);
3641                         temp = I915_READ(reg);
3642                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3643
3644                         if (temp & FDI_RX_BIT_LOCK ||
3645                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3646                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3647                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3648                                               i);
3649                                 break;
3650                         }
3651                         udelay(1); /* should be 0.5us */
3652                 }
3653                 if (i == 4) {
3654                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3655                         continue;
3656                 }
3657
3658                 /* Train 2 */
3659                 reg = FDI_TX_CTL(pipe);
3660                 temp = I915_READ(reg);
3661                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3662                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3663                 I915_WRITE(reg, temp);
3664
3665                 reg = FDI_RX_CTL(pipe);
3666                 temp = I915_READ(reg);
3667                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3668                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3669                 I915_WRITE(reg, temp);
3670
3671                 POSTING_READ(reg);
3672                 udelay(2); /* should be 1.5us */
3673
3674                 for (i = 0; i < 4; i++) {
3675                         reg = FDI_RX_IIR(pipe);
3676                         temp = I915_READ(reg);
3677                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3678
3679                         if (temp & FDI_RX_SYMBOL_LOCK ||
3680                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3681                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3682                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3683                                               i);
3684                                 goto train_done;
3685                         }
3686                         udelay(2); /* should be 1.5us */
3687                 }
3688                 if (i == 4)
3689                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3690         }
3691
3692 train_done:
3693         DRM_DEBUG_KMS("FDI train done.\n");
3694 }
3695
3696 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3697 {
3698         struct drm_device *dev = intel_crtc->base.dev;
3699         struct drm_i915_private *dev_priv = dev->dev_private;
3700         int pipe = intel_crtc->pipe;
3701         u32 reg, temp;
3702
3703
3704         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3705         reg = FDI_RX_CTL(pipe);
3706         temp = I915_READ(reg);
3707         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3708         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3709         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3710         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3711
3712         POSTING_READ(reg);
3713         udelay(200);
3714
3715         /* Switch from Rawclk to PCDclk */
3716         temp = I915_READ(reg);
3717         I915_WRITE(reg, temp | FDI_PCDCLK);
3718
3719         POSTING_READ(reg);
3720         udelay(200);
3721
3722         /* Enable CPU FDI TX PLL, always on for Ironlake */
3723         reg = FDI_TX_CTL(pipe);
3724         temp = I915_READ(reg);
3725         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3726                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3727
3728                 POSTING_READ(reg);
3729                 udelay(100);
3730         }
3731 }
3732
3733 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3734 {
3735         struct drm_device *dev = intel_crtc->base.dev;
3736         struct drm_i915_private *dev_priv = dev->dev_private;
3737         int pipe = intel_crtc->pipe;
3738         u32 reg, temp;
3739
3740         /* Switch from PCDclk to Rawclk */
3741         reg = FDI_RX_CTL(pipe);
3742         temp = I915_READ(reg);
3743         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3744
3745         /* Disable CPU FDI TX PLL */
3746         reg = FDI_TX_CTL(pipe);
3747         temp = I915_READ(reg);
3748         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3749
3750         POSTING_READ(reg);
3751         udelay(100);
3752
3753         reg = FDI_RX_CTL(pipe);
3754         temp = I915_READ(reg);
3755         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3756
3757         /* Wait for the clocks to turn off. */
3758         POSTING_READ(reg);
3759         udelay(100);
3760 }
3761
3762 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3763 {
3764         struct drm_device *dev = crtc->dev;
3765         struct drm_i915_private *dev_priv = dev->dev_private;
3766         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3767         int pipe = intel_crtc->pipe;
3768         u32 reg, temp;
3769
3770         /* disable CPU FDI tx and PCH FDI rx */
3771         reg = FDI_TX_CTL(pipe);
3772         temp = I915_READ(reg);
3773         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3774         POSTING_READ(reg);
3775
3776         reg = FDI_RX_CTL(pipe);
3777         temp = I915_READ(reg);
3778         temp &= ~(0x7 << 16);
3779         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3780         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3781
3782         POSTING_READ(reg);
3783         udelay(100);
3784
3785         /* Ironlake workaround, disable clock pointer after downing FDI */
3786         if (HAS_PCH_IBX(dev))
3787                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3788
3789         /* still set train pattern 1 */
3790         reg = FDI_TX_CTL(pipe);
3791         temp = I915_READ(reg);
3792         temp &= ~FDI_LINK_TRAIN_NONE;
3793         temp |= FDI_LINK_TRAIN_PATTERN_1;
3794         I915_WRITE(reg, temp);
3795
3796         reg = FDI_RX_CTL(pipe);
3797         temp = I915_READ(reg);
3798         if (HAS_PCH_CPT(dev)) {
3799                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3800                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3801         } else {
3802                 temp &= ~FDI_LINK_TRAIN_NONE;
3803                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3804         }
3805         /* BPC in FDI rx is consistent with that in PIPECONF */
3806         temp &= ~(0x07 << 16);
3807         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3808         I915_WRITE(reg, temp);
3809
3810         POSTING_READ(reg);
3811         udelay(100);
3812 }
3813
3814 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3815 {
3816         struct intel_crtc *crtc;
3817
3818         /* Note that we don't need to be called with mode_config.lock here
3819          * as our list of CRTC objects is static for the lifetime of the
3820          * device and so cannot disappear as we iterate. Similarly, we can
3821          * happily treat the predicates as racy, atomic checks as userspace
3822          * cannot claim and pin a new fb without at least acquring the
3823          * struct_mutex and so serialising with us.
3824          */
3825         for_each_intel_crtc(dev, crtc) {
3826                 if (atomic_read(&crtc->unpin_work_count) == 0)
3827                         continue;
3828
3829                 if (crtc->unpin_work)
3830                         intel_wait_for_vblank(dev, crtc->pipe);
3831
3832                 return true;
3833         }
3834
3835         return false;
3836 }
3837
3838 static void page_flip_completed(struct intel_crtc *intel_crtc)
3839 {
3840         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3841         struct intel_unpin_work *work = intel_crtc->unpin_work;
3842
3843         /* ensure that the unpin work is consistent wrt ->pending. */
3844         smp_rmb();
3845         intel_crtc->unpin_work = NULL;
3846
3847         if (work->event)
3848                 drm_send_vblank_event(intel_crtc->base.dev,
3849                                       intel_crtc->pipe,
3850                                       work->event);
3851
3852         drm_crtc_vblank_put(&intel_crtc->base);
3853
3854         wake_up_all(&dev_priv->pending_flip_queue);
3855         queue_work(dev_priv->wq, &work->work);
3856
3857         trace_i915_flip_complete(intel_crtc->plane,
3858                                  work->pending_flip_obj);
3859 }
3860
3861 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3862 {
3863         struct drm_device *dev = crtc->dev;
3864         struct drm_i915_private *dev_priv = dev->dev_private;
3865
3866         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3867         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3868                                        !intel_crtc_has_pending_flip(crtc),
3869                                        60*HZ) == 0)) {
3870                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3871
3872                 spin_lock_irq(&dev->event_lock);
3873                 if (intel_crtc->unpin_work) {
3874                         WARN_ONCE(1, "Removing stuck page flip\n");
3875                         page_flip_completed(intel_crtc);
3876                 }
3877                 spin_unlock_irq(&dev->event_lock);
3878         }
3879
3880         if (crtc->primary->fb) {
3881                 mutex_lock(&dev->struct_mutex);
3882                 intel_finish_fb(crtc->primary->fb);
3883                 mutex_unlock(&dev->struct_mutex);
3884         }
3885 }
3886
3887 /* Program iCLKIP clock to the desired frequency */
3888 static void lpt_program_iclkip(struct drm_crtc *crtc)
3889 {
3890         struct drm_device *dev = crtc->dev;
3891         struct drm_i915_private *dev_priv = dev->dev_private;
3892         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3893         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3894         u32 temp;
3895
3896         mutex_lock(&dev_priv->sb_lock);
3897
3898         /* It is necessary to ungate the pixclk gate prior to programming
3899          * the divisors, and gate it back when it is done.
3900          */
3901         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3902
3903         /* Disable SSCCTL */
3904         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3905                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3906                                 SBI_SSCCTL_DISABLE,
3907                         SBI_ICLK);
3908
3909         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3910         if (clock == 20000) {
3911                 auxdiv = 1;
3912                 divsel = 0x41;
3913                 phaseinc = 0x20;
3914         } else {
3915                 /* The iCLK virtual clock root frequency is in MHz,
3916                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3917                  * divisors, it is necessary to divide one by another, so we
3918                  * convert the virtual clock precision to KHz here for higher
3919                  * precision.
3920                  */
3921                 u32 iclk_virtual_root_freq = 172800 * 1000;
3922                 u32 iclk_pi_range = 64;
3923                 u32 desired_divisor, msb_divisor_value, pi_value;
3924
3925                 desired_divisor = (iclk_virtual_root_freq / clock);
3926                 msb_divisor_value = desired_divisor / iclk_pi_range;
3927                 pi_value = desired_divisor % iclk_pi_range;
3928
3929                 auxdiv = 0;
3930                 divsel = msb_divisor_value - 2;
3931                 phaseinc = pi_value;
3932         }
3933
3934         /* This should not happen with any sane values */
3935         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3936                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3937         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3938                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3939
3940         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3941                         clock,
3942                         auxdiv,
3943                         divsel,
3944                         phasedir,
3945                         phaseinc);
3946
3947         /* Program SSCDIVINTPHASE6 */
3948         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3949         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3950         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3951         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3952         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3953         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3954         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3955         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3956
3957         /* Program SSCAUXDIV */
3958         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3959         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3960         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3961         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3962
3963         /* Enable modulator and associated divider */
3964         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3965         temp &= ~SBI_SSCCTL_DISABLE;
3966         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3967
3968         /* Wait for initialization time */
3969         udelay(24);
3970
3971         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3972
3973         mutex_unlock(&dev_priv->sb_lock);
3974 }
3975
3976 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3977                                                 enum pipe pch_transcoder)
3978 {
3979         struct drm_device *dev = crtc->base.dev;
3980         struct drm_i915_private *dev_priv = dev->dev_private;
3981         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3982
3983         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3984                    I915_READ(HTOTAL(cpu_transcoder)));
3985         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3986                    I915_READ(HBLANK(cpu_transcoder)));
3987         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3988                    I915_READ(HSYNC(cpu_transcoder)));
3989
3990         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3991                    I915_READ(VTOTAL(cpu_transcoder)));
3992         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3993                    I915_READ(VBLANK(cpu_transcoder)));
3994         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3995                    I915_READ(VSYNC(cpu_transcoder)));
3996         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3997                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
3998 }
3999
4000 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4001 {
4002         struct drm_i915_private *dev_priv = dev->dev_private;
4003         uint32_t temp;
4004
4005         temp = I915_READ(SOUTH_CHICKEN1);
4006         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4007                 return;
4008
4009         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4010         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4011
4012         temp &= ~FDI_BC_BIFURCATION_SELECT;
4013         if (enable)
4014                 temp |= FDI_BC_BIFURCATION_SELECT;
4015
4016         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4017         I915_WRITE(SOUTH_CHICKEN1, temp);
4018         POSTING_READ(SOUTH_CHICKEN1);
4019 }
4020
4021 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4022 {
4023         struct drm_device *dev = intel_crtc->base.dev;
4024
4025         switch (intel_crtc->pipe) {
4026         case PIPE_A:
4027                 break;
4028         case PIPE_B:
4029                 if (intel_crtc->config->fdi_lanes > 2)
4030                         cpt_set_fdi_bc_bifurcation(dev, false);
4031                 else
4032                         cpt_set_fdi_bc_bifurcation(dev, true);
4033
4034                 break;
4035         case PIPE_C:
4036                 cpt_set_fdi_bc_bifurcation(dev, true);
4037
4038                 break;
4039         default:
4040                 BUG();
4041         }
4042 }
4043
4044 /*
4045  * Enable PCH resources required for PCH ports:
4046  *   - PCH PLLs
4047  *   - FDI training & RX/TX
4048  *   - update transcoder timings
4049  *   - DP transcoding bits
4050  *   - transcoder
4051  */
4052 static void ironlake_pch_enable(struct drm_crtc *crtc)
4053 {
4054         struct drm_device *dev = crtc->dev;
4055         struct drm_i915_private *dev_priv = dev->dev_private;
4056         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4057         int pipe = intel_crtc->pipe;
4058         u32 reg, temp;
4059
4060         assert_pch_transcoder_disabled(dev_priv, pipe);
4061
4062         if (IS_IVYBRIDGE(dev))
4063                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4064
4065         /* Write the TU size bits before fdi link training, so that error
4066          * detection works. */
4067         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4068                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4069
4070         /* For PCH output, training FDI link */
4071         dev_priv->display.fdi_link_train(crtc);
4072
4073         /* We need to program the right clock selection before writing the pixel
4074          * mutliplier into the DPLL. */
4075         if (HAS_PCH_CPT(dev)) {
4076                 u32 sel;
4077
4078                 temp = I915_READ(PCH_DPLL_SEL);
4079                 temp |= TRANS_DPLL_ENABLE(pipe);
4080                 sel = TRANS_DPLLB_SEL(pipe);
4081                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4082                         temp |= sel;
4083                 else
4084                         temp &= ~sel;
4085                 I915_WRITE(PCH_DPLL_SEL, temp);
4086         }
4087
4088         /* XXX: pch pll's can be enabled any time before we enable the PCH
4089          * transcoder, and we actually should do this to not upset any PCH
4090          * transcoder that already use the clock when we share it.
4091          *
4092          * Note that enable_shared_dpll tries to do the right thing, but
4093          * get_shared_dpll unconditionally resets the pll - we need that to have
4094          * the right LVDS enable sequence. */
4095         intel_enable_shared_dpll(intel_crtc);
4096
4097         /* set transcoder timing, panel must allow it */
4098         assert_panel_unlocked(dev_priv, pipe);
4099         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4100
4101         intel_fdi_normal_train(crtc);
4102
4103         /* For PCH DP, enable TRANS_DP_CTL */
4104         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4105                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4106                 reg = TRANS_DP_CTL(pipe);
4107                 temp = I915_READ(reg);
4108                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4109                           TRANS_DP_SYNC_MASK |
4110                           TRANS_DP_BPC_MASK);
4111                 temp |= TRANS_DP_OUTPUT_ENABLE;
4112                 temp |= bpc << 9; /* same format but at 11:9 */
4113
4114                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
4115                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4116                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
4117                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4118
4119                 switch (intel_trans_dp_port_sel(crtc)) {
4120                 case PCH_DP_B:
4121                         temp |= TRANS_DP_PORT_SEL_B;
4122                         break;
4123                 case PCH_DP_C:
4124                         temp |= TRANS_DP_PORT_SEL_C;
4125                         break;
4126                 case PCH_DP_D:
4127                         temp |= TRANS_DP_PORT_SEL_D;
4128                         break;
4129                 default:
4130                         BUG();
4131                 }
4132
4133                 I915_WRITE(reg, temp);
4134         }
4135
4136         ironlake_enable_pch_transcoder(dev_priv, pipe);
4137 }
4138
4139 static void lpt_pch_enable(struct drm_crtc *crtc)
4140 {
4141         struct drm_device *dev = crtc->dev;
4142         struct drm_i915_private *dev_priv = dev->dev_private;
4143         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4144         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4145
4146         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4147
4148         lpt_program_iclkip(crtc);
4149
4150         /* Set transcoder timing. */
4151         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4152
4153         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4154 }
4155
4156 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4157                                                 struct intel_crtc_state *crtc_state)
4158 {
4159         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4160         struct intel_shared_dpll *pll;
4161         struct intel_shared_dpll_config *shared_dpll;
4162         enum intel_dpll_id i;
4163
4164         shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state);
4165
4166         if (HAS_PCH_IBX(dev_priv->dev)) {
4167                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4168                 i = (enum intel_dpll_id) crtc->pipe;
4169                 pll = &dev_priv->shared_dplls[i];
4170
4171                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4172                               crtc->base.base.id, pll->name);
4173
4174                 WARN_ON(shared_dpll[i].crtc_mask);
4175
4176                 goto found;
4177         }
4178
4179         if (IS_BROXTON(dev_priv->dev)) {
4180                 /* PLL is attached to port in bxt */
4181                 struct intel_encoder *encoder;
4182                 struct intel_digital_port *intel_dig_port;
4183
4184                 encoder = intel_ddi_get_crtc_new_encoder(crtc_state);
4185                 if (WARN_ON(!encoder))
4186                         return NULL;
4187
4188                 intel_dig_port = enc_to_dig_port(&encoder->base);
4189                 /* 1:1 mapping between ports and PLLs */
4190                 i = (enum intel_dpll_id)intel_dig_port->port;
4191                 pll = &dev_priv->shared_dplls[i];
4192                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4193                         crtc->base.base.id, pll->name);
4194                 WARN_ON(shared_dpll[i].crtc_mask);
4195
4196                 goto found;
4197         }
4198
4199         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4200                 pll = &dev_priv->shared_dplls[i];
4201
4202                 /* Only want to check enabled timings first */
4203                 if (shared_dpll[i].crtc_mask == 0)
4204                         continue;
4205
4206                 if (memcmp(&crtc_state->dpll_hw_state,
4207                            &shared_dpll[i].hw_state,
4208                            sizeof(crtc_state->dpll_hw_state)) == 0) {
4209                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4210                                       crtc->base.base.id, pll->name,
4211                                       shared_dpll[i].crtc_mask,
4212                                       pll->active);
4213                         goto found;
4214                 }
4215         }
4216
4217         /* Ok no matching timings, maybe there's a free one? */
4218         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4219                 pll = &dev_priv->shared_dplls[i];
4220                 if (shared_dpll[i].crtc_mask == 0) {
4221                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4222                                       crtc->base.base.id, pll->name);
4223                         goto found;
4224                 }
4225         }
4226
4227         return NULL;
4228
4229 found:
4230         if (shared_dpll[i].crtc_mask == 0)
4231                 shared_dpll[i].hw_state =
4232                         crtc_state->dpll_hw_state;
4233
4234         crtc_state->shared_dpll = i;
4235         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4236                          pipe_name(crtc->pipe));
4237
4238         shared_dpll[i].crtc_mask |= 1 << crtc->pipe;
4239
4240         return pll;
4241 }
4242
4243 static void intel_shared_dpll_commit(struct drm_atomic_state *state)
4244 {
4245         struct drm_i915_private *dev_priv = to_i915(state->dev);
4246         struct intel_shared_dpll_config *shared_dpll;
4247         struct intel_shared_dpll *pll;
4248         enum intel_dpll_id i;
4249
4250         if (!to_intel_atomic_state(state)->dpll_set)
4251                 return;
4252
4253         shared_dpll = to_intel_atomic_state(state)->shared_dpll;
4254         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4255                 pll = &dev_priv->shared_dplls[i];
4256                 pll->config = shared_dpll[i];
4257         }
4258 }
4259
4260 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4261 {
4262         struct drm_i915_private *dev_priv = dev->dev_private;
4263         int dslreg = PIPEDSL(pipe);
4264         u32 temp;
4265
4266         temp = I915_READ(dslreg);
4267         udelay(500);
4268         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4269                 if (wait_for(I915_READ(dslreg) != temp, 5))
4270                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4271         }
4272 }
4273
4274 static int
4275 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4276                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4277                   int src_w, int src_h, int dst_w, int dst_h)
4278 {
4279         struct intel_crtc_scaler_state *scaler_state =
4280                 &crtc_state->scaler_state;
4281         struct intel_crtc *intel_crtc =
4282                 to_intel_crtc(crtc_state->base.crtc);
4283         int need_scaling;
4284
4285         need_scaling = intel_rotation_90_or_270(rotation) ?
4286                 (src_h != dst_w || src_w != dst_h):
4287                 (src_w != dst_w || src_h != dst_h);
4288
4289         /*
4290          * if plane is being disabled or scaler is no more required or force detach
4291          *  - free scaler binded to this plane/crtc
4292          *  - in order to do this, update crtc->scaler_usage
4293          *
4294          * Here scaler state in crtc_state is set free so that
4295          * scaler can be assigned to other user. Actual register
4296          * update to free the scaler is done in plane/panel-fit programming.
4297          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4298          */
4299         if (force_detach || !need_scaling) {
4300                 if (*scaler_id >= 0) {
4301                         scaler_state->scaler_users &= ~(1 << scaler_user);
4302                         scaler_state->scalers[*scaler_id].in_use = 0;
4303
4304                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4305                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4306                                 intel_crtc->pipe, scaler_user, *scaler_id,
4307                                 scaler_state->scaler_users);
4308                         *scaler_id = -1;
4309                 }
4310                 return 0;
4311         }
4312
4313         /* range checks */
4314         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4315                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4316
4317                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4318                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4319                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4320                         "size is out of scaler range\n",
4321                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4322                 return -EINVAL;
4323         }
4324
4325         /* mark this plane as a scaler user in crtc_state */
4326         scaler_state->scaler_users |= (1 << scaler_user);
4327         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4328                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4329                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4330                 scaler_state->scaler_users);
4331
4332         return 0;
4333 }
4334
4335 /**
4336  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4337  *
4338  * @state: crtc's scaler state
4339  *
4340  * Return
4341  *     0 - scaler_usage updated successfully
4342  *    error - requested scaling cannot be supported or other error condition
4343  */
4344 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4345 {
4346         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4347         struct drm_display_mode *adjusted_mode =
4348                 &state->base.adjusted_mode;
4349
4350         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4351                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4352
4353         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4354                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4355                 state->pipe_src_w, state->pipe_src_h,
4356                 adjusted_mode->hdisplay, adjusted_mode->vdisplay);
4357 }
4358
4359 /**
4360  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4361  *
4362  * @state: crtc's scaler state
4363  * @plane_state: atomic plane state to update
4364  *
4365  * Return
4366  *     0 - scaler_usage updated successfully
4367  *    error - requested scaling cannot be supported or other error condition
4368  */
4369 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4370                                    struct intel_plane_state *plane_state)
4371 {
4372
4373         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4374         struct intel_plane *intel_plane =
4375                 to_intel_plane(plane_state->base.plane);
4376         struct drm_framebuffer *fb = plane_state->base.fb;
4377         int ret;
4378
4379         bool force_detach = !fb || !plane_state->visible;
4380
4381         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4382                       intel_plane->base.base.id, intel_crtc->pipe,
4383                       drm_plane_index(&intel_plane->base));
4384
4385         ret = skl_update_scaler(crtc_state, force_detach,
4386                                 drm_plane_index(&intel_plane->base),
4387                                 &plane_state->scaler_id,
4388                                 plane_state->base.rotation,
4389                                 drm_rect_width(&plane_state->src) >> 16,
4390                                 drm_rect_height(&plane_state->src) >> 16,
4391                                 drm_rect_width(&plane_state->dst),
4392                                 drm_rect_height(&plane_state->dst));
4393
4394         if (ret || plane_state->scaler_id < 0)
4395                 return ret;
4396
4397         /* check colorkey */
4398         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4399                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4400                               intel_plane->base.base.id);
4401                 return -EINVAL;
4402         }
4403
4404         /* Check src format */
4405         switch (fb->pixel_format) {
4406         case DRM_FORMAT_RGB565:
4407         case DRM_FORMAT_XBGR8888:
4408         case DRM_FORMAT_XRGB8888:
4409         case DRM_FORMAT_ABGR8888:
4410         case DRM_FORMAT_ARGB8888:
4411         case DRM_FORMAT_XRGB2101010:
4412         case DRM_FORMAT_XBGR2101010:
4413         case DRM_FORMAT_YUYV:
4414         case DRM_FORMAT_YVYU:
4415         case DRM_FORMAT_UYVY:
4416         case DRM_FORMAT_VYUY:
4417                 break;
4418         default:
4419                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4420                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4421                 return -EINVAL;
4422         }
4423
4424         return 0;
4425 }
4426
4427 static void skylake_scaler_disable(struct intel_crtc *crtc)
4428 {
4429         int i;
4430
4431         for (i = 0; i < crtc->num_scalers; i++)
4432                 skl_detach_scaler(crtc, i);
4433 }
4434
4435 static void skylake_pfit_enable(struct intel_crtc *crtc)
4436 {
4437         struct drm_device *dev = crtc->base.dev;
4438         struct drm_i915_private *dev_priv = dev->dev_private;
4439         int pipe = crtc->pipe;
4440         struct intel_crtc_scaler_state *scaler_state =
4441                 &crtc->config->scaler_state;
4442
4443         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4444
4445         if (crtc->config->pch_pfit.enabled) {
4446                 int id;
4447
4448                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4449                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4450                         return;
4451                 }
4452
4453                 id = scaler_state->scaler_id;
4454                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4455                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4456                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4457                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4458
4459                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4460         }
4461 }
4462
4463 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4464 {
4465         struct drm_device *dev = crtc->base.dev;
4466         struct drm_i915_private *dev_priv = dev->dev_private;
4467         int pipe = crtc->pipe;
4468
4469         if (crtc->config->pch_pfit.enabled) {
4470                 /* Force use of hard-coded filter coefficients
4471                  * as some pre-programmed values are broken,
4472                  * e.g. x201.
4473                  */
4474                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4475                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4476                                                  PF_PIPE_SEL_IVB(pipe));
4477                 else
4478                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4479                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4480                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4481         }
4482 }
4483
4484 void hsw_enable_ips(struct intel_crtc *crtc)
4485 {
4486         struct drm_device *dev = crtc->base.dev;
4487         struct drm_i915_private *dev_priv = dev->dev_private;
4488
4489         if (!crtc->config->ips_enabled)
4490                 return;
4491
4492         /* We can only enable IPS after we enable a plane and wait for a vblank */
4493         intel_wait_for_vblank(dev, crtc->pipe);
4494
4495         assert_plane_enabled(dev_priv, crtc->plane);
4496         if (IS_BROADWELL(dev)) {
4497                 mutex_lock(&dev_priv->rps.hw_lock);
4498                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4499                 mutex_unlock(&dev_priv->rps.hw_lock);
4500                 /* Quoting Art Runyan: "its not safe to expect any particular
4501                  * value in IPS_CTL bit 31 after enabling IPS through the
4502                  * mailbox." Moreover, the mailbox may return a bogus state,
4503                  * so we need to just enable it and continue on.
4504                  */
4505         } else {
4506                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4507                 /* The bit only becomes 1 in the next vblank, so this wait here
4508                  * is essentially intel_wait_for_vblank. If we don't have this
4509                  * and don't wait for vblanks until the end of crtc_enable, then
4510                  * the HW state readout code will complain that the expected
4511                  * IPS_CTL value is not the one we read. */
4512                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4513                         DRM_ERROR("Timed out waiting for IPS enable\n");
4514         }
4515 }
4516
4517 void hsw_disable_ips(struct intel_crtc *crtc)
4518 {
4519         struct drm_device *dev = crtc->base.dev;
4520         struct drm_i915_private *dev_priv = dev->dev_private;
4521
4522         if (!crtc->config->ips_enabled)
4523                 return;
4524
4525         assert_plane_enabled(dev_priv, crtc->plane);
4526         if (IS_BROADWELL(dev)) {
4527                 mutex_lock(&dev_priv->rps.hw_lock);
4528                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4529                 mutex_unlock(&dev_priv->rps.hw_lock);
4530                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4531                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4532                         DRM_ERROR("Timed out waiting for IPS disable\n");
4533         } else {
4534                 I915_WRITE(IPS_CTL, 0);
4535                 POSTING_READ(IPS_CTL);
4536         }
4537
4538         /* We need to wait for a vblank before we can disable the plane. */
4539         intel_wait_for_vblank(dev, crtc->pipe);
4540 }
4541
4542 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4543 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4544 {
4545         struct drm_device *dev = crtc->dev;
4546         struct drm_i915_private *dev_priv = dev->dev_private;
4547         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4548         enum pipe pipe = intel_crtc->pipe;
4549         int palreg = PALETTE(pipe);
4550         int i;
4551         bool reenable_ips = false;
4552
4553         /* The clocks have to be on to load the palette. */
4554         if (!crtc->state->active)
4555                 return;
4556
4557         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4558                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4559                         assert_dsi_pll_enabled(dev_priv);
4560                 else
4561                         assert_pll_enabled(dev_priv, pipe);
4562         }
4563
4564         /* use legacy palette for Ironlake */
4565         if (!HAS_GMCH_DISPLAY(dev))
4566                 palreg = LGC_PALETTE(pipe);
4567
4568         /* Workaround : Do not read or write the pipe palette/gamma data while
4569          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4570          */
4571         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4572             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4573              GAMMA_MODE_MODE_SPLIT)) {
4574                 hsw_disable_ips(intel_crtc);
4575                 reenable_ips = true;
4576         }
4577
4578         for (i = 0; i < 256; i++) {
4579                 I915_WRITE(palreg + 4 * i,
4580                            (intel_crtc->lut_r[i] << 16) |
4581                            (intel_crtc->lut_g[i] << 8) |
4582                            intel_crtc->lut_b[i]);
4583         }
4584
4585         if (reenable_ips)
4586                 hsw_enable_ips(intel_crtc);
4587 }
4588
4589 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4590 {
4591         if (intel_crtc->overlay) {
4592                 struct drm_device *dev = intel_crtc->base.dev;
4593                 struct drm_i915_private *dev_priv = dev->dev_private;
4594
4595                 mutex_lock(&dev->struct_mutex);
4596                 dev_priv->mm.interruptible = false;
4597                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4598                 dev_priv->mm.interruptible = true;
4599                 mutex_unlock(&dev->struct_mutex);
4600         }
4601
4602         /* Let userspace switch the overlay on again. In most cases userspace
4603          * has to recompute where to put it anyway.
4604          */
4605 }
4606
4607 /**
4608  * intel_post_enable_primary - Perform operations after enabling primary plane
4609  * @crtc: the CRTC whose primary plane was just enabled
4610  *
4611  * Performs potentially sleeping operations that must be done after the primary
4612  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4613  * called due to an explicit primary plane update, or due to an implicit
4614  * re-enable that is caused when a sprite plane is updated to no longer
4615  * completely hide the primary plane.
4616  */
4617 static void
4618 intel_post_enable_primary(struct drm_crtc *crtc)
4619 {
4620         struct drm_device *dev = crtc->dev;
4621         struct drm_i915_private *dev_priv = dev->dev_private;
4622         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4623         int pipe = intel_crtc->pipe;
4624
4625         /*
4626          * BDW signals flip done immediately if the plane
4627          * is disabled, even if the plane enable is already
4628          * armed to occur at the next vblank :(
4629          */
4630         if (IS_BROADWELL(dev))
4631                 intel_wait_for_vblank(dev, pipe);
4632
4633         /*
4634          * FIXME IPS should be fine as long as one plane is
4635          * enabled, but in practice it seems to have problems
4636          * when going from primary only to sprite only and vice
4637          * versa.
4638          */
4639         hsw_enable_ips(intel_crtc);
4640
4641         /*
4642          * Gen2 reports pipe underruns whenever all planes are disabled.
4643          * So don't enable underrun reporting before at least some planes
4644          * are enabled.
4645          * FIXME: Need to fix the logic to work when we turn off all planes
4646          * but leave the pipe running.
4647          */
4648         if (IS_GEN2(dev))
4649                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4650
4651         /* Underruns don't raise interrupts, so check manually. */
4652         if (HAS_GMCH_DISPLAY(dev))
4653                 i9xx_check_fifo_underruns(dev_priv);
4654 }
4655
4656 /**
4657  * intel_pre_disable_primary - Perform operations before disabling primary plane
4658  * @crtc: the CRTC whose primary plane is to be disabled
4659  *
4660  * Performs potentially sleeping operations that must be done before the
4661  * primary plane is disabled, such as updating FBC and IPS.  Note that this may
4662  * be called due to an explicit primary plane update, or due to an implicit
4663  * disable that is caused when a sprite plane completely hides the primary
4664  * plane.
4665  */
4666 static void
4667 intel_pre_disable_primary(struct drm_crtc *crtc)
4668 {
4669         struct drm_device *dev = crtc->dev;
4670         struct drm_i915_private *dev_priv = dev->dev_private;
4671         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4672         int pipe = intel_crtc->pipe;
4673
4674         /*
4675          * Gen2 reports pipe underruns whenever all planes are disabled.
4676          * So diasble underrun reporting before all the planes get disabled.
4677          * FIXME: Need to fix the logic to work when we turn off all planes
4678          * but leave the pipe running.
4679          */
4680         if (IS_GEN2(dev))
4681                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4682
4683         /*
4684          * Vblank time updates from the shadow to live plane control register
4685          * are blocked if the memory self-refresh mode is active at that
4686          * moment. So to make sure the plane gets truly disabled, disable
4687          * first the self-refresh mode. The self-refresh enable bit in turn
4688          * will be checked/applied by the HW only at the next frame start
4689          * event which is after the vblank start event, so we need to have a
4690          * wait-for-vblank between disabling the plane and the pipe.
4691          */
4692         if (HAS_GMCH_DISPLAY(dev)) {
4693                 intel_set_memory_cxsr(dev_priv, false);
4694                 dev_priv->wm.vlv.cxsr = false;
4695                 intel_wait_for_vblank(dev, pipe);
4696         }
4697
4698         /*
4699          * FIXME IPS should be fine as long as one plane is
4700          * enabled, but in practice it seems to have problems
4701          * when going from primary only to sprite only and vice
4702          * versa.
4703          */
4704         hsw_disable_ips(intel_crtc);
4705 }
4706
4707 static void intel_post_plane_update(struct intel_crtc *crtc)
4708 {
4709         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4710         struct drm_device *dev = crtc->base.dev;
4711         struct drm_i915_private *dev_priv = dev->dev_private;
4712         struct drm_plane *plane;
4713
4714         if (atomic->wait_vblank)
4715                 intel_wait_for_vblank(dev, crtc->pipe);
4716
4717         intel_frontbuffer_flip(dev, atomic->fb_bits);
4718
4719         if (atomic->disable_cxsr)
4720                 crtc->wm.cxsr_allowed = true;
4721
4722         if (crtc->atomic.update_wm_post)
4723                 intel_update_watermarks(&crtc->base);
4724
4725         if (atomic->update_fbc)
4726                 intel_fbc_update(dev_priv);
4727
4728         if (atomic->post_enable_primary)
4729                 intel_post_enable_primary(&crtc->base);
4730
4731         drm_for_each_plane_mask(plane, dev, atomic->update_sprite_watermarks)
4732                 intel_update_sprite_watermarks(plane, &crtc->base,
4733                                                0, 0, 0, false, false);
4734
4735         memset(atomic, 0, sizeof(*atomic));
4736 }
4737
4738 static void intel_pre_plane_update(struct intel_crtc *crtc)
4739 {
4740         struct drm_device *dev = crtc->base.dev;
4741         struct drm_i915_private *dev_priv = dev->dev_private;
4742         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4743         struct drm_plane *p;
4744
4745         /* Track fb's for any planes being disabled */
4746         drm_for_each_plane_mask(p, dev, atomic->disabled_planes) {
4747                 struct intel_plane *plane = to_intel_plane(p);
4748
4749                 mutex_lock(&dev->struct_mutex);
4750                 i915_gem_track_fb(intel_fb_obj(plane->base.fb), NULL,
4751                                   plane->frontbuffer_bit);
4752                 mutex_unlock(&dev->struct_mutex);
4753         }
4754
4755         if (atomic->wait_for_flips)
4756                 intel_crtc_wait_for_pending_flips(&crtc->base);
4757
4758         if (atomic->disable_fbc)
4759                 intel_fbc_disable_crtc(crtc);
4760
4761         if (crtc->atomic.disable_ips)
4762                 hsw_disable_ips(crtc);
4763
4764         if (atomic->pre_disable_primary)
4765                 intel_pre_disable_primary(&crtc->base);
4766
4767         if (atomic->disable_cxsr) {
4768                 crtc->wm.cxsr_allowed = false;
4769                 intel_set_memory_cxsr(dev_priv, false);
4770         }
4771 }
4772
4773 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4774 {
4775         struct drm_device *dev = crtc->dev;
4776         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4777         struct drm_plane *p;
4778         int pipe = intel_crtc->pipe;
4779
4780         intel_crtc_dpms_overlay_disable(intel_crtc);
4781
4782         drm_for_each_plane_mask(p, dev, plane_mask)
4783                 to_intel_plane(p)->disable_plane(p, crtc);
4784
4785         /*
4786          * FIXME: Once we grow proper nuclear flip support out of this we need
4787          * to compute the mask of flip planes precisely. For the time being
4788          * consider this a flip to a NULL plane.
4789          */
4790         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4791 }
4792
4793 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4794 {
4795         struct drm_device *dev = crtc->dev;
4796         struct drm_i915_private *dev_priv = dev->dev_private;
4797         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4798         struct intel_encoder *encoder;
4799         int pipe = intel_crtc->pipe;
4800
4801         if (WARN_ON(intel_crtc->active))
4802                 return;
4803
4804         if (intel_crtc->config->has_pch_encoder)
4805                 intel_prepare_shared_dpll(intel_crtc);
4806
4807         if (intel_crtc->config->has_dp_encoder)
4808                 intel_dp_set_m_n(intel_crtc, M1_N1);
4809
4810         intel_set_pipe_timings(intel_crtc);
4811
4812         if (intel_crtc->config->has_pch_encoder) {
4813                 intel_cpu_transcoder_set_m_n(intel_crtc,
4814                                      &intel_crtc->config->fdi_m_n, NULL);
4815         }
4816
4817         ironlake_set_pipeconf(crtc);
4818
4819         intel_crtc->active = true;
4820
4821         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4822         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4823
4824         for_each_encoder_on_crtc(dev, crtc, encoder)
4825                 if (encoder->pre_enable)
4826                         encoder->pre_enable(encoder);
4827
4828         if (intel_crtc->config->has_pch_encoder) {
4829                 /* Note: FDI PLL enabling _must_ be done before we enable the
4830                  * cpu pipes, hence this is separate from all the other fdi/pch
4831                  * enabling. */
4832                 ironlake_fdi_pll_enable(intel_crtc);
4833         } else {
4834                 assert_fdi_tx_disabled(dev_priv, pipe);
4835                 assert_fdi_rx_disabled(dev_priv, pipe);
4836         }
4837
4838         ironlake_pfit_enable(intel_crtc);
4839
4840         /*
4841          * On ILK+ LUT must be loaded before the pipe is running but with
4842          * clocks enabled
4843          */
4844         intel_crtc_load_lut(crtc);
4845
4846         intel_update_watermarks(crtc);
4847         intel_enable_pipe(intel_crtc);
4848
4849         if (intel_crtc->config->has_pch_encoder)
4850                 ironlake_pch_enable(crtc);
4851
4852         assert_vblank_disabled(crtc);
4853         drm_crtc_vblank_on(crtc);
4854
4855         for_each_encoder_on_crtc(dev, crtc, encoder)
4856                 encoder->enable(encoder);
4857
4858         if (HAS_PCH_CPT(dev))
4859                 cpt_verify_modeset(dev, intel_crtc->pipe);
4860 }
4861
4862 /* IPS only exists on ULT machines and is tied to pipe A. */
4863 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4864 {
4865         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4866 }
4867
4868 static void haswell_crtc_enable(struct drm_crtc *crtc)
4869 {
4870         struct drm_device *dev = crtc->dev;
4871         struct drm_i915_private *dev_priv = dev->dev_private;
4872         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4873         struct intel_encoder *encoder;
4874         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4875         struct intel_crtc_state *pipe_config =
4876                 to_intel_crtc_state(crtc->state);
4877
4878         if (WARN_ON(intel_crtc->active))
4879                 return;
4880
4881         if (intel_crtc_to_shared_dpll(intel_crtc))
4882                 intel_enable_shared_dpll(intel_crtc);
4883
4884         if (intel_crtc->config->has_dp_encoder)
4885                 intel_dp_set_m_n(intel_crtc, M1_N1);
4886
4887         intel_set_pipe_timings(intel_crtc);
4888
4889         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4890                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4891                            intel_crtc->config->pixel_multiplier - 1);
4892         }
4893
4894         if (intel_crtc->config->has_pch_encoder) {
4895                 intel_cpu_transcoder_set_m_n(intel_crtc,
4896                                      &intel_crtc->config->fdi_m_n, NULL);
4897         }
4898
4899         haswell_set_pipeconf(crtc);
4900
4901         intel_set_pipe_csc(crtc);
4902
4903         intel_crtc->active = true;
4904
4905         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4906         for_each_encoder_on_crtc(dev, crtc, encoder)
4907                 if (encoder->pre_enable)
4908                         encoder->pre_enable(encoder);
4909
4910         if (intel_crtc->config->has_pch_encoder) {
4911                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4912                                                       true);
4913                 dev_priv->display.fdi_link_train(crtc);
4914         }
4915
4916         intel_ddi_enable_pipe_clock(intel_crtc);
4917
4918         if (INTEL_INFO(dev)->gen == 9)
4919                 skylake_pfit_enable(intel_crtc);
4920         else if (INTEL_INFO(dev)->gen < 9)
4921                 ironlake_pfit_enable(intel_crtc);
4922         else
4923                 MISSING_CASE(INTEL_INFO(dev)->gen);
4924
4925         /*
4926          * On ILK+ LUT must be loaded before the pipe is running but with
4927          * clocks enabled
4928          */
4929         intel_crtc_load_lut(crtc);
4930
4931         intel_ddi_set_pipe_settings(crtc);
4932         intel_ddi_enable_transcoder_func(crtc);
4933
4934         intel_update_watermarks(crtc);
4935         intel_enable_pipe(intel_crtc);
4936
4937         if (intel_crtc->config->has_pch_encoder)
4938                 lpt_pch_enable(crtc);
4939
4940         if (intel_crtc->config->dp_encoder_is_mst)
4941                 intel_ddi_set_vc_payload_alloc(crtc, true);
4942
4943         assert_vblank_disabled(crtc);
4944         drm_crtc_vblank_on(crtc);
4945
4946         for_each_encoder_on_crtc(dev, crtc, encoder) {
4947                 encoder->enable(encoder);
4948                 intel_opregion_notify_encoder(encoder, true);
4949         }
4950
4951         /* If we change the relative order between pipe/planes enabling, we need
4952          * to change the workaround. */
4953         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4954         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4955                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4956                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4957         }
4958 }
4959
4960 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4961 {
4962         struct drm_device *dev = crtc->base.dev;
4963         struct drm_i915_private *dev_priv = dev->dev_private;
4964         int pipe = crtc->pipe;
4965
4966         /* To avoid upsetting the power well on haswell only disable the pfit if
4967          * it's in use. The hw state code will make sure we get this right. */
4968         if (crtc->config->pch_pfit.enabled) {
4969                 I915_WRITE(PF_CTL(pipe), 0);
4970                 I915_WRITE(PF_WIN_POS(pipe), 0);
4971                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4972         }
4973 }
4974
4975 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4976 {
4977         struct drm_device *dev = crtc->dev;
4978         struct drm_i915_private *dev_priv = dev->dev_private;
4979         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4980         struct intel_encoder *encoder;
4981         int pipe = intel_crtc->pipe;
4982         u32 reg, temp;
4983
4984         for_each_encoder_on_crtc(dev, crtc, encoder)
4985                 encoder->disable(encoder);
4986
4987         drm_crtc_vblank_off(crtc);
4988         assert_vblank_disabled(crtc);
4989
4990         if (intel_crtc->config->has_pch_encoder)
4991                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4992
4993         intel_disable_pipe(intel_crtc);
4994
4995         ironlake_pfit_disable(intel_crtc);
4996
4997         if (intel_crtc->config->has_pch_encoder)
4998                 ironlake_fdi_disable(crtc);
4999
5000         for_each_encoder_on_crtc(dev, crtc, encoder)
5001                 if (encoder->post_disable)
5002                         encoder->post_disable(encoder);
5003
5004         if (intel_crtc->config->has_pch_encoder) {
5005                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5006
5007                 if (HAS_PCH_CPT(dev)) {
5008                         /* disable TRANS_DP_CTL */
5009                         reg = TRANS_DP_CTL(pipe);
5010                         temp = I915_READ(reg);
5011                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5012                                   TRANS_DP_PORT_SEL_MASK);
5013                         temp |= TRANS_DP_PORT_SEL_NONE;
5014                         I915_WRITE(reg, temp);
5015
5016                         /* disable DPLL_SEL */
5017                         temp = I915_READ(PCH_DPLL_SEL);
5018                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5019                         I915_WRITE(PCH_DPLL_SEL, temp);
5020                 }
5021
5022                 ironlake_fdi_pll_disable(intel_crtc);
5023         }
5024
5025         intel_crtc->active = false;
5026         intel_update_watermarks(crtc);
5027 }
5028
5029 static void haswell_crtc_disable(struct drm_crtc *crtc)
5030 {
5031         struct drm_device *dev = crtc->dev;
5032         struct drm_i915_private *dev_priv = dev->dev_private;
5033         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5034         struct intel_encoder *encoder;
5035         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5036
5037         for_each_encoder_on_crtc(dev, crtc, encoder) {
5038                 intel_opregion_notify_encoder(encoder, false);
5039                 encoder->disable(encoder);
5040         }
5041
5042         drm_crtc_vblank_off(crtc);
5043         assert_vblank_disabled(crtc);
5044
5045         if (intel_crtc->config->has_pch_encoder)
5046                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5047                                                       false);
5048         intel_disable_pipe(intel_crtc);
5049
5050         if (intel_crtc->config->dp_encoder_is_mst)
5051                 intel_ddi_set_vc_payload_alloc(crtc, false);
5052
5053         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5054
5055         if (INTEL_INFO(dev)->gen == 9)
5056                 skylake_scaler_disable(intel_crtc);
5057         else if (INTEL_INFO(dev)->gen < 9)
5058                 ironlake_pfit_disable(intel_crtc);
5059         else
5060                 MISSING_CASE(INTEL_INFO(dev)->gen);
5061
5062         intel_ddi_disable_pipe_clock(intel_crtc);
5063
5064         if (intel_crtc->config->has_pch_encoder) {
5065                 lpt_disable_pch_transcoder(dev_priv);
5066                 intel_ddi_fdi_disable(crtc);
5067         }
5068
5069         for_each_encoder_on_crtc(dev, crtc, encoder)
5070                 if (encoder->post_disable)
5071                         encoder->post_disable(encoder);
5072
5073         intel_crtc->active = false;
5074         intel_update_watermarks(crtc);
5075 }
5076
5077 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5078 {
5079         struct drm_device *dev = crtc->base.dev;
5080         struct drm_i915_private *dev_priv = dev->dev_private;
5081         struct intel_crtc_state *pipe_config = crtc->config;
5082
5083         if (!pipe_config->gmch_pfit.control)
5084                 return;
5085
5086         /*
5087          * The panel fitter should only be adjusted whilst the pipe is disabled,
5088          * according to register description and PRM.
5089          */
5090         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5091         assert_pipe_disabled(dev_priv, crtc->pipe);
5092
5093         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5094         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5095
5096         /* Border color in case we don't scale up to the full screen. Black by
5097          * default, change to something else for debugging. */
5098         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5099 }
5100
5101 static enum intel_display_power_domain port_to_power_domain(enum port port)
5102 {
5103         switch (port) {
5104         case PORT_A:
5105                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
5106         case PORT_B:
5107                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
5108         case PORT_C:
5109                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
5110         case PORT_D:
5111                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
5112         case PORT_E:
5113                 return POWER_DOMAIN_PORT_DDI_E_2_LANES;
5114         default:
5115                 WARN_ON_ONCE(1);
5116                 return POWER_DOMAIN_PORT_OTHER;
5117         }
5118 }
5119
5120 #define for_each_power_domain(domain, mask)                             \
5121         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
5122                 if ((1 << (domain)) & (mask))
5123
5124 enum intel_display_power_domain
5125 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5126 {
5127         struct drm_device *dev = intel_encoder->base.dev;
5128         struct intel_digital_port *intel_dig_port;
5129
5130         switch (intel_encoder->type) {
5131         case INTEL_OUTPUT_UNKNOWN:
5132                 /* Only DDI platforms should ever use this output type */
5133                 WARN_ON_ONCE(!HAS_DDI(dev));
5134         case INTEL_OUTPUT_DISPLAYPORT:
5135         case INTEL_OUTPUT_HDMI:
5136         case INTEL_OUTPUT_EDP:
5137                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5138                 return port_to_power_domain(intel_dig_port->port);
5139         case INTEL_OUTPUT_DP_MST:
5140                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5141                 return port_to_power_domain(intel_dig_port->port);
5142         case INTEL_OUTPUT_ANALOG:
5143                 return POWER_DOMAIN_PORT_CRT;
5144         case INTEL_OUTPUT_DSI:
5145                 return POWER_DOMAIN_PORT_DSI;
5146         default:
5147                 return POWER_DOMAIN_PORT_OTHER;
5148         }
5149 }
5150
5151 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
5152 {
5153         struct drm_device *dev = crtc->dev;
5154         struct intel_encoder *intel_encoder;
5155         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5156         enum pipe pipe = intel_crtc->pipe;
5157         unsigned long mask;
5158         enum transcoder transcoder;
5159
5160         if (!crtc->state->active)
5161                 return 0;
5162
5163         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
5164
5165         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5166         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5167         if (intel_crtc->config->pch_pfit.enabled ||
5168             intel_crtc->config->pch_pfit.force_thru)
5169                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5170
5171         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5172                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5173
5174         return mask;
5175 }
5176
5177 static unsigned long modeset_get_crtc_power_domains(struct drm_crtc *crtc)
5178 {
5179         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5180         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5181         enum intel_display_power_domain domain;
5182         unsigned long domains, new_domains, old_domains;
5183
5184         old_domains = intel_crtc->enabled_power_domains;
5185         intel_crtc->enabled_power_domains = new_domains = get_crtc_power_domains(crtc);
5186
5187         domains = new_domains & ~old_domains;
5188
5189         for_each_power_domain(domain, domains)
5190                 intel_display_power_get(dev_priv, domain);
5191
5192         return old_domains & ~new_domains;
5193 }
5194
5195 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5196                                       unsigned long domains)
5197 {
5198         enum intel_display_power_domain domain;
5199
5200         for_each_power_domain(domain, domains)
5201                 intel_display_power_put(dev_priv, domain);
5202 }
5203
5204 static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
5205 {
5206         struct drm_device *dev = state->dev;
5207         struct drm_i915_private *dev_priv = dev->dev_private;
5208         unsigned long put_domains[I915_MAX_PIPES] = {};
5209         struct drm_crtc_state *crtc_state;
5210         struct drm_crtc *crtc;
5211         int i;
5212
5213         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5214                 if (needs_modeset(crtc->state))
5215                         put_domains[to_intel_crtc(crtc)->pipe] =
5216                                 modeset_get_crtc_power_domains(crtc);
5217         }
5218
5219         if (dev_priv->display.modeset_commit_cdclk) {
5220                 unsigned int cdclk = to_intel_atomic_state(state)->cdclk;
5221
5222                 if (cdclk != dev_priv->cdclk_freq &&
5223                     !WARN_ON(!state->allow_modeset))
5224                         dev_priv->display.modeset_commit_cdclk(state);
5225         }
5226
5227         for (i = 0; i < I915_MAX_PIPES; i++)
5228                 if (put_domains[i])
5229                         modeset_put_power_domains(dev_priv, put_domains[i]);
5230 }
5231
5232 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5233 {
5234         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5235
5236         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5237             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5238                 return max_cdclk_freq;
5239         else if (IS_CHERRYVIEW(dev_priv))
5240                 return max_cdclk_freq*95/100;
5241         else if (INTEL_INFO(dev_priv)->gen < 4)
5242                 return 2*max_cdclk_freq*90/100;
5243         else
5244                 return max_cdclk_freq*90/100;
5245 }
5246
5247 static void intel_update_max_cdclk(struct drm_device *dev)
5248 {
5249         struct drm_i915_private *dev_priv = dev->dev_private;
5250
5251         if (IS_SKYLAKE(dev)) {
5252                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5253
5254                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5255                         dev_priv->max_cdclk_freq = 675000;
5256                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5257                         dev_priv->max_cdclk_freq = 540000;
5258                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5259                         dev_priv->max_cdclk_freq = 450000;
5260                 else
5261                         dev_priv->max_cdclk_freq = 337500;
5262         } else if (IS_BROADWELL(dev))  {
5263                 /*
5264                  * FIXME with extra cooling we can allow
5265                  * 540 MHz for ULX and 675 Mhz for ULT.
5266                  * How can we know if extra cooling is
5267                  * available? PCI ID, VTB, something else?
5268                  */
5269                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5270                         dev_priv->max_cdclk_freq = 450000;
5271                 else if (IS_BDW_ULX(dev))
5272                         dev_priv->max_cdclk_freq = 450000;
5273                 else if (IS_BDW_ULT(dev))
5274                         dev_priv->max_cdclk_freq = 540000;
5275                 else
5276                         dev_priv->max_cdclk_freq = 675000;
5277         } else if (IS_CHERRYVIEW(dev)) {
5278                 dev_priv->max_cdclk_freq = 320000;
5279         } else if (IS_VALLEYVIEW(dev)) {
5280                 dev_priv->max_cdclk_freq = 400000;
5281         } else {
5282                 /* otherwise assume cdclk is fixed */
5283                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5284         }
5285
5286         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5287
5288         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5289                          dev_priv->max_cdclk_freq);
5290
5291         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5292                          dev_priv->max_dotclk_freq);
5293 }
5294
5295 static void intel_update_cdclk(struct drm_device *dev)
5296 {
5297         struct drm_i915_private *dev_priv = dev->dev_private;
5298
5299         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5300         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5301                          dev_priv->cdclk_freq);
5302
5303         /*
5304          * Program the gmbus_freq based on the cdclk frequency.
5305          * BSpec erroneously claims we should aim for 4MHz, but
5306          * in fact 1MHz is the correct frequency.
5307          */
5308         if (IS_VALLEYVIEW(dev)) {
5309                 /*
5310                  * Program the gmbus_freq based on the cdclk frequency.
5311                  * BSpec erroneously claims we should aim for 4MHz, but
5312                  * in fact 1MHz is the correct frequency.
5313                  */
5314                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5315         }
5316
5317         if (dev_priv->max_cdclk_freq == 0)
5318                 intel_update_max_cdclk(dev);
5319 }
5320
5321 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5322 {
5323         struct drm_i915_private *dev_priv = dev->dev_private;
5324         uint32_t divider;
5325         uint32_t ratio;
5326         uint32_t current_freq;
5327         int ret;
5328
5329         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5330         switch (frequency) {
5331         case 144000:
5332                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5333                 ratio = BXT_DE_PLL_RATIO(60);
5334                 break;
5335         case 288000:
5336                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5337                 ratio = BXT_DE_PLL_RATIO(60);
5338                 break;
5339         case 384000:
5340                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5341                 ratio = BXT_DE_PLL_RATIO(60);
5342                 break;
5343         case 576000:
5344                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5345                 ratio = BXT_DE_PLL_RATIO(60);
5346                 break;
5347         case 624000:
5348                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5349                 ratio = BXT_DE_PLL_RATIO(65);
5350                 break;
5351         case 19200:
5352                 /*
5353                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5354                  * to suppress GCC warning.
5355                  */
5356                 ratio = 0;
5357                 divider = 0;
5358                 break;
5359         default:
5360                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5361
5362                 return;
5363         }
5364
5365         mutex_lock(&dev_priv->rps.hw_lock);
5366         /* Inform power controller of upcoming frequency change */
5367         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5368                                       0x80000000);
5369         mutex_unlock(&dev_priv->rps.hw_lock);
5370
5371         if (ret) {
5372                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5373                           ret, frequency);
5374                 return;
5375         }
5376
5377         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5378         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5379         current_freq = current_freq * 500 + 1000;
5380
5381         /*
5382          * DE PLL has to be disabled when
5383          * - setting to 19.2MHz (bypass, PLL isn't used)
5384          * - before setting to 624MHz (PLL needs toggling)
5385          * - before setting to any frequency from 624MHz (PLL needs toggling)
5386          */
5387         if (frequency == 19200 || frequency == 624000 ||
5388             current_freq == 624000) {
5389                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5390                 /* Timeout 200us */
5391                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5392                              1))
5393                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5394         }
5395
5396         if (frequency != 19200) {
5397                 uint32_t val;
5398
5399                 val = I915_READ(BXT_DE_PLL_CTL);
5400                 val &= ~BXT_DE_PLL_RATIO_MASK;
5401                 val |= ratio;
5402                 I915_WRITE(BXT_DE_PLL_CTL, val);
5403
5404                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5405                 /* Timeout 200us */
5406                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5407                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5408
5409                 val = I915_READ(CDCLK_CTL);
5410                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5411                 val |= divider;
5412                 /*
5413                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5414                  * enable otherwise.
5415                  */
5416                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5417                 if (frequency >= 500000)
5418                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5419
5420                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5421                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5422                 val |= (frequency - 1000) / 500;
5423                 I915_WRITE(CDCLK_CTL, val);
5424         }
5425
5426         mutex_lock(&dev_priv->rps.hw_lock);
5427         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5428                                       DIV_ROUND_UP(frequency, 25000));
5429         mutex_unlock(&dev_priv->rps.hw_lock);
5430
5431         if (ret) {
5432                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5433                           ret, frequency);
5434                 return;
5435         }
5436
5437         intel_update_cdclk(dev);
5438 }
5439
5440 void broxton_init_cdclk(struct drm_device *dev)
5441 {
5442         struct drm_i915_private *dev_priv = dev->dev_private;
5443         uint32_t val;
5444
5445         /*
5446          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5447          * or else the reset will hang because there is no PCH to respond.
5448          * Move the handshake programming to initialization sequence.
5449          * Previously was left up to BIOS.
5450          */
5451         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5452         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5453         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5454
5455         /* Enable PG1 for cdclk */
5456         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5457
5458         /* check if cd clock is enabled */
5459         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5460                 DRM_DEBUG_KMS("Display already initialized\n");
5461                 return;
5462         }
5463
5464         /*
5465          * FIXME:
5466          * - The initial CDCLK needs to be read from VBT.
5467          *   Need to make this change after VBT has changes for BXT.
5468          * - check if setting the max (or any) cdclk freq is really necessary
5469          *   here, it belongs to modeset time
5470          */
5471         broxton_set_cdclk(dev, 624000);
5472
5473         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5474         POSTING_READ(DBUF_CTL);
5475
5476         udelay(10);
5477
5478         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5479                 DRM_ERROR("DBuf power enable timeout!\n");
5480 }
5481
5482 void broxton_uninit_cdclk(struct drm_device *dev)
5483 {
5484         struct drm_i915_private *dev_priv = dev->dev_private;
5485
5486         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5487         POSTING_READ(DBUF_CTL);
5488
5489         udelay(10);
5490
5491         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5492                 DRM_ERROR("DBuf power disable timeout!\n");
5493
5494         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5495         broxton_set_cdclk(dev, 19200);
5496
5497         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5498 }
5499
5500 static const struct skl_cdclk_entry {
5501         unsigned int freq;
5502         unsigned int vco;
5503 } skl_cdclk_frequencies[] = {
5504         { .freq = 308570, .vco = 8640 },
5505         { .freq = 337500, .vco = 8100 },
5506         { .freq = 432000, .vco = 8640 },
5507         { .freq = 450000, .vco = 8100 },
5508         { .freq = 540000, .vco = 8100 },
5509         { .freq = 617140, .vco = 8640 },
5510         { .freq = 675000, .vco = 8100 },
5511 };
5512
5513 static unsigned int skl_cdclk_decimal(unsigned int freq)
5514 {
5515         return (freq - 1000) / 500;
5516 }
5517
5518 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5519 {
5520         unsigned int i;
5521
5522         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5523                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5524
5525                 if (e->freq == freq)
5526                         return e->vco;
5527         }
5528
5529         return 8100;
5530 }
5531
5532 static void
5533 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5534 {
5535         unsigned int min_freq;
5536         u32 val;
5537
5538         /* select the minimum CDCLK before enabling DPLL 0 */
5539         val = I915_READ(CDCLK_CTL);
5540         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5541         val |= CDCLK_FREQ_337_308;
5542
5543         if (required_vco == 8640)
5544                 min_freq = 308570;
5545         else
5546                 min_freq = 337500;
5547
5548         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5549
5550         I915_WRITE(CDCLK_CTL, val);
5551         POSTING_READ(CDCLK_CTL);
5552
5553         /*
5554          * We always enable DPLL0 with the lowest link rate possible, but still
5555          * taking into account the VCO required to operate the eDP panel at the
5556          * desired frequency. The usual DP link rates operate with a VCO of
5557          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5558          * The modeset code is responsible for the selection of the exact link
5559          * rate later on, with the constraint of choosing a frequency that
5560          * works with required_vco.
5561          */
5562         val = I915_READ(DPLL_CTRL1);
5563
5564         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5565                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5566         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5567         if (required_vco == 8640)
5568                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5569                                             SKL_DPLL0);
5570         else
5571                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5572                                             SKL_DPLL0);
5573
5574         I915_WRITE(DPLL_CTRL1, val);
5575         POSTING_READ(DPLL_CTRL1);
5576
5577         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5578
5579         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5580                 DRM_ERROR("DPLL0 not locked\n");
5581 }
5582
5583 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5584 {
5585         int ret;
5586         u32 val;
5587
5588         /* inform PCU we want to change CDCLK */
5589         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5590         mutex_lock(&dev_priv->rps.hw_lock);
5591         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5592         mutex_unlock(&dev_priv->rps.hw_lock);
5593
5594         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5595 }
5596
5597 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5598 {
5599         unsigned int i;
5600
5601         for (i = 0; i < 15; i++) {
5602                 if (skl_cdclk_pcu_ready(dev_priv))
5603                         return true;
5604                 udelay(10);
5605         }
5606
5607         return false;
5608 }
5609
5610 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5611 {
5612         struct drm_device *dev = dev_priv->dev;
5613         u32 freq_select, pcu_ack;
5614
5615         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5616
5617         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5618                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5619                 return;
5620         }
5621
5622         /* set CDCLK_CTL */
5623         switch(freq) {
5624         case 450000:
5625         case 432000:
5626                 freq_select = CDCLK_FREQ_450_432;
5627                 pcu_ack = 1;
5628                 break;
5629         case 540000:
5630                 freq_select = CDCLK_FREQ_540;
5631                 pcu_ack = 2;
5632                 break;
5633         case 308570:
5634         case 337500:
5635         default:
5636                 freq_select = CDCLK_FREQ_337_308;
5637                 pcu_ack = 0;
5638                 break;
5639         case 617140:
5640         case 675000:
5641                 freq_select = CDCLK_FREQ_675_617;
5642                 pcu_ack = 3;
5643                 break;
5644         }
5645
5646         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5647         POSTING_READ(CDCLK_CTL);
5648
5649         /* inform PCU of the change */
5650         mutex_lock(&dev_priv->rps.hw_lock);
5651         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5652         mutex_unlock(&dev_priv->rps.hw_lock);
5653
5654         intel_update_cdclk(dev);
5655 }
5656
5657 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5658 {
5659         /* disable DBUF power */
5660         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5661         POSTING_READ(DBUF_CTL);
5662
5663         udelay(10);
5664
5665         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5666                 DRM_ERROR("DBuf power disable timeout\n");
5667
5668         /* disable DPLL0 */
5669         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5670         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5671                 DRM_ERROR("Couldn't disable DPLL0\n");
5672
5673         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5674 }
5675
5676 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5677 {
5678         u32 val;
5679         unsigned int required_vco;
5680
5681         /* enable PCH reset handshake */
5682         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5683         I915_WRITE(HSW_NDE_RSTWRN_OPT, val | RESET_PCH_HANDSHAKE_ENABLE);
5684
5685         /* enable PG1 and Misc I/O */
5686         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5687
5688         /* DPLL0 not enabled (happens on early BIOS versions) */
5689         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5690                 /* enable DPLL0 */
5691                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5692                 skl_dpll0_enable(dev_priv, required_vco);
5693         }
5694
5695         /* set CDCLK to the frequency the BIOS chose */
5696         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5697
5698         /* enable DBUF power */
5699         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5700         POSTING_READ(DBUF_CTL);
5701
5702         udelay(10);
5703
5704         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5705                 DRM_ERROR("DBuf power enable timeout\n");
5706 }
5707
5708 /* returns HPLL frequency in kHz */
5709 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
5710 {
5711         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
5712
5713         /* Obtain SKU information */
5714         mutex_lock(&dev_priv->sb_lock);
5715         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
5716                 CCK_FUSE_HPLL_FREQ_MASK;
5717         mutex_unlock(&dev_priv->sb_lock);
5718
5719         return vco_freq[hpll_freq] * 1000;
5720 }
5721
5722 /* Adjust CDclk dividers to allow high res or save power if possible */
5723 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5724 {
5725         struct drm_i915_private *dev_priv = dev->dev_private;
5726         u32 val, cmd;
5727
5728         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5729                                         != dev_priv->cdclk_freq);
5730
5731         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5732                 cmd = 2;
5733         else if (cdclk == 266667)
5734                 cmd = 1;
5735         else
5736                 cmd = 0;
5737
5738         mutex_lock(&dev_priv->rps.hw_lock);
5739         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5740         val &= ~DSPFREQGUAR_MASK;
5741         val |= (cmd << DSPFREQGUAR_SHIFT);
5742         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5743         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5744                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5745                      50)) {
5746                 DRM_ERROR("timed out waiting for CDclk change\n");
5747         }
5748         mutex_unlock(&dev_priv->rps.hw_lock);
5749
5750         mutex_lock(&dev_priv->sb_lock);
5751
5752         if (cdclk == 400000) {
5753                 u32 divider;
5754
5755                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5756
5757                 /* adjust cdclk divider */
5758                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5759                 val &= ~DISPLAY_FREQUENCY_VALUES;
5760                 val |= divider;
5761                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5762
5763                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5764                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5765                              50))
5766                         DRM_ERROR("timed out waiting for CDclk change\n");
5767         }
5768
5769         /* adjust self-refresh exit latency value */
5770         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5771         val &= ~0x7f;
5772
5773         /*
5774          * For high bandwidth configs, we set a higher latency in the bunit
5775          * so that the core display fetch happens in time to avoid underruns.
5776          */
5777         if (cdclk == 400000)
5778                 val |= 4500 / 250; /* 4.5 usec */
5779         else
5780                 val |= 3000 / 250; /* 3.0 usec */
5781         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5782
5783         mutex_unlock(&dev_priv->sb_lock);
5784
5785         intel_update_cdclk(dev);
5786 }
5787
5788 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5789 {
5790         struct drm_i915_private *dev_priv = dev->dev_private;
5791         u32 val, cmd;
5792
5793         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5794                                                 != dev_priv->cdclk_freq);
5795
5796         switch (cdclk) {
5797         case 333333:
5798         case 320000:
5799         case 266667:
5800         case 200000:
5801                 break;
5802         default:
5803                 MISSING_CASE(cdclk);
5804                 return;
5805         }
5806
5807         /*
5808          * Specs are full of misinformation, but testing on actual
5809          * hardware has shown that we just need to write the desired
5810          * CCK divider into the Punit register.
5811          */
5812         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5813
5814         mutex_lock(&dev_priv->rps.hw_lock);
5815         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5816         val &= ~DSPFREQGUAR_MASK_CHV;
5817         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5818         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5819         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5820                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5821                      50)) {
5822                 DRM_ERROR("timed out waiting for CDclk change\n");
5823         }
5824         mutex_unlock(&dev_priv->rps.hw_lock);
5825
5826         intel_update_cdclk(dev);
5827 }
5828
5829 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5830                                  int max_pixclk)
5831 {
5832         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5833         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5834
5835         /*
5836          * Really only a few cases to deal with, as only 4 CDclks are supported:
5837          *   200MHz
5838          *   267MHz
5839          *   320/333MHz (depends on HPLL freq)
5840          *   400MHz (VLV only)
5841          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5842          * of the lower bin and adjust if needed.
5843          *
5844          * We seem to get an unstable or solid color picture at 200MHz.
5845          * Not sure what's wrong. For now use 200MHz only when all pipes
5846          * are off.
5847          */
5848         if (!IS_CHERRYVIEW(dev_priv) &&
5849             max_pixclk > freq_320*limit/100)
5850                 return 400000;
5851         else if (max_pixclk > 266667*limit/100)
5852                 return freq_320;
5853         else if (max_pixclk > 0)
5854                 return 266667;
5855         else
5856                 return 200000;
5857 }
5858
5859 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5860                               int max_pixclk)
5861 {
5862         /*
5863          * FIXME:
5864          * - remove the guardband, it's not needed on BXT
5865          * - set 19.2MHz bypass frequency if there are no active pipes
5866          */
5867         if (max_pixclk > 576000*9/10)
5868                 return 624000;
5869         else if (max_pixclk > 384000*9/10)
5870                 return 576000;
5871         else if (max_pixclk > 288000*9/10)
5872                 return 384000;
5873         else if (max_pixclk > 144000*9/10)
5874                 return 288000;
5875         else
5876                 return 144000;
5877 }
5878
5879 /* Compute the max pixel clock for new configuration. Uses atomic state if
5880  * that's non-NULL, look at current state otherwise. */
5881 static int intel_mode_max_pixclk(struct drm_device *dev,
5882                                  struct drm_atomic_state *state)
5883 {
5884         struct intel_crtc *intel_crtc;
5885         struct intel_crtc_state *crtc_state;
5886         int max_pixclk = 0;
5887
5888         for_each_intel_crtc(dev, intel_crtc) {
5889                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5890                 if (IS_ERR(crtc_state))
5891                         return PTR_ERR(crtc_state);
5892
5893                 if (!crtc_state->base.enable)
5894                         continue;
5895
5896                 max_pixclk = max(max_pixclk,
5897                                  crtc_state->base.adjusted_mode.crtc_clock);
5898         }
5899
5900         return max_pixclk;
5901 }
5902
5903 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5904 {
5905         struct drm_device *dev = state->dev;
5906         struct drm_i915_private *dev_priv = dev->dev_private;
5907         int max_pixclk = intel_mode_max_pixclk(dev, state);
5908
5909         if (max_pixclk < 0)
5910                 return max_pixclk;
5911
5912         to_intel_atomic_state(state)->cdclk =
5913                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5914
5915         return 0;
5916 }
5917
5918 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5919 {
5920         struct drm_device *dev = state->dev;
5921         struct drm_i915_private *dev_priv = dev->dev_private;
5922         int max_pixclk = intel_mode_max_pixclk(dev, state);
5923
5924         if (max_pixclk < 0)
5925                 return max_pixclk;
5926
5927         to_intel_atomic_state(state)->cdclk =
5928                 broxton_calc_cdclk(dev_priv, max_pixclk);
5929
5930         return 0;
5931 }
5932
5933 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5934 {
5935         unsigned int credits, default_credits;
5936
5937         if (IS_CHERRYVIEW(dev_priv))
5938                 default_credits = PFI_CREDIT(12);
5939         else
5940                 default_credits = PFI_CREDIT(8);
5941
5942         if (DIV_ROUND_CLOSEST(dev_priv->cdclk_freq, 1000) >= dev_priv->rps.cz_freq) {
5943                 /* CHV suggested value is 31 or 63 */
5944                 if (IS_CHERRYVIEW(dev_priv))
5945                         credits = PFI_CREDIT_63;
5946                 else
5947                         credits = PFI_CREDIT(15);
5948         } else {
5949                 credits = default_credits;
5950         }
5951
5952         /*
5953          * WA - write default credits before re-programming
5954          * FIXME: should we also set the resend bit here?
5955          */
5956         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5957                    default_credits);
5958
5959         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5960                    credits | PFI_CREDIT_RESEND);
5961
5962         /*
5963          * FIXME is this guaranteed to clear
5964          * immediately or should we poll for it?
5965          */
5966         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5967 }
5968
5969 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
5970 {
5971         struct drm_device *dev = old_state->dev;
5972         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
5973         struct drm_i915_private *dev_priv = dev->dev_private;
5974
5975         /*
5976          * FIXME: We can end up here with all power domains off, yet
5977          * with a CDCLK frequency other than the minimum. To account
5978          * for this take the PIPE-A power domain, which covers the HW
5979          * blocks needed for the following programming. This can be
5980          * removed once it's guaranteed that we get here either with
5981          * the minimum CDCLK set, or the required power domains
5982          * enabled.
5983          */
5984         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5985
5986         if (IS_CHERRYVIEW(dev))
5987                 cherryview_set_cdclk(dev, req_cdclk);
5988         else
5989                 valleyview_set_cdclk(dev, req_cdclk);
5990
5991         vlv_program_pfi_credits(dev_priv);
5992
5993         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5994 }
5995
5996 static void valleyview_crtc_enable(struct drm_crtc *crtc)
5997 {
5998         struct drm_device *dev = crtc->dev;
5999         struct drm_i915_private *dev_priv = to_i915(dev);
6000         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6001         struct intel_encoder *encoder;
6002         int pipe = intel_crtc->pipe;
6003         bool is_dsi;
6004
6005         if (WARN_ON(intel_crtc->active))
6006                 return;
6007
6008         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
6009
6010         if (intel_crtc->config->has_dp_encoder)
6011                 intel_dp_set_m_n(intel_crtc, M1_N1);
6012
6013         intel_set_pipe_timings(intel_crtc);
6014
6015         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6016                 struct drm_i915_private *dev_priv = dev->dev_private;
6017
6018                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6019                 I915_WRITE(CHV_CANVAS(pipe), 0);
6020         }
6021
6022         i9xx_set_pipeconf(intel_crtc);
6023
6024         intel_crtc->active = true;
6025
6026         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6027
6028         for_each_encoder_on_crtc(dev, crtc, encoder)
6029                 if (encoder->pre_pll_enable)
6030                         encoder->pre_pll_enable(encoder);
6031
6032         if (!is_dsi) {
6033                 if (IS_CHERRYVIEW(dev)) {
6034                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6035                         chv_enable_pll(intel_crtc, intel_crtc->config);
6036                 } else {
6037                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6038                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6039                 }
6040         }
6041
6042         for_each_encoder_on_crtc(dev, crtc, encoder)
6043                 if (encoder->pre_enable)
6044                         encoder->pre_enable(encoder);
6045
6046         i9xx_pfit_enable(intel_crtc);
6047
6048         intel_crtc_load_lut(crtc);
6049
6050         intel_enable_pipe(intel_crtc);
6051
6052         assert_vblank_disabled(crtc);
6053         drm_crtc_vblank_on(crtc);
6054
6055         for_each_encoder_on_crtc(dev, crtc, encoder)
6056                 encoder->enable(encoder);
6057 }
6058
6059 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6060 {
6061         struct drm_device *dev = crtc->base.dev;
6062         struct drm_i915_private *dev_priv = dev->dev_private;
6063
6064         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6065         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6066 }
6067
6068 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6069 {
6070         struct drm_device *dev = crtc->dev;
6071         struct drm_i915_private *dev_priv = to_i915(dev);
6072         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6073         struct intel_encoder *encoder;
6074         int pipe = intel_crtc->pipe;
6075
6076         if (WARN_ON(intel_crtc->active))
6077                 return;
6078
6079         i9xx_set_pll_dividers(intel_crtc);
6080
6081         if (intel_crtc->config->has_dp_encoder)
6082                 intel_dp_set_m_n(intel_crtc, M1_N1);
6083
6084         intel_set_pipe_timings(intel_crtc);
6085
6086         i9xx_set_pipeconf(intel_crtc);
6087
6088         intel_crtc->active = true;
6089
6090         if (!IS_GEN2(dev))
6091                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6092
6093         for_each_encoder_on_crtc(dev, crtc, encoder)
6094                 if (encoder->pre_enable)
6095                         encoder->pre_enable(encoder);
6096
6097         i9xx_enable_pll(intel_crtc);
6098
6099         i9xx_pfit_enable(intel_crtc);
6100
6101         intel_crtc_load_lut(crtc);
6102
6103         intel_update_watermarks(crtc);
6104         intel_enable_pipe(intel_crtc);
6105
6106         assert_vblank_disabled(crtc);
6107         drm_crtc_vblank_on(crtc);
6108
6109         for_each_encoder_on_crtc(dev, crtc, encoder)
6110                 encoder->enable(encoder);
6111 }
6112
6113 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6114 {
6115         struct drm_device *dev = crtc->base.dev;
6116         struct drm_i915_private *dev_priv = dev->dev_private;
6117
6118         if (!crtc->config->gmch_pfit.control)
6119                 return;
6120
6121         assert_pipe_disabled(dev_priv, crtc->pipe);
6122
6123         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6124                          I915_READ(PFIT_CONTROL));
6125         I915_WRITE(PFIT_CONTROL, 0);
6126 }
6127
6128 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6129 {
6130         struct drm_device *dev = crtc->dev;
6131         struct drm_i915_private *dev_priv = dev->dev_private;
6132         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6133         struct intel_encoder *encoder;
6134         int pipe = intel_crtc->pipe;
6135
6136         /*
6137          * On gen2 planes are double buffered but the pipe isn't, so we must
6138          * wait for planes to fully turn off before disabling the pipe.
6139          * We also need to wait on all gmch platforms because of the
6140          * self-refresh mode constraint explained above.
6141          */
6142         intel_wait_for_vblank(dev, pipe);
6143
6144         for_each_encoder_on_crtc(dev, crtc, encoder)
6145                 encoder->disable(encoder);
6146
6147         drm_crtc_vblank_off(crtc);
6148         assert_vblank_disabled(crtc);
6149
6150         intel_disable_pipe(intel_crtc);
6151
6152         i9xx_pfit_disable(intel_crtc);
6153
6154         for_each_encoder_on_crtc(dev, crtc, encoder)
6155                 if (encoder->post_disable)
6156                         encoder->post_disable(encoder);
6157
6158         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
6159                 if (IS_CHERRYVIEW(dev))
6160                         chv_disable_pll(dev_priv, pipe);
6161                 else if (IS_VALLEYVIEW(dev))
6162                         vlv_disable_pll(dev_priv, pipe);
6163                 else
6164                         i9xx_disable_pll(intel_crtc);
6165         }
6166
6167         for_each_encoder_on_crtc(dev, crtc, encoder)
6168                 if (encoder->post_pll_disable)
6169                         encoder->post_pll_disable(encoder);
6170
6171         if (!IS_GEN2(dev))
6172                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6173
6174         intel_crtc->active = false;
6175         intel_update_watermarks(crtc);
6176 }
6177
6178 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6179 {
6180         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6181         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6182         enum intel_display_power_domain domain;
6183         unsigned long domains;
6184
6185         if (!intel_crtc->active)
6186                 return;
6187
6188         if (to_intel_plane_state(crtc->primary->state)->visible) {
6189                 intel_crtc_wait_for_pending_flips(crtc);
6190                 intel_pre_disable_primary(crtc);
6191         }
6192
6193         intel_crtc_disable_planes(crtc, crtc->state->plane_mask);
6194         dev_priv->display.crtc_disable(crtc);
6195         intel_disable_shared_dpll(intel_crtc);
6196
6197         domains = intel_crtc->enabled_power_domains;
6198         for_each_power_domain(domain, domains)
6199                 intel_display_power_put(dev_priv, domain);
6200         intel_crtc->enabled_power_domains = 0;
6201 }
6202
6203 /*
6204  * turn all crtc's off, but do not adjust state
6205  * This has to be paired with a call to intel_modeset_setup_hw_state.
6206  */
6207 int intel_display_suspend(struct drm_device *dev)
6208 {
6209         struct drm_mode_config *config = &dev->mode_config;
6210         struct drm_modeset_acquire_ctx *ctx = config->acquire_ctx;
6211         struct drm_atomic_state *state;
6212         struct drm_crtc *crtc;
6213         unsigned crtc_mask = 0;
6214         int ret = 0;
6215
6216         if (WARN_ON(!ctx))
6217                 return 0;
6218
6219         lockdep_assert_held(&ctx->ww_ctx);
6220         state = drm_atomic_state_alloc(dev);
6221         if (WARN_ON(!state))
6222                 return -ENOMEM;
6223
6224         state->acquire_ctx = ctx;
6225         state->allow_modeset = true;
6226
6227         for_each_crtc(dev, crtc) {
6228                 struct drm_crtc_state *crtc_state =
6229                         drm_atomic_get_crtc_state(state, crtc);
6230
6231                 ret = PTR_ERR_OR_ZERO(crtc_state);
6232                 if (ret)
6233                         goto free;
6234
6235                 if (!crtc_state->active)
6236                         continue;
6237
6238                 crtc_state->active = false;
6239                 crtc_mask |= 1 << drm_crtc_index(crtc);
6240         }
6241
6242         if (crtc_mask) {
6243                 ret = drm_atomic_commit(state);
6244
6245                 if (!ret) {
6246                         for_each_crtc(dev, crtc)
6247                                 if (crtc_mask & (1 << drm_crtc_index(crtc)))
6248                                         crtc->state->active = true;
6249
6250                         return ret;
6251                 }
6252         }
6253
6254 free:
6255         if (ret)
6256                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6257         drm_atomic_state_free(state);
6258         return ret;
6259 }
6260
6261 void intel_encoder_destroy(struct drm_encoder *encoder)
6262 {
6263         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6264
6265         drm_encoder_cleanup(encoder);
6266         kfree(intel_encoder);
6267 }
6268
6269 /* Cross check the actual hw state with our own modeset state tracking (and it's
6270  * internal consistency). */
6271 static void intel_connector_check_state(struct intel_connector *connector)
6272 {
6273         struct drm_crtc *crtc = connector->base.state->crtc;
6274
6275         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6276                       connector->base.base.id,
6277                       connector->base.name);
6278
6279         if (connector->get_hw_state(connector)) {
6280                 struct drm_encoder *encoder = &connector->encoder->base;
6281                 struct drm_connector_state *conn_state = connector->base.state;
6282
6283                 I915_STATE_WARN(!crtc,
6284                          "connector enabled without attached crtc\n");
6285
6286                 if (!crtc)
6287                         return;
6288
6289                 I915_STATE_WARN(!crtc->state->active,
6290                       "connector is active, but attached crtc isn't\n");
6291
6292                 if (!encoder)
6293                         return;
6294
6295                 I915_STATE_WARN(conn_state->best_encoder != encoder,
6296                         "atomic encoder doesn't match attached encoder\n");
6297
6298                 I915_STATE_WARN(conn_state->crtc != encoder->crtc,
6299                         "attached encoder crtc differs from connector crtc\n");
6300         } else {
6301                 I915_STATE_WARN(crtc && crtc->state->active,
6302                         "attached crtc is active, but connector isn't\n");
6303                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6304                         "best encoder set without crtc!\n");
6305         }
6306 }
6307
6308 int intel_connector_init(struct intel_connector *connector)
6309 {
6310         struct drm_connector_state *connector_state;
6311
6312         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6313         if (!connector_state)
6314                 return -ENOMEM;
6315
6316         connector->base.state = connector_state;
6317         return 0;
6318 }
6319
6320 struct intel_connector *intel_connector_alloc(void)
6321 {
6322         struct intel_connector *connector;
6323
6324         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6325         if (!connector)
6326                 return NULL;
6327
6328         if (intel_connector_init(connector) < 0) {
6329                 kfree(connector);
6330                 return NULL;
6331         }
6332
6333         return connector;
6334 }
6335
6336 /* Simple connector->get_hw_state implementation for encoders that support only
6337  * one connector and no cloning and hence the encoder state determines the state
6338  * of the connector. */
6339 bool intel_connector_get_hw_state(struct intel_connector *connector)
6340 {
6341         enum pipe pipe = 0;
6342         struct intel_encoder *encoder = connector->encoder;
6343
6344         return encoder->get_hw_state(encoder, &pipe);
6345 }
6346
6347 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6348 {
6349         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6350                 return crtc_state->fdi_lanes;
6351
6352         return 0;
6353 }
6354
6355 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6356                                      struct intel_crtc_state *pipe_config)
6357 {
6358         struct drm_atomic_state *state = pipe_config->base.state;
6359         struct intel_crtc *other_crtc;
6360         struct intel_crtc_state *other_crtc_state;
6361
6362         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6363                       pipe_name(pipe), pipe_config->fdi_lanes);
6364         if (pipe_config->fdi_lanes > 4) {
6365                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6366                               pipe_name(pipe), pipe_config->fdi_lanes);
6367                 return -EINVAL;
6368         }
6369
6370         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6371                 if (pipe_config->fdi_lanes > 2) {
6372                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6373                                       pipe_config->fdi_lanes);
6374                         return -EINVAL;
6375                 } else {
6376                         return 0;
6377                 }
6378         }
6379
6380         if (INTEL_INFO(dev)->num_pipes == 2)
6381                 return 0;
6382
6383         /* Ivybridge 3 pipe is really complicated */
6384         switch (pipe) {
6385         case PIPE_A:
6386                 return 0;
6387         case PIPE_B:
6388                 if (pipe_config->fdi_lanes <= 2)
6389                         return 0;
6390
6391                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6392                 other_crtc_state =
6393                         intel_atomic_get_crtc_state(state, other_crtc);
6394                 if (IS_ERR(other_crtc_state))
6395                         return PTR_ERR(other_crtc_state);
6396
6397                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6398                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6399                                       pipe_name(pipe), pipe_config->fdi_lanes);
6400                         return -EINVAL;
6401                 }
6402                 return 0;
6403         case PIPE_C:
6404                 if (pipe_config->fdi_lanes > 2) {
6405                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6406                                       pipe_name(pipe), pipe_config->fdi_lanes);
6407                         return -EINVAL;
6408                 }
6409
6410                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6411                 other_crtc_state =
6412                         intel_atomic_get_crtc_state(state, other_crtc);
6413                 if (IS_ERR(other_crtc_state))
6414                         return PTR_ERR(other_crtc_state);
6415
6416                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6417                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6418                         return -EINVAL;
6419                 }
6420                 return 0;
6421         default:
6422                 BUG();
6423         }
6424 }
6425
6426 #define RETRY 1
6427 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6428                                        struct intel_crtc_state *pipe_config)
6429 {
6430         struct drm_device *dev = intel_crtc->base.dev;
6431         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6432         int lane, link_bw, fdi_dotclock, ret;
6433         bool needs_recompute = false;
6434
6435 retry:
6436         /* FDI is a binary signal running at ~2.7GHz, encoding
6437          * each output octet as 10 bits. The actual frequency
6438          * is stored as a divider into a 100MHz clock, and the
6439          * mode pixel clock is stored in units of 1KHz.
6440          * Hence the bw of each lane in terms of the mode signal
6441          * is:
6442          */
6443         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6444
6445         fdi_dotclock = adjusted_mode->crtc_clock;
6446
6447         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6448                                            pipe_config->pipe_bpp);
6449
6450         pipe_config->fdi_lanes = lane;
6451
6452         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6453                                link_bw, &pipe_config->fdi_m_n);
6454
6455         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6456                                        intel_crtc->pipe, pipe_config);
6457         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6458                 pipe_config->pipe_bpp -= 2*3;
6459                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6460                               pipe_config->pipe_bpp);
6461                 needs_recompute = true;
6462                 pipe_config->bw_constrained = true;
6463
6464                 goto retry;
6465         }
6466
6467         if (needs_recompute)
6468                 return RETRY;
6469
6470         return ret;
6471 }
6472
6473 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6474                                      struct intel_crtc_state *pipe_config)
6475 {
6476         if (pipe_config->pipe_bpp > 24)
6477                 return false;
6478
6479         /* HSW can handle pixel rate up to cdclk? */
6480         if (IS_HASWELL(dev_priv->dev))
6481                 return true;
6482
6483         /*
6484          * We compare against max which means we must take
6485          * the increased cdclk requirement into account when
6486          * calculating the new cdclk.
6487          *
6488          * Should measure whether using a lower cdclk w/o IPS
6489          */
6490         return ilk_pipe_pixel_rate(pipe_config) <=
6491                 dev_priv->max_cdclk_freq * 95 / 100;
6492 }
6493
6494 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6495                                    struct intel_crtc_state *pipe_config)
6496 {
6497         struct drm_device *dev = crtc->base.dev;
6498         struct drm_i915_private *dev_priv = dev->dev_private;
6499
6500         pipe_config->ips_enabled = i915.enable_ips &&
6501                 hsw_crtc_supports_ips(crtc) &&
6502                 pipe_config_supports_ips(dev_priv, pipe_config);
6503 }
6504
6505 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6506                                      struct intel_crtc_state *pipe_config)
6507 {
6508         struct drm_device *dev = crtc->base.dev;
6509         struct drm_i915_private *dev_priv = dev->dev_private;
6510         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6511
6512         /* FIXME should check pixel clock limits on all platforms */
6513         if (INTEL_INFO(dev)->gen < 4) {
6514                 int clock_limit = dev_priv->max_cdclk_freq;
6515
6516                 /*
6517                  * Enable pixel doubling when the dot clock
6518                  * is > 90% of the (display) core speed.
6519                  *
6520                  * GDG double wide on either pipe,
6521                  * otherwise pipe A only.
6522                  */
6523                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
6524                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
6525                         clock_limit *= 2;
6526                         pipe_config->double_wide = true;
6527                 }
6528
6529                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
6530                         return -EINVAL;
6531         }
6532
6533         /*
6534          * Pipe horizontal size must be even in:
6535          * - DVO ganged mode
6536          * - LVDS dual channel mode
6537          * - Double wide pipe
6538          */
6539         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6540              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6541                 pipe_config->pipe_src_w &= ~1;
6542
6543         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6544          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6545          */
6546         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6547                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
6548                 return -EINVAL;
6549
6550         if (HAS_IPS(dev))
6551                 hsw_compute_ips_config(crtc, pipe_config);
6552
6553         if (pipe_config->has_pch_encoder)
6554                 return ironlake_fdi_compute_config(crtc, pipe_config);
6555
6556         return 0;
6557 }
6558
6559 static int skylake_get_display_clock_speed(struct drm_device *dev)
6560 {
6561         struct drm_i915_private *dev_priv = to_i915(dev);
6562         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6563         uint32_t cdctl = I915_READ(CDCLK_CTL);
6564         uint32_t linkrate;
6565
6566         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6567                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6568
6569         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6570                 return 540000;
6571
6572         linkrate = (I915_READ(DPLL_CTRL1) &
6573                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6574
6575         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6576             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6577                 /* vco 8640 */
6578                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6579                 case CDCLK_FREQ_450_432:
6580                         return 432000;
6581                 case CDCLK_FREQ_337_308:
6582                         return 308570;
6583                 case CDCLK_FREQ_675_617:
6584                         return 617140;
6585                 default:
6586                         WARN(1, "Unknown cd freq selection\n");
6587                 }
6588         } else {
6589                 /* vco 8100 */
6590                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6591                 case CDCLK_FREQ_450_432:
6592                         return 450000;
6593                 case CDCLK_FREQ_337_308:
6594                         return 337500;
6595                 case CDCLK_FREQ_675_617:
6596                         return 675000;
6597                 default:
6598                         WARN(1, "Unknown cd freq selection\n");
6599                 }
6600         }
6601
6602         /* error case, do as if DPLL0 isn't enabled */
6603         return 24000;
6604 }
6605
6606 static int broxton_get_display_clock_speed(struct drm_device *dev)
6607 {
6608         struct drm_i915_private *dev_priv = to_i915(dev);
6609         uint32_t cdctl = I915_READ(CDCLK_CTL);
6610         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6611         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6612         int cdclk;
6613
6614         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6615                 return 19200;
6616
6617         cdclk = 19200 * pll_ratio / 2;
6618
6619         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6620         case BXT_CDCLK_CD2X_DIV_SEL_1:
6621                 return cdclk;  /* 576MHz or 624MHz */
6622         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6623                 return cdclk * 2 / 3; /* 384MHz */
6624         case BXT_CDCLK_CD2X_DIV_SEL_2:
6625                 return cdclk / 2; /* 288MHz */
6626         case BXT_CDCLK_CD2X_DIV_SEL_4:
6627                 return cdclk / 4; /* 144MHz */
6628         }
6629
6630         /* error case, do as if DE PLL isn't enabled */
6631         return 19200;
6632 }
6633
6634 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6635 {
6636         struct drm_i915_private *dev_priv = dev->dev_private;
6637         uint32_t lcpll = I915_READ(LCPLL_CTL);
6638         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6639
6640         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6641                 return 800000;
6642         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6643                 return 450000;
6644         else if (freq == LCPLL_CLK_FREQ_450)
6645                 return 450000;
6646         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6647                 return 540000;
6648         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6649                 return 337500;
6650         else
6651                 return 675000;
6652 }
6653
6654 static int haswell_get_display_clock_speed(struct drm_device *dev)
6655 {
6656         struct drm_i915_private *dev_priv = dev->dev_private;
6657         uint32_t lcpll = I915_READ(LCPLL_CTL);
6658         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6659
6660         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6661                 return 800000;
6662         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6663                 return 450000;
6664         else if (freq == LCPLL_CLK_FREQ_450)
6665                 return 450000;
6666         else if (IS_HSW_ULT(dev))
6667                 return 337500;
6668         else
6669                 return 540000;
6670 }
6671
6672 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6673 {
6674         struct drm_i915_private *dev_priv = dev->dev_private;
6675         u32 val;
6676         int divider;
6677
6678         if (dev_priv->hpll_freq == 0)
6679                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
6680
6681         mutex_lock(&dev_priv->sb_lock);
6682         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6683         mutex_unlock(&dev_priv->sb_lock);
6684
6685         divider = val & DISPLAY_FREQUENCY_VALUES;
6686
6687         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
6688              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
6689              "cdclk change in progress\n");
6690
6691         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
6692 }
6693
6694 static int ilk_get_display_clock_speed(struct drm_device *dev)
6695 {
6696         return 450000;
6697 }
6698
6699 static int i945_get_display_clock_speed(struct drm_device *dev)
6700 {
6701         return 400000;
6702 }
6703
6704 static int i915_get_display_clock_speed(struct drm_device *dev)
6705 {
6706         return 333333;
6707 }
6708
6709 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6710 {
6711         return 200000;
6712 }
6713
6714 static int pnv_get_display_clock_speed(struct drm_device *dev)
6715 {
6716         u16 gcfgc = 0;
6717
6718         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6719
6720         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6721         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6722                 return 266667;
6723         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6724                 return 333333;
6725         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6726                 return 444444;
6727         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6728                 return 200000;
6729         default:
6730                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6731         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6732                 return 133333;
6733         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6734                 return 166667;
6735         }
6736 }
6737
6738 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6739 {
6740         u16 gcfgc = 0;
6741
6742         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6743
6744         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6745                 return 133333;
6746         else {
6747                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6748                 case GC_DISPLAY_CLOCK_333_MHZ:
6749                         return 333333;
6750                 default:
6751                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6752                         return 190000;
6753                 }
6754         }
6755 }
6756
6757 static int i865_get_display_clock_speed(struct drm_device *dev)
6758 {
6759         return 266667;
6760 }
6761
6762 static int i85x_get_display_clock_speed(struct drm_device *dev)
6763 {
6764         u16 hpllcc = 0;
6765
6766         /*
6767          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6768          * encoding is different :(
6769          * FIXME is this the right way to detect 852GM/852GMV?
6770          */
6771         if (dev->pdev->revision == 0x1)
6772                 return 133333;
6773
6774         pci_bus_read_config_word(dev->pdev->bus,
6775                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6776
6777         /* Assume that the hardware is in the high speed state.  This
6778          * should be the default.
6779          */
6780         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6781         case GC_CLOCK_133_200:
6782         case GC_CLOCK_133_200_2:
6783         case GC_CLOCK_100_200:
6784                 return 200000;
6785         case GC_CLOCK_166_250:
6786                 return 250000;
6787         case GC_CLOCK_100_133:
6788                 return 133333;
6789         case GC_CLOCK_133_266:
6790         case GC_CLOCK_133_266_2:
6791         case GC_CLOCK_166_266:
6792                 return 266667;
6793         }
6794
6795         /* Shouldn't happen */
6796         return 0;
6797 }
6798
6799 static int i830_get_display_clock_speed(struct drm_device *dev)
6800 {
6801         return 133333;
6802 }
6803
6804 static unsigned int intel_hpll_vco(struct drm_device *dev)
6805 {
6806         struct drm_i915_private *dev_priv = dev->dev_private;
6807         static const unsigned int blb_vco[8] = {
6808                 [0] = 3200000,
6809                 [1] = 4000000,
6810                 [2] = 5333333,
6811                 [3] = 4800000,
6812                 [4] = 6400000,
6813         };
6814         static const unsigned int pnv_vco[8] = {
6815                 [0] = 3200000,
6816                 [1] = 4000000,
6817                 [2] = 5333333,
6818                 [3] = 4800000,
6819                 [4] = 2666667,
6820         };
6821         static const unsigned int cl_vco[8] = {
6822                 [0] = 3200000,
6823                 [1] = 4000000,
6824                 [2] = 5333333,
6825                 [3] = 6400000,
6826                 [4] = 3333333,
6827                 [5] = 3566667,
6828                 [6] = 4266667,
6829         };
6830         static const unsigned int elk_vco[8] = {
6831                 [0] = 3200000,
6832                 [1] = 4000000,
6833                 [2] = 5333333,
6834                 [3] = 4800000,
6835         };
6836         static const unsigned int ctg_vco[8] = {
6837                 [0] = 3200000,
6838                 [1] = 4000000,
6839                 [2] = 5333333,
6840                 [3] = 6400000,
6841                 [4] = 2666667,
6842                 [5] = 4266667,
6843         };
6844         const unsigned int *vco_table;
6845         unsigned int vco;
6846         uint8_t tmp = 0;
6847
6848         /* FIXME other chipsets? */
6849         if (IS_GM45(dev))
6850                 vco_table = ctg_vco;
6851         else if (IS_G4X(dev))
6852                 vco_table = elk_vco;
6853         else if (IS_CRESTLINE(dev))
6854                 vco_table = cl_vco;
6855         else if (IS_PINEVIEW(dev))
6856                 vco_table = pnv_vco;
6857         else if (IS_G33(dev))
6858                 vco_table = blb_vco;
6859         else
6860                 return 0;
6861
6862         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6863
6864         vco = vco_table[tmp & 0x7];
6865         if (vco == 0)
6866                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6867         else
6868                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6869
6870         return vco;
6871 }
6872
6873 static int gm45_get_display_clock_speed(struct drm_device *dev)
6874 {
6875         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6876         uint16_t tmp = 0;
6877
6878         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6879
6880         cdclk_sel = (tmp >> 12) & 0x1;
6881
6882         switch (vco) {
6883         case 2666667:
6884         case 4000000:
6885         case 5333333:
6886                 return cdclk_sel ? 333333 : 222222;
6887         case 3200000:
6888                 return cdclk_sel ? 320000 : 228571;
6889         default:
6890                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6891                 return 222222;
6892         }
6893 }
6894
6895 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6896 {
6897         static const uint8_t div_3200[] = { 16, 10,  8 };
6898         static const uint8_t div_4000[] = { 20, 12, 10 };
6899         static const uint8_t div_5333[] = { 24, 16, 14 };
6900         const uint8_t *div_table;
6901         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6902         uint16_t tmp = 0;
6903
6904         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6905
6906         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6907
6908         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6909                 goto fail;
6910
6911         switch (vco) {
6912         case 3200000:
6913                 div_table = div_3200;
6914                 break;
6915         case 4000000:
6916                 div_table = div_4000;
6917                 break;
6918         case 5333333:
6919                 div_table = div_5333;
6920                 break;
6921         default:
6922                 goto fail;
6923         }
6924
6925         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6926
6927 fail:
6928         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6929         return 200000;
6930 }
6931
6932 static int g33_get_display_clock_speed(struct drm_device *dev)
6933 {
6934         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6935         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6936         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6937         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6938         const uint8_t *div_table;
6939         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6940         uint16_t tmp = 0;
6941
6942         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6943
6944         cdclk_sel = (tmp >> 4) & 0x7;
6945
6946         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6947                 goto fail;
6948
6949         switch (vco) {
6950         case 3200000:
6951                 div_table = div_3200;
6952                 break;
6953         case 4000000:
6954                 div_table = div_4000;
6955                 break;
6956         case 4800000:
6957                 div_table = div_4800;
6958                 break;
6959         case 5333333:
6960                 div_table = div_5333;
6961                 break;
6962         default:
6963                 goto fail;
6964         }
6965
6966         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6967
6968 fail:
6969         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6970         return 190476;
6971 }
6972
6973 static void
6974 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6975 {
6976         while (*num > DATA_LINK_M_N_MASK ||
6977                *den > DATA_LINK_M_N_MASK) {
6978                 *num >>= 1;
6979                 *den >>= 1;
6980         }
6981 }
6982
6983 static void compute_m_n(unsigned int m, unsigned int n,
6984                         uint32_t *ret_m, uint32_t *ret_n)
6985 {
6986         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6987         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6988         intel_reduce_m_n_ratio(ret_m, ret_n);
6989 }
6990
6991 void
6992 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6993                        int pixel_clock, int link_clock,
6994                        struct intel_link_m_n *m_n)
6995 {
6996         m_n->tu = 64;
6997
6998         compute_m_n(bits_per_pixel * pixel_clock,
6999                     link_clock * nlanes * 8,
7000                     &m_n->gmch_m, &m_n->gmch_n);
7001
7002         compute_m_n(pixel_clock, link_clock,
7003                     &m_n->link_m, &m_n->link_n);
7004 }
7005
7006 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7007 {
7008         if (i915.panel_use_ssc >= 0)
7009                 return i915.panel_use_ssc != 0;
7010         return dev_priv->vbt.lvds_use_ssc
7011                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7012 }
7013
7014 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7015                            int num_connectors)
7016 {
7017         struct drm_device *dev = crtc_state->base.crtc->dev;
7018         struct drm_i915_private *dev_priv = dev->dev_private;
7019         int refclk;
7020
7021         WARN_ON(!crtc_state->base.state);
7022
7023         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
7024                 refclk = 100000;
7025         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7026             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7027                 refclk = dev_priv->vbt.lvds_ssc_freq;
7028                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7029         } else if (!IS_GEN2(dev)) {
7030                 refclk = 96000;
7031         } else {
7032                 refclk = 48000;
7033         }
7034
7035         return refclk;
7036 }
7037
7038 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7039 {
7040         return (1 << dpll->n) << 16 | dpll->m2;
7041 }
7042
7043 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7044 {
7045         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7046 }
7047
7048 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7049                                      struct intel_crtc_state *crtc_state,
7050                                      intel_clock_t *reduced_clock)
7051 {
7052         struct drm_device *dev = crtc->base.dev;
7053         u32 fp, fp2 = 0;
7054
7055         if (IS_PINEVIEW(dev)) {
7056                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7057                 if (reduced_clock)
7058                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7059         } else {
7060                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7061                 if (reduced_clock)
7062                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7063         }
7064
7065         crtc_state->dpll_hw_state.fp0 = fp;
7066
7067         crtc->lowfreq_avail = false;
7068         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7069             reduced_clock) {
7070                 crtc_state->dpll_hw_state.fp1 = fp2;
7071                 crtc->lowfreq_avail = true;
7072         } else {
7073                 crtc_state->dpll_hw_state.fp1 = fp;
7074         }
7075 }
7076
7077 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7078                 pipe)
7079 {
7080         u32 reg_val;
7081
7082         /*
7083          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7084          * and set it to a reasonable value instead.
7085          */
7086         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7087         reg_val &= 0xffffff00;
7088         reg_val |= 0x00000030;
7089         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7090
7091         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7092         reg_val &= 0x8cffffff;
7093         reg_val = 0x8c000000;
7094         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7095
7096         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7097         reg_val &= 0xffffff00;
7098         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7099
7100         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7101         reg_val &= 0x00ffffff;
7102         reg_val |= 0xb0000000;
7103         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7104 }
7105
7106 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7107                                          struct intel_link_m_n *m_n)
7108 {
7109         struct drm_device *dev = crtc->base.dev;
7110         struct drm_i915_private *dev_priv = dev->dev_private;
7111         int pipe = crtc->pipe;
7112
7113         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7114         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7115         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7116         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7117 }
7118
7119 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7120                                          struct intel_link_m_n *m_n,
7121                                          struct intel_link_m_n *m2_n2)
7122 {
7123         struct drm_device *dev = crtc->base.dev;
7124         struct drm_i915_private *dev_priv = dev->dev_private;
7125         int pipe = crtc->pipe;
7126         enum transcoder transcoder = crtc->config->cpu_transcoder;
7127
7128         if (INTEL_INFO(dev)->gen >= 5) {
7129                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7130                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7131                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7132                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7133                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7134                  * for gen < 8) and if DRRS is supported (to make sure the
7135                  * registers are not unnecessarily accessed).
7136                  */
7137                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7138                         crtc->config->has_drrs) {
7139                         I915_WRITE(PIPE_DATA_M2(transcoder),
7140                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7141                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7142                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7143                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7144                 }
7145         } else {
7146                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7147                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7148                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7149                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7150         }
7151 }
7152
7153 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7154 {
7155         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7156
7157         if (m_n == M1_N1) {
7158                 dp_m_n = &crtc->config->dp_m_n;
7159                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7160         } else if (m_n == M2_N2) {
7161
7162                 /*
7163                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7164                  * needs to be programmed into M1_N1.
7165                  */
7166                 dp_m_n = &crtc->config->dp_m2_n2;
7167         } else {
7168                 DRM_ERROR("Unsupported divider value\n");
7169                 return;
7170         }
7171
7172         if (crtc->config->has_pch_encoder)
7173                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7174         else
7175                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7176 }
7177
7178 static void vlv_compute_dpll(struct intel_crtc *crtc,
7179                              struct intel_crtc_state *pipe_config)
7180 {
7181         u32 dpll, dpll_md;
7182
7183         /*
7184          * Enable DPIO clock input. We should never disable the reference
7185          * clock for pipe B, since VGA hotplug / manual detection depends
7186          * on it.
7187          */
7188         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7189                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7190         /* We should never disable this, set it here for state tracking */
7191         if (crtc->pipe == PIPE_B)
7192                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7193         dpll |= DPLL_VCO_ENABLE;
7194         pipe_config->dpll_hw_state.dpll = dpll;
7195
7196         dpll_md = (pipe_config->pixel_multiplier - 1)
7197                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7198         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7199 }
7200
7201 static void vlv_prepare_pll(struct intel_crtc *crtc,
7202                             const struct intel_crtc_state *pipe_config)
7203 {
7204         struct drm_device *dev = crtc->base.dev;
7205         struct drm_i915_private *dev_priv = dev->dev_private;
7206         int pipe = crtc->pipe;
7207         u32 mdiv;
7208         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7209         u32 coreclk, reg_val;
7210
7211         mutex_lock(&dev_priv->sb_lock);
7212
7213         bestn = pipe_config->dpll.n;
7214         bestm1 = pipe_config->dpll.m1;
7215         bestm2 = pipe_config->dpll.m2;
7216         bestp1 = pipe_config->dpll.p1;
7217         bestp2 = pipe_config->dpll.p2;
7218
7219         /* See eDP HDMI DPIO driver vbios notes doc */
7220
7221         /* PLL B needs special handling */
7222         if (pipe == PIPE_B)
7223                 vlv_pllb_recal_opamp(dev_priv, pipe);
7224
7225         /* Set up Tx target for periodic Rcomp update */
7226         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7227
7228         /* Disable target IRef on PLL */
7229         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7230         reg_val &= 0x00ffffff;
7231         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7232
7233         /* Disable fast lock */
7234         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7235
7236         /* Set idtafcrecal before PLL is enabled */
7237         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7238         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7239         mdiv |= ((bestn << DPIO_N_SHIFT));
7240         mdiv |= (1 << DPIO_K_SHIFT);
7241
7242         /*
7243          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7244          * but we don't support that).
7245          * Note: don't use the DAC post divider as it seems unstable.
7246          */
7247         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7248         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7249
7250         mdiv |= DPIO_ENABLE_CALIBRATION;
7251         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7252
7253         /* Set HBR and RBR LPF coefficients */
7254         if (pipe_config->port_clock == 162000 ||
7255             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7256             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7257                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7258                                  0x009f0003);
7259         else
7260                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7261                                  0x00d0000f);
7262
7263         if (pipe_config->has_dp_encoder) {
7264                 /* Use SSC source */
7265                 if (pipe == PIPE_A)
7266                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7267                                          0x0df40000);
7268                 else
7269                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7270                                          0x0df70000);
7271         } else { /* HDMI or VGA */
7272                 /* Use bend source */
7273                 if (pipe == PIPE_A)
7274                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7275                                          0x0df70000);
7276                 else
7277                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7278                                          0x0df40000);
7279         }
7280
7281         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7282         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7283         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7284             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7285                 coreclk |= 0x01000000;
7286         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7287
7288         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7289         mutex_unlock(&dev_priv->sb_lock);
7290 }
7291
7292 static void chv_compute_dpll(struct intel_crtc *crtc,
7293                              struct intel_crtc_state *pipe_config)
7294 {
7295         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7296                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7297                 DPLL_VCO_ENABLE;
7298         if (crtc->pipe != PIPE_A)
7299                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7300
7301         pipe_config->dpll_hw_state.dpll_md =
7302                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7303 }
7304
7305 static void chv_prepare_pll(struct intel_crtc *crtc,
7306                             const struct intel_crtc_state *pipe_config)
7307 {
7308         struct drm_device *dev = crtc->base.dev;
7309         struct drm_i915_private *dev_priv = dev->dev_private;
7310         int pipe = crtc->pipe;
7311         int dpll_reg = DPLL(crtc->pipe);
7312         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7313         u32 loopfilter, tribuf_calcntr;
7314         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7315         u32 dpio_val;
7316         int vco;
7317
7318         bestn = pipe_config->dpll.n;
7319         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7320         bestm1 = pipe_config->dpll.m1;
7321         bestm2 = pipe_config->dpll.m2 >> 22;
7322         bestp1 = pipe_config->dpll.p1;
7323         bestp2 = pipe_config->dpll.p2;
7324         vco = pipe_config->dpll.vco;
7325         dpio_val = 0;
7326         loopfilter = 0;
7327
7328         /*
7329          * Enable Refclk and SSC
7330          */
7331         I915_WRITE(dpll_reg,
7332                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7333
7334         mutex_lock(&dev_priv->sb_lock);
7335
7336         /* p1 and p2 divider */
7337         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7338                         5 << DPIO_CHV_S1_DIV_SHIFT |
7339                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7340                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7341                         1 << DPIO_CHV_K_DIV_SHIFT);
7342
7343         /* Feedback post-divider - m2 */
7344         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7345
7346         /* Feedback refclk divider - n and m1 */
7347         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7348                         DPIO_CHV_M1_DIV_BY_2 |
7349                         1 << DPIO_CHV_N_DIV_SHIFT);
7350
7351         /* M2 fraction division */
7352         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7353
7354         /* M2 fraction division enable */
7355         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7356         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7357         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7358         if (bestm2_frac)
7359                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7360         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7361
7362         /* Program digital lock detect threshold */
7363         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7364         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7365                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7366         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7367         if (!bestm2_frac)
7368                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7369         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7370
7371         /* Loop filter */
7372         if (vco == 5400000) {
7373                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7374                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7375                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7376                 tribuf_calcntr = 0x9;
7377         } else if (vco <= 6200000) {
7378                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7379                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7380                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7381                 tribuf_calcntr = 0x9;
7382         } else if (vco <= 6480000) {
7383                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7384                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7385                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7386                 tribuf_calcntr = 0x8;
7387         } else {
7388                 /* Not supported. Apply the same limits as in the max case */
7389                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7390                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7391                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7392                 tribuf_calcntr = 0;
7393         }
7394         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7395
7396         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7397         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7398         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7399         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7400
7401         /* AFC Recal */
7402         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7403                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7404                         DPIO_AFC_RECAL);
7405
7406         mutex_unlock(&dev_priv->sb_lock);
7407 }
7408
7409 /**
7410  * vlv_force_pll_on - forcibly enable just the PLL
7411  * @dev_priv: i915 private structure
7412  * @pipe: pipe PLL to enable
7413  * @dpll: PLL configuration
7414  *
7415  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7416  * in cases where we need the PLL enabled even when @pipe is not going to
7417  * be enabled.
7418  */
7419 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7420                       const struct dpll *dpll)
7421 {
7422         struct intel_crtc *crtc =
7423                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7424         struct intel_crtc_state pipe_config = {
7425                 .base.crtc = &crtc->base,
7426                 .pixel_multiplier = 1,
7427                 .dpll = *dpll,
7428         };
7429
7430         if (IS_CHERRYVIEW(dev)) {
7431                 chv_compute_dpll(crtc, &pipe_config);
7432                 chv_prepare_pll(crtc, &pipe_config);
7433                 chv_enable_pll(crtc, &pipe_config);
7434         } else {
7435                 vlv_compute_dpll(crtc, &pipe_config);
7436                 vlv_prepare_pll(crtc, &pipe_config);
7437                 vlv_enable_pll(crtc, &pipe_config);
7438         }
7439 }
7440
7441 /**
7442  * vlv_force_pll_off - forcibly disable just the PLL
7443  * @dev_priv: i915 private structure
7444  * @pipe: pipe PLL to disable
7445  *
7446  * Disable the PLL for @pipe. To be used in cases where we need
7447  * the PLL enabled even when @pipe is not going to be enabled.
7448  */
7449 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7450 {
7451         if (IS_CHERRYVIEW(dev))
7452                 chv_disable_pll(to_i915(dev), pipe);
7453         else
7454                 vlv_disable_pll(to_i915(dev), pipe);
7455 }
7456
7457 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7458                               struct intel_crtc_state *crtc_state,
7459                               intel_clock_t *reduced_clock,
7460                               int num_connectors)
7461 {
7462         struct drm_device *dev = crtc->base.dev;
7463         struct drm_i915_private *dev_priv = dev->dev_private;
7464         u32 dpll;
7465         bool is_sdvo;
7466         struct dpll *clock = &crtc_state->dpll;
7467
7468         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7469
7470         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7471                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7472
7473         dpll = DPLL_VGA_MODE_DIS;
7474
7475         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7476                 dpll |= DPLLB_MODE_LVDS;
7477         else
7478                 dpll |= DPLLB_MODE_DAC_SERIAL;
7479
7480         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7481                 dpll |= (crtc_state->pixel_multiplier - 1)
7482                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7483         }
7484
7485         if (is_sdvo)
7486                 dpll |= DPLL_SDVO_HIGH_SPEED;
7487
7488         if (crtc_state->has_dp_encoder)
7489                 dpll |= DPLL_SDVO_HIGH_SPEED;
7490
7491         /* compute bitmask from p1 value */
7492         if (IS_PINEVIEW(dev))
7493                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7494         else {
7495                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7496                 if (IS_G4X(dev) && reduced_clock)
7497                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7498         }
7499         switch (clock->p2) {
7500         case 5:
7501                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7502                 break;
7503         case 7:
7504                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7505                 break;
7506         case 10:
7507                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7508                 break;
7509         case 14:
7510                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7511                 break;
7512         }
7513         if (INTEL_INFO(dev)->gen >= 4)
7514                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7515
7516         if (crtc_state->sdvo_tv_clock)
7517                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7518         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7519                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7520                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7521         else
7522                 dpll |= PLL_REF_INPUT_DREFCLK;
7523
7524         dpll |= DPLL_VCO_ENABLE;
7525         crtc_state->dpll_hw_state.dpll = dpll;
7526
7527         if (INTEL_INFO(dev)->gen >= 4) {
7528                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7529                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7530                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7531         }
7532 }
7533
7534 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7535                               struct intel_crtc_state *crtc_state,
7536                               intel_clock_t *reduced_clock,
7537                               int num_connectors)
7538 {
7539         struct drm_device *dev = crtc->base.dev;
7540         struct drm_i915_private *dev_priv = dev->dev_private;
7541         u32 dpll;
7542         struct dpll *clock = &crtc_state->dpll;
7543
7544         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7545
7546         dpll = DPLL_VGA_MODE_DIS;
7547
7548         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7549                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7550         } else {
7551                 if (clock->p1 == 2)
7552                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7553                 else
7554                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7555                 if (clock->p2 == 4)
7556                         dpll |= PLL_P2_DIVIDE_BY_4;
7557         }
7558
7559         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7560                 dpll |= DPLL_DVO_2X_MODE;
7561
7562         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7563                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7564                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7565         else
7566                 dpll |= PLL_REF_INPUT_DREFCLK;
7567
7568         dpll |= DPLL_VCO_ENABLE;
7569         crtc_state->dpll_hw_state.dpll = dpll;
7570 }
7571
7572 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7573 {
7574         struct drm_device *dev = intel_crtc->base.dev;
7575         struct drm_i915_private *dev_priv = dev->dev_private;
7576         enum pipe pipe = intel_crtc->pipe;
7577         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7578         struct drm_display_mode *adjusted_mode =
7579                 &intel_crtc->config->base.adjusted_mode;
7580         uint32_t crtc_vtotal, crtc_vblank_end;
7581         int vsyncshift = 0;
7582
7583         /* We need to be careful not to changed the adjusted mode, for otherwise
7584          * the hw state checker will get angry at the mismatch. */
7585         crtc_vtotal = adjusted_mode->crtc_vtotal;
7586         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7587
7588         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7589                 /* the chip adds 2 halflines automatically */
7590                 crtc_vtotal -= 1;
7591                 crtc_vblank_end -= 1;
7592
7593                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7594                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7595                 else
7596                         vsyncshift = adjusted_mode->crtc_hsync_start -
7597                                 adjusted_mode->crtc_htotal / 2;
7598                 if (vsyncshift < 0)
7599                         vsyncshift += adjusted_mode->crtc_htotal;
7600         }
7601
7602         if (INTEL_INFO(dev)->gen > 3)
7603                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7604
7605         I915_WRITE(HTOTAL(cpu_transcoder),
7606                    (adjusted_mode->crtc_hdisplay - 1) |
7607                    ((adjusted_mode->crtc_htotal - 1) << 16));
7608         I915_WRITE(HBLANK(cpu_transcoder),
7609                    (adjusted_mode->crtc_hblank_start - 1) |
7610                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7611         I915_WRITE(HSYNC(cpu_transcoder),
7612                    (adjusted_mode->crtc_hsync_start - 1) |
7613                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7614
7615         I915_WRITE(VTOTAL(cpu_transcoder),
7616                    (adjusted_mode->crtc_vdisplay - 1) |
7617                    ((crtc_vtotal - 1) << 16));
7618         I915_WRITE(VBLANK(cpu_transcoder),
7619                    (adjusted_mode->crtc_vblank_start - 1) |
7620                    ((crtc_vblank_end - 1) << 16));
7621         I915_WRITE(VSYNC(cpu_transcoder),
7622                    (adjusted_mode->crtc_vsync_start - 1) |
7623                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7624
7625         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7626          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7627          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7628          * bits. */
7629         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7630             (pipe == PIPE_B || pipe == PIPE_C))
7631                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7632
7633         /* pipesrc controls the size that is scaled from, which should
7634          * always be the user's requested size.
7635          */
7636         I915_WRITE(PIPESRC(pipe),
7637                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7638                    (intel_crtc->config->pipe_src_h - 1));
7639 }
7640
7641 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7642                                    struct intel_crtc_state *pipe_config)
7643 {
7644         struct drm_device *dev = crtc->base.dev;
7645         struct drm_i915_private *dev_priv = dev->dev_private;
7646         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7647         uint32_t tmp;
7648
7649         tmp = I915_READ(HTOTAL(cpu_transcoder));
7650         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7651         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7652         tmp = I915_READ(HBLANK(cpu_transcoder));
7653         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7654         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7655         tmp = I915_READ(HSYNC(cpu_transcoder));
7656         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7657         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7658
7659         tmp = I915_READ(VTOTAL(cpu_transcoder));
7660         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7661         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7662         tmp = I915_READ(VBLANK(cpu_transcoder));
7663         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7664         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7665         tmp = I915_READ(VSYNC(cpu_transcoder));
7666         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7667         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7668
7669         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7670                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7671                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7672                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7673         }
7674
7675         tmp = I915_READ(PIPESRC(crtc->pipe));
7676         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7677         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7678
7679         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7680         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7681 }
7682
7683 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7684                                  struct intel_crtc_state *pipe_config)
7685 {
7686         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7687         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7688         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7689         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7690
7691         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7692         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7693         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7694         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7695
7696         mode->flags = pipe_config->base.adjusted_mode.flags;
7697         mode->type = DRM_MODE_TYPE_DRIVER;
7698
7699         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7700         mode->flags |= pipe_config->base.adjusted_mode.flags;
7701
7702         mode->hsync = drm_mode_hsync(mode);
7703         mode->vrefresh = drm_mode_vrefresh(mode);
7704         drm_mode_set_name(mode);
7705 }
7706
7707 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7708 {
7709         struct drm_device *dev = intel_crtc->base.dev;
7710         struct drm_i915_private *dev_priv = dev->dev_private;
7711         uint32_t pipeconf;
7712
7713         pipeconf = 0;
7714
7715         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7716             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7717                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7718
7719         if (intel_crtc->config->double_wide)
7720                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7721
7722         /* only g4x and later have fancy bpc/dither controls */
7723         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7724                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7725                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7726                         pipeconf |= PIPECONF_DITHER_EN |
7727                                     PIPECONF_DITHER_TYPE_SP;
7728
7729                 switch (intel_crtc->config->pipe_bpp) {
7730                 case 18:
7731                         pipeconf |= PIPECONF_6BPC;
7732                         break;
7733                 case 24:
7734                         pipeconf |= PIPECONF_8BPC;
7735                         break;
7736                 case 30:
7737                         pipeconf |= PIPECONF_10BPC;
7738                         break;
7739                 default:
7740                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7741                         BUG();
7742                 }
7743         }
7744
7745         if (HAS_PIPE_CXSR(dev)) {
7746                 if (intel_crtc->lowfreq_avail) {
7747                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7748                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7749                 } else {
7750                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7751                 }
7752         }
7753
7754         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7755                 if (INTEL_INFO(dev)->gen < 4 ||
7756                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7757                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7758                 else
7759                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7760         } else
7761                 pipeconf |= PIPECONF_PROGRESSIVE;
7762
7763         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
7764                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7765
7766         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7767         POSTING_READ(PIPECONF(intel_crtc->pipe));
7768 }
7769
7770 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7771                                    struct intel_crtc_state *crtc_state)
7772 {
7773         struct drm_device *dev = crtc->base.dev;
7774         struct drm_i915_private *dev_priv = dev->dev_private;
7775         int refclk, num_connectors = 0;
7776         intel_clock_t clock;
7777         bool ok;
7778         bool is_dsi = false;
7779         struct intel_encoder *encoder;
7780         const intel_limit_t *limit;
7781         struct drm_atomic_state *state = crtc_state->base.state;
7782         struct drm_connector *connector;
7783         struct drm_connector_state *connector_state;
7784         int i;
7785
7786         memset(&crtc_state->dpll_hw_state, 0,
7787                sizeof(crtc_state->dpll_hw_state));
7788
7789         for_each_connector_in_state(state, connector, connector_state, i) {
7790                 if (connector_state->crtc != &crtc->base)
7791                         continue;
7792
7793                 encoder = to_intel_encoder(connector_state->best_encoder);
7794
7795                 switch (encoder->type) {
7796                 case INTEL_OUTPUT_DSI:
7797                         is_dsi = true;
7798                         break;
7799                 default:
7800                         break;
7801                 }
7802
7803                 num_connectors++;
7804         }
7805
7806         if (is_dsi)
7807                 return 0;
7808
7809         if (!crtc_state->clock_set) {
7810                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7811
7812                 /*
7813                  * Returns a set of divisors for the desired target clock with
7814                  * the given refclk, or FALSE.  The returned values represent
7815                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7816                  * 2) / p1 / p2.
7817                  */
7818                 limit = intel_limit(crtc_state, refclk);
7819                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7820                                                  crtc_state->port_clock,
7821                                                  refclk, NULL, &clock);
7822                 if (!ok) {
7823                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7824                         return -EINVAL;
7825                 }
7826
7827                 /* Compat-code for transition, will disappear. */
7828                 crtc_state->dpll.n = clock.n;
7829                 crtc_state->dpll.m1 = clock.m1;
7830                 crtc_state->dpll.m2 = clock.m2;
7831                 crtc_state->dpll.p1 = clock.p1;
7832                 crtc_state->dpll.p2 = clock.p2;
7833         }
7834
7835         if (IS_GEN2(dev)) {
7836                 i8xx_compute_dpll(crtc, crtc_state, NULL,
7837                                   num_connectors);
7838         } else if (IS_CHERRYVIEW(dev)) {
7839                 chv_compute_dpll(crtc, crtc_state);
7840         } else if (IS_VALLEYVIEW(dev)) {
7841                 vlv_compute_dpll(crtc, crtc_state);
7842         } else {
7843                 i9xx_compute_dpll(crtc, crtc_state, NULL,
7844                                   num_connectors);
7845         }
7846
7847         return 0;
7848 }
7849
7850 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7851                                  struct intel_crtc_state *pipe_config)
7852 {
7853         struct drm_device *dev = crtc->base.dev;
7854         struct drm_i915_private *dev_priv = dev->dev_private;
7855         uint32_t tmp;
7856
7857         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7858                 return;
7859
7860         tmp = I915_READ(PFIT_CONTROL);
7861         if (!(tmp & PFIT_ENABLE))
7862                 return;
7863
7864         /* Check whether the pfit is attached to our pipe. */
7865         if (INTEL_INFO(dev)->gen < 4) {
7866                 if (crtc->pipe != PIPE_B)
7867                         return;
7868         } else {
7869                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7870                         return;
7871         }
7872
7873         pipe_config->gmch_pfit.control = tmp;
7874         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7875         if (INTEL_INFO(dev)->gen < 5)
7876                 pipe_config->gmch_pfit.lvds_border_bits =
7877                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7878 }
7879
7880 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7881                                struct intel_crtc_state *pipe_config)
7882 {
7883         struct drm_device *dev = crtc->base.dev;
7884         struct drm_i915_private *dev_priv = dev->dev_private;
7885         int pipe = pipe_config->cpu_transcoder;
7886         intel_clock_t clock;
7887         u32 mdiv;
7888         int refclk = 100000;
7889
7890         /* In case of MIPI DPLL will not even be used */
7891         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7892                 return;
7893
7894         mutex_lock(&dev_priv->sb_lock);
7895         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7896         mutex_unlock(&dev_priv->sb_lock);
7897
7898         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7899         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7900         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7901         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7902         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7903
7904         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7905 }
7906
7907 static void
7908 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7909                               struct intel_initial_plane_config *plane_config)
7910 {
7911         struct drm_device *dev = crtc->base.dev;
7912         struct drm_i915_private *dev_priv = dev->dev_private;
7913         u32 val, base, offset;
7914         int pipe = crtc->pipe, plane = crtc->plane;
7915         int fourcc, pixel_format;
7916         unsigned int aligned_height;
7917         struct drm_framebuffer *fb;
7918         struct intel_framebuffer *intel_fb;
7919
7920         val = I915_READ(DSPCNTR(plane));
7921         if (!(val & DISPLAY_PLANE_ENABLE))
7922                 return;
7923
7924         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7925         if (!intel_fb) {
7926                 DRM_DEBUG_KMS("failed to alloc fb\n");
7927                 return;
7928         }
7929
7930         fb = &intel_fb->base;
7931
7932         if (INTEL_INFO(dev)->gen >= 4) {
7933                 if (val & DISPPLANE_TILED) {
7934                         plane_config->tiling = I915_TILING_X;
7935                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7936                 }
7937         }
7938
7939         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7940         fourcc = i9xx_format_to_fourcc(pixel_format);
7941         fb->pixel_format = fourcc;
7942         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7943
7944         if (INTEL_INFO(dev)->gen >= 4) {
7945                 if (plane_config->tiling)
7946                         offset = I915_READ(DSPTILEOFF(plane));
7947                 else
7948                         offset = I915_READ(DSPLINOFF(plane));
7949                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7950         } else {
7951                 base = I915_READ(DSPADDR(plane));
7952         }
7953         plane_config->base = base;
7954
7955         val = I915_READ(PIPESRC(pipe));
7956         fb->width = ((val >> 16) & 0xfff) + 1;
7957         fb->height = ((val >> 0) & 0xfff) + 1;
7958
7959         val = I915_READ(DSPSTRIDE(pipe));
7960         fb->pitches[0] = val & 0xffffffc0;
7961
7962         aligned_height = intel_fb_align_height(dev, fb->height,
7963                                                fb->pixel_format,
7964                                                fb->modifier[0]);
7965
7966         plane_config->size = fb->pitches[0] * aligned_height;
7967
7968         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7969                       pipe_name(pipe), plane, fb->width, fb->height,
7970                       fb->bits_per_pixel, base, fb->pitches[0],
7971                       plane_config->size);
7972
7973         plane_config->fb = intel_fb;
7974 }
7975
7976 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7977                                struct intel_crtc_state *pipe_config)
7978 {
7979         struct drm_device *dev = crtc->base.dev;
7980         struct drm_i915_private *dev_priv = dev->dev_private;
7981         int pipe = pipe_config->cpu_transcoder;
7982         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7983         intel_clock_t clock;
7984         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7985         int refclk = 100000;
7986
7987         mutex_lock(&dev_priv->sb_lock);
7988         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7989         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7990         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7991         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7992         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7993         mutex_unlock(&dev_priv->sb_lock);
7994
7995         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7996         clock.m2 = (pll_dw0 & 0xff) << 22;
7997         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7998                 clock.m2 |= pll_dw2 & 0x3fffff;
7999         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8000         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8001         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8002
8003         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8004 }
8005
8006 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8007                                  struct intel_crtc_state *pipe_config)
8008 {
8009         struct drm_device *dev = crtc->base.dev;
8010         struct drm_i915_private *dev_priv = dev->dev_private;
8011         uint32_t tmp;
8012
8013         if (!intel_display_power_is_enabled(dev_priv,
8014                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8015                 return false;
8016
8017         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8018         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8019
8020         tmp = I915_READ(PIPECONF(crtc->pipe));
8021         if (!(tmp & PIPECONF_ENABLE))
8022                 return false;
8023
8024         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
8025                 switch (tmp & PIPECONF_BPC_MASK) {
8026                 case PIPECONF_6BPC:
8027                         pipe_config->pipe_bpp = 18;
8028                         break;
8029                 case PIPECONF_8BPC:
8030                         pipe_config->pipe_bpp = 24;
8031                         break;
8032                 case PIPECONF_10BPC:
8033                         pipe_config->pipe_bpp = 30;
8034                         break;
8035                 default:
8036                         break;
8037                 }
8038         }
8039
8040         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
8041                 pipe_config->limited_color_range = true;
8042
8043         if (INTEL_INFO(dev)->gen < 4)
8044                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8045
8046         intel_get_pipe_timings(crtc, pipe_config);
8047
8048         i9xx_get_pfit_config(crtc, pipe_config);
8049
8050         if (INTEL_INFO(dev)->gen >= 4) {
8051                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8052                 pipe_config->pixel_multiplier =
8053                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8054                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8055                 pipe_config->dpll_hw_state.dpll_md = tmp;
8056         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8057                 tmp = I915_READ(DPLL(crtc->pipe));
8058                 pipe_config->pixel_multiplier =
8059                         ((tmp & SDVO_MULTIPLIER_MASK)
8060                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8061         } else {
8062                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8063                  * port and will be fixed up in the encoder->get_config
8064                  * function. */
8065                 pipe_config->pixel_multiplier = 1;
8066         }
8067         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8068         if (!IS_VALLEYVIEW(dev)) {
8069                 /*
8070                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8071                  * on 830. Filter it out here so that we don't
8072                  * report errors due to that.
8073                  */
8074                 if (IS_I830(dev))
8075                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8076
8077                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8078                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8079         } else {
8080                 /* Mask out read-only status bits. */
8081                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8082                                                      DPLL_PORTC_READY_MASK |
8083                                                      DPLL_PORTB_READY_MASK);
8084         }
8085
8086         if (IS_CHERRYVIEW(dev))
8087                 chv_crtc_clock_get(crtc, pipe_config);
8088         else if (IS_VALLEYVIEW(dev))
8089                 vlv_crtc_clock_get(crtc, pipe_config);
8090         else
8091                 i9xx_crtc_clock_get(crtc, pipe_config);
8092
8093         /*
8094          * Normally the dotclock is filled in by the encoder .get_config()
8095          * but in case the pipe is enabled w/o any ports we need a sane
8096          * default.
8097          */
8098         pipe_config->base.adjusted_mode.crtc_clock =
8099                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8100
8101         return true;
8102 }
8103
8104 static void ironlake_init_pch_refclk(struct drm_device *dev)
8105 {
8106         struct drm_i915_private *dev_priv = dev->dev_private;
8107         struct intel_encoder *encoder;
8108         u32 val, final;
8109         bool has_lvds = false;
8110         bool has_cpu_edp = false;
8111         bool has_panel = false;
8112         bool has_ck505 = false;
8113         bool can_ssc = false;
8114
8115         /* We need to take the global config into account */
8116         for_each_intel_encoder(dev, encoder) {
8117                 switch (encoder->type) {
8118                 case INTEL_OUTPUT_LVDS:
8119                         has_panel = true;
8120                         has_lvds = true;
8121                         break;
8122                 case INTEL_OUTPUT_EDP:
8123                         has_panel = true;
8124                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8125                                 has_cpu_edp = true;
8126                         break;
8127                 default:
8128                         break;
8129                 }
8130         }
8131
8132         if (HAS_PCH_IBX(dev)) {
8133                 has_ck505 = dev_priv->vbt.display_clock_mode;
8134                 can_ssc = has_ck505;
8135         } else {
8136                 has_ck505 = false;
8137                 can_ssc = true;
8138         }
8139
8140         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8141                       has_panel, has_lvds, has_ck505);
8142
8143         /* Ironlake: try to setup display ref clock before DPLL
8144          * enabling. This is only under driver's control after
8145          * PCH B stepping, previous chipset stepping should be
8146          * ignoring this setting.
8147          */
8148         val = I915_READ(PCH_DREF_CONTROL);
8149
8150         /* As we must carefully and slowly disable/enable each source in turn,
8151          * compute the final state we want first and check if we need to
8152          * make any changes at all.
8153          */
8154         final = val;
8155         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8156         if (has_ck505)
8157                 final |= DREF_NONSPREAD_CK505_ENABLE;
8158         else
8159                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8160
8161         final &= ~DREF_SSC_SOURCE_MASK;
8162         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8163         final &= ~DREF_SSC1_ENABLE;
8164
8165         if (has_panel) {
8166                 final |= DREF_SSC_SOURCE_ENABLE;
8167
8168                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8169                         final |= DREF_SSC1_ENABLE;
8170
8171                 if (has_cpu_edp) {
8172                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8173                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8174                         else
8175                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8176                 } else
8177                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8178         } else {
8179                 final |= DREF_SSC_SOURCE_DISABLE;
8180                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8181         }
8182
8183         if (final == val)
8184                 return;
8185
8186         /* Always enable nonspread source */
8187         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8188
8189         if (has_ck505)
8190                 val |= DREF_NONSPREAD_CK505_ENABLE;
8191         else
8192                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8193
8194         if (has_panel) {
8195                 val &= ~DREF_SSC_SOURCE_MASK;
8196                 val |= DREF_SSC_SOURCE_ENABLE;
8197
8198                 /* SSC must be turned on before enabling the CPU output  */
8199                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8200                         DRM_DEBUG_KMS("Using SSC on panel\n");
8201                         val |= DREF_SSC1_ENABLE;
8202                 } else
8203                         val &= ~DREF_SSC1_ENABLE;
8204
8205                 /* Get SSC going before enabling the outputs */
8206                 I915_WRITE(PCH_DREF_CONTROL, val);
8207                 POSTING_READ(PCH_DREF_CONTROL);
8208                 udelay(200);
8209
8210                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8211
8212                 /* Enable CPU source on CPU attached eDP */
8213                 if (has_cpu_edp) {
8214                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8215                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8216                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8217                         } else
8218                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8219                 } else
8220                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8221
8222                 I915_WRITE(PCH_DREF_CONTROL, val);
8223                 POSTING_READ(PCH_DREF_CONTROL);
8224                 udelay(200);
8225         } else {
8226                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8227
8228                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8229
8230                 /* Turn off CPU output */
8231                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8232
8233                 I915_WRITE(PCH_DREF_CONTROL, val);
8234                 POSTING_READ(PCH_DREF_CONTROL);
8235                 udelay(200);
8236
8237                 /* Turn off the SSC source */
8238                 val &= ~DREF_SSC_SOURCE_MASK;
8239                 val |= DREF_SSC_SOURCE_DISABLE;
8240
8241                 /* Turn off SSC1 */
8242                 val &= ~DREF_SSC1_ENABLE;
8243
8244                 I915_WRITE(PCH_DREF_CONTROL, val);
8245                 POSTING_READ(PCH_DREF_CONTROL);
8246                 udelay(200);
8247         }
8248
8249         BUG_ON(val != final);
8250 }
8251
8252 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8253 {
8254         uint32_t tmp;
8255
8256         tmp = I915_READ(SOUTH_CHICKEN2);
8257         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8258         I915_WRITE(SOUTH_CHICKEN2, tmp);
8259
8260         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8261                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8262                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8263
8264         tmp = I915_READ(SOUTH_CHICKEN2);
8265         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8266         I915_WRITE(SOUTH_CHICKEN2, tmp);
8267
8268         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8269                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8270                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8271 }
8272
8273 /* WaMPhyProgramming:hsw */
8274 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8275 {
8276         uint32_t tmp;
8277
8278         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8279         tmp &= ~(0xFF << 24);
8280         tmp |= (0x12 << 24);
8281         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8282
8283         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8284         tmp |= (1 << 11);
8285         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8286
8287         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8288         tmp |= (1 << 11);
8289         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8290
8291         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8292         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8293         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8294
8295         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8296         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8297         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8298
8299         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8300         tmp &= ~(7 << 13);
8301         tmp |= (5 << 13);
8302         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8303
8304         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8305         tmp &= ~(7 << 13);
8306         tmp |= (5 << 13);
8307         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8308
8309         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8310         tmp &= ~0xFF;
8311         tmp |= 0x1C;
8312         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8313
8314         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8315         tmp &= ~0xFF;
8316         tmp |= 0x1C;
8317         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8318
8319         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8320         tmp &= ~(0xFF << 16);
8321         tmp |= (0x1C << 16);
8322         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8323
8324         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8325         tmp &= ~(0xFF << 16);
8326         tmp |= (0x1C << 16);
8327         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8328
8329         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8330         tmp |= (1 << 27);
8331         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8332
8333         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8334         tmp |= (1 << 27);
8335         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8336
8337         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8338         tmp &= ~(0xF << 28);
8339         tmp |= (4 << 28);
8340         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8341
8342         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8343         tmp &= ~(0xF << 28);
8344         tmp |= (4 << 28);
8345         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8346 }
8347
8348 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8349  * Programming" based on the parameters passed:
8350  * - Sequence to enable CLKOUT_DP
8351  * - Sequence to enable CLKOUT_DP without spread
8352  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8353  */
8354 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8355                                  bool with_fdi)
8356 {
8357         struct drm_i915_private *dev_priv = dev->dev_private;
8358         uint32_t reg, tmp;
8359
8360         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8361                 with_spread = true;
8362         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
8363                  with_fdi, "LP PCH doesn't have FDI\n"))
8364                 with_fdi = false;
8365
8366         mutex_lock(&dev_priv->sb_lock);
8367
8368         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8369         tmp &= ~SBI_SSCCTL_DISABLE;
8370         tmp |= SBI_SSCCTL_PATHALT;
8371         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8372
8373         udelay(24);
8374
8375         if (with_spread) {
8376                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8377                 tmp &= ~SBI_SSCCTL_PATHALT;
8378                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8379
8380                 if (with_fdi) {
8381                         lpt_reset_fdi_mphy(dev_priv);
8382                         lpt_program_fdi_mphy(dev_priv);
8383                 }
8384         }
8385
8386         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8387                SBI_GEN0 : SBI_DBUFF0;
8388         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8389         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8390         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8391
8392         mutex_unlock(&dev_priv->sb_lock);
8393 }
8394
8395 /* Sequence to disable CLKOUT_DP */
8396 static void lpt_disable_clkout_dp(struct drm_device *dev)
8397 {
8398         struct drm_i915_private *dev_priv = dev->dev_private;
8399         uint32_t reg, tmp;
8400
8401         mutex_lock(&dev_priv->sb_lock);
8402
8403         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8404                SBI_GEN0 : SBI_DBUFF0;
8405         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8406         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8407         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8408
8409         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8410         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8411                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8412                         tmp |= SBI_SSCCTL_PATHALT;
8413                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8414                         udelay(32);
8415                 }
8416                 tmp |= SBI_SSCCTL_DISABLE;
8417                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8418         }
8419
8420         mutex_unlock(&dev_priv->sb_lock);
8421 }
8422
8423 static void lpt_init_pch_refclk(struct drm_device *dev)
8424 {
8425         struct intel_encoder *encoder;
8426         bool has_vga = false;
8427
8428         for_each_intel_encoder(dev, encoder) {
8429                 switch (encoder->type) {
8430                 case INTEL_OUTPUT_ANALOG:
8431                         has_vga = true;
8432                         break;
8433                 default:
8434                         break;
8435                 }
8436         }
8437
8438         if (has_vga)
8439                 lpt_enable_clkout_dp(dev, true, true);
8440         else
8441                 lpt_disable_clkout_dp(dev);
8442 }
8443
8444 /*
8445  * Initialize reference clocks when the driver loads
8446  */
8447 void intel_init_pch_refclk(struct drm_device *dev)
8448 {
8449         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8450                 ironlake_init_pch_refclk(dev);
8451         else if (HAS_PCH_LPT(dev))
8452                 lpt_init_pch_refclk(dev);
8453 }
8454
8455 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8456 {
8457         struct drm_device *dev = crtc_state->base.crtc->dev;
8458         struct drm_i915_private *dev_priv = dev->dev_private;
8459         struct drm_atomic_state *state = crtc_state->base.state;
8460         struct drm_connector *connector;
8461         struct drm_connector_state *connector_state;
8462         struct intel_encoder *encoder;
8463         int num_connectors = 0, i;
8464         bool is_lvds = false;
8465
8466         for_each_connector_in_state(state, connector, connector_state, i) {
8467                 if (connector_state->crtc != crtc_state->base.crtc)
8468                         continue;
8469
8470                 encoder = to_intel_encoder(connector_state->best_encoder);
8471
8472                 switch (encoder->type) {
8473                 case INTEL_OUTPUT_LVDS:
8474                         is_lvds = true;
8475                         break;
8476                 default:
8477                         break;
8478                 }
8479                 num_connectors++;
8480         }
8481
8482         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8483                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8484                               dev_priv->vbt.lvds_ssc_freq);
8485                 return dev_priv->vbt.lvds_ssc_freq;
8486         }
8487
8488         return 120000;
8489 }
8490
8491 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8492 {
8493         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8494         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8495         int pipe = intel_crtc->pipe;
8496         uint32_t val;
8497
8498         val = 0;
8499
8500         switch (intel_crtc->config->pipe_bpp) {
8501         case 18:
8502                 val |= PIPECONF_6BPC;
8503                 break;
8504         case 24:
8505                 val |= PIPECONF_8BPC;
8506                 break;
8507         case 30:
8508                 val |= PIPECONF_10BPC;
8509                 break;
8510         case 36:
8511                 val |= PIPECONF_12BPC;
8512                 break;
8513         default:
8514                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8515                 BUG();
8516         }
8517
8518         if (intel_crtc->config->dither)
8519                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8520
8521         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8522                 val |= PIPECONF_INTERLACED_ILK;
8523         else
8524                 val |= PIPECONF_PROGRESSIVE;
8525
8526         if (intel_crtc->config->limited_color_range)
8527                 val |= PIPECONF_COLOR_RANGE_SELECT;
8528
8529         I915_WRITE(PIPECONF(pipe), val);
8530         POSTING_READ(PIPECONF(pipe));
8531 }
8532
8533 /*
8534  * Set up the pipe CSC unit.
8535  *
8536  * Currently only full range RGB to limited range RGB conversion
8537  * is supported, but eventually this should handle various
8538  * RGB<->YCbCr scenarios as well.
8539  */
8540 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8541 {
8542         struct drm_device *dev = crtc->dev;
8543         struct drm_i915_private *dev_priv = dev->dev_private;
8544         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8545         int pipe = intel_crtc->pipe;
8546         uint16_t coeff = 0x7800; /* 1.0 */
8547
8548         /*
8549          * TODO: Check what kind of values actually come out of the pipe
8550          * with these coeff/postoff values and adjust to get the best
8551          * accuracy. Perhaps we even need to take the bpc value into
8552          * consideration.
8553          */
8554
8555         if (intel_crtc->config->limited_color_range)
8556                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8557
8558         /*
8559          * GY/GU and RY/RU should be the other way around according
8560          * to BSpec, but reality doesn't agree. Just set them up in
8561          * a way that results in the correct picture.
8562          */
8563         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8564         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8565
8566         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8567         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8568
8569         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8570         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8571
8572         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8573         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8574         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8575
8576         if (INTEL_INFO(dev)->gen > 6) {
8577                 uint16_t postoff = 0;
8578
8579                 if (intel_crtc->config->limited_color_range)
8580                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8581
8582                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8583                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8584                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8585
8586                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8587         } else {
8588                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8589
8590                 if (intel_crtc->config->limited_color_range)
8591                         mode |= CSC_BLACK_SCREEN_OFFSET;
8592
8593                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8594         }
8595 }
8596
8597 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8598 {
8599         struct drm_device *dev = crtc->dev;
8600         struct drm_i915_private *dev_priv = dev->dev_private;
8601         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8602         enum pipe pipe = intel_crtc->pipe;
8603         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8604         uint32_t val;
8605
8606         val = 0;
8607
8608         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8609                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8610
8611         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8612                 val |= PIPECONF_INTERLACED_ILK;
8613         else
8614                 val |= PIPECONF_PROGRESSIVE;
8615
8616         I915_WRITE(PIPECONF(cpu_transcoder), val);
8617         POSTING_READ(PIPECONF(cpu_transcoder));
8618
8619         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8620         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8621
8622         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8623                 val = 0;
8624
8625                 switch (intel_crtc->config->pipe_bpp) {
8626                 case 18:
8627                         val |= PIPEMISC_DITHER_6_BPC;
8628                         break;
8629                 case 24:
8630                         val |= PIPEMISC_DITHER_8_BPC;
8631                         break;
8632                 case 30:
8633                         val |= PIPEMISC_DITHER_10_BPC;
8634                         break;
8635                 case 36:
8636                         val |= PIPEMISC_DITHER_12_BPC;
8637                         break;
8638                 default:
8639                         /* Case prevented by pipe_config_set_bpp. */
8640                         BUG();
8641                 }
8642
8643                 if (intel_crtc->config->dither)
8644                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8645
8646                 I915_WRITE(PIPEMISC(pipe), val);
8647         }
8648 }
8649
8650 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8651                                     struct intel_crtc_state *crtc_state,
8652                                     intel_clock_t *clock,
8653                                     bool *has_reduced_clock,
8654                                     intel_clock_t *reduced_clock)
8655 {
8656         struct drm_device *dev = crtc->dev;
8657         struct drm_i915_private *dev_priv = dev->dev_private;
8658         int refclk;
8659         const intel_limit_t *limit;
8660         bool ret;
8661
8662         refclk = ironlake_get_refclk(crtc_state);
8663
8664         /*
8665          * Returns a set of divisors for the desired target clock with the given
8666          * refclk, or FALSE.  The returned values represent the clock equation:
8667          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8668          */
8669         limit = intel_limit(crtc_state, refclk);
8670         ret = dev_priv->display.find_dpll(limit, crtc_state,
8671                                           crtc_state->port_clock,
8672                                           refclk, NULL, clock);
8673         if (!ret)
8674                 return false;
8675
8676         return true;
8677 }
8678
8679 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8680 {
8681         /*
8682          * Account for spread spectrum to avoid
8683          * oversubscribing the link. Max center spread
8684          * is 2.5%; use 5% for safety's sake.
8685          */
8686         u32 bps = target_clock * bpp * 21 / 20;
8687         return DIV_ROUND_UP(bps, link_bw * 8);
8688 }
8689
8690 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8691 {
8692         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8693 }
8694
8695 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8696                                       struct intel_crtc_state *crtc_state,
8697                                       u32 *fp,
8698                                       intel_clock_t *reduced_clock, u32 *fp2)
8699 {
8700         struct drm_crtc *crtc = &intel_crtc->base;
8701         struct drm_device *dev = crtc->dev;
8702         struct drm_i915_private *dev_priv = dev->dev_private;
8703         struct drm_atomic_state *state = crtc_state->base.state;
8704         struct drm_connector *connector;
8705         struct drm_connector_state *connector_state;
8706         struct intel_encoder *encoder;
8707         uint32_t dpll;
8708         int factor, num_connectors = 0, i;
8709         bool is_lvds = false, is_sdvo = false;
8710
8711         for_each_connector_in_state(state, connector, connector_state, i) {
8712                 if (connector_state->crtc != crtc_state->base.crtc)
8713                         continue;
8714
8715                 encoder = to_intel_encoder(connector_state->best_encoder);
8716
8717                 switch (encoder->type) {
8718                 case INTEL_OUTPUT_LVDS:
8719                         is_lvds = true;
8720                         break;
8721                 case INTEL_OUTPUT_SDVO:
8722                 case INTEL_OUTPUT_HDMI:
8723                         is_sdvo = true;
8724                         break;
8725                 default:
8726                         break;
8727                 }
8728
8729                 num_connectors++;
8730         }
8731
8732         /* Enable autotuning of the PLL clock (if permissible) */
8733         factor = 21;
8734         if (is_lvds) {
8735                 if ((intel_panel_use_ssc(dev_priv) &&
8736                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8737                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8738                         factor = 25;
8739         } else if (crtc_state->sdvo_tv_clock)
8740                 factor = 20;
8741
8742         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8743                 *fp |= FP_CB_TUNE;
8744
8745         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8746                 *fp2 |= FP_CB_TUNE;
8747
8748         dpll = 0;
8749
8750         if (is_lvds)
8751                 dpll |= DPLLB_MODE_LVDS;
8752         else
8753                 dpll |= DPLLB_MODE_DAC_SERIAL;
8754
8755         dpll |= (crtc_state->pixel_multiplier - 1)
8756                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8757
8758         if (is_sdvo)
8759                 dpll |= DPLL_SDVO_HIGH_SPEED;
8760         if (crtc_state->has_dp_encoder)
8761                 dpll |= DPLL_SDVO_HIGH_SPEED;
8762
8763         /* compute bitmask from p1 value */
8764         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8765         /* also FPA1 */
8766         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8767
8768         switch (crtc_state->dpll.p2) {
8769         case 5:
8770                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8771                 break;
8772         case 7:
8773                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8774                 break;
8775         case 10:
8776                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8777                 break;
8778         case 14:
8779                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8780                 break;
8781         }
8782
8783         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8784                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8785         else
8786                 dpll |= PLL_REF_INPUT_DREFCLK;
8787
8788         return dpll | DPLL_VCO_ENABLE;
8789 }
8790
8791 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8792                                        struct intel_crtc_state *crtc_state)
8793 {
8794         struct drm_device *dev = crtc->base.dev;
8795         intel_clock_t clock, reduced_clock;
8796         u32 dpll = 0, fp = 0, fp2 = 0;
8797         bool ok, has_reduced_clock = false;
8798         bool is_lvds = false;
8799         struct intel_shared_dpll *pll;
8800
8801         memset(&crtc_state->dpll_hw_state, 0,
8802                sizeof(crtc_state->dpll_hw_state));
8803
8804         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
8805
8806         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8807              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8808
8809         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8810                                      &has_reduced_clock, &reduced_clock);
8811         if (!ok && !crtc_state->clock_set) {
8812                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8813                 return -EINVAL;
8814         }
8815         /* Compat-code for transition, will disappear. */
8816         if (!crtc_state->clock_set) {
8817                 crtc_state->dpll.n = clock.n;
8818                 crtc_state->dpll.m1 = clock.m1;
8819                 crtc_state->dpll.m2 = clock.m2;
8820                 crtc_state->dpll.p1 = clock.p1;
8821                 crtc_state->dpll.p2 = clock.p2;
8822         }
8823
8824         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8825         if (crtc_state->has_pch_encoder) {
8826                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8827                 if (has_reduced_clock)
8828                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8829
8830                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8831                                              &fp, &reduced_clock,
8832                                              has_reduced_clock ? &fp2 : NULL);
8833
8834                 crtc_state->dpll_hw_state.dpll = dpll;
8835                 crtc_state->dpll_hw_state.fp0 = fp;
8836                 if (has_reduced_clock)
8837                         crtc_state->dpll_hw_state.fp1 = fp2;
8838                 else
8839                         crtc_state->dpll_hw_state.fp1 = fp;
8840
8841                 pll = intel_get_shared_dpll(crtc, crtc_state);
8842                 if (pll == NULL) {
8843                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8844                                          pipe_name(crtc->pipe));
8845                         return -EINVAL;
8846                 }
8847         }
8848
8849         if (is_lvds && has_reduced_clock)
8850                 crtc->lowfreq_avail = true;
8851         else
8852                 crtc->lowfreq_avail = false;
8853
8854         return 0;
8855 }
8856
8857 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8858                                          struct intel_link_m_n *m_n)
8859 {
8860         struct drm_device *dev = crtc->base.dev;
8861         struct drm_i915_private *dev_priv = dev->dev_private;
8862         enum pipe pipe = crtc->pipe;
8863
8864         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8865         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8866         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8867                 & ~TU_SIZE_MASK;
8868         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8869         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8870                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8871 }
8872
8873 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8874                                          enum transcoder transcoder,
8875                                          struct intel_link_m_n *m_n,
8876                                          struct intel_link_m_n *m2_n2)
8877 {
8878         struct drm_device *dev = crtc->base.dev;
8879         struct drm_i915_private *dev_priv = dev->dev_private;
8880         enum pipe pipe = crtc->pipe;
8881
8882         if (INTEL_INFO(dev)->gen >= 5) {
8883                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8884                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8885                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8886                         & ~TU_SIZE_MASK;
8887                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8888                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8889                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8890                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8891                  * gen < 8) and if DRRS is supported (to make sure the
8892                  * registers are not unnecessarily read).
8893                  */
8894                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8895                         crtc->config->has_drrs) {
8896                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8897                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8898                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8899                                         & ~TU_SIZE_MASK;
8900                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8901                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8902                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8903                 }
8904         } else {
8905                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8906                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8907                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8908                         & ~TU_SIZE_MASK;
8909                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8910                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8911                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8912         }
8913 }
8914
8915 void intel_dp_get_m_n(struct intel_crtc *crtc,
8916                       struct intel_crtc_state *pipe_config)
8917 {
8918         if (pipe_config->has_pch_encoder)
8919                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8920         else
8921                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8922                                              &pipe_config->dp_m_n,
8923                                              &pipe_config->dp_m2_n2);
8924 }
8925
8926 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8927                                         struct intel_crtc_state *pipe_config)
8928 {
8929         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8930                                      &pipe_config->fdi_m_n, NULL);
8931 }
8932
8933 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8934                                     struct intel_crtc_state *pipe_config)
8935 {
8936         struct drm_device *dev = crtc->base.dev;
8937         struct drm_i915_private *dev_priv = dev->dev_private;
8938         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8939         uint32_t ps_ctrl = 0;
8940         int id = -1;
8941         int i;
8942
8943         /* find scaler attached to this pipe */
8944         for (i = 0; i < crtc->num_scalers; i++) {
8945                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8946                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8947                         id = i;
8948                         pipe_config->pch_pfit.enabled = true;
8949                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8950                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8951                         break;
8952                 }
8953         }
8954
8955         scaler_state->scaler_id = id;
8956         if (id >= 0) {
8957                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8958         } else {
8959                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8960         }
8961 }
8962
8963 static void
8964 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8965                                  struct intel_initial_plane_config *plane_config)
8966 {
8967         struct drm_device *dev = crtc->base.dev;
8968         struct drm_i915_private *dev_priv = dev->dev_private;
8969         u32 val, base, offset, stride_mult, tiling;
8970         int pipe = crtc->pipe;
8971         int fourcc, pixel_format;
8972         unsigned int aligned_height;
8973         struct drm_framebuffer *fb;
8974         struct intel_framebuffer *intel_fb;
8975
8976         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8977         if (!intel_fb) {
8978                 DRM_DEBUG_KMS("failed to alloc fb\n");
8979                 return;
8980         }
8981
8982         fb = &intel_fb->base;
8983
8984         val = I915_READ(PLANE_CTL(pipe, 0));
8985         if (!(val & PLANE_CTL_ENABLE))
8986                 goto error;
8987
8988         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8989         fourcc = skl_format_to_fourcc(pixel_format,
8990                                       val & PLANE_CTL_ORDER_RGBX,
8991                                       val & PLANE_CTL_ALPHA_MASK);
8992         fb->pixel_format = fourcc;
8993         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8994
8995         tiling = val & PLANE_CTL_TILED_MASK;
8996         switch (tiling) {
8997         case PLANE_CTL_TILED_LINEAR:
8998                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
8999                 break;
9000         case PLANE_CTL_TILED_X:
9001                 plane_config->tiling = I915_TILING_X;
9002                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9003                 break;
9004         case PLANE_CTL_TILED_Y:
9005                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9006                 break;
9007         case PLANE_CTL_TILED_YF:
9008                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9009                 break;
9010         default:
9011                 MISSING_CASE(tiling);
9012                 goto error;
9013         }
9014
9015         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9016         plane_config->base = base;
9017
9018         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9019
9020         val = I915_READ(PLANE_SIZE(pipe, 0));
9021         fb->height = ((val >> 16) & 0xfff) + 1;
9022         fb->width = ((val >> 0) & 0x1fff) + 1;
9023
9024         val = I915_READ(PLANE_STRIDE(pipe, 0));
9025         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
9026                                                 fb->pixel_format);
9027         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9028
9029         aligned_height = intel_fb_align_height(dev, fb->height,
9030                                                fb->pixel_format,
9031                                                fb->modifier[0]);
9032
9033         plane_config->size = fb->pitches[0] * aligned_height;
9034
9035         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9036                       pipe_name(pipe), fb->width, fb->height,
9037                       fb->bits_per_pixel, base, fb->pitches[0],
9038                       plane_config->size);
9039
9040         plane_config->fb = intel_fb;
9041         return;
9042
9043 error:
9044         kfree(fb);
9045 }
9046
9047 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9048                                      struct intel_crtc_state *pipe_config)
9049 {
9050         struct drm_device *dev = crtc->base.dev;
9051         struct drm_i915_private *dev_priv = dev->dev_private;
9052         uint32_t tmp;
9053
9054         tmp = I915_READ(PF_CTL(crtc->pipe));
9055
9056         if (tmp & PF_ENABLE) {
9057                 pipe_config->pch_pfit.enabled = true;
9058                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9059                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9060
9061                 /* We currently do not free assignements of panel fitters on
9062                  * ivb/hsw (since we don't use the higher upscaling modes which
9063                  * differentiates them) so just WARN about this case for now. */
9064                 if (IS_GEN7(dev)) {
9065                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9066                                 PF_PIPE_SEL_IVB(crtc->pipe));
9067                 }
9068         }
9069 }
9070
9071 static void
9072 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9073                                   struct intel_initial_plane_config *plane_config)
9074 {
9075         struct drm_device *dev = crtc->base.dev;
9076         struct drm_i915_private *dev_priv = dev->dev_private;
9077         u32 val, base, offset;
9078         int pipe = crtc->pipe;
9079         int fourcc, pixel_format;
9080         unsigned int aligned_height;
9081         struct drm_framebuffer *fb;
9082         struct intel_framebuffer *intel_fb;
9083
9084         val = I915_READ(DSPCNTR(pipe));
9085         if (!(val & DISPLAY_PLANE_ENABLE))
9086                 return;
9087
9088         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9089         if (!intel_fb) {
9090                 DRM_DEBUG_KMS("failed to alloc fb\n");
9091                 return;
9092         }
9093
9094         fb = &intel_fb->base;
9095
9096         if (INTEL_INFO(dev)->gen >= 4) {
9097                 if (val & DISPPLANE_TILED) {
9098                         plane_config->tiling = I915_TILING_X;
9099                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9100                 }
9101         }
9102
9103         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9104         fourcc = i9xx_format_to_fourcc(pixel_format);
9105         fb->pixel_format = fourcc;
9106         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9107
9108         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9109         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9110                 offset = I915_READ(DSPOFFSET(pipe));
9111         } else {
9112                 if (plane_config->tiling)
9113                         offset = I915_READ(DSPTILEOFF(pipe));
9114                 else
9115                         offset = I915_READ(DSPLINOFF(pipe));
9116         }
9117         plane_config->base = base;
9118
9119         val = I915_READ(PIPESRC(pipe));
9120         fb->width = ((val >> 16) & 0xfff) + 1;
9121         fb->height = ((val >> 0) & 0xfff) + 1;
9122
9123         val = I915_READ(DSPSTRIDE(pipe));
9124         fb->pitches[0] = val & 0xffffffc0;
9125
9126         aligned_height = intel_fb_align_height(dev, fb->height,
9127                                                fb->pixel_format,
9128                                                fb->modifier[0]);
9129
9130         plane_config->size = fb->pitches[0] * aligned_height;
9131
9132         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9133                       pipe_name(pipe), fb->width, fb->height,
9134                       fb->bits_per_pixel, base, fb->pitches[0],
9135                       plane_config->size);
9136
9137         plane_config->fb = intel_fb;
9138 }
9139
9140 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9141                                      struct intel_crtc_state *pipe_config)
9142 {
9143         struct drm_device *dev = crtc->base.dev;
9144         struct drm_i915_private *dev_priv = dev->dev_private;
9145         uint32_t tmp;
9146
9147         if (!intel_display_power_is_enabled(dev_priv,
9148                                             POWER_DOMAIN_PIPE(crtc->pipe)))
9149                 return false;
9150
9151         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9152         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9153
9154         tmp = I915_READ(PIPECONF(crtc->pipe));
9155         if (!(tmp & PIPECONF_ENABLE))
9156                 return false;
9157
9158         switch (tmp & PIPECONF_BPC_MASK) {
9159         case PIPECONF_6BPC:
9160                 pipe_config->pipe_bpp = 18;
9161                 break;
9162         case PIPECONF_8BPC:
9163                 pipe_config->pipe_bpp = 24;
9164                 break;
9165         case PIPECONF_10BPC:
9166                 pipe_config->pipe_bpp = 30;
9167                 break;
9168         case PIPECONF_12BPC:
9169                 pipe_config->pipe_bpp = 36;
9170                 break;
9171         default:
9172                 break;
9173         }
9174
9175         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9176                 pipe_config->limited_color_range = true;
9177
9178         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9179                 struct intel_shared_dpll *pll;
9180
9181                 pipe_config->has_pch_encoder = true;
9182
9183                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9184                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9185                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9186
9187                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9188
9189                 if (HAS_PCH_IBX(dev_priv->dev)) {
9190                         pipe_config->shared_dpll =
9191                                 (enum intel_dpll_id) crtc->pipe;
9192                 } else {
9193                         tmp = I915_READ(PCH_DPLL_SEL);
9194                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9195                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
9196                         else
9197                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
9198                 }
9199
9200                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9201
9202                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9203                                            &pipe_config->dpll_hw_state));
9204
9205                 tmp = pipe_config->dpll_hw_state.dpll;
9206                 pipe_config->pixel_multiplier =
9207                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9208                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9209
9210                 ironlake_pch_clock_get(crtc, pipe_config);
9211         } else {
9212                 pipe_config->pixel_multiplier = 1;
9213         }
9214
9215         intel_get_pipe_timings(crtc, pipe_config);
9216
9217         ironlake_get_pfit_config(crtc, pipe_config);
9218
9219         return true;
9220 }
9221
9222 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9223 {
9224         struct drm_device *dev = dev_priv->dev;
9225         struct intel_crtc *crtc;
9226
9227         for_each_intel_crtc(dev, crtc)
9228                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9229                      pipe_name(crtc->pipe));
9230
9231         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9232         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9233         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9234         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9235         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9236         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9237              "CPU PWM1 enabled\n");
9238         if (IS_HASWELL(dev))
9239                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9240                      "CPU PWM2 enabled\n");
9241         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9242              "PCH PWM1 enabled\n");
9243         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9244              "Utility pin enabled\n");
9245         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9246
9247         /*
9248          * In theory we can still leave IRQs enabled, as long as only the HPD
9249          * interrupts remain enabled. We used to check for that, but since it's
9250          * gen-specific and since we only disable LCPLL after we fully disable
9251          * the interrupts, the check below should be enough.
9252          */
9253         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9254 }
9255
9256 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9257 {
9258         struct drm_device *dev = dev_priv->dev;
9259
9260         if (IS_HASWELL(dev))
9261                 return I915_READ(D_COMP_HSW);
9262         else
9263                 return I915_READ(D_COMP_BDW);
9264 }
9265
9266 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9267 {
9268         struct drm_device *dev = dev_priv->dev;
9269
9270         if (IS_HASWELL(dev)) {
9271                 mutex_lock(&dev_priv->rps.hw_lock);
9272                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9273                                             val))
9274                         DRM_ERROR("Failed to write to D_COMP\n");
9275                 mutex_unlock(&dev_priv->rps.hw_lock);
9276         } else {
9277                 I915_WRITE(D_COMP_BDW, val);
9278                 POSTING_READ(D_COMP_BDW);
9279         }
9280 }
9281
9282 /*
9283  * This function implements pieces of two sequences from BSpec:
9284  * - Sequence for display software to disable LCPLL
9285  * - Sequence for display software to allow package C8+
9286  * The steps implemented here are just the steps that actually touch the LCPLL
9287  * register. Callers should take care of disabling all the display engine
9288  * functions, doing the mode unset, fixing interrupts, etc.
9289  */
9290 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9291                               bool switch_to_fclk, bool allow_power_down)
9292 {
9293         uint32_t val;
9294
9295         assert_can_disable_lcpll(dev_priv);
9296
9297         val = I915_READ(LCPLL_CTL);
9298
9299         if (switch_to_fclk) {
9300                 val |= LCPLL_CD_SOURCE_FCLK;
9301                 I915_WRITE(LCPLL_CTL, val);
9302
9303                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9304                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9305                         DRM_ERROR("Switching to FCLK failed\n");
9306
9307                 val = I915_READ(LCPLL_CTL);
9308         }
9309
9310         val |= LCPLL_PLL_DISABLE;
9311         I915_WRITE(LCPLL_CTL, val);
9312         POSTING_READ(LCPLL_CTL);
9313
9314         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9315                 DRM_ERROR("LCPLL still locked\n");
9316
9317         val = hsw_read_dcomp(dev_priv);
9318         val |= D_COMP_COMP_DISABLE;
9319         hsw_write_dcomp(dev_priv, val);
9320         ndelay(100);
9321
9322         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9323                      1))
9324                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9325
9326         if (allow_power_down) {
9327                 val = I915_READ(LCPLL_CTL);
9328                 val |= LCPLL_POWER_DOWN_ALLOW;
9329                 I915_WRITE(LCPLL_CTL, val);
9330                 POSTING_READ(LCPLL_CTL);
9331         }
9332 }
9333
9334 /*
9335  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9336  * source.
9337  */
9338 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9339 {
9340         uint32_t val;
9341
9342         val = I915_READ(LCPLL_CTL);
9343
9344         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9345                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9346                 return;
9347
9348         /*
9349          * Make sure we're not on PC8 state before disabling PC8, otherwise
9350          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9351          */
9352         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9353
9354         if (val & LCPLL_POWER_DOWN_ALLOW) {
9355                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9356                 I915_WRITE(LCPLL_CTL, val);
9357                 POSTING_READ(LCPLL_CTL);
9358         }
9359
9360         val = hsw_read_dcomp(dev_priv);
9361         val |= D_COMP_COMP_FORCE;
9362         val &= ~D_COMP_COMP_DISABLE;
9363         hsw_write_dcomp(dev_priv, val);
9364
9365         val = I915_READ(LCPLL_CTL);
9366         val &= ~LCPLL_PLL_DISABLE;
9367         I915_WRITE(LCPLL_CTL, val);
9368
9369         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9370                 DRM_ERROR("LCPLL not locked yet\n");
9371
9372         if (val & LCPLL_CD_SOURCE_FCLK) {
9373                 val = I915_READ(LCPLL_CTL);
9374                 val &= ~LCPLL_CD_SOURCE_FCLK;
9375                 I915_WRITE(LCPLL_CTL, val);
9376
9377                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9378                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9379                         DRM_ERROR("Switching back to LCPLL failed\n");
9380         }
9381
9382         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9383         intel_update_cdclk(dev_priv->dev);
9384 }
9385
9386 /*
9387  * Package states C8 and deeper are really deep PC states that can only be
9388  * reached when all the devices on the system allow it, so even if the graphics
9389  * device allows PC8+, it doesn't mean the system will actually get to these
9390  * states. Our driver only allows PC8+ when going into runtime PM.
9391  *
9392  * The requirements for PC8+ are that all the outputs are disabled, the power
9393  * well is disabled and most interrupts are disabled, and these are also
9394  * requirements for runtime PM. When these conditions are met, we manually do
9395  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9396  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9397  * hang the machine.
9398  *
9399  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9400  * the state of some registers, so when we come back from PC8+ we need to
9401  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9402  * need to take care of the registers kept by RC6. Notice that this happens even
9403  * if we don't put the device in PCI D3 state (which is what currently happens
9404  * because of the runtime PM support).
9405  *
9406  * For more, read "Display Sequences for Package C8" on the hardware
9407  * documentation.
9408  */
9409 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9410 {
9411         struct drm_device *dev = dev_priv->dev;
9412         uint32_t val;
9413
9414         DRM_DEBUG_KMS("Enabling package C8+\n");
9415
9416         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9417                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9418                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9419                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9420         }
9421
9422         lpt_disable_clkout_dp(dev);
9423         hsw_disable_lcpll(dev_priv, true, true);
9424 }
9425
9426 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9427 {
9428         struct drm_device *dev = dev_priv->dev;
9429         uint32_t val;
9430
9431         DRM_DEBUG_KMS("Disabling package C8+\n");
9432
9433         hsw_restore_lcpll(dev_priv);
9434         lpt_init_pch_refclk(dev);
9435
9436         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9437                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9438                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9439                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9440         }
9441
9442         intel_prepare_ddi(dev);
9443 }
9444
9445 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9446 {
9447         struct drm_device *dev = old_state->dev;
9448         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9449
9450         broxton_set_cdclk(dev, req_cdclk);
9451 }
9452
9453 /* compute the max rate for new configuration */
9454 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9455 {
9456         struct intel_crtc *intel_crtc;
9457         struct intel_crtc_state *crtc_state;
9458         int max_pixel_rate = 0;
9459
9460         for_each_intel_crtc(state->dev, intel_crtc) {
9461                 int pixel_rate;
9462
9463                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9464                 if (IS_ERR(crtc_state))
9465                         return PTR_ERR(crtc_state);
9466
9467                 if (!crtc_state->base.enable)
9468                         continue;
9469
9470                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9471
9472                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9473                 if (IS_BROADWELL(state->dev) && crtc_state->ips_enabled)
9474                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9475
9476                 max_pixel_rate = max(max_pixel_rate, pixel_rate);
9477         }
9478
9479         return max_pixel_rate;
9480 }
9481
9482 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9483 {
9484         struct drm_i915_private *dev_priv = dev->dev_private;
9485         uint32_t val, data;
9486         int ret;
9487
9488         if (WARN((I915_READ(LCPLL_CTL) &
9489                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9490                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9491                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9492                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9493                  "trying to change cdclk frequency with cdclk not enabled\n"))
9494                 return;
9495
9496         mutex_lock(&dev_priv->rps.hw_lock);
9497         ret = sandybridge_pcode_write(dev_priv,
9498                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9499         mutex_unlock(&dev_priv->rps.hw_lock);
9500         if (ret) {
9501                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9502                 return;
9503         }
9504
9505         val = I915_READ(LCPLL_CTL);
9506         val |= LCPLL_CD_SOURCE_FCLK;
9507         I915_WRITE(LCPLL_CTL, val);
9508
9509         if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9510                                LCPLL_CD_SOURCE_FCLK_DONE, 1))
9511                 DRM_ERROR("Switching to FCLK failed\n");
9512
9513         val = I915_READ(LCPLL_CTL);
9514         val &= ~LCPLL_CLK_FREQ_MASK;
9515
9516         switch (cdclk) {
9517         case 450000:
9518                 val |= LCPLL_CLK_FREQ_450;
9519                 data = 0;
9520                 break;
9521         case 540000:
9522                 val |= LCPLL_CLK_FREQ_54O_BDW;
9523                 data = 1;
9524                 break;
9525         case 337500:
9526                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9527                 data = 2;
9528                 break;
9529         case 675000:
9530                 val |= LCPLL_CLK_FREQ_675_BDW;
9531                 data = 3;
9532                 break;
9533         default:
9534                 WARN(1, "invalid cdclk frequency\n");
9535                 return;
9536         }
9537
9538         I915_WRITE(LCPLL_CTL, val);
9539
9540         val = I915_READ(LCPLL_CTL);
9541         val &= ~LCPLL_CD_SOURCE_FCLK;
9542         I915_WRITE(LCPLL_CTL, val);
9543
9544         if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9545                                 LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9546                 DRM_ERROR("Switching back to LCPLL failed\n");
9547
9548         mutex_lock(&dev_priv->rps.hw_lock);
9549         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9550         mutex_unlock(&dev_priv->rps.hw_lock);
9551
9552         intel_update_cdclk(dev);
9553
9554         WARN(cdclk != dev_priv->cdclk_freq,
9555              "cdclk requested %d kHz but got %d kHz\n",
9556              cdclk, dev_priv->cdclk_freq);
9557 }
9558
9559 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9560 {
9561         struct drm_i915_private *dev_priv = to_i915(state->dev);
9562         int max_pixclk = ilk_max_pixel_rate(state);
9563         int cdclk;
9564
9565         /*
9566          * FIXME should also account for plane ratio
9567          * once 64bpp pixel formats are supported.
9568          */
9569         if (max_pixclk > 540000)
9570                 cdclk = 675000;
9571         else if (max_pixclk > 450000)
9572                 cdclk = 540000;
9573         else if (max_pixclk > 337500)
9574                 cdclk = 450000;
9575         else
9576                 cdclk = 337500;
9577
9578         /*
9579          * FIXME move the cdclk caclulation to
9580          * compute_config() so we can fail gracegully.
9581          */
9582         if (cdclk > dev_priv->max_cdclk_freq) {
9583                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9584                           cdclk, dev_priv->max_cdclk_freq);
9585                 cdclk = dev_priv->max_cdclk_freq;
9586         }
9587
9588         to_intel_atomic_state(state)->cdclk = cdclk;
9589
9590         return 0;
9591 }
9592
9593 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9594 {
9595         struct drm_device *dev = old_state->dev;
9596         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9597
9598         broadwell_set_cdclk(dev, req_cdclk);
9599 }
9600
9601 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9602                                       struct intel_crtc_state *crtc_state)
9603 {
9604         if (!intel_ddi_pll_select(crtc, crtc_state))
9605                 return -EINVAL;
9606
9607         crtc->lowfreq_avail = false;
9608
9609         return 0;
9610 }
9611
9612 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9613                                 enum port port,
9614                                 struct intel_crtc_state *pipe_config)
9615 {
9616         switch (port) {
9617         case PORT_A:
9618                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9619                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9620                 break;
9621         case PORT_B:
9622                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9623                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9624                 break;
9625         case PORT_C:
9626                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9627                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9628                 break;
9629         default:
9630                 DRM_ERROR("Incorrect port type\n");
9631         }
9632 }
9633
9634 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9635                                 enum port port,
9636                                 struct intel_crtc_state *pipe_config)
9637 {
9638         u32 temp, dpll_ctl1;
9639
9640         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9641         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9642
9643         switch (pipe_config->ddi_pll_sel) {
9644         case SKL_DPLL0:
9645                 /*
9646                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9647                  * of the shared DPLL framework and thus needs to be read out
9648                  * separately
9649                  */
9650                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9651                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9652                 break;
9653         case SKL_DPLL1:
9654                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9655                 break;
9656         case SKL_DPLL2:
9657                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9658                 break;
9659         case SKL_DPLL3:
9660                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9661                 break;
9662         }
9663 }
9664
9665 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9666                                 enum port port,
9667                                 struct intel_crtc_state *pipe_config)
9668 {
9669         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9670
9671         switch (pipe_config->ddi_pll_sel) {
9672         case PORT_CLK_SEL_WRPLL1:
9673                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9674                 break;
9675         case PORT_CLK_SEL_WRPLL2:
9676                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9677                 break;
9678         }
9679 }
9680
9681 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9682                                        struct intel_crtc_state *pipe_config)
9683 {
9684         struct drm_device *dev = crtc->base.dev;
9685         struct drm_i915_private *dev_priv = dev->dev_private;
9686         struct intel_shared_dpll *pll;
9687         enum port port;
9688         uint32_t tmp;
9689
9690         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9691
9692         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9693
9694         if (IS_SKYLAKE(dev))
9695                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9696         else if (IS_BROXTON(dev))
9697                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9698         else
9699                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9700
9701         if (pipe_config->shared_dpll >= 0) {
9702                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9703
9704                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9705                                            &pipe_config->dpll_hw_state));
9706         }
9707
9708         /*
9709          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9710          * DDI E. So just check whether this pipe is wired to DDI E and whether
9711          * the PCH transcoder is on.
9712          */
9713         if (INTEL_INFO(dev)->gen < 9 &&
9714             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9715                 pipe_config->has_pch_encoder = true;
9716
9717                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9718                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9719                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9720
9721                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9722         }
9723 }
9724
9725 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9726                                     struct intel_crtc_state *pipe_config)
9727 {
9728         struct drm_device *dev = crtc->base.dev;
9729         struct drm_i915_private *dev_priv = dev->dev_private;
9730         enum intel_display_power_domain pfit_domain;
9731         uint32_t tmp;
9732
9733         if (!intel_display_power_is_enabled(dev_priv,
9734                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9735                 return false;
9736
9737         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9738         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9739
9740         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9741         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9742                 enum pipe trans_edp_pipe;
9743                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9744                 default:
9745                         WARN(1, "unknown pipe linked to edp transcoder\n");
9746                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9747                 case TRANS_DDI_EDP_INPUT_A_ON:
9748                         trans_edp_pipe = PIPE_A;
9749                         break;
9750                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9751                         trans_edp_pipe = PIPE_B;
9752                         break;
9753                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9754                         trans_edp_pipe = PIPE_C;
9755                         break;
9756                 }
9757
9758                 if (trans_edp_pipe == crtc->pipe)
9759                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9760         }
9761
9762         if (!intel_display_power_is_enabled(dev_priv,
9763                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9764                 return false;
9765
9766         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9767         if (!(tmp & PIPECONF_ENABLE))
9768                 return false;
9769
9770         haswell_get_ddi_port_state(crtc, pipe_config);
9771
9772         intel_get_pipe_timings(crtc, pipe_config);
9773
9774         if (INTEL_INFO(dev)->gen >= 9) {
9775                 skl_init_scalers(dev, crtc, pipe_config);
9776         }
9777
9778         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9779
9780         if (INTEL_INFO(dev)->gen >= 9) {
9781                 pipe_config->scaler_state.scaler_id = -1;
9782                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9783         }
9784
9785         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
9786                 if (INTEL_INFO(dev)->gen == 9)
9787                         skylake_get_pfit_config(crtc, pipe_config);
9788                 else if (INTEL_INFO(dev)->gen < 9)
9789                         ironlake_get_pfit_config(crtc, pipe_config);
9790                 else
9791                         MISSING_CASE(INTEL_INFO(dev)->gen);
9792         }
9793
9794         if (IS_HASWELL(dev))
9795                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9796                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9797
9798         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9799                 pipe_config->pixel_multiplier =
9800                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9801         } else {
9802                 pipe_config->pixel_multiplier = 1;
9803         }
9804
9805         return true;
9806 }
9807
9808 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
9809 {
9810         struct drm_device *dev = crtc->dev;
9811         struct drm_i915_private *dev_priv = dev->dev_private;
9812         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9813         uint32_t cntl = 0, size = 0;
9814
9815         if (base) {
9816                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
9817                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
9818                 unsigned int stride = roundup_pow_of_two(width) * 4;
9819
9820                 switch (stride) {
9821                 default:
9822                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
9823                                   width, stride);
9824                         stride = 256;
9825                         /* fallthrough */
9826                 case 256:
9827                 case 512:
9828                 case 1024:
9829                 case 2048:
9830                         break;
9831                 }
9832
9833                 cntl |= CURSOR_ENABLE |
9834                         CURSOR_GAMMA_ENABLE |
9835                         CURSOR_FORMAT_ARGB |
9836                         CURSOR_STRIDE(stride);
9837
9838                 size = (height << 12) | width;
9839         }
9840
9841         if (intel_crtc->cursor_cntl != 0 &&
9842             (intel_crtc->cursor_base != base ||
9843              intel_crtc->cursor_size != size ||
9844              intel_crtc->cursor_cntl != cntl)) {
9845                 /* On these chipsets we can only modify the base/size/stride
9846                  * whilst the cursor is disabled.
9847                  */
9848                 I915_WRITE(_CURACNTR, 0);
9849                 POSTING_READ(_CURACNTR);
9850                 intel_crtc->cursor_cntl = 0;
9851         }
9852
9853         if (intel_crtc->cursor_base != base) {
9854                 I915_WRITE(_CURABASE, base);
9855                 intel_crtc->cursor_base = base;
9856         }
9857
9858         if (intel_crtc->cursor_size != size) {
9859                 I915_WRITE(CURSIZE, size);
9860                 intel_crtc->cursor_size = size;
9861         }
9862
9863         if (intel_crtc->cursor_cntl != cntl) {
9864                 I915_WRITE(_CURACNTR, cntl);
9865                 POSTING_READ(_CURACNTR);
9866                 intel_crtc->cursor_cntl = cntl;
9867         }
9868 }
9869
9870 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
9871 {
9872         struct drm_device *dev = crtc->dev;
9873         struct drm_i915_private *dev_priv = dev->dev_private;
9874         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9875         int pipe = intel_crtc->pipe;
9876         uint32_t cntl;
9877
9878         cntl = 0;
9879         if (base) {
9880                 cntl = MCURSOR_GAMMA_ENABLE;
9881                 switch (intel_crtc->base.cursor->state->crtc_w) {
9882                         case 64:
9883                                 cntl |= CURSOR_MODE_64_ARGB_AX;
9884                                 break;
9885                         case 128:
9886                                 cntl |= CURSOR_MODE_128_ARGB_AX;
9887                                 break;
9888                         case 256:
9889                                 cntl |= CURSOR_MODE_256_ARGB_AX;
9890                                 break;
9891                         default:
9892                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
9893                                 return;
9894                 }
9895                 cntl |= pipe << 28; /* Connect to correct pipe */
9896
9897                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
9898                         cntl |= CURSOR_PIPE_CSC_ENABLE;
9899         }
9900
9901         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
9902                 cntl |= CURSOR_ROTATE_180;
9903
9904         if (intel_crtc->cursor_cntl != cntl) {
9905                 I915_WRITE(CURCNTR(pipe), cntl);
9906                 POSTING_READ(CURCNTR(pipe));
9907                 intel_crtc->cursor_cntl = cntl;
9908         }
9909
9910         /* and commit changes on next vblank */
9911         I915_WRITE(CURBASE(pipe), base);
9912         POSTING_READ(CURBASE(pipe));
9913
9914         intel_crtc->cursor_base = base;
9915 }
9916
9917 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
9918 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
9919                                      bool on)
9920 {
9921         struct drm_device *dev = crtc->dev;
9922         struct drm_i915_private *dev_priv = dev->dev_private;
9923         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9924         int pipe = intel_crtc->pipe;
9925         int x = crtc->cursor_x;
9926         int y = crtc->cursor_y;
9927         u32 base = 0, pos = 0;
9928
9929         if (on)
9930                 base = intel_crtc->cursor_addr;
9931
9932         if (x >= intel_crtc->config->pipe_src_w)
9933                 base = 0;
9934
9935         if (y >= intel_crtc->config->pipe_src_h)
9936                 base = 0;
9937
9938         if (x < 0) {
9939                 if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
9940                         base = 0;
9941
9942                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9943                 x = -x;
9944         }
9945         pos |= x << CURSOR_X_SHIFT;
9946
9947         if (y < 0) {
9948                 if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
9949                         base = 0;
9950
9951                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9952                 y = -y;
9953         }
9954         pos |= y << CURSOR_Y_SHIFT;
9955
9956         if (base == 0 && intel_crtc->cursor_base == 0)
9957                 return;
9958
9959         I915_WRITE(CURPOS(pipe), pos);
9960
9961         /* ILK+ do this automagically */
9962         if (HAS_GMCH_DISPLAY(dev) &&
9963             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
9964                 base += (intel_crtc->base.cursor->state->crtc_h *
9965                         intel_crtc->base.cursor->state->crtc_w - 1) * 4;
9966         }
9967
9968         if (IS_845G(dev) || IS_I865G(dev))
9969                 i845_update_cursor(crtc, base);
9970         else
9971                 i9xx_update_cursor(crtc, base);
9972 }
9973
9974 static bool cursor_size_ok(struct drm_device *dev,
9975                            uint32_t width, uint32_t height)
9976 {
9977         if (width == 0 || height == 0)
9978                 return false;
9979
9980         /*
9981          * 845g/865g are special in that they are only limited by
9982          * the width of their cursors, the height is arbitrary up to
9983          * the precision of the register. Everything else requires
9984          * square cursors, limited to a few power-of-two sizes.
9985          */
9986         if (IS_845G(dev) || IS_I865G(dev)) {
9987                 if ((width & 63) != 0)
9988                         return false;
9989
9990                 if (width > (IS_845G(dev) ? 64 : 512))
9991                         return false;
9992
9993                 if (height > 1023)
9994                         return false;
9995         } else {
9996                 switch (width | height) {
9997                 case 256:
9998                 case 128:
9999                         if (IS_GEN2(dev))
10000                                 return false;
10001                 case 64:
10002                         break;
10003                 default:
10004                         return false;
10005                 }
10006         }
10007
10008         return true;
10009 }
10010
10011 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10012                                  u16 *blue, uint32_t start, uint32_t size)
10013 {
10014         int end = (start + size > 256) ? 256 : start + size, i;
10015         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10016
10017         for (i = start; i < end; i++) {
10018                 intel_crtc->lut_r[i] = red[i] >> 8;
10019                 intel_crtc->lut_g[i] = green[i] >> 8;
10020                 intel_crtc->lut_b[i] = blue[i] >> 8;
10021         }
10022
10023         intel_crtc_load_lut(crtc);
10024 }
10025
10026 /* VESA 640x480x72Hz mode to set on the pipe */
10027 static struct drm_display_mode load_detect_mode = {
10028         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10029                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10030 };
10031
10032 struct drm_framebuffer *
10033 __intel_framebuffer_create(struct drm_device *dev,
10034                            struct drm_mode_fb_cmd2 *mode_cmd,
10035                            struct drm_i915_gem_object *obj)
10036 {
10037         struct intel_framebuffer *intel_fb;
10038         int ret;
10039
10040         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10041         if (!intel_fb) {
10042                 drm_gem_object_unreference(&obj->base);
10043                 return ERR_PTR(-ENOMEM);
10044         }
10045
10046         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10047         if (ret)
10048                 goto err;
10049
10050         return &intel_fb->base;
10051 err:
10052         drm_gem_object_unreference(&obj->base);
10053         kfree(intel_fb);
10054
10055         return ERR_PTR(ret);
10056 }
10057
10058 static struct drm_framebuffer *
10059 intel_framebuffer_create(struct drm_device *dev,
10060                          struct drm_mode_fb_cmd2 *mode_cmd,
10061                          struct drm_i915_gem_object *obj)
10062 {
10063         struct drm_framebuffer *fb;
10064         int ret;
10065
10066         ret = i915_mutex_lock_interruptible(dev);
10067         if (ret)
10068                 return ERR_PTR(ret);
10069         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10070         mutex_unlock(&dev->struct_mutex);
10071
10072         return fb;
10073 }
10074
10075 static u32
10076 intel_framebuffer_pitch_for_width(int width, int bpp)
10077 {
10078         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10079         return ALIGN(pitch, 64);
10080 }
10081
10082 static u32
10083 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10084 {
10085         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10086         return PAGE_ALIGN(pitch * mode->vdisplay);
10087 }
10088
10089 static struct drm_framebuffer *
10090 intel_framebuffer_create_for_mode(struct drm_device *dev,
10091                                   struct drm_display_mode *mode,
10092                                   int depth, int bpp)
10093 {
10094         struct drm_i915_gem_object *obj;
10095         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10096
10097         obj = i915_gem_alloc_object(dev,
10098                                     intel_framebuffer_size_for_mode(mode, bpp));
10099         if (obj == NULL)
10100                 return ERR_PTR(-ENOMEM);
10101
10102         mode_cmd.width = mode->hdisplay;
10103         mode_cmd.height = mode->vdisplay;
10104         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10105                                                                 bpp);
10106         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10107
10108         return intel_framebuffer_create(dev, &mode_cmd, obj);
10109 }
10110
10111 static struct drm_framebuffer *
10112 mode_fits_in_fbdev(struct drm_device *dev,
10113                    struct drm_display_mode *mode)
10114 {
10115 #ifdef CONFIG_DRM_FBDEV_EMULATION
10116         struct drm_i915_private *dev_priv = dev->dev_private;
10117         struct drm_i915_gem_object *obj;
10118         struct drm_framebuffer *fb;
10119
10120         if (!dev_priv->fbdev)
10121                 return NULL;
10122
10123         if (!dev_priv->fbdev->fb)
10124                 return NULL;
10125
10126         obj = dev_priv->fbdev->fb->obj;
10127         BUG_ON(!obj);
10128
10129         fb = &dev_priv->fbdev->fb->base;
10130         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10131                                                                fb->bits_per_pixel))
10132                 return NULL;
10133
10134         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10135                 return NULL;
10136
10137         return fb;
10138 #else
10139         return NULL;
10140 #endif
10141 }
10142
10143 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10144                                            struct drm_crtc *crtc,
10145                                            struct drm_display_mode *mode,
10146                                            struct drm_framebuffer *fb,
10147                                            int x, int y)
10148 {
10149         struct drm_plane_state *plane_state;
10150         int hdisplay, vdisplay;
10151         int ret;
10152
10153         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10154         if (IS_ERR(plane_state))
10155                 return PTR_ERR(plane_state);
10156
10157         if (mode)
10158                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10159         else
10160                 hdisplay = vdisplay = 0;
10161
10162         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10163         if (ret)
10164                 return ret;
10165         drm_atomic_set_fb_for_plane(plane_state, fb);
10166         plane_state->crtc_x = 0;
10167         plane_state->crtc_y = 0;
10168         plane_state->crtc_w = hdisplay;
10169         plane_state->crtc_h = vdisplay;
10170         plane_state->src_x = x << 16;
10171         plane_state->src_y = y << 16;
10172         plane_state->src_w = hdisplay << 16;
10173         plane_state->src_h = vdisplay << 16;
10174
10175         return 0;
10176 }
10177
10178 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10179                                 struct drm_display_mode *mode,
10180                                 struct intel_load_detect_pipe *old,
10181                                 struct drm_modeset_acquire_ctx *ctx)
10182 {
10183         struct intel_crtc *intel_crtc;
10184         struct intel_encoder *intel_encoder =
10185                 intel_attached_encoder(connector);
10186         struct drm_crtc *possible_crtc;
10187         struct drm_encoder *encoder = &intel_encoder->base;
10188         struct drm_crtc *crtc = NULL;
10189         struct drm_device *dev = encoder->dev;
10190         struct drm_framebuffer *fb;
10191         struct drm_mode_config *config = &dev->mode_config;
10192         struct drm_atomic_state *state = NULL;
10193         struct drm_connector_state *connector_state;
10194         struct intel_crtc_state *crtc_state;
10195         int ret, i = -1;
10196
10197         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10198                       connector->base.id, connector->name,
10199                       encoder->base.id, encoder->name);
10200
10201 retry:
10202         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10203         if (ret)
10204                 goto fail;
10205
10206         /*
10207          * Algorithm gets a little messy:
10208          *
10209          *   - if the connector already has an assigned crtc, use it (but make
10210          *     sure it's on first)
10211          *
10212          *   - try to find the first unused crtc that can drive this connector,
10213          *     and use that if we find one
10214          */
10215
10216         /* See if we already have a CRTC for this connector */
10217         if (encoder->crtc) {
10218                 crtc = encoder->crtc;
10219
10220                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10221                 if (ret)
10222                         goto fail;
10223                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10224                 if (ret)
10225                         goto fail;
10226
10227                 old->dpms_mode = connector->dpms;
10228                 old->load_detect_temp = false;
10229
10230                 /* Make sure the crtc and connector are running */
10231                 if (connector->dpms != DRM_MODE_DPMS_ON)
10232                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
10233
10234                 return true;
10235         }
10236
10237         /* Find an unused one (if possible) */
10238         for_each_crtc(dev, possible_crtc) {
10239                 i++;
10240                 if (!(encoder->possible_crtcs & (1 << i)))
10241                         continue;
10242                 if (possible_crtc->state->enable)
10243                         continue;
10244
10245                 crtc = possible_crtc;
10246                 break;
10247         }
10248
10249         /*
10250          * If we didn't find an unused CRTC, don't use any.
10251          */
10252         if (!crtc) {
10253                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10254                 goto fail;
10255         }
10256
10257         ret = drm_modeset_lock(&crtc->mutex, ctx);
10258         if (ret)
10259                 goto fail;
10260         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10261         if (ret)
10262                 goto fail;
10263
10264         intel_crtc = to_intel_crtc(crtc);
10265         old->dpms_mode = connector->dpms;
10266         old->load_detect_temp = true;
10267         old->release_fb = NULL;
10268
10269         state = drm_atomic_state_alloc(dev);
10270         if (!state)
10271                 return false;
10272
10273         state->acquire_ctx = ctx;
10274
10275         connector_state = drm_atomic_get_connector_state(state, connector);
10276         if (IS_ERR(connector_state)) {
10277                 ret = PTR_ERR(connector_state);
10278                 goto fail;
10279         }
10280
10281         connector_state->crtc = crtc;
10282         connector_state->best_encoder = &intel_encoder->base;
10283
10284         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10285         if (IS_ERR(crtc_state)) {
10286                 ret = PTR_ERR(crtc_state);
10287                 goto fail;
10288         }
10289
10290         crtc_state->base.active = crtc_state->base.enable = true;
10291
10292         if (!mode)
10293                 mode = &load_detect_mode;
10294
10295         /* We need a framebuffer large enough to accommodate all accesses
10296          * that the plane may generate whilst we perform load detection.
10297          * We can not rely on the fbcon either being present (we get called
10298          * during its initialisation to detect all boot displays, or it may
10299          * not even exist) or that it is large enough to satisfy the
10300          * requested mode.
10301          */
10302         fb = mode_fits_in_fbdev(dev, mode);
10303         if (fb == NULL) {
10304                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10305                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10306                 old->release_fb = fb;
10307         } else
10308                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10309         if (IS_ERR(fb)) {
10310                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10311                 goto fail;
10312         }
10313
10314         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10315         if (ret)
10316                 goto fail;
10317
10318         drm_mode_copy(&crtc_state->base.mode, mode);
10319
10320         if (drm_atomic_commit(state)) {
10321                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10322                 if (old->release_fb)
10323                         old->release_fb->funcs->destroy(old->release_fb);
10324                 goto fail;
10325         }
10326         crtc->primary->crtc = crtc;
10327
10328         /* let the connector get through one full cycle before testing */
10329         intel_wait_for_vblank(dev, intel_crtc->pipe);
10330         return true;
10331
10332 fail:
10333         drm_atomic_state_free(state);
10334         state = NULL;
10335
10336         if (ret == -EDEADLK) {
10337                 drm_modeset_backoff(ctx);
10338                 goto retry;
10339         }
10340
10341         return false;
10342 }
10343
10344 void intel_release_load_detect_pipe(struct drm_connector *connector,
10345                                     struct intel_load_detect_pipe *old,
10346                                     struct drm_modeset_acquire_ctx *ctx)
10347 {
10348         struct drm_device *dev = connector->dev;
10349         struct intel_encoder *intel_encoder =
10350                 intel_attached_encoder(connector);
10351         struct drm_encoder *encoder = &intel_encoder->base;
10352         struct drm_crtc *crtc = encoder->crtc;
10353         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10354         struct drm_atomic_state *state;
10355         struct drm_connector_state *connector_state;
10356         struct intel_crtc_state *crtc_state;
10357         int ret;
10358
10359         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10360                       connector->base.id, connector->name,
10361                       encoder->base.id, encoder->name);
10362
10363         if (old->load_detect_temp) {
10364                 state = drm_atomic_state_alloc(dev);
10365                 if (!state)
10366                         goto fail;
10367
10368                 state->acquire_ctx = ctx;
10369
10370                 connector_state = drm_atomic_get_connector_state(state, connector);
10371                 if (IS_ERR(connector_state))
10372                         goto fail;
10373
10374                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10375                 if (IS_ERR(crtc_state))
10376                         goto fail;
10377
10378                 connector_state->best_encoder = NULL;
10379                 connector_state->crtc = NULL;
10380
10381                 crtc_state->base.enable = crtc_state->base.active = false;
10382
10383                 ret = intel_modeset_setup_plane_state(state, crtc, NULL, NULL,
10384                                                       0, 0);
10385                 if (ret)
10386                         goto fail;
10387
10388                 ret = drm_atomic_commit(state);
10389                 if (ret)
10390                         goto fail;
10391
10392                 if (old->release_fb) {
10393                         drm_framebuffer_unregister_private(old->release_fb);
10394                         drm_framebuffer_unreference(old->release_fb);
10395                 }
10396
10397                 return;
10398         }
10399
10400         /* Switch crtc and encoder back off if necessary */
10401         if (old->dpms_mode != DRM_MODE_DPMS_ON)
10402                 connector->funcs->dpms(connector, old->dpms_mode);
10403
10404         return;
10405 fail:
10406         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
10407         drm_atomic_state_free(state);
10408 }
10409
10410 static int i9xx_pll_refclk(struct drm_device *dev,
10411                            const struct intel_crtc_state *pipe_config)
10412 {
10413         struct drm_i915_private *dev_priv = dev->dev_private;
10414         u32 dpll = pipe_config->dpll_hw_state.dpll;
10415
10416         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10417                 return dev_priv->vbt.lvds_ssc_freq;
10418         else if (HAS_PCH_SPLIT(dev))
10419                 return 120000;
10420         else if (!IS_GEN2(dev))
10421                 return 96000;
10422         else
10423                 return 48000;
10424 }
10425
10426 /* Returns the clock of the currently programmed mode of the given pipe. */
10427 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10428                                 struct intel_crtc_state *pipe_config)
10429 {
10430         struct drm_device *dev = crtc->base.dev;
10431         struct drm_i915_private *dev_priv = dev->dev_private;
10432         int pipe = pipe_config->cpu_transcoder;
10433         u32 dpll = pipe_config->dpll_hw_state.dpll;
10434         u32 fp;
10435         intel_clock_t clock;
10436         int port_clock;
10437         int refclk = i9xx_pll_refclk(dev, pipe_config);
10438
10439         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10440                 fp = pipe_config->dpll_hw_state.fp0;
10441         else
10442                 fp = pipe_config->dpll_hw_state.fp1;
10443
10444         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10445         if (IS_PINEVIEW(dev)) {
10446                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10447                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10448         } else {
10449                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10450                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10451         }
10452
10453         if (!IS_GEN2(dev)) {
10454                 if (IS_PINEVIEW(dev))
10455                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10456                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10457                 else
10458                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10459                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10460
10461                 switch (dpll & DPLL_MODE_MASK) {
10462                 case DPLLB_MODE_DAC_SERIAL:
10463                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10464                                 5 : 10;
10465                         break;
10466                 case DPLLB_MODE_LVDS:
10467                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10468                                 7 : 14;
10469                         break;
10470                 default:
10471                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10472                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10473                         return;
10474                 }
10475
10476                 if (IS_PINEVIEW(dev))
10477                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10478                 else
10479                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10480         } else {
10481                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10482                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10483
10484                 if (is_lvds) {
10485                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10486                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10487
10488                         if (lvds & LVDS_CLKB_POWER_UP)
10489                                 clock.p2 = 7;
10490                         else
10491                                 clock.p2 = 14;
10492                 } else {
10493                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10494                                 clock.p1 = 2;
10495                         else {
10496                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10497                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10498                         }
10499                         if (dpll & PLL_P2_DIVIDE_BY_4)
10500                                 clock.p2 = 4;
10501                         else
10502                                 clock.p2 = 2;
10503                 }
10504
10505                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10506         }
10507
10508         /*
10509          * This value includes pixel_multiplier. We will use
10510          * port_clock to compute adjusted_mode.crtc_clock in the
10511          * encoder's get_config() function.
10512          */
10513         pipe_config->port_clock = port_clock;
10514 }
10515
10516 int intel_dotclock_calculate(int link_freq,
10517                              const struct intel_link_m_n *m_n)
10518 {
10519         /*
10520          * The calculation for the data clock is:
10521          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10522          * But we want to avoid losing precison if possible, so:
10523          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10524          *
10525          * and the link clock is simpler:
10526          * link_clock = (m * link_clock) / n
10527          */
10528
10529         if (!m_n->link_n)
10530                 return 0;
10531
10532         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10533 }
10534
10535 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10536                                    struct intel_crtc_state *pipe_config)
10537 {
10538         struct drm_device *dev = crtc->base.dev;
10539
10540         /* read out port_clock from the DPLL */
10541         i9xx_crtc_clock_get(crtc, pipe_config);
10542
10543         /*
10544          * This value does not include pixel_multiplier.
10545          * We will check that port_clock and adjusted_mode.crtc_clock
10546          * agree once we know their relationship in the encoder's
10547          * get_config() function.
10548          */
10549         pipe_config->base.adjusted_mode.crtc_clock =
10550                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
10551                                          &pipe_config->fdi_m_n);
10552 }
10553
10554 /** Returns the currently programmed mode of the given pipe. */
10555 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10556                                              struct drm_crtc *crtc)
10557 {
10558         struct drm_i915_private *dev_priv = dev->dev_private;
10559         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10560         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10561         struct drm_display_mode *mode;
10562         struct intel_crtc_state pipe_config;
10563         int htot = I915_READ(HTOTAL(cpu_transcoder));
10564         int hsync = I915_READ(HSYNC(cpu_transcoder));
10565         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10566         int vsync = I915_READ(VSYNC(cpu_transcoder));
10567         enum pipe pipe = intel_crtc->pipe;
10568
10569         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10570         if (!mode)
10571                 return NULL;
10572
10573         /*
10574          * Construct a pipe_config sufficient for getting the clock info
10575          * back out of crtc_clock_get.
10576          *
10577          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10578          * to use a real value here instead.
10579          */
10580         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10581         pipe_config.pixel_multiplier = 1;
10582         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10583         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10584         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10585         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10586
10587         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10588         mode->hdisplay = (htot & 0xffff) + 1;
10589         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10590         mode->hsync_start = (hsync & 0xffff) + 1;
10591         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10592         mode->vdisplay = (vtot & 0xffff) + 1;
10593         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10594         mode->vsync_start = (vsync & 0xffff) + 1;
10595         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10596
10597         drm_mode_set_name(mode);
10598
10599         return mode;
10600 }
10601
10602 void intel_mark_busy(struct drm_device *dev)
10603 {
10604         struct drm_i915_private *dev_priv = dev->dev_private;
10605
10606         if (dev_priv->mm.busy)
10607                 return;
10608
10609         intel_runtime_pm_get(dev_priv);
10610         i915_update_gfx_val(dev_priv);
10611         if (INTEL_INFO(dev)->gen >= 6)
10612                 gen6_rps_busy(dev_priv);
10613         dev_priv->mm.busy = true;
10614 }
10615
10616 void intel_mark_idle(struct drm_device *dev)
10617 {
10618         struct drm_i915_private *dev_priv = dev->dev_private;
10619
10620         if (!dev_priv->mm.busy)
10621                 return;
10622
10623         dev_priv->mm.busy = false;
10624
10625         if (INTEL_INFO(dev)->gen >= 6)
10626                 gen6_rps_idle(dev->dev_private);
10627
10628         intel_runtime_pm_put(dev_priv);
10629 }
10630
10631 static void intel_crtc_destroy(struct drm_crtc *crtc)
10632 {
10633         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10634         struct drm_device *dev = crtc->dev;
10635         struct intel_unpin_work *work;
10636
10637         spin_lock_irq(&dev->event_lock);
10638         work = intel_crtc->unpin_work;
10639         intel_crtc->unpin_work = NULL;
10640         spin_unlock_irq(&dev->event_lock);
10641
10642         if (work) {
10643                 cancel_work_sync(&work->work);
10644                 kfree(work);
10645         }
10646
10647         drm_crtc_cleanup(crtc);
10648
10649         kfree(intel_crtc);
10650 }
10651
10652 static void intel_unpin_work_fn(struct work_struct *__work)
10653 {
10654         struct intel_unpin_work *work =
10655                 container_of(__work, struct intel_unpin_work, work);
10656         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10657         struct drm_device *dev = crtc->base.dev;
10658         struct drm_plane *primary = crtc->base.primary;
10659
10660         mutex_lock(&dev->struct_mutex);
10661         intel_unpin_fb_obj(work->old_fb, primary->state);
10662         drm_gem_object_unreference(&work->pending_flip_obj->base);
10663
10664         if (work->flip_queued_req)
10665                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10666         mutex_unlock(&dev->struct_mutex);
10667
10668         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10669         drm_framebuffer_unreference(work->old_fb);
10670
10671         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10672         atomic_dec(&crtc->unpin_work_count);
10673
10674         kfree(work);
10675 }
10676
10677 static void do_intel_finish_page_flip(struct drm_device *dev,
10678                                       struct drm_crtc *crtc)
10679 {
10680         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10681         struct intel_unpin_work *work;
10682         unsigned long flags;
10683
10684         /* Ignore early vblank irqs */
10685         if (intel_crtc == NULL)
10686                 return;
10687
10688         /*
10689          * This is called both by irq handlers and the reset code (to complete
10690          * lost pageflips) so needs the full irqsave spinlocks.
10691          */
10692         spin_lock_irqsave(&dev->event_lock, flags);
10693         work = intel_crtc->unpin_work;
10694
10695         /* Ensure we don't miss a work->pending update ... */
10696         smp_rmb();
10697
10698         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10699                 spin_unlock_irqrestore(&dev->event_lock, flags);
10700                 return;
10701         }
10702
10703         page_flip_completed(intel_crtc);
10704
10705         spin_unlock_irqrestore(&dev->event_lock, flags);
10706 }
10707
10708 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10709 {
10710         struct drm_i915_private *dev_priv = dev->dev_private;
10711         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10712
10713         do_intel_finish_page_flip(dev, crtc);
10714 }
10715
10716 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10717 {
10718         struct drm_i915_private *dev_priv = dev->dev_private;
10719         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10720
10721         do_intel_finish_page_flip(dev, crtc);
10722 }
10723
10724 /* Is 'a' after or equal to 'b'? */
10725 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10726 {
10727         return !((a - b) & 0x80000000);
10728 }
10729
10730 static bool page_flip_finished(struct intel_crtc *crtc)
10731 {
10732         struct drm_device *dev = crtc->base.dev;
10733         struct drm_i915_private *dev_priv = dev->dev_private;
10734
10735         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10736             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10737                 return true;
10738
10739         /*
10740          * The relevant registers doen't exist on pre-ctg.
10741          * As the flip done interrupt doesn't trigger for mmio
10742          * flips on gmch platforms, a flip count check isn't
10743          * really needed there. But since ctg has the registers,
10744          * include it in the check anyway.
10745          */
10746         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10747                 return true;
10748
10749         /*
10750          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10751          * used the same base address. In that case the mmio flip might
10752          * have completed, but the CS hasn't even executed the flip yet.
10753          *
10754          * A flip count check isn't enough as the CS might have updated
10755          * the base address just after start of vblank, but before we
10756          * managed to process the interrupt. This means we'd complete the
10757          * CS flip too soon.
10758          *
10759          * Combining both checks should get us a good enough result. It may
10760          * still happen that the CS flip has been executed, but has not
10761          * yet actually completed. But in case the base address is the same
10762          * anyway, we don't really care.
10763          */
10764         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10765                 crtc->unpin_work->gtt_offset &&
10766                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10767                                     crtc->unpin_work->flip_count);
10768 }
10769
10770 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10771 {
10772         struct drm_i915_private *dev_priv = dev->dev_private;
10773         struct intel_crtc *intel_crtc =
10774                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10775         unsigned long flags;
10776
10777
10778         /*
10779          * This is called both by irq handlers and the reset code (to complete
10780          * lost pageflips) so needs the full irqsave spinlocks.
10781          *
10782          * NB: An MMIO update of the plane base pointer will also
10783          * generate a page-flip completion irq, i.e. every modeset
10784          * is also accompanied by a spurious intel_prepare_page_flip().
10785          */
10786         spin_lock_irqsave(&dev->event_lock, flags);
10787         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10788                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10789         spin_unlock_irqrestore(&dev->event_lock, flags);
10790 }
10791
10792 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10793 {
10794         /* Ensure that the work item is consistent when activating it ... */
10795         smp_wmb();
10796         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10797         /* and that it is marked active as soon as the irq could fire. */
10798         smp_wmb();
10799 }
10800
10801 static int intel_gen2_queue_flip(struct drm_device *dev,
10802                                  struct drm_crtc *crtc,
10803                                  struct drm_framebuffer *fb,
10804                                  struct drm_i915_gem_object *obj,
10805                                  struct drm_i915_gem_request *req,
10806                                  uint32_t flags)
10807 {
10808         struct intel_engine_cs *ring = req->ring;
10809         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10810         u32 flip_mask;
10811         int ret;
10812
10813         ret = intel_ring_begin(req, 6);
10814         if (ret)
10815                 return ret;
10816
10817         /* Can't queue multiple flips, so wait for the previous
10818          * one to finish before executing the next.
10819          */
10820         if (intel_crtc->plane)
10821                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10822         else
10823                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10824         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10825         intel_ring_emit(ring, MI_NOOP);
10826         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10827                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10828         intel_ring_emit(ring, fb->pitches[0]);
10829         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10830         intel_ring_emit(ring, 0); /* aux display base address, unused */
10831
10832         intel_mark_page_flip_active(intel_crtc);
10833         return 0;
10834 }
10835
10836 static int intel_gen3_queue_flip(struct drm_device *dev,
10837                                  struct drm_crtc *crtc,
10838                                  struct drm_framebuffer *fb,
10839                                  struct drm_i915_gem_object *obj,
10840                                  struct drm_i915_gem_request *req,
10841                                  uint32_t flags)
10842 {
10843         struct intel_engine_cs *ring = req->ring;
10844         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10845         u32 flip_mask;
10846         int ret;
10847
10848         ret = intel_ring_begin(req, 6);
10849         if (ret)
10850                 return ret;
10851
10852         if (intel_crtc->plane)
10853                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10854         else
10855                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10856         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10857         intel_ring_emit(ring, MI_NOOP);
10858         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
10859                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10860         intel_ring_emit(ring, fb->pitches[0]);
10861         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10862         intel_ring_emit(ring, MI_NOOP);
10863
10864         intel_mark_page_flip_active(intel_crtc);
10865         return 0;
10866 }
10867
10868 static int intel_gen4_queue_flip(struct drm_device *dev,
10869                                  struct drm_crtc *crtc,
10870                                  struct drm_framebuffer *fb,
10871                                  struct drm_i915_gem_object *obj,
10872                                  struct drm_i915_gem_request *req,
10873                                  uint32_t flags)
10874 {
10875         struct intel_engine_cs *ring = req->ring;
10876         struct drm_i915_private *dev_priv = dev->dev_private;
10877         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10878         uint32_t pf, pipesrc;
10879         int ret;
10880
10881         ret = intel_ring_begin(req, 4);
10882         if (ret)
10883                 return ret;
10884
10885         /* i965+ uses the linear or tiled offsets from the
10886          * Display Registers (which do not change across a page-flip)
10887          * so we need only reprogram the base address.
10888          */
10889         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10890                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10891         intel_ring_emit(ring, fb->pitches[0]);
10892         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
10893                         obj->tiling_mode);
10894
10895         /* XXX Enabling the panel-fitter across page-flip is so far
10896          * untested on non-native modes, so ignore it for now.
10897          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10898          */
10899         pf = 0;
10900         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10901         intel_ring_emit(ring, pf | pipesrc);
10902
10903         intel_mark_page_flip_active(intel_crtc);
10904         return 0;
10905 }
10906
10907 static int intel_gen6_queue_flip(struct drm_device *dev,
10908                                  struct drm_crtc *crtc,
10909                                  struct drm_framebuffer *fb,
10910                                  struct drm_i915_gem_object *obj,
10911                                  struct drm_i915_gem_request *req,
10912                                  uint32_t flags)
10913 {
10914         struct intel_engine_cs *ring = req->ring;
10915         struct drm_i915_private *dev_priv = dev->dev_private;
10916         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10917         uint32_t pf, pipesrc;
10918         int ret;
10919
10920         ret = intel_ring_begin(req, 4);
10921         if (ret)
10922                 return ret;
10923
10924         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10925                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10926         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
10927         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10928
10929         /* Contrary to the suggestions in the documentation,
10930          * "Enable Panel Fitter" does not seem to be required when page
10931          * flipping with a non-native mode, and worse causes a normal
10932          * modeset to fail.
10933          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10934          */
10935         pf = 0;
10936         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10937         intel_ring_emit(ring, pf | pipesrc);
10938
10939         intel_mark_page_flip_active(intel_crtc);
10940         return 0;
10941 }
10942
10943 static int intel_gen7_queue_flip(struct drm_device *dev,
10944                                  struct drm_crtc *crtc,
10945                                  struct drm_framebuffer *fb,
10946                                  struct drm_i915_gem_object *obj,
10947                                  struct drm_i915_gem_request *req,
10948                                  uint32_t flags)
10949 {
10950         struct intel_engine_cs *ring = req->ring;
10951         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10952         uint32_t plane_bit = 0;
10953         int len, ret;
10954
10955         switch (intel_crtc->plane) {
10956         case PLANE_A:
10957                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10958                 break;
10959         case PLANE_B:
10960                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10961                 break;
10962         case PLANE_C:
10963                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10964                 break;
10965         default:
10966                 WARN_ONCE(1, "unknown plane in flip command\n");
10967                 return -ENODEV;
10968         }
10969
10970         len = 4;
10971         if (ring->id == RCS) {
10972                 len += 6;
10973                 /*
10974                  * On Gen 8, SRM is now taking an extra dword to accommodate
10975                  * 48bits addresses, and we need a NOOP for the batch size to
10976                  * stay even.
10977                  */
10978                 if (IS_GEN8(dev))
10979                         len += 2;
10980         }
10981
10982         /*
10983          * BSpec MI_DISPLAY_FLIP for IVB:
10984          * "The full packet must be contained within the same cache line."
10985          *
10986          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10987          * cacheline, if we ever start emitting more commands before
10988          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10989          * then do the cacheline alignment, and finally emit the
10990          * MI_DISPLAY_FLIP.
10991          */
10992         ret = intel_ring_cacheline_align(req);
10993         if (ret)
10994                 return ret;
10995
10996         ret = intel_ring_begin(req, len);
10997         if (ret)
10998                 return ret;
10999
11000         /* Unmask the flip-done completion message. Note that the bspec says that
11001          * we should do this for both the BCS and RCS, and that we must not unmask
11002          * more than one flip event at any time (or ensure that one flip message
11003          * can be sent by waiting for flip-done prior to queueing new flips).
11004          * Experimentation says that BCS works despite DERRMR masking all
11005          * flip-done completion events and that unmasking all planes at once
11006          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11007          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11008          */
11009         if (ring->id == RCS) {
11010                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11011                 intel_ring_emit(ring, DERRMR);
11012                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11013                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11014                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11015                 if (IS_GEN8(dev))
11016                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11017                                               MI_SRM_LRM_GLOBAL_GTT);
11018                 else
11019                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11020                                               MI_SRM_LRM_GLOBAL_GTT);
11021                 intel_ring_emit(ring, DERRMR);
11022                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11023                 if (IS_GEN8(dev)) {
11024                         intel_ring_emit(ring, 0);
11025                         intel_ring_emit(ring, MI_NOOP);
11026                 }
11027         }
11028
11029         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11030         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11031         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11032         intel_ring_emit(ring, (MI_NOOP));
11033
11034         intel_mark_page_flip_active(intel_crtc);
11035         return 0;
11036 }
11037
11038 static bool use_mmio_flip(struct intel_engine_cs *ring,
11039                           struct drm_i915_gem_object *obj)
11040 {
11041         /*
11042          * This is not being used for older platforms, because
11043          * non-availability of flip done interrupt forces us to use
11044          * CS flips. Older platforms derive flip done using some clever
11045          * tricks involving the flip_pending status bits and vblank irqs.
11046          * So using MMIO flips there would disrupt this mechanism.
11047          */
11048
11049         if (ring == NULL)
11050                 return true;
11051
11052         if (INTEL_INFO(ring->dev)->gen < 5)
11053                 return false;
11054
11055         if (i915.use_mmio_flip < 0)
11056                 return false;
11057         else if (i915.use_mmio_flip > 0)
11058                 return true;
11059         else if (i915.enable_execlists)
11060                 return true;
11061         else
11062                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11063 }
11064
11065 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
11066 {
11067         struct drm_device *dev = intel_crtc->base.dev;
11068         struct drm_i915_private *dev_priv = dev->dev_private;
11069         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11070         const enum pipe pipe = intel_crtc->pipe;
11071         u32 ctl, stride;
11072
11073         ctl = I915_READ(PLANE_CTL(pipe, 0));
11074         ctl &= ~PLANE_CTL_TILED_MASK;
11075         switch (fb->modifier[0]) {
11076         case DRM_FORMAT_MOD_NONE:
11077                 break;
11078         case I915_FORMAT_MOD_X_TILED:
11079                 ctl |= PLANE_CTL_TILED_X;
11080                 break;
11081         case I915_FORMAT_MOD_Y_TILED:
11082                 ctl |= PLANE_CTL_TILED_Y;
11083                 break;
11084         case I915_FORMAT_MOD_Yf_TILED:
11085                 ctl |= PLANE_CTL_TILED_YF;
11086                 break;
11087         default:
11088                 MISSING_CASE(fb->modifier[0]);
11089         }
11090
11091         /*
11092          * The stride is either expressed as a multiple of 64 bytes chunks for
11093          * linear buffers or in number of tiles for tiled buffers.
11094          */
11095         stride = fb->pitches[0] /
11096                  intel_fb_stride_alignment(dev, fb->modifier[0],
11097                                            fb->pixel_format);
11098
11099         /*
11100          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11101          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11102          */
11103         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11104         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11105
11106         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
11107         POSTING_READ(PLANE_SURF(pipe, 0));
11108 }
11109
11110 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
11111 {
11112         struct drm_device *dev = intel_crtc->base.dev;
11113         struct drm_i915_private *dev_priv = dev->dev_private;
11114         struct intel_framebuffer *intel_fb =
11115                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11116         struct drm_i915_gem_object *obj = intel_fb->obj;
11117         u32 dspcntr;
11118         u32 reg;
11119
11120         reg = DSPCNTR(intel_crtc->plane);
11121         dspcntr = I915_READ(reg);
11122
11123         if (obj->tiling_mode != I915_TILING_NONE)
11124                 dspcntr |= DISPPLANE_TILED;
11125         else
11126                 dspcntr &= ~DISPPLANE_TILED;
11127
11128         I915_WRITE(reg, dspcntr);
11129
11130         I915_WRITE(DSPSURF(intel_crtc->plane),
11131                    intel_crtc->unpin_work->gtt_offset);
11132         POSTING_READ(DSPSURF(intel_crtc->plane));
11133
11134 }
11135
11136 /*
11137  * XXX: This is the temporary way to update the plane registers until we get
11138  * around to using the usual plane update functions for MMIO flips
11139  */
11140 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
11141 {
11142         struct drm_device *dev = intel_crtc->base.dev;
11143
11144         intel_mark_page_flip_active(intel_crtc);
11145
11146         intel_pipe_update_start(intel_crtc);
11147
11148         if (INTEL_INFO(dev)->gen >= 9)
11149                 skl_do_mmio_flip(intel_crtc);
11150         else
11151                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11152                 ilk_do_mmio_flip(intel_crtc);
11153
11154         intel_pipe_update_end(intel_crtc);
11155 }
11156
11157 static void intel_mmio_flip_work_func(struct work_struct *work)
11158 {
11159         struct intel_mmio_flip *mmio_flip =
11160                 container_of(work, struct intel_mmio_flip, work);
11161
11162         if (mmio_flip->req)
11163                 WARN_ON(__i915_wait_request(mmio_flip->req,
11164                                             mmio_flip->crtc->reset_counter,
11165                                             false, NULL,
11166                                             &mmio_flip->i915->rps.mmioflips));
11167
11168         intel_do_mmio_flip(mmio_flip->crtc);
11169
11170         i915_gem_request_unreference__unlocked(mmio_flip->req);
11171         kfree(mmio_flip);
11172 }
11173
11174 static int intel_queue_mmio_flip(struct drm_device *dev,
11175                                  struct drm_crtc *crtc,
11176                                  struct drm_framebuffer *fb,
11177                                  struct drm_i915_gem_object *obj,
11178                                  struct intel_engine_cs *ring,
11179                                  uint32_t flags)
11180 {
11181         struct intel_mmio_flip *mmio_flip;
11182
11183         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11184         if (mmio_flip == NULL)
11185                 return -ENOMEM;
11186
11187         mmio_flip->i915 = to_i915(dev);
11188         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11189         mmio_flip->crtc = to_intel_crtc(crtc);
11190
11191         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11192         schedule_work(&mmio_flip->work);
11193
11194         return 0;
11195 }
11196
11197 static int intel_default_queue_flip(struct drm_device *dev,
11198                                     struct drm_crtc *crtc,
11199                                     struct drm_framebuffer *fb,
11200                                     struct drm_i915_gem_object *obj,
11201                                     struct drm_i915_gem_request *req,
11202                                     uint32_t flags)
11203 {
11204         return -ENODEV;
11205 }
11206
11207 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11208                                          struct drm_crtc *crtc)
11209 {
11210         struct drm_i915_private *dev_priv = dev->dev_private;
11211         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11212         struct intel_unpin_work *work = intel_crtc->unpin_work;
11213         u32 addr;
11214
11215         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11216                 return true;
11217
11218         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11219                 return false;
11220
11221         if (!work->enable_stall_check)
11222                 return false;
11223
11224         if (work->flip_ready_vblank == 0) {
11225                 if (work->flip_queued_req &&
11226                     !i915_gem_request_completed(work->flip_queued_req, true))
11227                         return false;
11228
11229                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11230         }
11231
11232         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11233                 return false;
11234
11235         /* Potential stall - if we see that the flip has happened,
11236          * assume a missed interrupt. */
11237         if (INTEL_INFO(dev)->gen >= 4)
11238                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11239         else
11240                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11241
11242         /* There is a potential issue here with a false positive after a flip
11243          * to the same address. We could address this by checking for a
11244          * non-incrementing frame counter.
11245          */
11246         return addr == work->gtt_offset;
11247 }
11248
11249 void intel_check_page_flip(struct drm_device *dev, int pipe)
11250 {
11251         struct drm_i915_private *dev_priv = dev->dev_private;
11252         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11253         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11254         struct intel_unpin_work *work;
11255
11256         WARN_ON(!in_interrupt());
11257
11258         if (crtc == NULL)
11259                 return;
11260
11261         spin_lock(&dev->event_lock);
11262         work = intel_crtc->unpin_work;
11263         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11264                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11265                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11266                 page_flip_completed(intel_crtc);
11267                 work = NULL;
11268         }
11269         if (work != NULL &&
11270             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11271                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11272         spin_unlock(&dev->event_lock);
11273 }
11274
11275 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11276                                 struct drm_framebuffer *fb,
11277                                 struct drm_pending_vblank_event *event,
11278                                 uint32_t page_flip_flags)
11279 {
11280         struct drm_device *dev = crtc->dev;
11281         struct drm_i915_private *dev_priv = dev->dev_private;
11282         struct drm_framebuffer *old_fb = crtc->primary->fb;
11283         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11284         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11285         struct drm_plane *primary = crtc->primary;
11286         enum pipe pipe = intel_crtc->pipe;
11287         struct intel_unpin_work *work;
11288         struct intel_engine_cs *ring;
11289         bool mmio_flip;
11290         struct drm_i915_gem_request *request = NULL;
11291         int ret;
11292
11293         /*
11294          * drm_mode_page_flip_ioctl() should already catch this, but double
11295          * check to be safe.  In the future we may enable pageflipping from
11296          * a disabled primary plane.
11297          */
11298         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11299                 return -EBUSY;
11300
11301         /* Can't change pixel format via MI display flips. */
11302         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11303                 return -EINVAL;
11304
11305         /*
11306          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11307          * Note that pitch changes could also affect these register.
11308          */
11309         if (INTEL_INFO(dev)->gen > 3 &&
11310             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11311              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11312                 return -EINVAL;
11313
11314         if (i915_terminally_wedged(&dev_priv->gpu_error))
11315                 goto out_hang;
11316
11317         work = kzalloc(sizeof(*work), GFP_KERNEL);
11318         if (work == NULL)
11319                 return -ENOMEM;
11320
11321         work->event = event;
11322         work->crtc = crtc;
11323         work->old_fb = old_fb;
11324         INIT_WORK(&work->work, intel_unpin_work_fn);
11325
11326         ret = drm_crtc_vblank_get(crtc);
11327         if (ret)
11328                 goto free_work;
11329
11330         /* We borrow the event spin lock for protecting unpin_work */
11331         spin_lock_irq(&dev->event_lock);
11332         if (intel_crtc->unpin_work) {
11333                 /* Before declaring the flip queue wedged, check if
11334                  * the hardware completed the operation behind our backs.
11335                  */
11336                 if (__intel_pageflip_stall_check(dev, crtc)) {
11337                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11338                         page_flip_completed(intel_crtc);
11339                 } else {
11340                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11341                         spin_unlock_irq(&dev->event_lock);
11342
11343                         drm_crtc_vblank_put(crtc);
11344                         kfree(work);
11345                         return -EBUSY;
11346                 }
11347         }
11348         intel_crtc->unpin_work = work;
11349         spin_unlock_irq(&dev->event_lock);
11350
11351         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11352                 flush_workqueue(dev_priv->wq);
11353
11354         /* Reference the objects for the scheduled work. */
11355         drm_framebuffer_reference(work->old_fb);
11356         drm_gem_object_reference(&obj->base);
11357
11358         crtc->primary->fb = fb;
11359         update_state_fb(crtc->primary);
11360
11361         work->pending_flip_obj = obj;
11362
11363         ret = i915_mutex_lock_interruptible(dev);
11364         if (ret)
11365                 goto cleanup;
11366
11367         atomic_inc(&intel_crtc->unpin_work_count);
11368         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11369
11370         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11371                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
11372
11373         if (IS_VALLEYVIEW(dev)) {
11374                 ring = &dev_priv->ring[BCS];
11375                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11376                         /* vlv: DISPLAY_FLIP fails to change tiling */
11377                         ring = NULL;
11378         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11379                 ring = &dev_priv->ring[BCS];
11380         } else if (INTEL_INFO(dev)->gen >= 7) {
11381                 ring = i915_gem_request_get_ring(obj->last_write_req);
11382                 if (ring == NULL || ring->id != RCS)
11383                         ring = &dev_priv->ring[BCS];
11384         } else {
11385                 ring = &dev_priv->ring[RCS];
11386         }
11387
11388         mmio_flip = use_mmio_flip(ring, obj);
11389
11390         /* When using CS flips, we want to emit semaphores between rings.
11391          * However, when using mmio flips we will create a task to do the
11392          * synchronisation, so all we want here is to pin the framebuffer
11393          * into the display plane and skip any waits.
11394          */
11395         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
11396                                          crtc->primary->state,
11397                                          mmio_flip ? i915_gem_request_get_ring(obj->last_write_req) : ring, &request);
11398         if (ret)
11399                 goto cleanup_pending;
11400
11401         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
11402                                                   + intel_crtc->dspaddr_offset;
11403
11404         if (mmio_flip) {
11405                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
11406                                             page_flip_flags);
11407                 if (ret)
11408                         goto cleanup_unpin;
11409
11410                 i915_gem_request_assign(&work->flip_queued_req,
11411                                         obj->last_write_req);
11412         } else {
11413                 if (!request) {
11414                         ret = i915_gem_request_alloc(ring, ring->default_context, &request);
11415                         if (ret)
11416                                 goto cleanup_unpin;
11417                 }
11418
11419                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11420                                                    page_flip_flags);
11421                 if (ret)
11422                         goto cleanup_unpin;
11423
11424                 i915_gem_request_assign(&work->flip_queued_req, request);
11425         }
11426
11427         if (request)
11428                 i915_add_request_no_flush(request);
11429
11430         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11431         work->enable_stall_check = true;
11432
11433         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11434                           to_intel_plane(primary)->frontbuffer_bit);
11435         mutex_unlock(&dev->struct_mutex);
11436
11437         intel_fbc_disable_crtc(intel_crtc);
11438         intel_frontbuffer_flip_prepare(dev,
11439                                        to_intel_plane(primary)->frontbuffer_bit);
11440
11441         trace_i915_flip_request(intel_crtc->plane, obj);
11442
11443         return 0;
11444
11445 cleanup_unpin:
11446         intel_unpin_fb_obj(fb, crtc->primary->state);
11447 cleanup_pending:
11448         if (request)
11449                 i915_gem_request_cancel(request);
11450         atomic_dec(&intel_crtc->unpin_work_count);
11451         mutex_unlock(&dev->struct_mutex);
11452 cleanup:
11453         crtc->primary->fb = old_fb;
11454         update_state_fb(crtc->primary);
11455
11456         drm_gem_object_unreference_unlocked(&obj->base);
11457         drm_framebuffer_unreference(work->old_fb);
11458
11459         spin_lock_irq(&dev->event_lock);
11460         intel_crtc->unpin_work = NULL;
11461         spin_unlock_irq(&dev->event_lock);
11462
11463         drm_crtc_vblank_put(crtc);
11464 free_work:
11465         kfree(work);
11466
11467         if (ret == -EIO) {
11468                 struct drm_atomic_state *state;
11469                 struct drm_plane_state *plane_state;
11470
11471 out_hang:
11472                 state = drm_atomic_state_alloc(dev);
11473                 if (!state)
11474                         return -ENOMEM;
11475                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11476
11477 retry:
11478                 plane_state = drm_atomic_get_plane_state(state, primary);
11479                 ret = PTR_ERR_OR_ZERO(plane_state);
11480                 if (!ret) {
11481                         drm_atomic_set_fb_for_plane(plane_state, fb);
11482
11483                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11484                         if (!ret)
11485                                 ret = drm_atomic_commit(state);
11486                 }
11487
11488                 if (ret == -EDEADLK) {
11489                         drm_modeset_backoff(state->acquire_ctx);
11490                         drm_atomic_state_clear(state);
11491                         goto retry;
11492                 }
11493
11494                 if (ret)
11495                         drm_atomic_state_free(state);
11496
11497                 if (ret == 0 && event) {
11498                         spin_lock_irq(&dev->event_lock);
11499                         drm_send_vblank_event(dev, pipe, event);
11500                         spin_unlock_irq(&dev->event_lock);
11501                 }
11502         }
11503         return ret;
11504 }
11505
11506
11507 /**
11508  * intel_wm_need_update - Check whether watermarks need updating
11509  * @plane: drm plane
11510  * @state: new plane state
11511  *
11512  * Check current plane state versus the new one to determine whether
11513  * watermarks need to be recalculated.
11514  *
11515  * Returns true or false.
11516  */
11517 static bool intel_wm_need_update(struct drm_plane *plane,
11518                                  struct drm_plane_state *state)
11519 {
11520         /* Update watermarks on tiling changes. */
11521         if (!plane->state->fb || !state->fb ||
11522             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
11523             plane->state->rotation != state->rotation)
11524                 return true;
11525
11526         if (plane->state->crtc_w != state->crtc_w)
11527                 return true;
11528
11529         return false;
11530 }
11531
11532 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11533                                     struct drm_plane_state *plane_state)
11534 {
11535         struct drm_crtc *crtc = crtc_state->crtc;
11536         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11537         struct drm_plane *plane = plane_state->plane;
11538         struct drm_device *dev = crtc->dev;
11539         struct drm_i915_private *dev_priv = dev->dev_private;
11540         struct intel_plane_state *old_plane_state =
11541                 to_intel_plane_state(plane->state);
11542         int idx = intel_crtc->base.base.id, ret;
11543         int i = drm_plane_index(plane);
11544         bool mode_changed = needs_modeset(crtc_state);
11545         bool was_crtc_enabled = crtc->state->active;
11546         bool is_crtc_enabled = crtc_state->active;
11547
11548         bool turn_off, turn_on, visible, was_visible;
11549         struct drm_framebuffer *fb = plane_state->fb;
11550
11551         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11552             plane->type != DRM_PLANE_TYPE_CURSOR) {
11553                 ret = skl_update_scaler_plane(
11554                         to_intel_crtc_state(crtc_state),
11555                         to_intel_plane_state(plane_state));
11556                 if (ret)
11557                         return ret;
11558         }
11559
11560         /*
11561          * Disabling a plane is always okay; we just need to update
11562          * fb tracking in a special way since cleanup_fb() won't
11563          * get called by the plane helpers.
11564          */
11565         if (old_plane_state->base.fb && !fb)
11566                 intel_crtc->atomic.disabled_planes |= 1 << i;
11567
11568         was_visible = old_plane_state->visible;
11569         visible = to_intel_plane_state(plane_state)->visible;
11570
11571         if (!was_crtc_enabled && WARN_ON(was_visible))
11572                 was_visible = false;
11573
11574         if (!is_crtc_enabled && WARN_ON(visible))
11575                 visible = false;
11576
11577         if (!was_visible && !visible)
11578                 return 0;
11579
11580         turn_off = was_visible && (!visible || mode_changed);
11581         turn_on = visible && (!was_visible || mode_changed);
11582
11583         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11584                          plane->base.id, fb ? fb->base.id : -1);
11585
11586         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11587                          plane->base.id, was_visible, visible,
11588                          turn_off, turn_on, mode_changed);
11589
11590         if (turn_on) {
11591                 intel_crtc->atomic.update_wm_pre = true;
11592                 /* must disable cxsr around plane enable/disable */
11593                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11594                         intel_crtc->atomic.disable_cxsr = true;
11595                         /* to potentially re-enable cxsr */
11596                         intel_crtc->atomic.wait_vblank = true;
11597                         intel_crtc->atomic.update_wm_post = true;
11598                 }
11599         } else if (turn_off) {
11600                 intel_crtc->atomic.update_wm_post = true;
11601                 /* must disable cxsr around plane enable/disable */
11602                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11603                         if (is_crtc_enabled)
11604                                 intel_crtc->atomic.wait_vblank = true;
11605                         intel_crtc->atomic.disable_cxsr = true;
11606                 }
11607         } else if (intel_wm_need_update(plane, plane_state)) {
11608                 intel_crtc->atomic.update_wm_pre = true;
11609         }
11610
11611         if (visible || was_visible)
11612                 intel_crtc->atomic.fb_bits |=
11613                         to_intel_plane(plane)->frontbuffer_bit;
11614
11615         switch (plane->type) {
11616         case DRM_PLANE_TYPE_PRIMARY:
11617                 intel_crtc->atomic.wait_for_flips = true;
11618                 intel_crtc->atomic.pre_disable_primary = turn_off;
11619                 intel_crtc->atomic.post_enable_primary = turn_on;
11620
11621                 if (turn_off) {
11622                         /*
11623                          * FIXME: Actually if we will still have any other
11624                          * plane enabled on the pipe we could let IPS enabled
11625                          * still, but for now lets consider that when we make
11626                          * primary invisible by setting DSPCNTR to 0 on
11627                          * update_primary_plane function IPS needs to be
11628                          * disable.
11629                          */
11630                         intel_crtc->atomic.disable_ips = true;
11631
11632                         intel_crtc->atomic.disable_fbc = true;
11633                 }
11634
11635                 /*
11636                  * FBC does not work on some platforms for rotated
11637                  * planes, so disable it when rotation is not 0 and
11638                  * update it when rotation is set back to 0.
11639                  *
11640                  * FIXME: This is redundant with the fbc update done in
11641                  * the primary plane enable function except that that
11642                  * one is done too late. We eventually need to unify
11643                  * this.
11644                  */
11645
11646                 if (visible &&
11647                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11648                     dev_priv->fbc.crtc == intel_crtc &&
11649                     plane_state->rotation != BIT(DRM_ROTATE_0))
11650                         intel_crtc->atomic.disable_fbc = true;
11651
11652                 /*
11653                  * BDW signals flip done immediately if the plane
11654                  * is disabled, even if the plane enable is already
11655                  * armed to occur at the next vblank :(
11656                  */
11657                 if (turn_on && IS_BROADWELL(dev))
11658                         intel_crtc->atomic.wait_vblank = true;
11659
11660                 intel_crtc->atomic.update_fbc |= visible || mode_changed;
11661                 break;
11662         case DRM_PLANE_TYPE_CURSOR:
11663                 break;
11664         case DRM_PLANE_TYPE_OVERLAY:
11665                 if (turn_off && !mode_changed) {
11666                         intel_crtc->atomic.wait_vblank = true;
11667                         intel_crtc->atomic.update_sprite_watermarks |=
11668                                 1 << i;
11669                 }
11670         }
11671         return 0;
11672 }
11673
11674 static bool encoders_cloneable(const struct intel_encoder *a,
11675                                const struct intel_encoder *b)
11676 {
11677         /* masks could be asymmetric, so check both ways */
11678         return a == b || (a->cloneable & (1 << b->type) &&
11679                           b->cloneable & (1 << a->type));
11680 }
11681
11682 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11683                                          struct intel_crtc *crtc,
11684                                          struct intel_encoder *encoder)
11685 {
11686         struct intel_encoder *source_encoder;
11687         struct drm_connector *connector;
11688         struct drm_connector_state *connector_state;
11689         int i;
11690
11691         for_each_connector_in_state(state, connector, connector_state, i) {
11692                 if (connector_state->crtc != &crtc->base)
11693                         continue;
11694
11695                 source_encoder =
11696                         to_intel_encoder(connector_state->best_encoder);
11697                 if (!encoders_cloneable(encoder, source_encoder))
11698                         return false;
11699         }
11700
11701         return true;
11702 }
11703
11704 static bool check_encoder_cloning(struct drm_atomic_state *state,
11705                                   struct intel_crtc *crtc)
11706 {
11707         struct intel_encoder *encoder;
11708         struct drm_connector *connector;
11709         struct drm_connector_state *connector_state;
11710         int i;
11711
11712         for_each_connector_in_state(state, connector, connector_state, i) {
11713                 if (connector_state->crtc != &crtc->base)
11714                         continue;
11715
11716                 encoder = to_intel_encoder(connector_state->best_encoder);
11717                 if (!check_single_encoder_cloning(state, crtc, encoder))
11718                         return false;
11719         }
11720
11721         return true;
11722 }
11723
11724 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11725                                    struct drm_crtc_state *crtc_state)
11726 {
11727         struct drm_device *dev = crtc->dev;
11728         struct drm_i915_private *dev_priv = dev->dev_private;
11729         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11730         struct intel_crtc_state *pipe_config =
11731                 to_intel_crtc_state(crtc_state);
11732         struct drm_atomic_state *state = crtc_state->state;
11733         int ret;
11734         bool mode_changed = needs_modeset(crtc_state);
11735
11736         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11737                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11738                 return -EINVAL;
11739         }
11740
11741         if (mode_changed && !crtc_state->active)
11742                 intel_crtc->atomic.update_wm_post = true;
11743
11744         if (mode_changed && crtc_state->enable &&
11745             dev_priv->display.crtc_compute_clock &&
11746             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
11747                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11748                                                            pipe_config);
11749                 if (ret)
11750                         return ret;
11751         }
11752
11753         ret = 0;
11754         if (INTEL_INFO(dev)->gen >= 9) {
11755                 if (mode_changed)
11756                         ret = skl_update_scaler_crtc(pipe_config);
11757
11758                 if (!ret)
11759                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11760                                                          pipe_config);
11761         }
11762
11763         return ret;
11764 }
11765
11766 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11767         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11768         .load_lut = intel_crtc_load_lut,
11769         .atomic_begin = intel_begin_crtc_commit,
11770         .atomic_flush = intel_finish_crtc_commit,
11771         .atomic_check = intel_crtc_atomic_check,
11772 };
11773
11774 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11775 {
11776         struct intel_connector *connector;
11777
11778         for_each_intel_connector(dev, connector) {
11779                 if (connector->base.encoder) {
11780                         connector->base.state->best_encoder =
11781                                 connector->base.encoder;
11782                         connector->base.state->crtc =
11783                                 connector->base.encoder->crtc;
11784                 } else {
11785                         connector->base.state->best_encoder = NULL;
11786                         connector->base.state->crtc = NULL;
11787                 }
11788         }
11789 }
11790
11791 static void
11792 connected_sink_compute_bpp(struct intel_connector *connector,
11793                            struct intel_crtc_state *pipe_config)
11794 {
11795         int bpp = pipe_config->pipe_bpp;
11796
11797         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11798                 connector->base.base.id,
11799                 connector->base.name);
11800
11801         /* Don't use an invalid EDID bpc value */
11802         if (connector->base.display_info.bpc &&
11803             connector->base.display_info.bpc * 3 < bpp) {
11804                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11805                               bpp, connector->base.display_info.bpc*3);
11806                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11807         }
11808
11809         /* Clamp bpp to 8 on screens without EDID 1.4 */
11810         if (connector->base.display_info.bpc == 0 && bpp > 24) {
11811                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11812                               bpp);
11813                 pipe_config->pipe_bpp = 24;
11814         }
11815 }
11816
11817 static int
11818 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11819                           struct intel_crtc_state *pipe_config)
11820 {
11821         struct drm_device *dev = crtc->base.dev;
11822         struct drm_atomic_state *state;
11823         struct drm_connector *connector;
11824         struct drm_connector_state *connector_state;
11825         int bpp, i;
11826
11827         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
11828                 bpp = 10*3;
11829         else if (INTEL_INFO(dev)->gen >= 5)
11830                 bpp = 12*3;
11831         else
11832                 bpp = 8*3;
11833
11834
11835         pipe_config->pipe_bpp = bpp;
11836
11837         state = pipe_config->base.state;
11838
11839         /* Clamp display bpp to EDID value */
11840         for_each_connector_in_state(state, connector, connector_state, i) {
11841                 if (connector_state->crtc != &crtc->base)
11842                         continue;
11843
11844                 connected_sink_compute_bpp(to_intel_connector(connector),
11845                                            pipe_config);
11846         }
11847
11848         return bpp;
11849 }
11850
11851 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11852 {
11853         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11854                         "type: 0x%x flags: 0x%x\n",
11855                 mode->crtc_clock,
11856                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11857                 mode->crtc_hsync_end, mode->crtc_htotal,
11858                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11859                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11860 }
11861
11862 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11863                                    struct intel_crtc_state *pipe_config,
11864                                    const char *context)
11865 {
11866         struct drm_device *dev = crtc->base.dev;
11867         struct drm_plane *plane;
11868         struct intel_plane *intel_plane;
11869         struct intel_plane_state *state;
11870         struct drm_framebuffer *fb;
11871
11872         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11873                       context, pipe_config, pipe_name(crtc->pipe));
11874
11875         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
11876         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11877                       pipe_config->pipe_bpp, pipe_config->dither);
11878         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11879                       pipe_config->has_pch_encoder,
11880                       pipe_config->fdi_lanes,
11881                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11882                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11883                       pipe_config->fdi_m_n.tu);
11884         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11885                       pipe_config->has_dp_encoder,
11886                       pipe_config->lane_count,
11887                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11888                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11889                       pipe_config->dp_m_n.tu);
11890
11891         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11892                       pipe_config->has_dp_encoder,
11893                       pipe_config->lane_count,
11894                       pipe_config->dp_m2_n2.gmch_m,
11895                       pipe_config->dp_m2_n2.gmch_n,
11896                       pipe_config->dp_m2_n2.link_m,
11897                       pipe_config->dp_m2_n2.link_n,
11898                       pipe_config->dp_m2_n2.tu);
11899
11900         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11901                       pipe_config->has_audio,
11902                       pipe_config->has_infoframe);
11903
11904         DRM_DEBUG_KMS("requested mode:\n");
11905         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11906         DRM_DEBUG_KMS("adjusted mode:\n");
11907         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11908         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11909         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
11910         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
11911                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
11912         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11913                       crtc->num_scalers,
11914                       pipe_config->scaler_state.scaler_users,
11915                       pipe_config->scaler_state.scaler_id);
11916         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11917                       pipe_config->gmch_pfit.control,
11918                       pipe_config->gmch_pfit.pgm_ratios,
11919                       pipe_config->gmch_pfit.lvds_border_bits);
11920         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11921                       pipe_config->pch_pfit.pos,
11922                       pipe_config->pch_pfit.size,
11923                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
11924         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
11925         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
11926
11927         if (IS_BROXTON(dev)) {
11928                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
11929                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
11930                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
11931                               pipe_config->ddi_pll_sel,
11932                               pipe_config->dpll_hw_state.ebb0,
11933                               pipe_config->dpll_hw_state.ebb4,
11934                               pipe_config->dpll_hw_state.pll0,
11935                               pipe_config->dpll_hw_state.pll1,
11936                               pipe_config->dpll_hw_state.pll2,
11937                               pipe_config->dpll_hw_state.pll3,
11938                               pipe_config->dpll_hw_state.pll6,
11939                               pipe_config->dpll_hw_state.pll8,
11940                               pipe_config->dpll_hw_state.pll9,
11941                               pipe_config->dpll_hw_state.pll10,
11942                               pipe_config->dpll_hw_state.pcsdw12);
11943         } else if (IS_SKYLAKE(dev)) {
11944                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
11945                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
11946                               pipe_config->ddi_pll_sel,
11947                               pipe_config->dpll_hw_state.ctrl1,
11948                               pipe_config->dpll_hw_state.cfgcr1,
11949                               pipe_config->dpll_hw_state.cfgcr2);
11950         } else if (HAS_DDI(dev)) {
11951                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: wrpll: 0x%x\n",
11952                               pipe_config->ddi_pll_sel,
11953                               pipe_config->dpll_hw_state.wrpll);
11954         } else {
11955                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
11956                               "fp0: 0x%x, fp1: 0x%x\n",
11957                               pipe_config->dpll_hw_state.dpll,
11958                               pipe_config->dpll_hw_state.dpll_md,
11959                               pipe_config->dpll_hw_state.fp0,
11960                               pipe_config->dpll_hw_state.fp1);
11961         }
11962
11963         DRM_DEBUG_KMS("planes on this crtc\n");
11964         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11965                 intel_plane = to_intel_plane(plane);
11966                 if (intel_plane->pipe != crtc->pipe)
11967                         continue;
11968
11969                 state = to_intel_plane_state(plane->state);
11970                 fb = state->base.fb;
11971                 if (!fb) {
11972                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
11973                                 "disabled, scaler_id = %d\n",
11974                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11975                                 plane->base.id, intel_plane->pipe,
11976                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
11977                                 drm_plane_index(plane), state->scaler_id);
11978                         continue;
11979                 }
11980
11981                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
11982                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11983                         plane->base.id, intel_plane->pipe,
11984                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
11985                         drm_plane_index(plane));
11986                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
11987                         fb->base.id, fb->width, fb->height, fb->pixel_format);
11988                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
11989                         state->scaler_id,
11990                         state->src.x1 >> 16, state->src.y1 >> 16,
11991                         drm_rect_width(&state->src) >> 16,
11992                         drm_rect_height(&state->src) >> 16,
11993                         state->dst.x1, state->dst.y1,
11994                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
11995         }
11996 }
11997
11998 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11999 {
12000         struct drm_device *dev = state->dev;
12001         struct intel_encoder *encoder;
12002         struct drm_connector *connector;
12003         struct drm_connector_state *connector_state;
12004         unsigned int used_ports = 0;
12005         int i;
12006
12007         /*
12008          * Walk the connector list instead of the encoder
12009          * list to detect the problem on ddi platforms
12010          * where there's just one encoder per digital port.
12011          */
12012         for_each_connector_in_state(state, connector, connector_state, i) {
12013                 if (!connector_state->best_encoder)
12014                         continue;
12015
12016                 encoder = to_intel_encoder(connector_state->best_encoder);
12017
12018                 WARN_ON(!connector_state->crtc);
12019
12020                 switch (encoder->type) {
12021                         unsigned int port_mask;
12022                 case INTEL_OUTPUT_UNKNOWN:
12023                         if (WARN_ON(!HAS_DDI(dev)))
12024                                 break;
12025                 case INTEL_OUTPUT_DISPLAYPORT:
12026                 case INTEL_OUTPUT_HDMI:
12027                 case INTEL_OUTPUT_EDP:
12028                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12029
12030                         /* the same port mustn't appear more than once */
12031                         if (used_ports & port_mask)
12032                                 return false;
12033
12034                         used_ports |= port_mask;
12035                 default:
12036                         break;
12037                 }
12038         }
12039
12040         return true;
12041 }
12042
12043 static void
12044 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12045 {
12046         struct drm_crtc_state tmp_state;
12047         struct intel_crtc_scaler_state scaler_state;
12048         struct intel_dpll_hw_state dpll_hw_state;
12049         enum intel_dpll_id shared_dpll;
12050         uint32_t ddi_pll_sel;
12051         bool force_thru;
12052
12053         /* FIXME: before the switch to atomic started, a new pipe_config was
12054          * kzalloc'd. Code that depends on any field being zero should be
12055          * fixed, so that the crtc_state can be safely duplicated. For now,
12056          * only fields that are know to not cause problems are preserved. */
12057
12058         tmp_state = crtc_state->base;
12059         scaler_state = crtc_state->scaler_state;
12060         shared_dpll = crtc_state->shared_dpll;
12061         dpll_hw_state = crtc_state->dpll_hw_state;
12062         ddi_pll_sel = crtc_state->ddi_pll_sel;
12063         force_thru = crtc_state->pch_pfit.force_thru;
12064
12065         memset(crtc_state, 0, sizeof *crtc_state);
12066
12067         crtc_state->base = tmp_state;
12068         crtc_state->scaler_state = scaler_state;
12069         crtc_state->shared_dpll = shared_dpll;
12070         crtc_state->dpll_hw_state = dpll_hw_state;
12071         crtc_state->ddi_pll_sel = ddi_pll_sel;
12072         crtc_state->pch_pfit.force_thru = force_thru;
12073 }
12074
12075 static int
12076 intel_modeset_pipe_config(struct drm_crtc *crtc,
12077                           struct intel_crtc_state *pipe_config)
12078 {
12079         struct drm_atomic_state *state = pipe_config->base.state;
12080         struct intel_encoder *encoder;
12081         struct drm_connector *connector;
12082         struct drm_connector_state *connector_state;
12083         int base_bpp, ret = -EINVAL;
12084         int i;
12085         bool retry = true;
12086
12087         clear_intel_crtc_state(pipe_config);
12088
12089         pipe_config->cpu_transcoder =
12090                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12091
12092         /*
12093          * Sanitize sync polarity flags based on requested ones. If neither
12094          * positive or negative polarity is requested, treat this as meaning
12095          * negative polarity.
12096          */
12097         if (!(pipe_config->base.adjusted_mode.flags &
12098               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12099                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12100
12101         if (!(pipe_config->base.adjusted_mode.flags &
12102               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12103                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12104
12105         /* Compute a starting value for pipe_config->pipe_bpp taking the source
12106          * plane pixel format and any sink constraints into account. Returns the
12107          * source plane bpp so that dithering can be selected on mismatches
12108          * after encoders and crtc also have had their say. */
12109         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12110                                              pipe_config);
12111         if (base_bpp < 0)
12112                 goto fail;
12113
12114         /*
12115          * Determine the real pipe dimensions. Note that stereo modes can
12116          * increase the actual pipe size due to the frame doubling and
12117          * insertion of additional space for blanks between the frame. This
12118          * is stored in the crtc timings. We use the requested mode to do this
12119          * computation to clearly distinguish it from the adjusted mode, which
12120          * can be changed by the connectors in the below retry loop.
12121          */
12122         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12123                                &pipe_config->pipe_src_w,
12124                                &pipe_config->pipe_src_h);
12125
12126 encoder_retry:
12127         /* Ensure the port clock defaults are reset when retrying. */
12128         pipe_config->port_clock = 0;
12129         pipe_config->pixel_multiplier = 1;
12130
12131         /* Fill in default crtc timings, allow encoders to overwrite them. */
12132         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12133                               CRTC_STEREO_DOUBLE);
12134
12135         /* Pass our mode to the connectors and the CRTC to give them a chance to
12136          * adjust it according to limitations or connector properties, and also
12137          * a chance to reject the mode entirely.
12138          */
12139         for_each_connector_in_state(state, connector, connector_state, i) {
12140                 if (connector_state->crtc != crtc)
12141                         continue;
12142
12143                 encoder = to_intel_encoder(connector_state->best_encoder);
12144
12145                 if (!(encoder->compute_config(encoder, pipe_config))) {
12146                         DRM_DEBUG_KMS("Encoder config failure\n");
12147                         goto fail;
12148                 }
12149         }
12150
12151         /* Set default port clock if not overwritten by the encoder. Needs to be
12152          * done afterwards in case the encoder adjusts the mode. */
12153         if (!pipe_config->port_clock)
12154                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12155                         * pipe_config->pixel_multiplier;
12156
12157         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12158         if (ret < 0) {
12159                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12160                 goto fail;
12161         }
12162
12163         if (ret == RETRY) {
12164                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12165                         ret = -EINVAL;
12166                         goto fail;
12167                 }
12168
12169                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12170                 retry = false;
12171                 goto encoder_retry;
12172         }
12173
12174         /* Dithering seems to not pass-through bits correctly when it should, so
12175          * only enable it on 6bpc panels. */
12176         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12177         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
12178                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12179
12180 fail:
12181         return ret;
12182 }
12183
12184 static void
12185 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12186 {
12187         struct drm_crtc *crtc;
12188         struct drm_crtc_state *crtc_state;
12189         int i;
12190
12191         /* Double check state. */
12192         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12193                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12194
12195                 /* Update hwmode for vblank functions */
12196                 if (crtc->state->active)
12197                         crtc->hwmode = crtc->state->adjusted_mode;
12198                 else
12199                         crtc->hwmode.crtc_clock = 0;
12200         }
12201 }
12202
12203 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12204 {
12205         int diff;
12206
12207         if (clock1 == clock2)
12208                 return true;
12209
12210         if (!clock1 || !clock2)
12211                 return false;
12212
12213         diff = abs(clock1 - clock2);
12214
12215         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12216                 return true;
12217
12218         return false;
12219 }
12220
12221 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12222         list_for_each_entry((intel_crtc), \
12223                             &(dev)->mode_config.crtc_list, \
12224                             base.head) \
12225                 if (mask & (1 <<(intel_crtc)->pipe))
12226
12227
12228 static bool
12229 intel_compare_m_n(unsigned int m, unsigned int n,
12230                   unsigned int m2, unsigned int n2,
12231                   bool exact)
12232 {
12233         if (m == m2 && n == n2)
12234                 return true;
12235
12236         if (exact || !m || !n || !m2 || !n2)
12237                 return false;
12238
12239         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12240
12241         if (m > m2) {
12242                 while (m > m2) {
12243                         m2 <<= 1;
12244                         n2 <<= 1;
12245                 }
12246         } else if (m < m2) {
12247                 while (m < m2) {
12248                         m <<= 1;
12249                         n <<= 1;
12250                 }
12251         }
12252
12253         return m == m2 && n == n2;
12254 }
12255
12256 static bool
12257 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12258                        struct intel_link_m_n *m2_n2,
12259                        bool adjust)
12260 {
12261         if (m_n->tu == m2_n2->tu &&
12262             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12263                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12264             intel_compare_m_n(m_n->link_m, m_n->link_n,
12265                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12266                 if (adjust)
12267                         *m2_n2 = *m_n;
12268
12269                 return true;
12270         }
12271
12272         return false;
12273 }
12274
12275 static bool
12276 intel_pipe_config_compare(struct drm_device *dev,
12277                           struct intel_crtc_state *current_config,
12278                           struct intel_crtc_state *pipe_config,
12279                           bool adjust)
12280 {
12281         bool ret = true;
12282
12283 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12284         do { \
12285                 if (!adjust) \
12286                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12287                 else \
12288                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12289         } while (0)
12290
12291 #define PIPE_CONF_CHECK_X(name) \
12292         if (current_config->name != pipe_config->name) { \
12293                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12294                           "(expected 0x%08x, found 0x%08x)\n", \
12295                           current_config->name, \
12296                           pipe_config->name); \
12297                 ret = false; \
12298         }
12299
12300 #define PIPE_CONF_CHECK_I(name) \
12301         if (current_config->name != pipe_config->name) { \
12302                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12303                           "(expected %i, found %i)\n", \
12304                           current_config->name, \
12305                           pipe_config->name); \
12306                 ret = false; \
12307         }
12308
12309 #define PIPE_CONF_CHECK_M_N(name) \
12310         if (!intel_compare_link_m_n(&current_config->name, \
12311                                     &pipe_config->name,\
12312                                     adjust)) { \
12313                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12314                           "(expected tu %i gmch %i/%i link %i/%i, " \
12315                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12316                           current_config->name.tu, \
12317                           current_config->name.gmch_m, \
12318                           current_config->name.gmch_n, \
12319                           current_config->name.link_m, \
12320                           current_config->name.link_n, \
12321                           pipe_config->name.tu, \
12322                           pipe_config->name.gmch_m, \
12323                           pipe_config->name.gmch_n, \
12324                           pipe_config->name.link_m, \
12325                           pipe_config->name.link_n); \
12326                 ret = false; \
12327         }
12328
12329 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12330         if (!intel_compare_link_m_n(&current_config->name, \
12331                                     &pipe_config->name, adjust) && \
12332             !intel_compare_link_m_n(&current_config->alt_name, \
12333                                     &pipe_config->name, adjust)) { \
12334                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12335                           "(expected tu %i gmch %i/%i link %i/%i, " \
12336                           "or tu %i gmch %i/%i link %i/%i, " \
12337                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12338                           current_config->name.tu, \
12339                           current_config->name.gmch_m, \
12340                           current_config->name.gmch_n, \
12341                           current_config->name.link_m, \
12342                           current_config->name.link_n, \
12343                           current_config->alt_name.tu, \
12344                           current_config->alt_name.gmch_m, \
12345                           current_config->alt_name.gmch_n, \
12346                           current_config->alt_name.link_m, \
12347                           current_config->alt_name.link_n, \
12348                           pipe_config->name.tu, \
12349                           pipe_config->name.gmch_m, \
12350                           pipe_config->name.gmch_n, \
12351                           pipe_config->name.link_m, \
12352                           pipe_config->name.link_n); \
12353                 ret = false; \
12354         }
12355
12356 /* This is required for BDW+ where there is only one set of registers for
12357  * switching between high and low RR.
12358  * This macro can be used whenever a comparison has to be made between one
12359  * hw state and multiple sw state variables.
12360  */
12361 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12362         if ((current_config->name != pipe_config->name) && \
12363                 (current_config->alt_name != pipe_config->name)) { \
12364                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12365                                   "(expected %i or %i, found %i)\n", \
12366                                   current_config->name, \
12367                                   current_config->alt_name, \
12368                                   pipe_config->name); \
12369                         ret = false; \
12370         }
12371
12372 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12373         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12374                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12375                           "(expected %i, found %i)\n", \
12376                           current_config->name & (mask), \
12377                           pipe_config->name & (mask)); \
12378                 ret = false; \
12379         }
12380
12381 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12382         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12383                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12384                           "(expected %i, found %i)\n", \
12385                           current_config->name, \
12386                           pipe_config->name); \
12387                 ret = false; \
12388         }
12389
12390 #define PIPE_CONF_QUIRK(quirk)  \
12391         ((current_config->quirks | pipe_config->quirks) & (quirk))
12392
12393         PIPE_CONF_CHECK_I(cpu_transcoder);
12394
12395         PIPE_CONF_CHECK_I(has_pch_encoder);
12396         PIPE_CONF_CHECK_I(fdi_lanes);
12397         PIPE_CONF_CHECK_M_N(fdi_m_n);
12398
12399         PIPE_CONF_CHECK_I(has_dp_encoder);
12400         PIPE_CONF_CHECK_I(lane_count);
12401
12402         if (INTEL_INFO(dev)->gen < 8) {
12403                 PIPE_CONF_CHECK_M_N(dp_m_n);
12404
12405                 PIPE_CONF_CHECK_I(has_drrs);
12406                 if (current_config->has_drrs)
12407                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12408         } else
12409                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12410
12411         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12412         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12413         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12414         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12415         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12416         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12417
12418         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12419         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12420         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12421         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12422         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12423         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12424
12425         PIPE_CONF_CHECK_I(pixel_multiplier);
12426         PIPE_CONF_CHECK_I(has_hdmi_sink);
12427         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12428             IS_VALLEYVIEW(dev))
12429                 PIPE_CONF_CHECK_I(limited_color_range);
12430         PIPE_CONF_CHECK_I(has_infoframe);
12431
12432         PIPE_CONF_CHECK_I(has_audio);
12433
12434         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12435                               DRM_MODE_FLAG_INTERLACE);
12436
12437         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12438                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12439                                       DRM_MODE_FLAG_PHSYNC);
12440                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12441                                       DRM_MODE_FLAG_NHSYNC);
12442                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12443                                       DRM_MODE_FLAG_PVSYNC);
12444                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12445                                       DRM_MODE_FLAG_NVSYNC);
12446         }
12447
12448         PIPE_CONF_CHECK_I(pipe_src_w);
12449         PIPE_CONF_CHECK_I(pipe_src_h);
12450
12451         PIPE_CONF_CHECK_I(gmch_pfit.control);
12452         /* pfit ratios are autocomputed by the hw on gen4+ */
12453         if (INTEL_INFO(dev)->gen < 4)
12454                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12455         PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
12456
12457         PIPE_CONF_CHECK_I(pch_pfit.enabled);
12458         if (current_config->pch_pfit.enabled) {
12459                 PIPE_CONF_CHECK_I(pch_pfit.pos);
12460                 PIPE_CONF_CHECK_I(pch_pfit.size);
12461         }
12462
12463         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12464
12465         /* BDW+ don't expose a synchronous way to read the state */
12466         if (IS_HASWELL(dev))
12467                 PIPE_CONF_CHECK_I(ips_enabled);
12468
12469         PIPE_CONF_CHECK_I(double_wide);
12470
12471         PIPE_CONF_CHECK_X(ddi_pll_sel);
12472
12473         PIPE_CONF_CHECK_I(shared_dpll);
12474         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12475         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12476         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12477         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12478         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12479         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12480         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12481         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12482
12483         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12484                 PIPE_CONF_CHECK_I(pipe_bpp);
12485
12486         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12487         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12488
12489 #undef PIPE_CONF_CHECK_X
12490 #undef PIPE_CONF_CHECK_I
12491 #undef PIPE_CONF_CHECK_I_ALT
12492 #undef PIPE_CONF_CHECK_FLAGS
12493 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12494 #undef PIPE_CONF_QUIRK
12495 #undef INTEL_ERR_OR_DBG_KMS
12496
12497         return ret;
12498 }
12499
12500 static void check_wm_state(struct drm_device *dev)
12501 {
12502         struct drm_i915_private *dev_priv = dev->dev_private;
12503         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12504         struct intel_crtc *intel_crtc;
12505         int plane;
12506
12507         if (INTEL_INFO(dev)->gen < 9)
12508                 return;
12509
12510         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12511         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12512
12513         for_each_intel_crtc(dev, intel_crtc) {
12514                 struct skl_ddb_entry *hw_entry, *sw_entry;
12515                 const enum pipe pipe = intel_crtc->pipe;
12516
12517                 if (!intel_crtc->active)
12518                         continue;
12519
12520                 /* planes */
12521                 for_each_plane(dev_priv, pipe, plane) {
12522                         hw_entry = &hw_ddb.plane[pipe][plane];
12523                         sw_entry = &sw_ddb->plane[pipe][plane];
12524
12525                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12526                                 continue;
12527
12528                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12529                                   "(expected (%u,%u), found (%u,%u))\n",
12530                                   pipe_name(pipe), plane + 1,
12531                                   sw_entry->start, sw_entry->end,
12532                                   hw_entry->start, hw_entry->end);
12533                 }
12534
12535                 /* cursor */
12536                 hw_entry = &hw_ddb.cursor[pipe];
12537                 sw_entry = &sw_ddb->cursor[pipe];
12538
12539                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12540                         continue;
12541
12542                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12543                           "(expected (%u,%u), found (%u,%u))\n",
12544                           pipe_name(pipe),
12545                           sw_entry->start, sw_entry->end,
12546                           hw_entry->start, hw_entry->end);
12547         }
12548 }
12549
12550 static void
12551 check_connector_state(struct drm_device *dev,
12552                       struct drm_atomic_state *old_state)
12553 {
12554         struct drm_connector_state *old_conn_state;
12555         struct drm_connector *connector;
12556         int i;
12557
12558         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12559                 struct drm_encoder *encoder = connector->encoder;
12560                 struct drm_connector_state *state = connector->state;
12561
12562                 /* This also checks the encoder/connector hw state with the
12563                  * ->get_hw_state callbacks. */
12564                 intel_connector_check_state(to_intel_connector(connector));
12565
12566                 I915_STATE_WARN(state->best_encoder != encoder,
12567                      "connector's atomic encoder doesn't match legacy encoder\n");
12568         }
12569 }
12570
12571 static void
12572 check_encoder_state(struct drm_device *dev)
12573 {
12574         struct intel_encoder *encoder;
12575         struct intel_connector *connector;
12576
12577         for_each_intel_encoder(dev, encoder) {
12578                 bool enabled = false;
12579                 enum pipe pipe;
12580
12581                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12582                               encoder->base.base.id,
12583                               encoder->base.name);
12584
12585                 for_each_intel_connector(dev, connector) {
12586                         if (connector->base.state->best_encoder != &encoder->base)
12587                                 continue;
12588                         enabled = true;
12589
12590                         I915_STATE_WARN(connector->base.state->crtc !=
12591                                         encoder->base.crtc,
12592                              "connector's crtc doesn't match encoder crtc\n");
12593                 }
12594
12595                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12596                      "encoder's enabled state mismatch "
12597                      "(expected %i, found %i)\n",
12598                      !!encoder->base.crtc, enabled);
12599
12600                 if (!encoder->base.crtc) {
12601                         bool active;
12602
12603                         active = encoder->get_hw_state(encoder, &pipe);
12604                         I915_STATE_WARN(active,
12605                              "encoder detached but still enabled on pipe %c.\n",
12606                              pipe_name(pipe));
12607                 }
12608         }
12609 }
12610
12611 static void
12612 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12613 {
12614         struct drm_i915_private *dev_priv = dev->dev_private;
12615         struct intel_encoder *encoder;
12616         struct drm_crtc_state *old_crtc_state;
12617         struct drm_crtc *crtc;
12618         int i;
12619
12620         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12621                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12622                 struct intel_crtc_state *pipe_config, *sw_config;
12623                 bool active;
12624
12625                 if (!needs_modeset(crtc->state))
12626                         continue;
12627
12628                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12629                 pipe_config = to_intel_crtc_state(old_crtc_state);
12630                 memset(pipe_config, 0, sizeof(*pipe_config));
12631                 pipe_config->base.crtc = crtc;
12632                 pipe_config->base.state = old_state;
12633
12634                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12635                               crtc->base.id);
12636
12637                 active = dev_priv->display.get_pipe_config(intel_crtc,
12638                                                            pipe_config);
12639
12640                 /* hw state is inconsistent with the pipe quirk */
12641                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12642                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12643                         active = crtc->state->active;
12644
12645                 I915_STATE_WARN(crtc->state->active != active,
12646                      "crtc active state doesn't match with hw state "
12647                      "(expected %i, found %i)\n", crtc->state->active, active);
12648
12649                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12650                      "transitional active state does not match atomic hw state "
12651                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12652
12653                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12654                         enum pipe pipe;
12655
12656                         active = encoder->get_hw_state(encoder, &pipe);
12657                         I915_STATE_WARN(active != crtc->state->active,
12658                                 "[ENCODER:%i] active %i with crtc active %i\n",
12659                                 encoder->base.base.id, active, crtc->state->active);
12660
12661                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12662                                         "Encoder connected to wrong pipe %c\n",
12663                                         pipe_name(pipe));
12664
12665                         if (active)
12666                                 encoder->get_config(encoder, pipe_config);
12667                 }
12668
12669                 if (!crtc->state->active)
12670                         continue;
12671
12672                 sw_config = to_intel_crtc_state(crtc->state);
12673                 if (!intel_pipe_config_compare(dev, sw_config,
12674                                                pipe_config, false)) {
12675                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12676                         intel_dump_pipe_config(intel_crtc, pipe_config,
12677                                                "[hw state]");
12678                         intel_dump_pipe_config(intel_crtc, sw_config,
12679                                                "[sw state]");
12680                 }
12681         }
12682 }
12683
12684 static void
12685 check_shared_dpll_state(struct drm_device *dev)
12686 {
12687         struct drm_i915_private *dev_priv = dev->dev_private;
12688         struct intel_crtc *crtc;
12689         struct intel_dpll_hw_state dpll_hw_state;
12690         int i;
12691
12692         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12693                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12694                 int enabled_crtcs = 0, active_crtcs = 0;
12695                 bool active;
12696
12697                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12698
12699                 DRM_DEBUG_KMS("%s\n", pll->name);
12700
12701                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12702
12703                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12704                      "more active pll users than references: %i vs %i\n",
12705                      pll->active, hweight32(pll->config.crtc_mask));
12706                 I915_STATE_WARN(pll->active && !pll->on,
12707                      "pll in active use but not on in sw tracking\n");
12708                 I915_STATE_WARN(pll->on && !pll->active,
12709                      "pll in on but not on in use in sw tracking\n");
12710                 I915_STATE_WARN(pll->on != active,
12711                      "pll on state mismatch (expected %i, found %i)\n",
12712                      pll->on, active);
12713
12714                 for_each_intel_crtc(dev, crtc) {
12715                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
12716                                 enabled_crtcs++;
12717                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
12718                                 active_crtcs++;
12719                 }
12720                 I915_STATE_WARN(pll->active != active_crtcs,
12721                      "pll active crtcs mismatch (expected %i, found %i)\n",
12722                      pll->active, active_crtcs);
12723                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
12724                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
12725                      hweight32(pll->config.crtc_mask), enabled_crtcs);
12726
12727                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12728                                        sizeof(dpll_hw_state)),
12729                      "pll hw state mismatch\n");
12730         }
12731 }
12732
12733 static void
12734 intel_modeset_check_state(struct drm_device *dev,
12735                           struct drm_atomic_state *old_state)
12736 {
12737         check_wm_state(dev);
12738         check_connector_state(dev, old_state);
12739         check_encoder_state(dev);
12740         check_crtc_state(dev, old_state);
12741         check_shared_dpll_state(dev);
12742 }
12743
12744 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
12745                                      int dotclock)
12746 {
12747         /*
12748          * FDI already provided one idea for the dotclock.
12749          * Yell if the encoder disagrees.
12750          */
12751         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12752              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12753              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12754 }
12755
12756 static void update_scanline_offset(struct intel_crtc *crtc)
12757 {
12758         struct drm_device *dev = crtc->base.dev;
12759
12760         /*
12761          * The scanline counter increments at the leading edge of hsync.
12762          *
12763          * On most platforms it starts counting from vtotal-1 on the
12764          * first active line. That means the scanline counter value is
12765          * always one less than what we would expect. Ie. just after
12766          * start of vblank, which also occurs at start of hsync (on the
12767          * last active line), the scanline counter will read vblank_start-1.
12768          *
12769          * On gen2 the scanline counter starts counting from 1 instead
12770          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12771          * to keep the value positive), instead of adding one.
12772          *
12773          * On HSW+ the behaviour of the scanline counter depends on the output
12774          * type. For DP ports it behaves like most other platforms, but on HDMI
12775          * there's an extra 1 line difference. So we need to add two instead of
12776          * one to the value.
12777          */
12778         if (IS_GEN2(dev)) {
12779                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12780                 int vtotal;
12781
12782                 vtotal = mode->crtc_vtotal;
12783                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12784                         vtotal /= 2;
12785
12786                 crtc->scanline_offset = vtotal - 1;
12787         } else if (HAS_DDI(dev) &&
12788                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12789                 crtc->scanline_offset = 2;
12790         } else
12791                 crtc->scanline_offset = 1;
12792 }
12793
12794 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12795 {
12796         struct drm_device *dev = state->dev;
12797         struct drm_i915_private *dev_priv = to_i915(dev);
12798         struct intel_shared_dpll_config *shared_dpll = NULL;
12799         struct intel_crtc *intel_crtc;
12800         struct intel_crtc_state *intel_crtc_state;
12801         struct drm_crtc *crtc;
12802         struct drm_crtc_state *crtc_state;
12803         int i;
12804
12805         if (!dev_priv->display.crtc_compute_clock)
12806                 return;
12807
12808         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12809                 int dpll;
12810
12811                 intel_crtc = to_intel_crtc(crtc);
12812                 intel_crtc_state = to_intel_crtc_state(crtc_state);
12813                 dpll = intel_crtc_state->shared_dpll;
12814
12815                 if (!needs_modeset(crtc_state) || dpll == DPLL_ID_PRIVATE)
12816                         continue;
12817
12818                 intel_crtc_state->shared_dpll = DPLL_ID_PRIVATE;
12819
12820                 if (!shared_dpll)
12821                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
12822
12823                 shared_dpll[dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
12824         }
12825 }
12826
12827 /*
12828  * This implements the workaround described in the "notes" section of the mode
12829  * set sequence documentation. When going from no pipes or single pipe to
12830  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12831  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12832  */
12833 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12834 {
12835         struct drm_crtc_state *crtc_state;
12836         struct intel_crtc *intel_crtc;
12837         struct drm_crtc *crtc;
12838         struct intel_crtc_state *first_crtc_state = NULL;
12839         struct intel_crtc_state *other_crtc_state = NULL;
12840         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12841         int i;
12842
12843         /* look at all crtc's that are going to be enabled in during modeset */
12844         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12845                 intel_crtc = to_intel_crtc(crtc);
12846
12847                 if (!crtc_state->active || !needs_modeset(crtc_state))
12848                         continue;
12849
12850                 if (first_crtc_state) {
12851                         other_crtc_state = to_intel_crtc_state(crtc_state);
12852                         break;
12853                 } else {
12854                         first_crtc_state = to_intel_crtc_state(crtc_state);
12855                         first_pipe = intel_crtc->pipe;
12856                 }
12857         }
12858
12859         /* No workaround needed? */
12860         if (!first_crtc_state)
12861                 return 0;
12862
12863         /* w/a possibly needed, check how many crtc's are already enabled. */
12864         for_each_intel_crtc(state->dev, intel_crtc) {
12865                 struct intel_crtc_state *pipe_config;
12866
12867                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12868                 if (IS_ERR(pipe_config))
12869                         return PTR_ERR(pipe_config);
12870
12871                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12872
12873                 if (!pipe_config->base.active ||
12874                     needs_modeset(&pipe_config->base))
12875                         continue;
12876
12877                 /* 2 or more enabled crtcs means no need for w/a */
12878                 if (enabled_pipe != INVALID_PIPE)
12879                         return 0;
12880
12881                 enabled_pipe = intel_crtc->pipe;
12882         }
12883
12884         if (enabled_pipe != INVALID_PIPE)
12885                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12886         else if (other_crtc_state)
12887                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12888
12889         return 0;
12890 }
12891
12892 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12893 {
12894         struct drm_crtc *crtc;
12895         struct drm_crtc_state *crtc_state;
12896         int ret = 0;
12897
12898         /* add all active pipes to the state */
12899         for_each_crtc(state->dev, crtc) {
12900                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12901                 if (IS_ERR(crtc_state))
12902                         return PTR_ERR(crtc_state);
12903
12904                 if (!crtc_state->active || needs_modeset(crtc_state))
12905                         continue;
12906
12907                 crtc_state->mode_changed = true;
12908
12909                 ret = drm_atomic_add_affected_connectors(state, crtc);
12910                 if (ret)
12911                         break;
12912
12913                 ret = drm_atomic_add_affected_planes(state, crtc);
12914                 if (ret)
12915                         break;
12916         }
12917
12918         return ret;
12919 }
12920
12921
12922 static int intel_modeset_checks(struct drm_atomic_state *state)
12923 {
12924         struct drm_device *dev = state->dev;
12925         struct drm_i915_private *dev_priv = dev->dev_private;
12926         int ret;
12927
12928         if (!check_digital_port_conflicts(state)) {
12929                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12930                 return -EINVAL;
12931         }
12932
12933         /*
12934          * See if the config requires any additional preparation, e.g.
12935          * to adjust global state with pipes off.  We need to do this
12936          * here so we can get the modeset_pipe updated config for the new
12937          * mode set on this crtc.  For other crtcs we need to use the
12938          * adjusted_mode bits in the crtc directly.
12939          */
12940         if (dev_priv->display.modeset_calc_cdclk) {
12941                 unsigned int cdclk;
12942
12943                 ret = dev_priv->display.modeset_calc_cdclk(state);
12944
12945                 cdclk = to_intel_atomic_state(state)->cdclk;
12946                 if (!ret && cdclk != dev_priv->cdclk_freq)
12947                         ret = intel_modeset_all_pipes(state);
12948
12949                 if (ret < 0)
12950                         return ret;
12951         } else
12952                 to_intel_atomic_state(state)->cdclk = dev_priv->cdclk_freq;
12953
12954         intel_modeset_clear_plls(state);
12955
12956         if (IS_HASWELL(dev))
12957                 return haswell_mode_set_planes_workaround(state);
12958
12959         return 0;
12960 }
12961
12962 /**
12963  * intel_atomic_check - validate state object
12964  * @dev: drm device
12965  * @state: state to validate
12966  */
12967 static int intel_atomic_check(struct drm_device *dev,
12968                               struct drm_atomic_state *state)
12969 {
12970         struct drm_crtc *crtc;
12971         struct drm_crtc_state *crtc_state;
12972         int ret, i;
12973         bool any_ms = false;
12974
12975         ret = drm_atomic_helper_check_modeset(dev, state);
12976         if (ret)
12977                 return ret;
12978
12979         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12980                 struct intel_crtc_state *pipe_config =
12981                         to_intel_crtc_state(crtc_state);
12982
12983                 /* Catch I915_MODE_FLAG_INHERITED */
12984                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
12985                         crtc_state->mode_changed = true;
12986
12987                 if (!crtc_state->enable) {
12988                         if (needs_modeset(crtc_state))
12989                                 any_ms = true;
12990                         continue;
12991                 }
12992
12993                 if (!needs_modeset(crtc_state))
12994                         continue;
12995
12996                 /* FIXME: For only active_changed we shouldn't need to do any
12997                  * state recomputation at all. */
12998
12999                 ret = drm_atomic_add_affected_connectors(state, crtc);
13000                 if (ret)
13001                         return ret;
13002
13003                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13004                 if (ret)
13005                         return ret;
13006
13007                 if (i915.fastboot &&
13008                     intel_pipe_config_compare(state->dev,
13009                                         to_intel_crtc_state(crtc->state),
13010                                         pipe_config, true)) {
13011                         crtc_state->mode_changed = false;
13012                 }
13013
13014                 if (needs_modeset(crtc_state)) {
13015                         any_ms = true;
13016
13017                         ret = drm_atomic_add_affected_planes(state, crtc);
13018                         if (ret)
13019                                 return ret;
13020                 }
13021
13022                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13023                                        needs_modeset(crtc_state) ?
13024                                        "[modeset]" : "[fastset]");
13025         }
13026
13027         if (any_ms) {
13028                 ret = intel_modeset_checks(state);
13029
13030                 if (ret)
13031                         return ret;
13032         } else
13033                 to_intel_atomic_state(state)->cdclk =
13034                         to_i915(state->dev)->cdclk_freq;
13035
13036         return drm_atomic_helper_check_planes(state->dev, state);
13037 }
13038
13039 /**
13040  * intel_atomic_commit - commit validated state object
13041  * @dev: DRM device
13042  * @state: the top-level driver state object
13043  * @async: asynchronous commit
13044  *
13045  * This function commits a top-level state object that has been validated
13046  * with drm_atomic_helper_check().
13047  *
13048  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13049  * we can only handle plane-related operations and do not yet support
13050  * asynchronous commit.
13051  *
13052  * RETURNS
13053  * Zero for success or -errno.
13054  */
13055 static int intel_atomic_commit(struct drm_device *dev,
13056                                struct drm_atomic_state *state,
13057                                bool async)
13058 {
13059         struct drm_i915_private *dev_priv = dev->dev_private;
13060         struct drm_crtc *crtc;
13061         struct drm_crtc_state *crtc_state;
13062         int ret = 0;
13063         int i;
13064         bool any_ms = false;
13065
13066         if (async) {
13067                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13068                 return -EINVAL;
13069         }
13070
13071         ret = drm_atomic_helper_prepare_planes(dev, state);
13072         if (ret)
13073                 return ret;
13074
13075         drm_atomic_helper_swap_state(dev, state);
13076
13077         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13078                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13079
13080                 if (!needs_modeset(crtc->state))
13081                         continue;
13082
13083                 any_ms = true;
13084                 intel_pre_plane_update(intel_crtc);
13085
13086                 if (crtc_state->active) {
13087                         intel_crtc_disable_planes(crtc, crtc_state->plane_mask);
13088                         dev_priv->display.crtc_disable(crtc);
13089                         intel_crtc->active = false;
13090                         intel_disable_shared_dpll(intel_crtc);
13091                 }
13092         }
13093
13094         /* Only after disabling all output pipelines that will be changed can we
13095          * update the the output configuration. */
13096         intel_modeset_update_crtc_state(state);
13097
13098         if (any_ms) {
13099                 intel_shared_dpll_commit(state);
13100
13101                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13102                 modeset_update_crtc_power_domains(state);
13103         }
13104
13105         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13106         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13107                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13108                 bool modeset = needs_modeset(crtc->state);
13109
13110                 if (modeset && crtc->state->active) {
13111                         update_scanline_offset(to_intel_crtc(crtc));
13112                         dev_priv->display.crtc_enable(crtc);
13113                 }
13114
13115                 if (!modeset)
13116                         intel_pre_plane_update(intel_crtc);
13117
13118                 drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13119                 intel_post_plane_update(intel_crtc);
13120         }
13121
13122         /* FIXME: add subpixel order */
13123
13124         drm_atomic_helper_wait_for_vblanks(dev, state);
13125         drm_atomic_helper_cleanup_planes(dev, state);
13126
13127         if (any_ms)
13128                 intel_modeset_check_state(dev, state);
13129
13130         drm_atomic_state_free(state);
13131
13132         return 0;
13133 }
13134
13135 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13136 {
13137         struct drm_device *dev = crtc->dev;
13138         struct drm_atomic_state *state;
13139         struct drm_crtc_state *crtc_state;
13140         int ret;
13141
13142         state = drm_atomic_state_alloc(dev);
13143         if (!state) {
13144                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13145                               crtc->base.id);
13146                 return;
13147         }
13148
13149         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13150
13151 retry:
13152         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13153         ret = PTR_ERR_OR_ZERO(crtc_state);
13154         if (!ret) {
13155                 if (!crtc_state->active)
13156                         goto out;
13157
13158                 crtc_state->mode_changed = true;
13159                 ret = drm_atomic_commit(state);
13160         }
13161
13162         if (ret == -EDEADLK) {
13163                 drm_atomic_state_clear(state);
13164                 drm_modeset_backoff(state->acquire_ctx);
13165                 goto retry;
13166         }
13167
13168         if (ret)
13169 out:
13170                 drm_atomic_state_free(state);
13171 }
13172
13173 #undef for_each_intel_crtc_masked
13174
13175 static const struct drm_crtc_funcs intel_crtc_funcs = {
13176         .gamma_set = intel_crtc_gamma_set,
13177         .set_config = drm_atomic_helper_set_config,
13178         .destroy = intel_crtc_destroy,
13179         .page_flip = intel_crtc_page_flip,
13180         .atomic_duplicate_state = intel_crtc_duplicate_state,
13181         .atomic_destroy_state = intel_crtc_destroy_state,
13182 };
13183
13184 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13185                                       struct intel_shared_dpll *pll,
13186                                       struct intel_dpll_hw_state *hw_state)
13187 {
13188         uint32_t val;
13189
13190         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
13191                 return false;
13192
13193         val = I915_READ(PCH_DPLL(pll->id));
13194         hw_state->dpll = val;
13195         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13196         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13197
13198         return val & DPLL_VCO_ENABLE;
13199 }
13200
13201 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13202                                   struct intel_shared_dpll *pll)
13203 {
13204         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13205         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13206 }
13207
13208 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13209                                 struct intel_shared_dpll *pll)
13210 {
13211         /* PCH refclock must be enabled first */
13212         ibx_assert_pch_refclk_enabled(dev_priv);
13213
13214         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13215
13216         /* Wait for the clocks to stabilize. */
13217         POSTING_READ(PCH_DPLL(pll->id));
13218         udelay(150);
13219
13220         /* The pixel multiplier can only be updated once the
13221          * DPLL is enabled and the clocks are stable.
13222          *
13223          * So write it again.
13224          */
13225         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13226         POSTING_READ(PCH_DPLL(pll->id));
13227         udelay(200);
13228 }
13229
13230 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13231                                  struct intel_shared_dpll *pll)
13232 {
13233         struct drm_device *dev = dev_priv->dev;
13234         struct intel_crtc *crtc;
13235
13236         /* Make sure no transcoder isn't still depending on us. */
13237         for_each_intel_crtc(dev, crtc) {
13238                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13239                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13240         }
13241
13242         I915_WRITE(PCH_DPLL(pll->id), 0);
13243         POSTING_READ(PCH_DPLL(pll->id));
13244         udelay(200);
13245 }
13246
13247 static char *ibx_pch_dpll_names[] = {
13248         "PCH DPLL A",
13249         "PCH DPLL B",
13250 };
13251
13252 static void ibx_pch_dpll_init(struct drm_device *dev)
13253 {
13254         struct drm_i915_private *dev_priv = dev->dev_private;
13255         int i;
13256
13257         dev_priv->num_shared_dpll = 2;
13258
13259         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13260                 dev_priv->shared_dplls[i].id = i;
13261                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13262                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13263                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13264                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13265                 dev_priv->shared_dplls[i].get_hw_state =
13266                         ibx_pch_dpll_get_hw_state;
13267         }
13268 }
13269
13270 static void intel_shared_dpll_init(struct drm_device *dev)
13271 {
13272         struct drm_i915_private *dev_priv = dev->dev_private;
13273
13274         intel_update_cdclk(dev);
13275
13276         if (HAS_DDI(dev))
13277                 intel_ddi_pll_init(dev);
13278         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13279                 ibx_pch_dpll_init(dev);
13280         else
13281                 dev_priv->num_shared_dpll = 0;
13282
13283         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13284 }
13285
13286 /**
13287  * intel_prepare_plane_fb - Prepare fb for usage on plane
13288  * @plane: drm plane to prepare for
13289  * @fb: framebuffer to prepare for presentation
13290  *
13291  * Prepares a framebuffer for usage on a display plane.  Generally this
13292  * involves pinning the underlying object and updating the frontbuffer tracking
13293  * bits.  Some older platforms need special physical address handling for
13294  * cursor planes.
13295  *
13296  * Returns 0 on success, negative error code on failure.
13297  */
13298 int
13299 intel_prepare_plane_fb(struct drm_plane *plane,
13300                        struct drm_framebuffer *fb,
13301                        const struct drm_plane_state *new_state)
13302 {
13303         struct drm_device *dev = plane->dev;
13304         struct intel_plane *intel_plane = to_intel_plane(plane);
13305         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13306         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
13307         int ret = 0;
13308
13309         if (!obj)
13310                 return 0;
13311
13312         mutex_lock(&dev->struct_mutex);
13313
13314         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13315             INTEL_INFO(dev)->cursor_needs_physical) {
13316                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13317                 ret = i915_gem_object_attach_phys(obj, align);
13318                 if (ret)
13319                         DRM_DEBUG_KMS("failed to attach phys object\n");
13320         } else {
13321                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL, NULL);
13322         }
13323
13324         if (ret == 0)
13325                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13326
13327         mutex_unlock(&dev->struct_mutex);
13328
13329         return ret;
13330 }
13331
13332 /**
13333  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13334  * @plane: drm plane to clean up for
13335  * @fb: old framebuffer that was on plane
13336  *
13337  * Cleans up a framebuffer that has just been removed from a plane.
13338  */
13339 void
13340 intel_cleanup_plane_fb(struct drm_plane *plane,
13341                        struct drm_framebuffer *fb,
13342                        const struct drm_plane_state *old_state)
13343 {
13344         struct drm_device *dev = plane->dev;
13345         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13346
13347         if (WARN_ON(!obj))
13348                 return;
13349
13350         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
13351             !INTEL_INFO(dev)->cursor_needs_physical) {
13352                 mutex_lock(&dev->struct_mutex);
13353                 intel_unpin_fb_obj(fb, old_state);
13354                 mutex_unlock(&dev->struct_mutex);
13355         }
13356 }
13357
13358 int
13359 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13360 {
13361         int max_scale;
13362         struct drm_device *dev;
13363         struct drm_i915_private *dev_priv;
13364         int crtc_clock, cdclk;
13365
13366         if (!intel_crtc || !crtc_state)
13367                 return DRM_PLANE_HELPER_NO_SCALING;
13368
13369         dev = intel_crtc->base.dev;
13370         dev_priv = dev->dev_private;
13371         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13372         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13373
13374         if (!crtc_clock || !cdclk)
13375                 return DRM_PLANE_HELPER_NO_SCALING;
13376
13377         /*
13378          * skl max scale is lower of:
13379          *    close to 3 but not 3, -1 is for that purpose
13380          *            or
13381          *    cdclk/crtc_clock
13382          */
13383         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13384
13385         return max_scale;
13386 }
13387
13388 static int
13389 intel_check_primary_plane(struct drm_plane *plane,
13390                           struct intel_crtc_state *crtc_state,
13391                           struct intel_plane_state *state)
13392 {
13393         struct drm_crtc *crtc = state->base.crtc;
13394         struct drm_framebuffer *fb = state->base.fb;
13395         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13396         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13397         bool can_position = false;
13398
13399         /* use scaler when colorkey is not required */
13400         if (INTEL_INFO(plane->dev)->gen >= 9 &&
13401             state->ckey.flags == I915_SET_COLORKEY_NONE) {
13402                 min_scale = 1;
13403                 max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13404                 can_position = true;
13405         }
13406
13407         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13408                                              &state->dst, &state->clip,
13409                                              min_scale, max_scale,
13410                                              can_position, true,
13411                                              &state->visible);
13412 }
13413
13414 static void
13415 intel_commit_primary_plane(struct drm_plane *plane,
13416                            struct intel_plane_state *state)
13417 {
13418         struct drm_crtc *crtc = state->base.crtc;
13419         struct drm_framebuffer *fb = state->base.fb;
13420         struct drm_device *dev = plane->dev;
13421         struct drm_i915_private *dev_priv = dev->dev_private;
13422         struct intel_crtc *intel_crtc;
13423         struct drm_rect *src = &state->src;
13424
13425         crtc = crtc ? crtc : plane->crtc;
13426         intel_crtc = to_intel_crtc(crtc);
13427
13428         plane->fb = fb;
13429         crtc->x = src->x1 >> 16;
13430         crtc->y = src->y1 >> 16;
13431
13432         if (!crtc->state->active)
13433                 return;
13434
13435         if (state->visible)
13436                 /* FIXME: kill this fastboot hack */
13437                 intel_update_pipe_size(intel_crtc);
13438
13439         dev_priv->display.update_primary_plane(crtc, fb, crtc->x, crtc->y);
13440 }
13441
13442 static void
13443 intel_disable_primary_plane(struct drm_plane *plane,
13444                             struct drm_crtc *crtc)
13445 {
13446         struct drm_device *dev = plane->dev;
13447         struct drm_i915_private *dev_priv = dev->dev_private;
13448
13449         dev_priv->display.update_primary_plane(crtc, NULL, 0, 0);
13450 }
13451
13452 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13453                                     struct drm_crtc_state *old_crtc_state)
13454 {
13455         struct drm_device *dev = crtc->dev;
13456         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13457
13458         if (intel_crtc->atomic.update_wm_pre)
13459                 intel_update_watermarks(crtc);
13460
13461         /* Perform vblank evasion around commit operation */
13462         if (crtc->state->active)
13463                 intel_pipe_update_start(intel_crtc);
13464
13465         if (!needs_modeset(crtc->state) && INTEL_INFO(dev)->gen >= 9)
13466                 skl_detach_scalers(intel_crtc);
13467 }
13468
13469 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13470                                      struct drm_crtc_state *old_crtc_state)
13471 {
13472         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13473
13474         if (crtc->state->active)
13475                 intel_pipe_update_end(intel_crtc);
13476 }
13477
13478 /**
13479  * intel_plane_destroy - destroy a plane
13480  * @plane: plane to destroy
13481  *
13482  * Common destruction function for all types of planes (primary, cursor,
13483  * sprite).
13484  */
13485 void intel_plane_destroy(struct drm_plane *plane)
13486 {
13487         struct intel_plane *intel_plane = to_intel_plane(plane);
13488         drm_plane_cleanup(plane);
13489         kfree(intel_plane);
13490 }
13491
13492 const struct drm_plane_funcs intel_plane_funcs = {
13493         .update_plane = drm_atomic_helper_update_plane,
13494         .disable_plane = drm_atomic_helper_disable_plane,
13495         .destroy = intel_plane_destroy,
13496         .set_property = drm_atomic_helper_plane_set_property,
13497         .atomic_get_property = intel_plane_atomic_get_property,
13498         .atomic_set_property = intel_plane_atomic_set_property,
13499         .atomic_duplicate_state = intel_plane_duplicate_state,
13500         .atomic_destroy_state = intel_plane_destroy_state,
13501
13502 };
13503
13504 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13505                                                     int pipe)
13506 {
13507         struct intel_plane *primary;
13508         struct intel_plane_state *state;
13509         const uint32_t *intel_primary_formats;
13510         unsigned int num_formats;
13511
13512         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13513         if (primary == NULL)
13514                 return NULL;
13515
13516         state = intel_create_plane_state(&primary->base);
13517         if (!state) {
13518                 kfree(primary);
13519                 return NULL;
13520         }
13521         primary->base.state = &state->base;
13522
13523         primary->can_scale = false;
13524         primary->max_downscale = 1;
13525         if (INTEL_INFO(dev)->gen >= 9) {
13526                 primary->can_scale = true;
13527                 state->scaler_id = -1;
13528         }
13529         primary->pipe = pipe;
13530         primary->plane = pipe;
13531         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13532         primary->check_plane = intel_check_primary_plane;
13533         primary->commit_plane = intel_commit_primary_plane;
13534         primary->disable_plane = intel_disable_primary_plane;
13535         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13536                 primary->plane = !pipe;
13537
13538         if (INTEL_INFO(dev)->gen >= 9) {
13539                 intel_primary_formats = skl_primary_formats;
13540                 num_formats = ARRAY_SIZE(skl_primary_formats);
13541         } else if (INTEL_INFO(dev)->gen >= 4) {
13542                 intel_primary_formats = i965_primary_formats;
13543                 num_formats = ARRAY_SIZE(i965_primary_formats);
13544         } else {
13545                 intel_primary_formats = i8xx_primary_formats;
13546                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13547         }
13548
13549         drm_universal_plane_init(dev, &primary->base, 0,
13550                                  &intel_plane_funcs,
13551                                  intel_primary_formats, num_formats,
13552                                  DRM_PLANE_TYPE_PRIMARY);
13553
13554         if (INTEL_INFO(dev)->gen >= 4)
13555                 intel_create_rotation_property(dev, primary);
13556
13557         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13558
13559         return &primary->base;
13560 }
13561
13562 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13563 {
13564         if (!dev->mode_config.rotation_property) {
13565                 unsigned long flags = BIT(DRM_ROTATE_0) |
13566                         BIT(DRM_ROTATE_180);
13567
13568                 if (INTEL_INFO(dev)->gen >= 9)
13569                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13570
13571                 dev->mode_config.rotation_property =
13572                         drm_mode_create_rotation_property(dev, flags);
13573         }
13574         if (dev->mode_config.rotation_property)
13575                 drm_object_attach_property(&plane->base.base,
13576                                 dev->mode_config.rotation_property,
13577                                 plane->base.state->rotation);
13578 }
13579
13580 static int
13581 intel_check_cursor_plane(struct drm_plane *plane,
13582                          struct intel_crtc_state *crtc_state,
13583                          struct intel_plane_state *state)
13584 {
13585         struct drm_crtc *crtc = crtc_state->base.crtc;
13586         struct drm_framebuffer *fb = state->base.fb;
13587         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13588         unsigned stride;
13589         int ret;
13590
13591         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13592                                             &state->dst, &state->clip,
13593                                             DRM_PLANE_HELPER_NO_SCALING,
13594                                             DRM_PLANE_HELPER_NO_SCALING,
13595                                             true, true, &state->visible);
13596         if (ret)
13597                 return ret;
13598
13599         /* if we want to turn off the cursor ignore width and height */
13600         if (!obj)
13601                 return 0;
13602
13603         /* Check for which cursor types we support */
13604         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
13605                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
13606                           state->base.crtc_w, state->base.crtc_h);
13607                 return -EINVAL;
13608         }
13609
13610         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
13611         if (obj->base.size < stride * state->base.crtc_h) {
13612                 DRM_DEBUG_KMS("buffer is too small\n");
13613                 return -ENOMEM;
13614         }
13615
13616         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
13617                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
13618                 return -EINVAL;
13619         }
13620
13621         return 0;
13622 }
13623
13624 static void
13625 intel_disable_cursor_plane(struct drm_plane *plane,
13626                            struct drm_crtc *crtc)
13627 {
13628         intel_crtc_update_cursor(crtc, false);
13629 }
13630
13631 static void
13632 intel_commit_cursor_plane(struct drm_plane *plane,
13633                           struct intel_plane_state *state)
13634 {
13635         struct drm_crtc *crtc = state->base.crtc;
13636         struct drm_device *dev = plane->dev;
13637         struct intel_crtc *intel_crtc;
13638         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
13639         uint32_t addr;
13640
13641         crtc = crtc ? crtc : plane->crtc;
13642         intel_crtc = to_intel_crtc(crtc);
13643
13644         plane->fb = state->base.fb;
13645         crtc->cursor_x = state->base.crtc_x;
13646         crtc->cursor_y = state->base.crtc_y;
13647
13648         if (intel_crtc->cursor_bo == obj)
13649                 goto update;
13650
13651         if (!obj)
13652                 addr = 0;
13653         else if (!INTEL_INFO(dev)->cursor_needs_physical)
13654                 addr = i915_gem_obj_ggtt_offset(obj);
13655         else
13656                 addr = obj->phys_handle->busaddr;
13657
13658         intel_crtc->cursor_addr = addr;
13659         intel_crtc->cursor_bo = obj;
13660
13661 update:
13662         if (crtc->state->active)
13663                 intel_crtc_update_cursor(crtc, state->visible);
13664 }
13665
13666 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
13667                                                    int pipe)
13668 {
13669         struct intel_plane *cursor;
13670         struct intel_plane_state *state;
13671
13672         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13673         if (cursor == NULL)
13674                 return NULL;
13675
13676         state = intel_create_plane_state(&cursor->base);
13677         if (!state) {
13678                 kfree(cursor);
13679                 return NULL;
13680         }
13681         cursor->base.state = &state->base;
13682
13683         cursor->can_scale = false;
13684         cursor->max_downscale = 1;
13685         cursor->pipe = pipe;
13686         cursor->plane = pipe;
13687         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13688         cursor->check_plane = intel_check_cursor_plane;
13689         cursor->commit_plane = intel_commit_cursor_plane;
13690         cursor->disable_plane = intel_disable_cursor_plane;
13691
13692         drm_universal_plane_init(dev, &cursor->base, 0,
13693                                  &intel_plane_funcs,
13694                                  intel_cursor_formats,
13695                                  ARRAY_SIZE(intel_cursor_formats),
13696                                  DRM_PLANE_TYPE_CURSOR);
13697
13698         if (INTEL_INFO(dev)->gen >= 4) {
13699                 if (!dev->mode_config.rotation_property)
13700                         dev->mode_config.rotation_property =
13701                                 drm_mode_create_rotation_property(dev,
13702                                                         BIT(DRM_ROTATE_0) |
13703                                                         BIT(DRM_ROTATE_180));
13704                 if (dev->mode_config.rotation_property)
13705                         drm_object_attach_property(&cursor->base.base,
13706                                 dev->mode_config.rotation_property,
13707                                 state->base.rotation);
13708         }
13709
13710         if (INTEL_INFO(dev)->gen >=9)
13711                 state->scaler_id = -1;
13712
13713         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13714
13715         return &cursor->base;
13716 }
13717
13718 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
13719         struct intel_crtc_state *crtc_state)
13720 {
13721         int i;
13722         struct intel_scaler *intel_scaler;
13723         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
13724
13725         for (i = 0; i < intel_crtc->num_scalers; i++) {
13726                 intel_scaler = &scaler_state->scalers[i];
13727                 intel_scaler->in_use = 0;
13728                 intel_scaler->mode = PS_SCALER_MODE_DYN;
13729         }
13730
13731         scaler_state->scaler_id = -1;
13732 }
13733
13734 static void intel_crtc_init(struct drm_device *dev, int pipe)
13735 {
13736         struct drm_i915_private *dev_priv = dev->dev_private;
13737         struct intel_crtc *intel_crtc;
13738         struct intel_crtc_state *crtc_state = NULL;
13739         struct drm_plane *primary = NULL;
13740         struct drm_plane *cursor = NULL;
13741         int i, ret;
13742
13743         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13744         if (intel_crtc == NULL)
13745                 return;
13746
13747         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13748         if (!crtc_state)
13749                 goto fail;
13750         intel_crtc->config = crtc_state;
13751         intel_crtc->base.state = &crtc_state->base;
13752         crtc_state->base.crtc = &intel_crtc->base;
13753
13754         /* initialize shared scalers */
13755         if (INTEL_INFO(dev)->gen >= 9) {
13756                 if (pipe == PIPE_C)
13757                         intel_crtc->num_scalers = 1;
13758                 else
13759                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
13760
13761                 skl_init_scalers(dev, intel_crtc, crtc_state);
13762         }
13763
13764         primary = intel_primary_plane_create(dev, pipe);
13765         if (!primary)
13766                 goto fail;
13767
13768         cursor = intel_cursor_plane_create(dev, pipe);
13769         if (!cursor)
13770                 goto fail;
13771
13772         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
13773                                         cursor, &intel_crtc_funcs);
13774         if (ret)
13775                 goto fail;
13776
13777         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
13778         for (i = 0; i < 256; i++) {
13779                 intel_crtc->lut_r[i] = i;
13780                 intel_crtc->lut_g[i] = i;
13781                 intel_crtc->lut_b[i] = i;
13782         }
13783
13784         /*
13785          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
13786          * is hooked to pipe B. Hence we want plane A feeding pipe B.
13787          */
13788         intel_crtc->pipe = pipe;
13789         intel_crtc->plane = pipe;
13790         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
13791                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
13792                 intel_crtc->plane = !pipe;
13793         }
13794
13795         intel_crtc->cursor_base = ~0;
13796         intel_crtc->cursor_cntl = ~0;
13797         intel_crtc->cursor_size = ~0;
13798
13799         intel_crtc->wm.cxsr_allowed = true;
13800
13801         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13802                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13803         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
13804         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
13805
13806         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13807
13808         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13809         return;
13810
13811 fail:
13812         if (primary)
13813                 drm_plane_cleanup(primary);
13814         if (cursor)
13815                 drm_plane_cleanup(cursor);
13816         kfree(crtc_state);
13817         kfree(intel_crtc);
13818 }
13819
13820 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13821 {
13822         struct drm_encoder *encoder = connector->base.encoder;
13823         struct drm_device *dev = connector->base.dev;
13824
13825         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13826
13827         if (!encoder || WARN_ON(!encoder->crtc))
13828                 return INVALID_PIPE;
13829
13830         return to_intel_crtc(encoder->crtc)->pipe;
13831 }
13832
13833 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13834                                 struct drm_file *file)
13835 {
13836         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13837         struct drm_crtc *drmmode_crtc;
13838         struct intel_crtc *crtc;
13839
13840         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13841
13842         if (!drmmode_crtc) {
13843                 DRM_ERROR("no such CRTC id\n");
13844                 return -ENOENT;
13845         }
13846
13847         crtc = to_intel_crtc(drmmode_crtc);
13848         pipe_from_crtc_id->pipe = crtc->pipe;
13849
13850         return 0;
13851 }
13852
13853 static int intel_encoder_clones(struct intel_encoder *encoder)
13854 {
13855         struct drm_device *dev = encoder->base.dev;
13856         struct intel_encoder *source_encoder;
13857         int index_mask = 0;
13858         int entry = 0;
13859
13860         for_each_intel_encoder(dev, source_encoder) {
13861                 if (encoders_cloneable(encoder, source_encoder))
13862                         index_mask |= (1 << entry);
13863
13864                 entry++;
13865         }
13866
13867         return index_mask;
13868 }
13869
13870 static bool has_edp_a(struct drm_device *dev)
13871 {
13872         struct drm_i915_private *dev_priv = dev->dev_private;
13873
13874         if (!IS_MOBILE(dev))
13875                 return false;
13876
13877         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13878                 return false;
13879
13880         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13881                 return false;
13882
13883         return true;
13884 }
13885
13886 static bool intel_crt_present(struct drm_device *dev)
13887 {
13888         struct drm_i915_private *dev_priv = dev->dev_private;
13889
13890         if (INTEL_INFO(dev)->gen >= 9)
13891                 return false;
13892
13893         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13894                 return false;
13895
13896         if (IS_CHERRYVIEW(dev))
13897                 return false;
13898
13899         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
13900                 return false;
13901
13902         return true;
13903 }
13904
13905 static void intel_setup_outputs(struct drm_device *dev)
13906 {
13907         struct drm_i915_private *dev_priv = dev->dev_private;
13908         struct intel_encoder *encoder;
13909         bool dpd_is_edp = false;
13910
13911         intel_lvds_init(dev);
13912
13913         if (intel_crt_present(dev))
13914                 intel_crt_init(dev);
13915
13916         if (IS_BROXTON(dev)) {
13917                 /*
13918                  * FIXME: Broxton doesn't support port detection via the
13919                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13920                  * detect the ports.
13921                  */
13922                 intel_ddi_init(dev, PORT_A);
13923                 intel_ddi_init(dev, PORT_B);
13924                 intel_ddi_init(dev, PORT_C);
13925         } else if (HAS_DDI(dev)) {
13926                 int found;
13927
13928                 /*
13929                  * Haswell uses DDI functions to detect digital outputs.
13930                  * On SKL pre-D0 the strap isn't connected, so we assume
13931                  * it's there.
13932                  */
13933                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
13934                 /* WaIgnoreDDIAStrap: skl */
13935                 if (found || IS_SKYLAKE(dev))
13936                         intel_ddi_init(dev, PORT_A);
13937
13938                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13939                  * register */
13940                 found = I915_READ(SFUSE_STRAP);
13941
13942                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13943                         intel_ddi_init(dev, PORT_B);
13944                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13945                         intel_ddi_init(dev, PORT_C);
13946                 if (found & SFUSE_STRAP_DDID_DETECTED)
13947                         intel_ddi_init(dev, PORT_D);
13948                 /*
13949                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13950                  */
13951                 if (IS_SKYLAKE(dev) &&
13952                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13953                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13954                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13955                         intel_ddi_init(dev, PORT_E);
13956
13957         } else if (HAS_PCH_SPLIT(dev)) {
13958                 int found;
13959                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13960
13961                 if (has_edp_a(dev))
13962                         intel_dp_init(dev, DP_A, PORT_A);
13963
13964                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13965                         /* PCH SDVOB multiplex with HDMIB */
13966                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
13967                         if (!found)
13968                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13969                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13970                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
13971                 }
13972
13973                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13974                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
13975
13976                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13977                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
13978
13979                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13980                         intel_dp_init(dev, PCH_DP_C, PORT_C);
13981
13982                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13983                         intel_dp_init(dev, PCH_DP_D, PORT_D);
13984         } else if (IS_VALLEYVIEW(dev)) {
13985                 /*
13986                  * The DP_DETECTED bit is the latched state of the DDC
13987                  * SDA pin at boot. However since eDP doesn't require DDC
13988                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13989                  * eDP ports may have been muxed to an alternate function.
13990                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13991                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13992                  * detect eDP ports.
13993                  */
13994                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
13995                     !intel_dp_is_edp(dev, PORT_B))
13996                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
13997                                         PORT_B);
13998                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
13999                     intel_dp_is_edp(dev, PORT_B))
14000                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
14001
14002                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
14003                     !intel_dp_is_edp(dev, PORT_C))
14004                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
14005                                         PORT_C);
14006                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
14007                     intel_dp_is_edp(dev, PORT_C))
14008                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
14009
14010                 if (IS_CHERRYVIEW(dev)) {
14011                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
14012                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
14013                                                 PORT_D);
14014                         /* eDP not supported on port D, so don't check VBT */
14015                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
14016                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
14017                 }
14018
14019                 intel_dsi_init(dev);
14020         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14021                 bool found = false;
14022
14023                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14024                         DRM_DEBUG_KMS("probing SDVOB\n");
14025                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
14026                         if (!found && IS_G4X(dev)) {
14027                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14028                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14029                         }
14030
14031                         if (!found && IS_G4X(dev))
14032                                 intel_dp_init(dev, DP_B, PORT_B);
14033                 }
14034
14035                 /* Before G4X SDVOC doesn't have its own detect register */
14036
14037                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14038                         DRM_DEBUG_KMS("probing SDVOC\n");
14039                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
14040                 }
14041
14042                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14043
14044                         if (IS_G4X(dev)) {
14045                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14046                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14047                         }
14048                         if (IS_G4X(dev))
14049                                 intel_dp_init(dev, DP_C, PORT_C);
14050                 }
14051
14052                 if (IS_G4X(dev) &&
14053                     (I915_READ(DP_D) & DP_DETECTED))
14054                         intel_dp_init(dev, DP_D, PORT_D);
14055         } else if (IS_GEN2(dev))
14056                 intel_dvo_init(dev);
14057
14058         if (SUPPORTS_TV(dev))
14059                 intel_tv_init(dev);
14060
14061         intel_psr_init(dev);
14062
14063         for_each_intel_encoder(dev, encoder) {
14064                 encoder->base.possible_crtcs = encoder->crtc_mask;
14065                 encoder->base.possible_clones =
14066                         intel_encoder_clones(encoder);
14067         }
14068
14069         intel_init_pch_refclk(dev);
14070
14071         drm_helper_move_panel_connectors_to_head(dev);
14072 }
14073
14074 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14075 {
14076         struct drm_device *dev = fb->dev;
14077         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14078
14079         drm_framebuffer_cleanup(fb);
14080         mutex_lock(&dev->struct_mutex);
14081         WARN_ON(!intel_fb->obj->framebuffer_references--);
14082         drm_gem_object_unreference(&intel_fb->obj->base);
14083         mutex_unlock(&dev->struct_mutex);
14084         kfree(intel_fb);
14085 }
14086
14087 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14088                                                 struct drm_file *file,
14089                                                 unsigned int *handle)
14090 {
14091         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14092         struct drm_i915_gem_object *obj = intel_fb->obj;
14093
14094         return drm_gem_handle_create(file, &obj->base, handle);
14095 }
14096
14097 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14098                                         struct drm_file *file,
14099                                         unsigned flags, unsigned color,
14100                                         struct drm_clip_rect *clips,
14101                                         unsigned num_clips)
14102 {
14103         struct drm_device *dev = fb->dev;
14104         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14105         struct drm_i915_gem_object *obj = intel_fb->obj;
14106
14107         mutex_lock(&dev->struct_mutex);
14108         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14109         mutex_unlock(&dev->struct_mutex);
14110
14111         return 0;
14112 }
14113
14114 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14115         .destroy = intel_user_framebuffer_destroy,
14116         .create_handle = intel_user_framebuffer_create_handle,
14117         .dirty = intel_user_framebuffer_dirty,
14118 };
14119
14120 static
14121 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14122                          uint32_t pixel_format)
14123 {
14124         u32 gen = INTEL_INFO(dev)->gen;
14125
14126         if (gen >= 9) {
14127                 /* "The stride in bytes must not exceed the of the size of 8K
14128                  *  pixels and 32K bytes."
14129                  */
14130                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
14131         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
14132                 return 32*1024;
14133         } else if (gen >= 4) {
14134                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14135                         return 16*1024;
14136                 else
14137                         return 32*1024;
14138         } else if (gen >= 3) {
14139                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14140                         return 8*1024;
14141                 else
14142                         return 16*1024;
14143         } else {
14144                 /* XXX DSPC is limited to 4k tiled */
14145                 return 8*1024;
14146         }
14147 }
14148
14149 static int intel_framebuffer_init(struct drm_device *dev,
14150                                   struct intel_framebuffer *intel_fb,
14151                                   struct drm_mode_fb_cmd2 *mode_cmd,
14152                                   struct drm_i915_gem_object *obj)
14153 {
14154         unsigned int aligned_height;
14155         int ret;
14156         u32 pitch_limit, stride_alignment;
14157
14158         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14159
14160         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14161                 /* Enforce that fb modifier and tiling mode match, but only for
14162                  * X-tiled. This is needed for FBC. */
14163                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14164                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14165                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14166                         return -EINVAL;
14167                 }
14168         } else {
14169                 if (obj->tiling_mode == I915_TILING_X)
14170                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14171                 else if (obj->tiling_mode == I915_TILING_Y) {
14172                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14173                         return -EINVAL;
14174                 }
14175         }
14176
14177         /* Passed in modifier sanity checking. */
14178         switch (mode_cmd->modifier[0]) {
14179         case I915_FORMAT_MOD_Y_TILED:
14180         case I915_FORMAT_MOD_Yf_TILED:
14181                 if (INTEL_INFO(dev)->gen < 9) {
14182                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14183                                   mode_cmd->modifier[0]);
14184                         return -EINVAL;
14185                 }
14186         case DRM_FORMAT_MOD_NONE:
14187         case I915_FORMAT_MOD_X_TILED:
14188                 break;
14189         default:
14190                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14191                           mode_cmd->modifier[0]);
14192                 return -EINVAL;
14193         }
14194
14195         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14196                                                      mode_cmd->pixel_format);
14197         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14198                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14199                           mode_cmd->pitches[0], stride_alignment);
14200                 return -EINVAL;
14201         }
14202
14203         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14204                                            mode_cmd->pixel_format);
14205         if (mode_cmd->pitches[0] > pitch_limit) {
14206                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14207                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14208                           "tiled" : "linear",
14209                           mode_cmd->pitches[0], pitch_limit);
14210                 return -EINVAL;
14211         }
14212
14213         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14214             mode_cmd->pitches[0] != obj->stride) {
14215                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14216                           mode_cmd->pitches[0], obj->stride);
14217                 return -EINVAL;
14218         }
14219
14220         /* Reject formats not supported by any plane early. */
14221         switch (mode_cmd->pixel_format) {
14222         case DRM_FORMAT_C8:
14223         case DRM_FORMAT_RGB565:
14224         case DRM_FORMAT_XRGB8888:
14225         case DRM_FORMAT_ARGB8888:
14226                 break;
14227         case DRM_FORMAT_XRGB1555:
14228                 if (INTEL_INFO(dev)->gen > 3) {
14229                         DRM_DEBUG("unsupported pixel format: %s\n",
14230                                   drm_get_format_name(mode_cmd->pixel_format));
14231                         return -EINVAL;
14232                 }
14233                 break;
14234         case DRM_FORMAT_ABGR8888:
14235                 if (!IS_VALLEYVIEW(dev) && INTEL_INFO(dev)->gen < 9) {
14236                         DRM_DEBUG("unsupported pixel format: %s\n",
14237                                   drm_get_format_name(mode_cmd->pixel_format));
14238                         return -EINVAL;
14239                 }
14240                 break;
14241         case DRM_FORMAT_XBGR8888:
14242         case DRM_FORMAT_XRGB2101010:
14243         case DRM_FORMAT_XBGR2101010:
14244                 if (INTEL_INFO(dev)->gen < 4) {
14245                         DRM_DEBUG("unsupported pixel format: %s\n",
14246                                   drm_get_format_name(mode_cmd->pixel_format));
14247                         return -EINVAL;
14248                 }
14249                 break;
14250         case DRM_FORMAT_ABGR2101010:
14251                 if (!IS_VALLEYVIEW(dev)) {
14252                         DRM_DEBUG("unsupported pixel format: %s\n",
14253                                   drm_get_format_name(mode_cmd->pixel_format));
14254                         return -EINVAL;
14255                 }
14256                 break;
14257         case DRM_FORMAT_YUYV:
14258         case DRM_FORMAT_UYVY:
14259         case DRM_FORMAT_YVYU:
14260         case DRM_FORMAT_VYUY:
14261                 if (INTEL_INFO(dev)->gen < 5) {
14262                         DRM_DEBUG("unsupported pixel format: %s\n",
14263                                   drm_get_format_name(mode_cmd->pixel_format));
14264                         return -EINVAL;
14265                 }
14266                 break;
14267         default:
14268                 DRM_DEBUG("unsupported pixel format: %s\n",
14269                           drm_get_format_name(mode_cmd->pixel_format));
14270                 return -EINVAL;
14271         }
14272
14273         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14274         if (mode_cmd->offsets[0] != 0)
14275                 return -EINVAL;
14276
14277         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14278                                                mode_cmd->pixel_format,
14279                                                mode_cmd->modifier[0]);
14280         /* FIXME drm helper for size checks (especially planar formats)? */
14281         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14282                 return -EINVAL;
14283
14284         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14285         intel_fb->obj = obj;
14286         intel_fb->obj->framebuffer_references++;
14287
14288         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14289         if (ret) {
14290                 DRM_ERROR("framebuffer init failed %d\n", ret);
14291                 return ret;
14292         }
14293
14294         return 0;
14295 }
14296
14297 static struct drm_framebuffer *
14298 intel_user_framebuffer_create(struct drm_device *dev,
14299                               struct drm_file *filp,
14300                               struct drm_mode_fb_cmd2 *mode_cmd)
14301 {
14302         struct drm_i915_gem_object *obj;
14303
14304         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14305                                                 mode_cmd->handles[0]));
14306         if (&obj->base == NULL)
14307                 return ERR_PTR(-ENOENT);
14308
14309         return intel_framebuffer_create(dev, mode_cmd, obj);
14310 }
14311
14312 #ifndef CONFIG_DRM_FBDEV_EMULATION
14313 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14314 {
14315 }
14316 #endif
14317
14318 static const struct drm_mode_config_funcs intel_mode_funcs = {
14319         .fb_create = intel_user_framebuffer_create,
14320         .output_poll_changed = intel_fbdev_output_poll_changed,
14321         .atomic_check = intel_atomic_check,
14322         .atomic_commit = intel_atomic_commit,
14323         .atomic_state_alloc = intel_atomic_state_alloc,
14324         .atomic_state_clear = intel_atomic_state_clear,
14325 };
14326
14327 /* Set up chip specific display functions */
14328 static void intel_init_display(struct drm_device *dev)
14329 {
14330         struct drm_i915_private *dev_priv = dev->dev_private;
14331
14332         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14333                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14334         else if (IS_CHERRYVIEW(dev))
14335                 dev_priv->display.find_dpll = chv_find_best_dpll;
14336         else if (IS_VALLEYVIEW(dev))
14337                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14338         else if (IS_PINEVIEW(dev))
14339                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14340         else
14341                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14342
14343         if (INTEL_INFO(dev)->gen >= 9) {
14344                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14345                 dev_priv->display.get_initial_plane_config =
14346                         skylake_get_initial_plane_config;
14347                 dev_priv->display.crtc_compute_clock =
14348                         haswell_crtc_compute_clock;
14349                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14350                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14351                 dev_priv->display.update_primary_plane =
14352                         skylake_update_primary_plane;
14353         } else if (HAS_DDI(dev)) {
14354                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14355                 dev_priv->display.get_initial_plane_config =
14356                         ironlake_get_initial_plane_config;
14357                 dev_priv->display.crtc_compute_clock =
14358                         haswell_crtc_compute_clock;
14359                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14360                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14361                 dev_priv->display.update_primary_plane =
14362                         ironlake_update_primary_plane;
14363         } else if (HAS_PCH_SPLIT(dev)) {
14364                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14365                 dev_priv->display.get_initial_plane_config =
14366                         ironlake_get_initial_plane_config;
14367                 dev_priv->display.crtc_compute_clock =
14368                         ironlake_crtc_compute_clock;
14369                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14370                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14371                 dev_priv->display.update_primary_plane =
14372                         ironlake_update_primary_plane;
14373         } else if (IS_VALLEYVIEW(dev)) {
14374                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14375                 dev_priv->display.get_initial_plane_config =
14376                         i9xx_get_initial_plane_config;
14377                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14378                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14379                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14380                 dev_priv->display.update_primary_plane =
14381                         i9xx_update_primary_plane;
14382         } else {
14383                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14384                 dev_priv->display.get_initial_plane_config =
14385                         i9xx_get_initial_plane_config;
14386                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14387                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14388                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14389                 dev_priv->display.update_primary_plane =
14390                         i9xx_update_primary_plane;
14391         }
14392
14393         /* Returns the core display clock speed */
14394         if (IS_SKYLAKE(dev))
14395                 dev_priv->display.get_display_clock_speed =
14396                         skylake_get_display_clock_speed;
14397         else if (IS_BROXTON(dev))
14398                 dev_priv->display.get_display_clock_speed =
14399                         broxton_get_display_clock_speed;
14400         else if (IS_BROADWELL(dev))
14401                 dev_priv->display.get_display_clock_speed =
14402                         broadwell_get_display_clock_speed;
14403         else if (IS_HASWELL(dev))
14404                 dev_priv->display.get_display_clock_speed =
14405                         haswell_get_display_clock_speed;
14406         else if (IS_VALLEYVIEW(dev))
14407                 dev_priv->display.get_display_clock_speed =
14408                         valleyview_get_display_clock_speed;
14409         else if (IS_GEN5(dev))
14410                 dev_priv->display.get_display_clock_speed =
14411                         ilk_get_display_clock_speed;
14412         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14413                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
14414                 dev_priv->display.get_display_clock_speed =
14415                         i945_get_display_clock_speed;
14416         else if (IS_GM45(dev))
14417                 dev_priv->display.get_display_clock_speed =
14418                         gm45_get_display_clock_speed;
14419         else if (IS_CRESTLINE(dev))
14420                 dev_priv->display.get_display_clock_speed =
14421                         i965gm_get_display_clock_speed;
14422         else if (IS_PINEVIEW(dev))
14423                 dev_priv->display.get_display_clock_speed =
14424                         pnv_get_display_clock_speed;
14425         else if (IS_G33(dev) || IS_G4X(dev))
14426                 dev_priv->display.get_display_clock_speed =
14427                         g33_get_display_clock_speed;
14428         else if (IS_I915G(dev))
14429                 dev_priv->display.get_display_clock_speed =
14430                         i915_get_display_clock_speed;
14431         else if (IS_I945GM(dev) || IS_845G(dev))
14432                 dev_priv->display.get_display_clock_speed =
14433                         i9xx_misc_get_display_clock_speed;
14434         else if (IS_PINEVIEW(dev))
14435                 dev_priv->display.get_display_clock_speed =
14436                         pnv_get_display_clock_speed;
14437         else if (IS_I915GM(dev))
14438                 dev_priv->display.get_display_clock_speed =
14439                         i915gm_get_display_clock_speed;
14440         else if (IS_I865G(dev))
14441                 dev_priv->display.get_display_clock_speed =
14442                         i865_get_display_clock_speed;
14443         else if (IS_I85X(dev))
14444                 dev_priv->display.get_display_clock_speed =
14445                         i85x_get_display_clock_speed;
14446         else { /* 830 */
14447                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
14448                 dev_priv->display.get_display_clock_speed =
14449                         i830_get_display_clock_speed;
14450         }
14451
14452         if (IS_GEN5(dev)) {
14453                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14454         } else if (IS_GEN6(dev)) {
14455                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14456         } else if (IS_IVYBRIDGE(dev)) {
14457                 /* FIXME: detect B0+ stepping and use auto training */
14458                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14459         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14460                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14461                 if (IS_BROADWELL(dev)) {
14462                         dev_priv->display.modeset_commit_cdclk =
14463                                 broadwell_modeset_commit_cdclk;
14464                         dev_priv->display.modeset_calc_cdclk =
14465                                 broadwell_modeset_calc_cdclk;
14466                 }
14467         } else if (IS_VALLEYVIEW(dev)) {
14468                 dev_priv->display.modeset_commit_cdclk =
14469                         valleyview_modeset_commit_cdclk;
14470                 dev_priv->display.modeset_calc_cdclk =
14471                         valleyview_modeset_calc_cdclk;
14472         } else if (IS_BROXTON(dev)) {
14473                 dev_priv->display.modeset_commit_cdclk =
14474                         broxton_modeset_commit_cdclk;
14475                 dev_priv->display.modeset_calc_cdclk =
14476                         broxton_modeset_calc_cdclk;
14477         }
14478
14479         switch (INTEL_INFO(dev)->gen) {
14480         case 2:
14481                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14482                 break;
14483
14484         case 3:
14485                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14486                 break;
14487
14488         case 4:
14489         case 5:
14490                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14491                 break;
14492
14493         case 6:
14494                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14495                 break;
14496         case 7:
14497         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14498                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14499                 break;
14500         case 9:
14501                 /* Drop through - unsupported since execlist only. */
14502         default:
14503                 /* Default just returns -ENODEV to indicate unsupported */
14504                 dev_priv->display.queue_flip = intel_default_queue_flip;
14505         }
14506
14507         intel_panel_init_backlight_funcs(dev);
14508
14509         mutex_init(&dev_priv->pps_mutex);
14510 }
14511
14512 /*
14513  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14514  * resume, or other times.  This quirk makes sure that's the case for
14515  * affected systems.
14516  */
14517 static void quirk_pipea_force(struct drm_device *dev)
14518 {
14519         struct drm_i915_private *dev_priv = dev->dev_private;
14520
14521         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14522         DRM_INFO("applying pipe a force quirk\n");
14523 }
14524
14525 static void quirk_pipeb_force(struct drm_device *dev)
14526 {
14527         struct drm_i915_private *dev_priv = dev->dev_private;
14528
14529         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14530         DRM_INFO("applying pipe b force quirk\n");
14531 }
14532
14533 /*
14534  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14535  */
14536 static void quirk_ssc_force_disable(struct drm_device *dev)
14537 {
14538         struct drm_i915_private *dev_priv = dev->dev_private;
14539         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14540         DRM_INFO("applying lvds SSC disable quirk\n");
14541 }
14542
14543 /*
14544  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14545  * brightness value
14546  */
14547 static void quirk_invert_brightness(struct drm_device *dev)
14548 {
14549         struct drm_i915_private *dev_priv = dev->dev_private;
14550         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14551         DRM_INFO("applying inverted panel brightness quirk\n");
14552 }
14553
14554 /* Some VBT's incorrectly indicate no backlight is present */
14555 static void quirk_backlight_present(struct drm_device *dev)
14556 {
14557         struct drm_i915_private *dev_priv = dev->dev_private;
14558         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14559         DRM_INFO("applying backlight present quirk\n");
14560 }
14561
14562 struct intel_quirk {
14563         int device;
14564         int subsystem_vendor;
14565         int subsystem_device;
14566         void (*hook)(struct drm_device *dev);
14567 };
14568
14569 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14570 struct intel_dmi_quirk {
14571         void (*hook)(struct drm_device *dev);
14572         const struct dmi_system_id (*dmi_id_list)[];
14573 };
14574
14575 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14576 {
14577         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14578         return 1;
14579 }
14580
14581 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14582         {
14583                 .dmi_id_list = &(const struct dmi_system_id[]) {
14584                         {
14585                                 .callback = intel_dmi_reverse_brightness,
14586                                 .ident = "NCR Corporation",
14587                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14588                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14589                                 },
14590                         },
14591                         { }  /* terminating entry */
14592                 },
14593                 .hook = quirk_invert_brightness,
14594         },
14595 };
14596
14597 static struct intel_quirk intel_quirks[] = {
14598         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14599         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14600
14601         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14602         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14603
14604         /* 830 needs to leave pipe A & dpll A up */
14605         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14606
14607         /* 830 needs to leave pipe B & dpll B up */
14608         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14609
14610         /* Lenovo U160 cannot use SSC on LVDS */
14611         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14612
14613         /* Sony Vaio Y cannot use SSC on LVDS */
14614         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14615
14616         /* Acer Aspire 5734Z must invert backlight brightness */
14617         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14618
14619         /* Acer/eMachines G725 */
14620         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14621
14622         /* Acer/eMachines e725 */
14623         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14624
14625         /* Acer/Packard Bell NCL20 */
14626         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14627
14628         /* Acer Aspire 4736Z */
14629         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14630
14631         /* Acer Aspire 5336 */
14632         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14633
14634         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14635         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14636
14637         /* Acer C720 Chromebook (Core i3 4005U) */
14638         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14639
14640         /* Apple Macbook 2,1 (Core 2 T7400) */
14641         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14642
14643         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14644         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14645
14646         /* HP Chromebook 14 (Celeron 2955U) */
14647         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14648
14649         /* Dell Chromebook 11 */
14650         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14651 };
14652
14653 static void intel_init_quirks(struct drm_device *dev)
14654 {
14655         struct pci_dev *d = dev->pdev;
14656         int i;
14657
14658         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14659                 struct intel_quirk *q = &intel_quirks[i];
14660
14661                 if (d->device == q->device &&
14662                     (d->subsystem_vendor == q->subsystem_vendor ||
14663                      q->subsystem_vendor == PCI_ANY_ID) &&
14664                     (d->subsystem_device == q->subsystem_device ||
14665                      q->subsystem_device == PCI_ANY_ID))
14666                         q->hook(dev);
14667         }
14668         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14669                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14670                         intel_dmi_quirks[i].hook(dev);
14671         }
14672 }
14673
14674 /* Disable the VGA plane that we never use */
14675 static void i915_disable_vga(struct drm_device *dev)
14676 {
14677         struct drm_i915_private *dev_priv = dev->dev_private;
14678         u8 sr1;
14679         u32 vga_reg = i915_vgacntrl_reg(dev);
14680
14681         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14682         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
14683         outb(SR01, VGA_SR_INDEX);
14684         sr1 = inb(VGA_SR_DATA);
14685         outb(sr1 | 1<<5, VGA_SR_DATA);
14686         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
14687         udelay(300);
14688
14689         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14690         POSTING_READ(vga_reg);
14691 }
14692
14693 void intel_modeset_init_hw(struct drm_device *dev)
14694 {
14695         intel_update_cdclk(dev);
14696         intel_prepare_ddi(dev);
14697         intel_init_clock_gating(dev);
14698         intel_enable_gt_powersave(dev);
14699 }
14700
14701 void intel_modeset_init(struct drm_device *dev)
14702 {
14703         struct drm_i915_private *dev_priv = dev->dev_private;
14704         int sprite, ret;
14705         enum pipe pipe;
14706         struct intel_crtc *crtc;
14707
14708         drm_mode_config_init(dev);
14709
14710         dev->mode_config.min_width = 0;
14711         dev->mode_config.min_height = 0;
14712
14713         dev->mode_config.preferred_depth = 24;
14714         dev->mode_config.prefer_shadow = 1;
14715
14716         dev->mode_config.allow_fb_modifiers = true;
14717
14718         dev->mode_config.funcs = &intel_mode_funcs;
14719
14720         intel_init_quirks(dev);
14721
14722         intel_init_pm(dev);
14723
14724         if (INTEL_INFO(dev)->num_pipes == 0)
14725                 return;
14726
14727         /*
14728          * There may be no VBT; and if the BIOS enabled SSC we can
14729          * just keep using it to avoid unnecessary flicker.  Whereas if the
14730          * BIOS isn't using it, don't assume it will work even if the VBT
14731          * indicates as much.
14732          */
14733         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
14734                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14735                                             DREF_SSC1_ENABLE);
14736
14737                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14738                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14739                                      bios_lvds_use_ssc ? "en" : "dis",
14740                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14741                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14742                 }
14743         }
14744
14745         intel_init_display(dev);
14746         intel_init_audio(dev);
14747
14748         if (IS_GEN2(dev)) {
14749                 dev->mode_config.max_width = 2048;
14750                 dev->mode_config.max_height = 2048;
14751         } else if (IS_GEN3(dev)) {
14752                 dev->mode_config.max_width = 4096;
14753                 dev->mode_config.max_height = 4096;
14754         } else {
14755                 dev->mode_config.max_width = 8192;
14756                 dev->mode_config.max_height = 8192;
14757         }
14758
14759         if (IS_845G(dev) || IS_I865G(dev)) {
14760                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
14761                 dev->mode_config.cursor_height = 1023;
14762         } else if (IS_GEN2(dev)) {
14763                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14764                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14765         } else {
14766                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14767                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14768         }
14769
14770         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
14771
14772         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14773                       INTEL_INFO(dev)->num_pipes,
14774                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
14775
14776         for_each_pipe(dev_priv, pipe) {
14777                 intel_crtc_init(dev, pipe);
14778                 for_each_sprite(dev_priv, pipe, sprite) {
14779                         ret = intel_plane_init(dev, pipe, sprite);
14780                         if (ret)
14781                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
14782                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
14783                 }
14784         }
14785
14786         intel_shared_dpll_init(dev);
14787
14788         /* Just disable it once at startup */
14789         i915_disable_vga(dev);
14790         intel_setup_outputs(dev);
14791
14792         /* Just in case the BIOS is doing something questionable. */
14793         intel_fbc_disable(dev_priv);
14794
14795         drm_modeset_lock_all(dev);
14796         intel_modeset_setup_hw_state(dev);
14797         drm_modeset_unlock_all(dev);
14798
14799         for_each_intel_crtc(dev, crtc) {
14800                 struct intel_initial_plane_config plane_config = {};
14801
14802                 if (!crtc->active)
14803                         continue;
14804
14805                 /*
14806                  * Note that reserving the BIOS fb up front prevents us
14807                  * from stuffing other stolen allocations like the ring
14808                  * on top.  This prevents some ugliness at boot time, and
14809                  * can even allow for smooth boot transitions if the BIOS
14810                  * fb is large enough for the active pipe configuration.
14811                  */
14812                 dev_priv->display.get_initial_plane_config(crtc,
14813                                                            &plane_config);
14814
14815                 /*
14816                  * If the fb is shared between multiple heads, we'll
14817                  * just get the first one.
14818                  */
14819                 intel_find_initial_plane_obj(crtc, &plane_config);
14820         }
14821 }
14822
14823 static void intel_enable_pipe_a(struct drm_device *dev)
14824 {
14825         struct intel_connector *connector;
14826         struct drm_connector *crt = NULL;
14827         struct intel_load_detect_pipe load_detect_temp;
14828         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
14829
14830         /* We can't just switch on the pipe A, we need to set things up with a
14831          * proper mode and output configuration. As a gross hack, enable pipe A
14832          * by enabling the load detect pipe once. */
14833         for_each_intel_connector(dev, connector) {
14834                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
14835                         crt = &connector->base;
14836                         break;
14837                 }
14838         }
14839
14840         if (!crt)
14841                 return;
14842
14843         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
14844                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
14845 }
14846
14847 static bool
14848 intel_check_plane_mapping(struct intel_crtc *crtc)
14849 {
14850         struct drm_device *dev = crtc->base.dev;
14851         struct drm_i915_private *dev_priv = dev->dev_private;
14852         u32 reg, val;
14853
14854         if (INTEL_INFO(dev)->num_pipes == 1)
14855                 return true;
14856
14857         reg = DSPCNTR(!crtc->plane);
14858         val = I915_READ(reg);
14859
14860         if ((val & DISPLAY_PLANE_ENABLE) &&
14861             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
14862                 return false;
14863
14864         return true;
14865 }
14866
14867 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14868 {
14869         struct drm_device *dev = crtc->base.dev;
14870         struct intel_encoder *encoder;
14871
14872         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14873                 return true;
14874
14875         return false;
14876 }
14877
14878 static void intel_sanitize_crtc(struct intel_crtc *crtc)
14879 {
14880         struct drm_device *dev = crtc->base.dev;
14881         struct drm_i915_private *dev_priv = dev->dev_private;
14882         u32 reg;
14883
14884         /* Clear any frame start delays used for debugging left by the BIOS */
14885         reg = PIPECONF(crtc->config->cpu_transcoder);
14886         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14887
14888         /* restore vblank interrupts to correct state */
14889         drm_crtc_vblank_reset(&crtc->base);
14890         if (crtc->active) {
14891                 drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
14892                 update_scanline_offset(crtc);
14893                 drm_crtc_vblank_on(&crtc->base);
14894         }
14895
14896         /* We need to sanitize the plane -> pipe mapping first because this will
14897          * disable the crtc (and hence change the state) if it is wrong. Note
14898          * that gen4+ has a fixed plane -> pipe mapping.  */
14899         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
14900                 bool plane;
14901
14902                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
14903                               crtc->base.base.id);
14904
14905                 /* Pipe has the wrong plane attached and the plane is active.
14906                  * Temporarily change the plane mapping and disable everything
14907                  * ...  */
14908                 plane = crtc->plane;
14909                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
14910                 crtc->plane = !plane;
14911                 intel_crtc_disable_noatomic(&crtc->base);
14912                 crtc->plane = plane;
14913         }
14914
14915         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
14916             crtc->pipe == PIPE_A && !crtc->active) {
14917                 /* BIOS forgot to enable pipe A, this mostly happens after
14918                  * resume. Force-enable the pipe to fix this, the update_dpms
14919                  * call below we restore the pipe to the right state, but leave
14920                  * the required bits on. */
14921                 intel_enable_pipe_a(dev);
14922         }
14923
14924         /* Adjust the state of the output pipe according to whether we
14925          * have active connectors/encoders. */
14926         if (!intel_crtc_has_encoders(crtc))
14927                 intel_crtc_disable_noatomic(&crtc->base);
14928
14929         if (crtc->active != crtc->base.state->active) {
14930                 struct intel_encoder *encoder;
14931
14932                 /* This can happen either due to bugs in the get_hw_state
14933                  * functions or because of calls to intel_crtc_disable_noatomic,
14934                  * or because the pipe is force-enabled due to the
14935                  * pipe A quirk. */
14936                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
14937                               crtc->base.base.id,
14938                               crtc->base.state->enable ? "enabled" : "disabled",
14939                               crtc->active ? "enabled" : "disabled");
14940
14941                 WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, NULL) < 0);
14942                 crtc->base.state->active = crtc->active;
14943                 crtc->base.enabled = crtc->active;
14944
14945                 /* Because we only establish the connector -> encoder ->
14946                  * crtc links if something is active, this means the
14947                  * crtc is now deactivated. Break the links. connector
14948                  * -> encoder links are only establish when things are
14949                  *  actually up, hence no need to break them. */
14950                 WARN_ON(crtc->active);
14951
14952                 for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14953                         encoder->base.crtc = NULL;
14954         }
14955
14956         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
14957                 /*
14958                  * We start out with underrun reporting disabled to avoid races.
14959                  * For correct bookkeeping mark this on active crtcs.
14960                  *
14961                  * Also on gmch platforms we dont have any hardware bits to
14962                  * disable the underrun reporting. Which means we need to start
14963                  * out with underrun reporting disabled also on inactive pipes,
14964                  * since otherwise we'll complain about the garbage we read when
14965                  * e.g. coming up after runtime pm.
14966                  *
14967                  * No protection against concurrent access is required - at
14968                  * worst a fifo underrun happens which also sets this to false.
14969                  */
14970                 crtc->cpu_fifo_underrun_disabled = true;
14971                 crtc->pch_fifo_underrun_disabled = true;
14972         }
14973 }
14974
14975 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14976 {
14977         struct intel_connector *connector;
14978         struct drm_device *dev = encoder->base.dev;
14979         bool active = false;
14980
14981         /* We need to check both for a crtc link (meaning that the
14982          * encoder is active and trying to read from a pipe) and the
14983          * pipe itself being active. */
14984         bool has_active_crtc = encoder->base.crtc &&
14985                 to_intel_crtc(encoder->base.crtc)->active;
14986
14987         for_each_intel_connector(dev, connector) {
14988                 if (connector->base.encoder != &encoder->base)
14989                         continue;
14990
14991                 active = true;
14992                 break;
14993         }
14994
14995         if (active && !has_active_crtc) {
14996                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14997                               encoder->base.base.id,
14998                               encoder->base.name);
14999
15000                 /* Connector is active, but has no active pipe. This is
15001                  * fallout from our resume register restoring. Disable
15002                  * the encoder manually again. */
15003                 if (encoder->base.crtc) {
15004                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15005                                       encoder->base.base.id,
15006                                       encoder->base.name);
15007                         encoder->disable(encoder);
15008                         if (encoder->post_disable)
15009                                 encoder->post_disable(encoder);
15010                 }
15011                 encoder->base.crtc = NULL;
15012
15013                 /* Inconsistent output/port/pipe state happens presumably due to
15014                  * a bug in one of the get_hw_state functions. Or someplace else
15015                  * in our code, like the register restore mess on resume. Clamp
15016                  * things to off as a safer default. */
15017                 for_each_intel_connector(dev, connector) {
15018                         if (connector->encoder != encoder)
15019                                 continue;
15020                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15021                         connector->base.encoder = NULL;
15022                 }
15023         }
15024         /* Enabled encoders without active connectors will be fixed in
15025          * the crtc fixup. */
15026 }
15027
15028 void i915_redisable_vga_power_on(struct drm_device *dev)
15029 {
15030         struct drm_i915_private *dev_priv = dev->dev_private;
15031         u32 vga_reg = i915_vgacntrl_reg(dev);
15032
15033         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15034                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15035                 i915_disable_vga(dev);
15036         }
15037 }
15038
15039 void i915_redisable_vga(struct drm_device *dev)
15040 {
15041         struct drm_i915_private *dev_priv = dev->dev_private;
15042
15043         /* This function can be called both from intel_modeset_setup_hw_state or
15044          * at a very early point in our resume sequence, where the power well
15045          * structures are not yet restored. Since this function is at a very
15046          * paranoid "someone might have enabled VGA while we were not looking"
15047          * level, just check if the power well is enabled instead of trying to
15048          * follow the "don't touch the power well if we don't need it" policy
15049          * the rest of the driver uses. */
15050         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
15051                 return;
15052
15053         i915_redisable_vga_power_on(dev);
15054 }
15055
15056 static bool primary_get_hw_state(struct intel_crtc *crtc)
15057 {
15058         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
15059
15060         return !!(I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE);
15061 }
15062
15063 static void readout_plane_state(struct intel_crtc *crtc,
15064                                 struct intel_crtc_state *crtc_state)
15065 {
15066         struct intel_plane *p;
15067         struct intel_plane_state *plane_state;
15068         bool active = crtc_state->base.active;
15069
15070         for_each_intel_plane(crtc->base.dev, p) {
15071                 if (crtc->pipe != p->pipe)
15072                         continue;
15073
15074                 plane_state = to_intel_plane_state(p->base.state);
15075
15076                 if (p->base.type == DRM_PLANE_TYPE_PRIMARY)
15077                         plane_state->visible = primary_get_hw_state(crtc);
15078                 else {
15079                         if (active)
15080                                 p->disable_plane(&p->base, &crtc->base);
15081
15082                         plane_state->visible = false;
15083                 }
15084         }
15085 }
15086
15087 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15088 {
15089         struct drm_i915_private *dev_priv = dev->dev_private;
15090         enum pipe pipe;
15091         struct intel_crtc *crtc;
15092         struct intel_encoder *encoder;
15093         struct intel_connector *connector;
15094         int i;
15095
15096         for_each_intel_crtc(dev, crtc) {
15097                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, crtc->base.state);
15098                 memset(crtc->config, 0, sizeof(*crtc->config));
15099                 crtc->config->base.crtc = &crtc->base;
15100
15101                 crtc->active = dev_priv->display.get_pipe_config(crtc,
15102                                                                  crtc->config);
15103
15104                 crtc->base.state->active = crtc->active;
15105                 crtc->base.enabled = crtc->active;
15106
15107                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15108                 if (crtc->base.state->active) {
15109                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15110                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15111                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15112
15113                         /*
15114                          * The initial mode needs to be set in order to keep
15115                          * the atomic core happy. It wants a valid mode if the
15116                          * crtc's enabled, so we do the above call.
15117                          *
15118                          * At this point some state updated by the connectors
15119                          * in their ->detect() callback has not run yet, so
15120                          * no recalculation can be done yet.
15121                          *
15122                          * Even if we could do a recalculation and modeset
15123                          * right now it would cause a double modeset if
15124                          * fbdev or userspace chooses a different initial mode.
15125                          *
15126                          * If that happens, someone indicated they wanted a
15127                          * mode change, which means it's safe to do a full
15128                          * recalculation.
15129                          */
15130                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15131                 }
15132
15133                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15134                 readout_plane_state(crtc, to_intel_crtc_state(crtc->base.state));
15135
15136                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15137                               crtc->base.base.id,
15138                               crtc->active ? "enabled" : "disabled");
15139         }
15140
15141         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15142                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15143
15144                 pll->on = pll->get_hw_state(dev_priv, pll,
15145                                             &pll->config.hw_state);
15146                 pll->active = 0;
15147                 pll->config.crtc_mask = 0;
15148                 for_each_intel_crtc(dev, crtc) {
15149                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15150                                 pll->active++;
15151                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15152                         }
15153                 }
15154
15155                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15156                               pll->name, pll->config.crtc_mask, pll->on);
15157
15158                 if (pll->config.crtc_mask)
15159                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15160         }
15161
15162         for_each_intel_encoder(dev, encoder) {
15163                 pipe = 0;
15164
15165                 if (encoder->get_hw_state(encoder, &pipe)) {
15166                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15167                         encoder->base.crtc = &crtc->base;
15168                         encoder->get_config(encoder, crtc->config);
15169                 } else {
15170                         encoder->base.crtc = NULL;
15171                 }
15172
15173                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15174                               encoder->base.base.id,
15175                               encoder->base.name,
15176                               encoder->base.crtc ? "enabled" : "disabled",
15177                               pipe_name(pipe));
15178         }
15179
15180         for_each_intel_connector(dev, connector) {
15181                 if (connector->get_hw_state(connector)) {
15182                         connector->base.dpms = DRM_MODE_DPMS_ON;
15183                         connector->base.encoder = &connector->encoder->base;
15184                 } else {
15185                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15186                         connector->base.encoder = NULL;
15187                 }
15188                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15189                               connector->base.base.id,
15190                               connector->base.name,
15191                               connector->base.encoder ? "enabled" : "disabled");
15192         }
15193 }
15194
15195 /* Scan out the current hw modeset state,
15196  * and sanitizes it to the current state
15197  */
15198 static void
15199 intel_modeset_setup_hw_state(struct drm_device *dev)
15200 {
15201         struct drm_i915_private *dev_priv = dev->dev_private;
15202         enum pipe pipe;
15203         struct intel_crtc *crtc;
15204         struct intel_encoder *encoder;
15205         int i;
15206
15207         intel_modeset_readout_hw_state(dev);
15208
15209         /* HW state is read out, now we need to sanitize this mess. */
15210         for_each_intel_encoder(dev, encoder) {
15211                 intel_sanitize_encoder(encoder);
15212         }
15213
15214         for_each_pipe(dev_priv, pipe) {
15215                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15216                 intel_sanitize_crtc(crtc);
15217                 intel_dump_pipe_config(crtc, crtc->config,
15218                                        "[setup_hw_state]");
15219         }
15220
15221         intel_modeset_update_connector_atomic_state(dev);
15222
15223         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15224                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15225
15226                 if (!pll->on || pll->active)
15227                         continue;
15228
15229                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15230
15231                 pll->disable(dev_priv, pll);
15232                 pll->on = false;
15233         }
15234
15235         if (IS_VALLEYVIEW(dev))
15236                 vlv_wm_get_hw_state(dev);
15237         else if (IS_GEN9(dev))
15238                 skl_wm_get_hw_state(dev);
15239         else if (HAS_PCH_SPLIT(dev))
15240                 ilk_wm_get_hw_state(dev);
15241
15242         for_each_intel_crtc(dev, crtc) {
15243                 unsigned long put_domains;
15244
15245                 put_domains = modeset_get_crtc_power_domains(&crtc->base);
15246                 if (WARN_ON(put_domains))
15247                         modeset_put_power_domains(dev_priv, put_domains);
15248         }
15249         intel_display_set_init_power(dev_priv, false);
15250 }
15251
15252 void intel_display_resume(struct drm_device *dev)
15253 {
15254         struct drm_atomic_state *state = drm_atomic_state_alloc(dev);
15255         struct intel_connector *conn;
15256         struct intel_plane *plane;
15257         struct drm_crtc *crtc;
15258         int ret;
15259
15260         if (!state)
15261                 return;
15262
15263         state->acquire_ctx = dev->mode_config.acquire_ctx;
15264
15265         /* preserve complete old state, including dpll */
15266         intel_atomic_get_shared_dpll_state(state);
15267
15268         for_each_crtc(dev, crtc) {
15269                 struct drm_crtc_state *crtc_state =
15270                         drm_atomic_get_crtc_state(state, crtc);
15271
15272                 ret = PTR_ERR_OR_ZERO(crtc_state);
15273                 if (ret)
15274                         goto err;
15275
15276                 /* force a restore */
15277                 crtc_state->mode_changed = true;
15278         }
15279
15280         for_each_intel_plane(dev, plane) {
15281                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(state, &plane->base));
15282                 if (ret)
15283                         goto err;
15284         }
15285
15286         for_each_intel_connector(dev, conn) {
15287                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(state, &conn->base));
15288                 if (ret)
15289                         goto err;
15290         }
15291
15292         intel_modeset_setup_hw_state(dev);
15293
15294         i915_redisable_vga(dev);
15295         ret = drm_atomic_commit(state);
15296         if (!ret)
15297                 return;
15298
15299 err:
15300         DRM_ERROR("Restoring old state failed with %i\n", ret);
15301         drm_atomic_state_free(state);
15302 }
15303
15304 void intel_modeset_gem_init(struct drm_device *dev)
15305 {
15306         struct drm_crtc *c;
15307         struct drm_i915_gem_object *obj;
15308         int ret;
15309
15310         mutex_lock(&dev->struct_mutex);
15311         intel_init_gt_powersave(dev);
15312         mutex_unlock(&dev->struct_mutex);
15313
15314         intel_modeset_init_hw(dev);
15315
15316         intel_setup_overlay(dev);
15317
15318         /*
15319          * Make sure any fbs we allocated at startup are properly
15320          * pinned & fenced.  When we do the allocation it's too early
15321          * for this.
15322          */
15323         for_each_crtc(dev, c) {
15324                 obj = intel_fb_obj(c->primary->fb);
15325                 if (obj == NULL)
15326                         continue;
15327
15328                 mutex_lock(&dev->struct_mutex);
15329                 ret = intel_pin_and_fence_fb_obj(c->primary,
15330                                                  c->primary->fb,
15331                                                  c->primary->state,
15332                                                  NULL, NULL);
15333                 mutex_unlock(&dev->struct_mutex);
15334                 if (ret) {
15335                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15336                                   to_intel_crtc(c)->pipe);
15337                         drm_framebuffer_unreference(c->primary->fb);
15338                         c->primary->fb = NULL;
15339                         c->primary->crtc = c->primary->state->crtc = NULL;
15340                         update_state_fb(c->primary);
15341                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15342                 }
15343         }
15344
15345         intel_backlight_register(dev);
15346 }
15347
15348 void intel_connector_unregister(struct intel_connector *intel_connector)
15349 {
15350         struct drm_connector *connector = &intel_connector->base;
15351
15352         intel_panel_destroy_backlight(connector);
15353         drm_connector_unregister(connector);
15354 }
15355
15356 void intel_modeset_cleanup(struct drm_device *dev)
15357 {
15358         struct drm_i915_private *dev_priv = dev->dev_private;
15359         struct drm_connector *connector;
15360
15361         intel_disable_gt_powersave(dev);
15362
15363         intel_backlight_unregister(dev);
15364
15365         /*
15366          * Interrupts and polling as the first thing to avoid creating havoc.
15367          * Too much stuff here (turning of connectors, ...) would
15368          * experience fancy races otherwise.
15369          */
15370         intel_irq_uninstall(dev_priv);
15371
15372         /*
15373          * Due to the hpd irq storm handling the hotplug work can re-arm the
15374          * poll handlers. Hence disable polling after hpd handling is shut down.
15375          */
15376         drm_kms_helper_poll_fini(dev);
15377
15378         intel_unregister_dsm_handler();
15379
15380         intel_fbc_disable(dev_priv);
15381
15382         /* flush any delayed tasks or pending work */
15383         flush_scheduled_work();
15384
15385         /* destroy the backlight and sysfs files before encoders/connectors */
15386         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15387                 struct intel_connector *intel_connector;
15388
15389                 intel_connector = to_intel_connector(connector);
15390                 intel_connector->unregister(intel_connector);
15391         }
15392
15393         drm_mode_config_cleanup(dev);
15394
15395         intel_cleanup_overlay(dev);
15396
15397         mutex_lock(&dev->struct_mutex);
15398         intel_cleanup_gt_powersave(dev);
15399         mutex_unlock(&dev->struct_mutex);
15400 }
15401
15402 /*
15403  * Return which encoder is currently attached for connector.
15404  */
15405 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15406 {
15407         return &intel_attached_encoder(connector)->base;
15408 }
15409
15410 void intel_connector_attach_encoder(struct intel_connector *connector,
15411                                     struct intel_encoder *encoder)
15412 {
15413         connector->encoder = encoder;
15414         drm_mode_connector_attach_encoder(&connector->base,
15415                                           &encoder->base);
15416 }
15417
15418 /*
15419  * set vga decode state - true == enable VGA decode
15420  */
15421 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15422 {
15423         struct drm_i915_private *dev_priv = dev->dev_private;
15424         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15425         u16 gmch_ctrl;
15426
15427         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15428                 DRM_ERROR("failed to read control word\n");
15429                 return -EIO;
15430         }
15431
15432         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15433                 return 0;
15434
15435         if (state)
15436                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15437         else
15438                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15439
15440         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15441                 DRM_ERROR("failed to write control word\n");
15442                 return -EIO;
15443         }
15444
15445         return 0;
15446 }
15447
15448 struct intel_display_error_state {
15449
15450         u32 power_well_driver;
15451
15452         int num_transcoders;
15453
15454         struct intel_cursor_error_state {
15455                 u32 control;
15456                 u32 position;
15457                 u32 base;
15458                 u32 size;
15459         } cursor[I915_MAX_PIPES];
15460
15461         struct intel_pipe_error_state {
15462                 bool power_domain_on;
15463                 u32 source;
15464                 u32 stat;
15465         } pipe[I915_MAX_PIPES];
15466
15467         struct intel_plane_error_state {
15468                 u32 control;
15469                 u32 stride;
15470                 u32 size;
15471                 u32 pos;
15472                 u32 addr;
15473                 u32 surface;
15474                 u32 tile_offset;
15475         } plane[I915_MAX_PIPES];
15476
15477         struct intel_transcoder_error_state {
15478                 bool power_domain_on;
15479                 enum transcoder cpu_transcoder;
15480
15481                 u32 conf;
15482
15483                 u32 htotal;
15484                 u32 hblank;
15485                 u32 hsync;
15486                 u32 vtotal;
15487                 u32 vblank;
15488                 u32 vsync;
15489         } transcoder[4];
15490 };
15491
15492 struct intel_display_error_state *
15493 intel_display_capture_error_state(struct drm_device *dev)
15494 {
15495         struct drm_i915_private *dev_priv = dev->dev_private;
15496         struct intel_display_error_state *error;
15497         int transcoders[] = {
15498                 TRANSCODER_A,
15499                 TRANSCODER_B,
15500                 TRANSCODER_C,
15501                 TRANSCODER_EDP,
15502         };
15503         int i;
15504
15505         if (INTEL_INFO(dev)->num_pipes == 0)
15506                 return NULL;
15507
15508         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15509         if (error == NULL)
15510                 return NULL;
15511
15512         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15513                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15514
15515         for_each_pipe(dev_priv, i) {
15516                 error->pipe[i].power_domain_on =
15517                         __intel_display_power_is_enabled(dev_priv,
15518                                                          POWER_DOMAIN_PIPE(i));
15519                 if (!error->pipe[i].power_domain_on)
15520                         continue;
15521
15522                 error->cursor[i].control = I915_READ(CURCNTR(i));
15523                 error->cursor[i].position = I915_READ(CURPOS(i));
15524                 error->cursor[i].base = I915_READ(CURBASE(i));
15525
15526                 error->plane[i].control = I915_READ(DSPCNTR(i));
15527                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15528                 if (INTEL_INFO(dev)->gen <= 3) {
15529                         error->plane[i].size = I915_READ(DSPSIZE(i));
15530                         error->plane[i].pos = I915_READ(DSPPOS(i));
15531                 }
15532                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15533                         error->plane[i].addr = I915_READ(DSPADDR(i));
15534                 if (INTEL_INFO(dev)->gen >= 4) {
15535                         error->plane[i].surface = I915_READ(DSPSURF(i));
15536                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15537                 }
15538
15539                 error->pipe[i].source = I915_READ(PIPESRC(i));
15540
15541                 if (HAS_GMCH_DISPLAY(dev))
15542                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15543         }
15544
15545         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15546         if (HAS_DDI(dev_priv->dev))
15547                 error->num_transcoders++; /* Account for eDP. */
15548
15549         for (i = 0; i < error->num_transcoders; i++) {
15550                 enum transcoder cpu_transcoder = transcoders[i];
15551
15552                 error->transcoder[i].power_domain_on =
15553                         __intel_display_power_is_enabled(dev_priv,
15554                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15555                 if (!error->transcoder[i].power_domain_on)
15556                         continue;
15557
15558                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15559
15560                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15561                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15562                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15563                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15564                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15565                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15566                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15567         }
15568
15569         return error;
15570 }
15571
15572 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15573
15574 void
15575 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15576                                 struct drm_device *dev,
15577                                 struct intel_display_error_state *error)
15578 {
15579         struct drm_i915_private *dev_priv = dev->dev_private;
15580         int i;
15581
15582         if (!error)
15583                 return;
15584
15585         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15586         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15587                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15588                            error->power_well_driver);
15589         for_each_pipe(dev_priv, i) {
15590                 err_printf(m, "Pipe [%d]:\n", i);
15591                 err_printf(m, "  Power: %s\n",
15592                            error->pipe[i].power_domain_on ? "on" : "off");
15593                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15594                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15595
15596                 err_printf(m, "Plane [%d]:\n", i);
15597                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15598                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15599                 if (INTEL_INFO(dev)->gen <= 3) {
15600                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15601                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15602                 }
15603                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15604                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15605                 if (INTEL_INFO(dev)->gen >= 4) {
15606                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15607                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15608                 }
15609
15610                 err_printf(m, "Cursor [%d]:\n", i);
15611                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15612                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15613                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15614         }
15615
15616         for (i = 0; i < error->num_transcoders; i++) {
15617                 err_printf(m, "CPU transcoder: %c\n",
15618                            transcoder_name(error->transcoder[i].cpu_transcoder));
15619                 err_printf(m, "  Power: %s\n",
15620                            error->transcoder[i].power_domain_on ? "on" : "off");
15621                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15622                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15623                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15624                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15625                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15626                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15627                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15628         }
15629 }
15630
15631 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15632 {
15633         struct intel_crtc *crtc;
15634
15635         for_each_intel_crtc(dev, crtc) {
15636                 struct intel_unpin_work *work;
15637
15638                 spin_lock_irq(&dev->event_lock);
15639
15640                 work = crtc->unpin_work;
15641
15642                 if (work && work->event &&
15643                     work->event->base.file_priv == file) {
15644                         kfree(work->event);
15645                         work->event = NULL;
15646                 }
15647
15648                 spin_unlock_irq(&dev->event_lock);
15649         }
15650 }