1/*
2 * Copyright © 2006-2007 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 *
23 * Authors:
24 *	Eric Anholt <eric@anholt.net>
25 */
26
27#include <linux/dmi.h>
28#include <linux/module.h>
29#include <linux/input.h>
30#include <linux/i2c.h>
31#include <linux/kernel.h>
32#include <linux/slab.h>
33#include <linux/vgaarb.h>
34#include <drm/drm_edid.h>
35#include <drm/drmP.h>
36#include "intel_drv.h"
37#include <drm/i915_drm.h>
38#include "i915_drv.h"
39#include "i915_trace.h"
40#include <drm/drm_atomic.h>
41#include <drm/drm_atomic_helper.h>
42#include <drm/drm_dp_helper.h>
43#include <drm/drm_crtc_helper.h>
44#include <drm/drm_plane_helper.h>
45#include <drm/drm_rect.h>
46#include <linux/dma_remapping.h>
47
48/* Primary plane formats supported by all gen */
49#define COMMON_PRIMARY_FORMATS \
50	DRM_FORMAT_C8, \
51	DRM_FORMAT_RGB565, \
52	DRM_FORMAT_XRGB8888, \
53	DRM_FORMAT_ARGB8888
54
55/* Primary plane formats for gen <= 3 */
56static const uint32_t intel_primary_formats_gen2[] = {
57	COMMON_PRIMARY_FORMATS,
58	DRM_FORMAT_XRGB1555,
59	DRM_FORMAT_ARGB1555,
60};
61
62/* Primary plane formats for gen >= 4 */
63static const uint32_t intel_primary_formats_gen4[] = {
64	COMMON_PRIMARY_FORMATS, \
65	DRM_FORMAT_XBGR8888,
66	DRM_FORMAT_ABGR8888,
67	DRM_FORMAT_XRGB2101010,
68	DRM_FORMAT_ARGB2101010,
69	DRM_FORMAT_XBGR2101010,
70	DRM_FORMAT_ABGR2101010,
71};
72
73/* Cursor formats */
74static const uint32_t intel_cursor_formats[] = {
75	DRM_FORMAT_ARGB8888,
76};
77
78static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
79
80static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
81				struct intel_crtc_state *pipe_config);
82static void ironlake_pch_clock_get(struct intel_crtc *crtc,
83				   struct intel_crtc_state *pipe_config);
84
85static int intel_set_mode(struct drm_crtc *crtc, struct drm_display_mode *mode,
86			  int x, int y, struct drm_framebuffer *old_fb,
87			  struct drm_atomic_state *state);
88static int intel_framebuffer_init(struct drm_device *dev,
89				  struct intel_framebuffer *ifb,
90				  struct drm_mode_fb_cmd2 *mode_cmd,
91				  struct drm_i915_gem_object *obj);
92static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
93static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
94static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
95					 struct intel_link_m_n *m_n,
96					 struct intel_link_m_n *m2_n2);
97static void ironlake_set_pipeconf(struct drm_crtc *crtc);
98static void haswell_set_pipeconf(struct drm_crtc *crtc);
99static void intel_set_pipe_csc(struct drm_crtc *crtc);
100static void vlv_prepare_pll(struct intel_crtc *crtc,
101			    const struct intel_crtc_state *pipe_config);
102static void chv_prepare_pll(struct intel_crtc *crtc,
103			    const struct intel_crtc_state *pipe_config);
104static void intel_begin_crtc_commit(struct drm_crtc *crtc);
105static void intel_finish_crtc_commit(struct drm_crtc *crtc);
106
107static struct intel_encoder *intel_find_encoder(struct intel_connector *connector, int pipe)
108{
109	if (!connector->mst_port)
110		return connector->encoder;
111	else
112		return &connector->mst_port->mst_encoders[pipe]->base;
113}
114
115typedef struct {
116	int	min, max;
117} intel_range_t;
118
119typedef struct {
120	int	dot_limit;
121	int	p2_slow, p2_fast;
122} intel_p2_t;
123
124typedef struct intel_limit intel_limit_t;
125struct intel_limit {
126	intel_range_t   dot, vco, n, m, m1, m2, p, p1;
127	intel_p2_t	    p2;
128};
129
130int
131intel_pch_rawclk(struct drm_device *dev)
132{
133	struct drm_i915_private *dev_priv = dev->dev_private;
134
135	WARN_ON(!HAS_PCH_SPLIT(dev));
136
137	return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
138}
139
140static inline u32 /* units of 100MHz */
141intel_fdi_link_freq(struct drm_device *dev)
142{
143	if (IS_GEN5(dev)) {
144		struct drm_i915_private *dev_priv = dev->dev_private;
145		return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
146	} else
147		return 27;
148}
149
150static const intel_limit_t intel_limits_i8xx_dac = {
151	.dot = { .min = 25000, .max = 350000 },
152	.vco = { .min = 908000, .max = 1512000 },
153	.n = { .min = 2, .max = 16 },
154	.m = { .min = 96, .max = 140 },
155	.m1 = { .min = 18, .max = 26 },
156	.m2 = { .min = 6, .max = 16 },
157	.p = { .min = 4, .max = 128 },
158	.p1 = { .min = 2, .max = 33 },
159	.p2 = { .dot_limit = 165000,
160		.p2_slow = 4, .p2_fast = 2 },
161};
162
163static const intel_limit_t intel_limits_i8xx_dvo = {
164	.dot = { .min = 25000, .max = 350000 },
165	.vco = { .min = 908000, .max = 1512000 },
166	.n = { .min = 2, .max = 16 },
167	.m = { .min = 96, .max = 140 },
168	.m1 = { .min = 18, .max = 26 },
169	.m2 = { .min = 6, .max = 16 },
170	.p = { .min = 4, .max = 128 },
171	.p1 = { .min = 2, .max = 33 },
172	.p2 = { .dot_limit = 165000,
173		.p2_slow = 4, .p2_fast = 4 },
174};
175
176static const intel_limit_t intel_limits_i8xx_lvds = {
177	.dot = { .min = 25000, .max = 350000 },
178	.vco = { .min = 908000, .max = 1512000 },
179	.n = { .min = 2, .max = 16 },
180	.m = { .min = 96, .max = 140 },
181	.m1 = { .min = 18, .max = 26 },
182	.m2 = { .min = 6, .max = 16 },
183	.p = { .min = 4, .max = 128 },
184	.p1 = { .min = 1, .max = 6 },
185	.p2 = { .dot_limit = 165000,
186		.p2_slow = 14, .p2_fast = 7 },
187};
188
189static const intel_limit_t intel_limits_i9xx_sdvo = {
190	.dot = { .min = 20000, .max = 400000 },
191	.vco = { .min = 1400000, .max = 2800000 },
192	.n = { .min = 1, .max = 6 },
193	.m = { .min = 70, .max = 120 },
194	.m1 = { .min = 8, .max = 18 },
195	.m2 = { .min = 3, .max = 7 },
196	.p = { .min = 5, .max = 80 },
197	.p1 = { .min = 1, .max = 8 },
198	.p2 = { .dot_limit = 200000,
199		.p2_slow = 10, .p2_fast = 5 },
200};
201
202static const intel_limit_t intel_limits_i9xx_lvds = {
203	.dot = { .min = 20000, .max = 400000 },
204	.vco = { .min = 1400000, .max = 2800000 },
205	.n = { .min = 1, .max = 6 },
206	.m = { .min = 70, .max = 120 },
207	.m1 = { .min = 8, .max = 18 },
208	.m2 = { .min = 3, .max = 7 },
209	.p = { .min = 7, .max = 98 },
210	.p1 = { .min = 1, .max = 8 },
211	.p2 = { .dot_limit = 112000,
212		.p2_slow = 14, .p2_fast = 7 },
213};
214
215
216static const intel_limit_t intel_limits_g4x_sdvo = {
217	.dot = { .min = 25000, .max = 270000 },
218	.vco = { .min = 1750000, .max = 3500000},
219	.n = { .min = 1, .max = 4 },
220	.m = { .min = 104, .max = 138 },
221	.m1 = { .min = 17, .max = 23 },
222	.m2 = { .min = 5, .max = 11 },
223	.p = { .min = 10, .max = 30 },
224	.p1 = { .min = 1, .max = 3},
225	.p2 = { .dot_limit = 270000,
226		.p2_slow = 10,
227		.p2_fast = 10
228	},
229};
230
231static const intel_limit_t intel_limits_g4x_hdmi = {
232	.dot = { .min = 22000, .max = 400000 },
233	.vco = { .min = 1750000, .max = 3500000},
234	.n = { .min = 1, .max = 4 },
235	.m = { .min = 104, .max = 138 },
236	.m1 = { .min = 16, .max = 23 },
237	.m2 = { .min = 5, .max = 11 },
238	.p = { .min = 5, .max = 80 },
239	.p1 = { .min = 1, .max = 8},
240	.p2 = { .dot_limit = 165000,
241		.p2_slow = 10, .p2_fast = 5 },
242};
243
244static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
245	.dot = { .min = 20000, .max = 115000 },
246	.vco = { .min = 1750000, .max = 3500000 },
247	.n = { .min = 1, .max = 3 },
248	.m = { .min = 104, .max = 138 },
249	.m1 = { .min = 17, .max = 23 },
250	.m2 = { .min = 5, .max = 11 },
251	.p = { .min = 28, .max = 112 },
252	.p1 = { .min = 2, .max = 8 },
253	.p2 = { .dot_limit = 0,
254		.p2_slow = 14, .p2_fast = 14
255	},
256};
257
258static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
259	.dot = { .min = 80000, .max = 224000 },
260	.vco = { .min = 1750000, .max = 3500000 },
261	.n = { .min = 1, .max = 3 },
262	.m = { .min = 104, .max = 138 },
263	.m1 = { .min = 17, .max = 23 },
264	.m2 = { .min = 5, .max = 11 },
265	.p = { .min = 14, .max = 42 },
266	.p1 = { .min = 2, .max = 6 },
267	.p2 = { .dot_limit = 0,
268		.p2_slow = 7, .p2_fast = 7
269	},
270};
271
272static const intel_limit_t intel_limits_pineview_sdvo = {
273	.dot = { .min = 20000, .max = 400000},
274	.vco = { .min = 1700000, .max = 3500000 },
275	/* Pineview's Ncounter is a ring counter */
276	.n = { .min = 3, .max = 6 },
277	.m = { .min = 2, .max = 256 },
278	/* Pineview only has one combined m divider, which we treat as m2. */
279	.m1 = { .min = 0, .max = 0 },
280	.m2 = { .min = 0, .max = 254 },
281	.p = { .min = 5, .max = 80 },
282	.p1 = { .min = 1, .max = 8 },
283	.p2 = { .dot_limit = 200000,
284		.p2_slow = 10, .p2_fast = 5 },
285};
286
287static const intel_limit_t intel_limits_pineview_lvds = {
288	.dot = { .min = 20000, .max = 400000 },
289	.vco = { .min = 1700000, .max = 3500000 },
290	.n = { .min = 3, .max = 6 },
291	.m = { .min = 2, .max = 256 },
292	.m1 = { .min = 0, .max = 0 },
293	.m2 = { .min = 0, .max = 254 },
294	.p = { .min = 7, .max = 112 },
295	.p1 = { .min = 1, .max = 8 },
296	.p2 = { .dot_limit = 112000,
297		.p2_slow = 14, .p2_fast = 14 },
298};
299
300/* Ironlake / Sandybridge
301 *
302 * We calculate clock using (register_value + 2) for N/M1/M2, so here
303 * the range value for them is (actual_value - 2).
304 */
305static const intel_limit_t intel_limits_ironlake_dac = {
306	.dot = { .min = 25000, .max = 350000 },
307	.vco = { .min = 1760000, .max = 3510000 },
308	.n = { .min = 1, .max = 5 },
309	.m = { .min = 79, .max = 127 },
310	.m1 = { .min = 12, .max = 22 },
311	.m2 = { .min = 5, .max = 9 },
312	.p = { .min = 5, .max = 80 },
313	.p1 = { .min = 1, .max = 8 },
314	.p2 = { .dot_limit = 225000,
315		.p2_slow = 10, .p2_fast = 5 },
316};
317
318static const intel_limit_t intel_limits_ironlake_single_lvds = {
319	.dot = { .min = 25000, .max = 350000 },
320	.vco = { .min = 1760000, .max = 3510000 },
321	.n = { .min = 1, .max = 3 },
322	.m = { .min = 79, .max = 118 },
323	.m1 = { .min = 12, .max = 22 },
324	.m2 = { .min = 5, .max = 9 },
325	.p = { .min = 28, .max = 112 },
326	.p1 = { .min = 2, .max = 8 },
327	.p2 = { .dot_limit = 225000,
328		.p2_slow = 14, .p2_fast = 14 },
329};
330
331static const intel_limit_t intel_limits_ironlake_dual_lvds = {
332	.dot = { .min = 25000, .max = 350000 },
333	.vco = { .min = 1760000, .max = 3510000 },
334	.n = { .min = 1, .max = 3 },
335	.m = { .min = 79, .max = 127 },
336	.m1 = { .min = 12, .max = 22 },
337	.m2 = { .min = 5, .max = 9 },
338	.p = { .min = 14, .max = 56 },
339	.p1 = { .min = 2, .max = 8 },
340	.p2 = { .dot_limit = 225000,
341		.p2_slow = 7, .p2_fast = 7 },
342};
343
344/* LVDS 100mhz refclk limits. */
345static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
346	.dot = { .min = 25000, .max = 350000 },
347	.vco = { .min = 1760000, .max = 3510000 },
348	.n = { .min = 1, .max = 2 },
349	.m = { .min = 79, .max = 126 },
350	.m1 = { .min = 12, .max = 22 },
351	.m2 = { .min = 5, .max = 9 },
352	.p = { .min = 28, .max = 112 },
353	.p1 = { .min = 2, .max = 8 },
354	.p2 = { .dot_limit = 225000,
355		.p2_slow = 14, .p2_fast = 14 },
356};
357
358static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
359	.dot = { .min = 25000, .max = 350000 },
360	.vco = { .min = 1760000, .max = 3510000 },
361	.n = { .min = 1, .max = 3 },
362	.m = { .min = 79, .max = 126 },
363	.m1 = { .min = 12, .max = 22 },
364	.m2 = { .min = 5, .max = 9 },
365	.p = { .min = 14, .max = 42 },
366	.p1 = { .min = 2, .max = 6 },
367	.p2 = { .dot_limit = 225000,
368		.p2_slow = 7, .p2_fast = 7 },
369};
370
371static const intel_limit_t intel_limits_vlv = {
372	 /*
373	  * These are the data rate limits (measured in fast clocks)
374	  * since those are the strictest limits we have. The fast
375	  * clock and actual rate limits are more relaxed, so checking
376	  * them would make no difference.
377	  */
378	.dot = { .min = 25000 * 5, .max = 270000 * 5 },
379	.vco = { .min = 4000000, .max = 6000000 },
380	.n = { .min = 1, .max = 7 },
381	.m1 = { .min = 2, .max = 3 },
382	.m2 = { .min = 11, .max = 156 },
383	.p1 = { .min = 2, .max = 3 },
384	.p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
385};
386
387static const intel_limit_t intel_limits_chv = {
388	/*
389	 * These are the data rate limits (measured in fast clocks)
390	 * since those are the strictest limits we have.  The fast
391	 * clock and actual rate limits are more relaxed, so checking
392	 * them would make no difference.
393	 */
394	.dot = { .min = 25000 * 5, .max = 540000 * 5},
395	.vco = { .min = 4800000, .max = 6480000 },
396	.n = { .min = 1, .max = 1 },
397	.m1 = { .min = 2, .max = 2 },
398	.m2 = { .min = 24 << 22, .max = 175 << 22 },
399	.p1 = { .min = 2, .max = 4 },
400	.p2 = {	.p2_slow = 1, .p2_fast = 14 },
401};
402
403static void vlv_clock(int refclk, intel_clock_t *clock)
404{
405	clock->m = clock->m1 * clock->m2;
406	clock->p = clock->p1 * clock->p2;
407	if (WARN_ON(clock->n == 0 || clock->p == 0))
408		return;
409	clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
410	clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
411}
412
413/**
414 * Returns whether any output on the specified pipe is of the specified type
415 */
416bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
417{
418	struct drm_device *dev = crtc->base.dev;
419	struct intel_encoder *encoder;
420
421	for_each_encoder_on_crtc(dev, &crtc->base, encoder)
422		if (encoder->type == type)
423			return true;
424
425	return false;
426}
427
428/**
429 * Returns whether any output on the specified pipe will have the specified
430 * type after a staged modeset is complete, i.e., the same as
431 * intel_pipe_has_type() but looking at encoder->new_crtc instead of
432 * encoder->crtc.
433 */
434static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
435				      int type)
436{
437	struct drm_atomic_state *state = crtc_state->base.state;
438	struct drm_connector_state *connector_state;
439	struct intel_encoder *encoder;
440	int i, num_connectors = 0;
441
442	for (i = 0; i < state->num_connector; i++) {
443		if (!state->connectors[i])
444			continue;
445
446		connector_state = state->connector_states[i];
447		if (connector_state->crtc != crtc_state->base.crtc)
448			continue;
449
450		num_connectors++;
451
452		encoder = to_intel_encoder(connector_state->best_encoder);
453		if (encoder->type == type)
454			return true;
455	}
456
457	WARN_ON(num_connectors == 0);
458
459	return false;
460}
461
462static const intel_limit_t *
463intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
464{
465	struct drm_device *dev = crtc_state->base.crtc->dev;
466	const intel_limit_t *limit;
467
468	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
469		if (intel_is_dual_link_lvds(dev)) {
470			if (refclk == 100000)
471				limit = &intel_limits_ironlake_dual_lvds_100m;
472			else
473				limit = &intel_limits_ironlake_dual_lvds;
474		} else {
475			if (refclk == 100000)
476				limit = &intel_limits_ironlake_single_lvds_100m;
477			else
478				limit = &intel_limits_ironlake_single_lvds;
479		}
480	} else
481		limit = &intel_limits_ironlake_dac;
482
483	return limit;
484}
485
486static const intel_limit_t *
487intel_g4x_limit(struct intel_crtc_state *crtc_state)
488{
489	struct drm_device *dev = crtc_state->base.crtc->dev;
490	const intel_limit_t *limit;
491
492	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
493		if (intel_is_dual_link_lvds(dev))
494			limit = &intel_limits_g4x_dual_channel_lvds;
495		else
496			limit = &intel_limits_g4x_single_channel_lvds;
497	} else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
498		   intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
499		limit = &intel_limits_g4x_hdmi;
500	} else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
501		limit = &intel_limits_g4x_sdvo;
502	} else /* The option is for other outputs */
503		limit = &intel_limits_i9xx_sdvo;
504
505	return limit;
506}
507
508static const intel_limit_t *
509intel_limit(struct intel_crtc_state *crtc_state, int refclk)
510{
511	struct drm_device *dev = crtc_state->base.crtc->dev;
512	const intel_limit_t *limit;
513
514	if (HAS_PCH_SPLIT(dev))
515		limit = intel_ironlake_limit(crtc_state, refclk);
516	else if (IS_G4X(dev)) {
517		limit = intel_g4x_limit(crtc_state);
518	} else if (IS_PINEVIEW(dev)) {
519		if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
520			limit = &intel_limits_pineview_lvds;
521		else
522			limit = &intel_limits_pineview_sdvo;
523	} else if (IS_CHERRYVIEW(dev)) {
524		limit = &intel_limits_chv;
525	} else if (IS_VALLEYVIEW(dev)) {
526		limit = &intel_limits_vlv;
527	} else if (!IS_GEN2(dev)) {
528		if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
529			limit = &intel_limits_i9xx_lvds;
530		else
531			limit = &intel_limits_i9xx_sdvo;
532	} else {
533		if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
534			limit = &intel_limits_i8xx_lvds;
535		else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
536			limit = &intel_limits_i8xx_dvo;
537		else
538			limit = &intel_limits_i8xx_dac;
539	}
540	return limit;
541}
542
543/* m1 is reserved as 0 in Pineview, n is a ring counter */
544static void pineview_clock(int refclk, intel_clock_t *clock)
545{
546	clock->m = clock->m2 + 2;
547	clock->p = clock->p1 * clock->p2;
548	if (WARN_ON(clock->n == 0 || clock->p == 0))
549		return;
550	clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
551	clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
552}
553
554static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
555{
556	return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
557}
558
559static void i9xx_clock(int refclk, intel_clock_t *clock)
560{
561	clock->m = i9xx_dpll_compute_m(clock);
562	clock->p = clock->p1 * clock->p2;
563	if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
564		return;
565	clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
566	clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
567}
568
569static void chv_clock(int refclk, intel_clock_t *clock)
570{
571	clock->m = clock->m1 * clock->m2;
572	clock->p = clock->p1 * clock->p2;
573	if (WARN_ON(clock->n == 0 || clock->p == 0))
574		return;
575	clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
576			clock->n << 22);
577	clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
578}
579
580#define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
581/**
582 * Returns whether the given set of divisors are valid for a given refclk with
583 * the given connectors.
584 */
585
586static bool intel_PLL_is_valid(struct drm_device *dev,
587			       const intel_limit_t *limit,
588			       const intel_clock_t *clock)
589{
590	if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
591		INTELPllInvalid("n out of range\n");
592	if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
593		INTELPllInvalid("p1 out of range\n");
594	if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
595		INTELPllInvalid("m2 out of range\n");
596	if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
597		INTELPllInvalid("m1 out of range\n");
598
599	if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev))
600		if (clock->m1 <= clock->m2)
601			INTELPllInvalid("m1 <= m2\n");
602
603	if (!IS_VALLEYVIEW(dev)) {
604		if (clock->p < limit->p.min || limit->p.max < clock->p)
605			INTELPllInvalid("p out of range\n");
606		if (clock->m < limit->m.min || limit->m.max < clock->m)
607			INTELPllInvalid("m out of range\n");
608	}
609
610	if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
611		INTELPllInvalid("vco out of range\n");
612	/* XXX: We may need to be checking "Dot clock" depending on the multiplier,
613	 * connector, etc., rather than just a single range.
614	 */
615	if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
616		INTELPllInvalid("dot out of range\n");
617
618	return true;
619}
620
621static bool
622i9xx_find_best_dpll(const intel_limit_t *limit,
623		    struct intel_crtc_state *crtc_state,
624		    int target, int refclk, intel_clock_t *match_clock,
625		    intel_clock_t *best_clock)
626{
627	struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
628	struct drm_device *dev = crtc->base.dev;
629	intel_clock_t clock;
630	int err = target;
631
632	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
633		/*
634		 * For LVDS just rely on its current settings for dual-channel.
635		 * We haven't figured out how to reliably set up different
636		 * single/dual channel state, if we even can.
637		 */
638		if (intel_is_dual_link_lvds(dev))
639			clock.p2 = limit->p2.p2_fast;
640		else
641			clock.p2 = limit->p2.p2_slow;
642	} else {
643		if (target < limit->p2.dot_limit)
644			clock.p2 = limit->p2.p2_slow;
645		else
646			clock.p2 = limit->p2.p2_fast;
647	}
648
649	memset(best_clock, 0, sizeof(*best_clock));
650
651	for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
652	     clock.m1++) {
653		for (clock.m2 = limit->m2.min;
654		     clock.m2 <= limit->m2.max; clock.m2++) {
655			if (clock.m2 >= clock.m1)
656				break;
657			for (clock.n = limit->n.min;
658			     clock.n <= limit->n.max; clock.n++) {
659				for (clock.p1 = limit->p1.min;
660					clock.p1 <= limit->p1.max; clock.p1++) {
661					int this_err;
662
663					i9xx_clock(refclk, &clock);
664					if (!intel_PLL_is_valid(dev, limit,
665								&clock))
666						continue;
667					if (match_clock &&
668					    clock.p != match_clock->p)
669						continue;
670
671					this_err = abs(clock.dot - target);
672					if (this_err < err) {
673						*best_clock = clock;
674						err = this_err;
675					}
676				}
677			}
678		}
679	}
680
681	return (err != target);
682}
683
684static bool
685pnv_find_best_dpll(const intel_limit_t *limit,
686		   struct intel_crtc_state *crtc_state,
687		   int target, int refclk, intel_clock_t *match_clock,
688		   intel_clock_t *best_clock)
689{
690	struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
691	struct drm_device *dev = crtc->base.dev;
692	intel_clock_t clock;
693	int err = target;
694
695	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
696		/*
697		 * For LVDS just rely on its current settings for dual-channel.
698		 * We haven't figured out how to reliably set up different
699		 * single/dual channel state, if we even can.
700		 */
701		if (intel_is_dual_link_lvds(dev))
702			clock.p2 = limit->p2.p2_fast;
703		else
704			clock.p2 = limit->p2.p2_slow;
705	} else {
706		if (target < limit->p2.dot_limit)
707			clock.p2 = limit->p2.p2_slow;
708		else
709			clock.p2 = limit->p2.p2_fast;
710	}
711
712	memset(best_clock, 0, sizeof(*best_clock));
713
714	for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
715	     clock.m1++) {
716		for (clock.m2 = limit->m2.min;
717		     clock.m2 <= limit->m2.max; clock.m2++) {
718			for (clock.n = limit->n.min;
719			     clock.n <= limit->n.max; clock.n++) {
720				for (clock.p1 = limit->p1.min;
721					clock.p1 <= limit->p1.max; clock.p1++) {
722					int this_err;
723
724					pineview_clock(refclk, &clock);
725					if (!intel_PLL_is_valid(dev, limit,
726								&clock))
727						continue;
728					if (match_clock &&
729					    clock.p != match_clock->p)
730						continue;
731
732					this_err = abs(clock.dot - target);
733					if (this_err < err) {
734						*best_clock = clock;
735						err = this_err;
736					}
737				}
738			}
739		}
740	}
741
742	return (err != target);
743}
744
745static bool
746g4x_find_best_dpll(const intel_limit_t *limit,
747		   struct intel_crtc_state *crtc_state,
748		   int target, int refclk, intel_clock_t *match_clock,
749		   intel_clock_t *best_clock)
750{
751	struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
752	struct drm_device *dev = crtc->base.dev;
753	intel_clock_t clock;
754	int max_n;
755	bool found;
756	/* approximately equals target * 0.00585 */
757	int err_most = (target >> 8) + (target >> 9);
758	found = false;
759
760	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
761		if (intel_is_dual_link_lvds(dev))
762			clock.p2 = limit->p2.p2_fast;
763		else
764			clock.p2 = limit->p2.p2_slow;
765	} else {
766		if (target < limit->p2.dot_limit)
767			clock.p2 = limit->p2.p2_slow;
768		else
769			clock.p2 = limit->p2.p2_fast;
770	}
771
772	memset(best_clock, 0, sizeof(*best_clock));
773	max_n = limit->n.max;
774	/* based on hardware requirement, prefer smaller n to precision */
775	for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
776		/* based on hardware requirement, prefere larger m1,m2 */
777		for (clock.m1 = limit->m1.max;
778		     clock.m1 >= limit->m1.min; clock.m1--) {
779			for (clock.m2 = limit->m2.max;
780			     clock.m2 >= limit->m2.min; clock.m2--) {
781				for (clock.p1 = limit->p1.max;
782				     clock.p1 >= limit->p1.min; clock.p1--) {
783					int this_err;
784
785					i9xx_clock(refclk, &clock);
786					if (!intel_PLL_is_valid(dev, limit,
787								&clock))
788						continue;
789
790					this_err = abs(clock.dot - target);
791					if (this_err < err_most) {
792						*best_clock = clock;
793						err_most = this_err;
794						max_n = clock.n;
795						found = true;
796					}
797				}
798			}
799		}
800	}
801	return found;
802}
803
804/*
805 * Check if the calculated PLL configuration is more optimal compared to the
806 * best configuration and error found so far. Return the calculated error.
807 */
808static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
809			       const intel_clock_t *calculated_clock,
810			       const intel_clock_t *best_clock,
811			       unsigned int best_error_ppm,
812			       unsigned int *error_ppm)
813{
814	/*
815	 * For CHV ignore the error and consider only the P value.
816	 * Prefer a bigger P value based on HW requirements.
817	 */
818	if (IS_CHERRYVIEW(dev)) {
819		*error_ppm = 0;
820
821		return calculated_clock->p > best_clock->p;
822	}
823
824	if (WARN_ON_ONCE(!target_freq))
825		return false;
826
827	*error_ppm = div_u64(1000000ULL *
828				abs(target_freq - calculated_clock->dot),
829			     target_freq);
830	/*
831	 * Prefer a better P value over a better (smaller) error if the error
832	 * is small. Ensure this preference for future configurations too by
833	 * setting the error to 0.
834	 */
835	if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
836		*error_ppm = 0;
837
838		return true;
839	}
840
841	return *error_ppm + 10 < best_error_ppm;
842}
843
844static bool
845vlv_find_best_dpll(const intel_limit_t *limit,
846		   struct intel_crtc_state *crtc_state,
847		   int target, int refclk, intel_clock_t *match_clock,
848		   intel_clock_t *best_clock)
849{
850	struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
851	struct drm_device *dev = crtc->base.dev;
852	intel_clock_t clock;
853	unsigned int bestppm = 1000000;
854	/* min update 19.2 MHz */
855	int max_n = min(limit->n.max, refclk / 19200);
856	bool found = false;
857
858	target *= 5; /* fast clock */
859
860	memset(best_clock, 0, sizeof(*best_clock));
861
862	/* based on hardware requirement, prefer smaller n to precision */
863	for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
864		for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
865			for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
866			     clock.p2 -= clock.p2 > 10 ? 2 : 1) {
867				clock.p = clock.p1 * clock.p2;
868				/* based on hardware requirement, prefer bigger m1,m2 values */
869				for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
870					unsigned int ppm;
871
872					clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
873								     refclk * clock.m1);
874
875					vlv_clock(refclk, &clock);
876
877					if (!intel_PLL_is_valid(dev, limit,
878								&clock))
879						continue;
880
881					if (!vlv_PLL_is_optimal(dev, target,
882								&clock,
883								best_clock,
884								bestppm, &ppm))
885						continue;
886
887					*best_clock = clock;
888					bestppm = ppm;
889					found = true;
890				}
891			}
892		}
893	}
894
895	return found;
896}
897
898static bool
899chv_find_best_dpll(const intel_limit_t *limit,
900		   struct intel_crtc_state *crtc_state,
901		   int target, int refclk, intel_clock_t *match_clock,
902		   intel_clock_t *best_clock)
903{
904	struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
905	struct drm_device *dev = crtc->base.dev;
906	unsigned int best_error_ppm;
907	intel_clock_t clock;
908	uint64_t m2;
909	int found = false;
910
911	memset(best_clock, 0, sizeof(*best_clock));
912	best_error_ppm = 1000000;
913
914	/*
915	 * Based on hardware doc, the n always set to 1, and m1 always
916	 * set to 2.  If requires to support 200Mhz refclk, we need to
917	 * revisit this because n may not 1 anymore.
918	 */
919	clock.n = 1, clock.m1 = 2;
920	target *= 5;	/* fast clock */
921
922	for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
923		for (clock.p2 = limit->p2.p2_fast;
924				clock.p2 >= limit->p2.p2_slow;
925				clock.p2 -= clock.p2 > 10 ? 2 : 1) {
926			unsigned int error_ppm;
927
928			clock.p = clock.p1 * clock.p2;
929
930			m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
931					clock.n) << 22, refclk * clock.m1);
932
933			if (m2 > INT_MAX/clock.m1)
934				continue;
935
936			clock.m2 = m2;
937
938			chv_clock(refclk, &clock);
939
940			if (!intel_PLL_is_valid(dev, limit, &clock))
941				continue;
942
943			if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
944						best_error_ppm, &error_ppm))
945				continue;
946
947			*best_clock = clock;
948			best_error_ppm = error_ppm;
949			found = true;
950		}
951	}
952
953	return found;
954}
955
956bool intel_crtc_active(struct drm_crtc *crtc)
957{
958	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
959
960	/* Be paranoid as we can arrive here with only partial
961	 * state retrieved from the hardware during setup.
962	 *
963	 * We can ditch the adjusted_mode.crtc_clock check as soon
964	 * as Haswell has gained clock readout/fastboot support.
965	 *
966	 * We can ditch the crtc->primary->fb check as soon as we can
967	 * properly reconstruct framebuffers.
968	 *
969	 * FIXME: The intel_crtc->active here should be switched to
970	 * crtc->state->active once we have proper CRTC states wired up
971	 * for atomic.
972	 */
973	return intel_crtc->active && crtc->primary->state->fb &&
974		intel_crtc->config->base.adjusted_mode.crtc_clock;
975}
976
977enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
978					     enum pipe pipe)
979{
980	struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
981	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
982
983	return intel_crtc->config->cpu_transcoder;
984}
985
986static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
987{
988	struct drm_i915_private *dev_priv = dev->dev_private;
989	u32 reg = PIPEDSL(pipe);
990	u32 line1, line2;
991	u32 line_mask;
992
993	if (IS_GEN2(dev))
994		line_mask = DSL_LINEMASK_GEN2;
995	else
996		line_mask = DSL_LINEMASK_GEN3;
997
998	line1 = I915_READ(reg) & line_mask;
999	mdelay(5);
1000	line2 = I915_READ(reg) & line_mask;
1001
1002	return line1 == line2;
1003}
1004
1005/*
1006 * intel_wait_for_pipe_off - wait for pipe to turn off
1007 * @crtc: crtc whose pipe to wait for
1008 *
1009 * After disabling a pipe, we can't wait for vblank in the usual way,
1010 * spinning on the vblank interrupt status bit, since we won't actually
1011 * see an interrupt when the pipe is disabled.
1012 *
1013 * On Gen4 and above:
1014 *   wait for the pipe register state bit to turn off
1015 *
1016 * Otherwise:
1017 *   wait for the display line value to settle (it usually
1018 *   ends up stopping at the start of the next frame).
1019 *
1020 */
1021static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1022{
1023	struct drm_device *dev = crtc->base.dev;
1024	struct drm_i915_private *dev_priv = dev->dev_private;
1025	enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1026	enum pipe pipe = crtc->pipe;
1027
1028	if (INTEL_INFO(dev)->gen >= 4) {
1029		int reg = PIPECONF(cpu_transcoder);
1030
1031		/* Wait for the Pipe State to go off */
1032		if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1033			     100))
1034			WARN(1, "pipe_off wait timed out\n");
1035	} else {
1036		/* Wait for the display line to settle */
1037		if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1038			WARN(1, "pipe_off wait timed out\n");
1039	}
1040}
1041
1042/*
1043 * ibx_digital_port_connected - is the specified port connected?
1044 * @dev_priv: i915 private structure
1045 * @port: the port to test
1046 *
1047 * Returns true if @port is connected, false otherwise.
1048 */
1049bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
1050				struct intel_digital_port *port)
1051{
1052	u32 bit;
1053
1054	if (HAS_PCH_IBX(dev_priv->dev)) {
1055		switch (port->port) {
1056		case PORT_B:
1057			bit = SDE_PORTB_HOTPLUG;
1058			break;
1059		case PORT_C:
1060			bit = SDE_PORTC_HOTPLUG;
1061			break;
1062		case PORT_D:
1063			bit = SDE_PORTD_HOTPLUG;
1064			break;
1065		default:
1066			return true;
1067		}
1068	} else {
1069		switch (port->port) {
1070		case PORT_B:
1071			bit = SDE_PORTB_HOTPLUG_CPT;
1072			break;
1073		case PORT_C:
1074			bit = SDE_PORTC_HOTPLUG_CPT;
1075			break;
1076		case PORT_D:
1077			bit = SDE_PORTD_HOTPLUG_CPT;
1078			break;
1079		default:
1080			return true;
1081		}
1082	}
1083
1084	return I915_READ(SDEISR) & bit;
1085}
1086
1087static const char *state_string(bool enabled)
1088{
1089	return enabled ? "on" : "off";
1090}
1091
1092/* Only for pre-ILK configs */
1093void assert_pll(struct drm_i915_private *dev_priv,
1094		enum pipe pipe, bool state)
1095{
1096	int reg;
1097	u32 val;
1098	bool cur_state;
1099
1100	reg = DPLL(pipe);
1101	val = I915_READ(reg);
1102	cur_state = !!(val & DPLL_VCO_ENABLE);
1103	I915_STATE_WARN(cur_state != state,
1104	     "PLL state assertion failure (expected %s, current %s)\n",
1105	     state_string(state), state_string(cur_state));
1106}
1107
1108/* XXX: the dsi pll is shared between MIPI DSI ports */
1109static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1110{
1111	u32 val;
1112	bool cur_state;
1113
1114	mutex_lock(&dev_priv->dpio_lock);
1115	val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1116	mutex_unlock(&dev_priv->dpio_lock);
1117
1118	cur_state = val & DSI_PLL_VCO_EN;
1119	I915_STATE_WARN(cur_state != state,
1120	     "DSI PLL state assertion failure (expected %s, current %s)\n",
1121	     state_string(state), state_string(cur_state));
1122}
1123#define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1124#define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1125
1126struct intel_shared_dpll *
1127intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1128{
1129	struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1130
1131	if (crtc->config->shared_dpll < 0)
1132		return NULL;
1133
1134	return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1135}
1136
1137/* For ILK+ */
1138void assert_shared_dpll(struct drm_i915_private *dev_priv,
1139			struct intel_shared_dpll *pll,
1140			bool state)
1141{
1142	bool cur_state;
1143	struct intel_dpll_hw_state hw_state;
1144
1145	if (WARN (!pll,
1146		  "asserting DPLL %s with no DPLL\n", state_string(state)))
1147		return;
1148
1149	cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1150	I915_STATE_WARN(cur_state != state,
1151	     "%s assertion failure (expected %s, current %s)\n",
1152	     pll->name, state_string(state), state_string(cur_state));
1153}
1154
1155static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1156			  enum pipe pipe, bool state)
1157{
1158	int reg;
1159	u32 val;
1160	bool cur_state;
1161	enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1162								      pipe);
1163
1164	if (HAS_DDI(dev_priv->dev)) {
1165		/* DDI does not have a specific FDI_TX register */
1166		reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1167		val = I915_READ(reg);
1168		cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1169	} else {
1170		reg = FDI_TX_CTL(pipe);
1171		val = I915_READ(reg);
1172		cur_state = !!(val & FDI_TX_ENABLE);
1173	}
1174	I915_STATE_WARN(cur_state != state,
1175	     "FDI TX state assertion failure (expected %s, current %s)\n",
1176	     state_string(state), state_string(cur_state));
1177}
1178#define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1179#define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1180
1181static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1182			  enum pipe pipe, bool state)
1183{
1184	int reg;
1185	u32 val;
1186	bool cur_state;
1187
1188	reg = FDI_RX_CTL(pipe);
1189	val = I915_READ(reg);
1190	cur_state = !!(val & FDI_RX_ENABLE);
1191	I915_STATE_WARN(cur_state != state,
1192	     "FDI RX state assertion failure (expected %s, current %s)\n",
1193	     state_string(state), state_string(cur_state));
1194}
1195#define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1196#define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1197
1198static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1199				      enum pipe pipe)
1200{
1201	int reg;
1202	u32 val;
1203
1204	/* ILK FDI PLL is always enabled */
1205	if (INTEL_INFO(dev_priv->dev)->gen == 5)
1206		return;
1207
1208	/* On Haswell, DDI ports are responsible for the FDI PLL setup */
1209	if (HAS_DDI(dev_priv->dev))
1210		return;
1211
1212	reg = FDI_TX_CTL(pipe);
1213	val = I915_READ(reg);
1214	I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1215}
1216
1217void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1218		       enum pipe pipe, bool state)
1219{
1220	int reg;
1221	u32 val;
1222	bool cur_state;
1223
1224	reg = FDI_RX_CTL(pipe);
1225	val = I915_READ(reg);
1226	cur_state = !!(val & FDI_RX_PLL_ENABLE);
1227	I915_STATE_WARN(cur_state != state,
1228	     "FDI RX PLL assertion failure (expected %s, current %s)\n",
1229	     state_string(state), state_string(cur_state));
1230}
1231
1232void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1233			   enum pipe pipe)
1234{
1235	struct drm_device *dev = dev_priv->dev;
1236	int pp_reg;
1237	u32 val;
1238	enum pipe panel_pipe = PIPE_A;
1239	bool locked = true;
1240
1241	if (WARN_ON(HAS_DDI(dev)))
1242		return;
1243
1244	if (HAS_PCH_SPLIT(dev)) {
1245		u32 port_sel;
1246
1247		pp_reg = PCH_PP_CONTROL;
1248		port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1249
1250		if (port_sel == PANEL_PORT_SELECT_LVDS &&
1251		    I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1252			panel_pipe = PIPE_B;
1253		/* XXX: else fix for eDP */
1254	} else if (IS_VALLEYVIEW(dev)) {
1255		/* presumably write lock depends on pipe, not port select */
1256		pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1257		panel_pipe = pipe;
1258	} else {
1259		pp_reg = PP_CONTROL;
1260		if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1261			panel_pipe = PIPE_B;
1262	}
1263
1264	val = I915_READ(pp_reg);
1265	if (!(val & PANEL_POWER_ON) ||
1266	    ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1267		locked = false;
1268
1269	I915_STATE_WARN(panel_pipe == pipe && locked,
1270	     "panel assertion failure, pipe %c regs locked\n",
1271	     pipe_name(pipe));
1272}
1273
1274static void assert_cursor(struct drm_i915_private *dev_priv,
1275			  enum pipe pipe, bool state)
1276{
1277	struct drm_device *dev = dev_priv->dev;
1278	bool cur_state;
1279
1280	if (IS_845G(dev) || IS_I865G(dev))
1281		cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1282	else
1283		cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1284
1285	I915_STATE_WARN(cur_state != state,
1286	     "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1287	     pipe_name(pipe), state_string(state), state_string(cur_state));
1288}
1289#define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1290#define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1291
1292void assert_pipe(struct drm_i915_private *dev_priv,
1293		 enum pipe pipe, bool state)
1294{
1295	int reg;
1296	u32 val;
1297	bool cur_state;
1298	enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1299								      pipe);
1300
1301	/* if we need the pipe quirk it must be always on */
1302	if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1303	    (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1304		state = true;
1305
1306	if (!intel_display_power_is_enabled(dev_priv,
1307				POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1308		cur_state = false;
1309	} else {
1310		reg = PIPECONF(cpu_transcoder);
1311		val = I915_READ(reg);
1312		cur_state = !!(val & PIPECONF_ENABLE);
1313	}
1314
1315	I915_STATE_WARN(cur_state != state,
1316	     "pipe %c assertion failure (expected %s, current %s)\n",
1317	     pipe_name(pipe), state_string(state), state_string(cur_state));
1318}
1319
1320static void assert_plane(struct drm_i915_private *dev_priv,
1321			 enum plane plane, bool state)
1322{
1323	int reg;
1324	u32 val;
1325	bool cur_state;
1326
1327	reg = DSPCNTR(plane);
1328	val = I915_READ(reg);
1329	cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1330	I915_STATE_WARN(cur_state != state,
1331	     "plane %c assertion failure (expected %s, current %s)\n",
1332	     plane_name(plane), state_string(state), state_string(cur_state));
1333}
1334
1335#define assert_plane_enabled(d, p) assert_plane(d, p, true)
1336#define assert_plane_disabled(d, p) assert_plane(d, p, false)
1337
1338static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1339				   enum pipe pipe)
1340{
1341	struct drm_device *dev = dev_priv->dev;
1342	int reg, i;
1343	u32 val;
1344	int cur_pipe;
1345
1346	/* Primary planes are fixed to pipes on gen4+ */
1347	if (INTEL_INFO(dev)->gen >= 4) {
1348		reg = DSPCNTR(pipe);
1349		val = I915_READ(reg);
1350		I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1351		     "plane %c assertion failure, should be disabled but not\n",
1352		     plane_name(pipe));
1353		return;
1354	}
1355
1356	/* Need to check both planes against the pipe */
1357	for_each_pipe(dev_priv, i) {
1358		reg = DSPCNTR(i);
1359		val = I915_READ(reg);
1360		cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1361			DISPPLANE_SEL_PIPE_SHIFT;
1362		I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1363		     "plane %c assertion failure, should be off on pipe %c but is still active\n",
1364		     plane_name(i), pipe_name(pipe));
1365	}
1366}
1367
1368static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1369				    enum pipe pipe)
1370{
1371	struct drm_device *dev = dev_priv->dev;
1372	int reg, sprite;
1373	u32 val;
1374
1375	if (INTEL_INFO(dev)->gen >= 9) {
1376		for_each_sprite(dev_priv, pipe, sprite) {
1377			val = I915_READ(PLANE_CTL(pipe, sprite));
1378			I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1379			     "plane %d assertion failure, should be off on pipe %c but is still active\n",
1380			     sprite, pipe_name(pipe));
1381		}
1382	} else if (IS_VALLEYVIEW(dev)) {
1383		for_each_sprite(dev_priv, pipe, sprite) {
1384			reg = SPCNTR(pipe, sprite);
1385			val = I915_READ(reg);
1386			I915_STATE_WARN(val & SP_ENABLE,
1387			     "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1388			     sprite_name(pipe, sprite), pipe_name(pipe));
1389		}
1390	} else if (INTEL_INFO(dev)->gen >= 7) {
1391		reg = SPRCTL(pipe);
1392		val = I915_READ(reg);
1393		I915_STATE_WARN(val & SPRITE_ENABLE,
1394		     "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1395		     plane_name(pipe), pipe_name(pipe));
1396	} else if (INTEL_INFO(dev)->gen >= 5) {
1397		reg = DVSCNTR(pipe);
1398		val = I915_READ(reg);
1399		I915_STATE_WARN(val & DVS_ENABLE,
1400		     "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1401		     plane_name(pipe), pipe_name(pipe));
1402	}
1403}
1404
1405static void assert_vblank_disabled(struct drm_crtc *crtc)
1406{
1407	if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1408		drm_crtc_vblank_put(crtc);
1409}
1410
1411static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1412{
1413	u32 val;
1414	bool enabled;
1415
1416	I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1417
1418	val = I915_READ(PCH_DREF_CONTROL);
1419	enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1420			    DREF_SUPERSPREAD_SOURCE_MASK));
1421	I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1422}
1423
1424static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1425					   enum pipe pipe)
1426{
1427	int reg;
1428	u32 val;
1429	bool enabled;
1430
1431	reg = PCH_TRANSCONF(pipe);
1432	val = I915_READ(reg);
1433	enabled = !!(val & TRANS_ENABLE);
1434	I915_STATE_WARN(enabled,
1435	     "transcoder assertion failed, should be off on pipe %c but is still active\n",
1436	     pipe_name(pipe));
1437}
1438
1439static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1440			    enum pipe pipe, u32 port_sel, u32 val)
1441{
1442	if ((val & DP_PORT_EN) == 0)
1443		return false;
1444
1445	if (HAS_PCH_CPT(dev_priv->dev)) {
1446		u32	trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1447		u32	trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1448		if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1449			return false;
1450	} else if (IS_CHERRYVIEW(dev_priv->dev)) {
1451		if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1452			return false;
1453	} else {
1454		if ((val & DP_PIPE_MASK) != (pipe << 30))
1455			return false;
1456	}
1457	return true;
1458}
1459
1460static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1461			      enum pipe pipe, u32 val)
1462{
1463	if ((val & SDVO_ENABLE) == 0)
1464		return false;
1465
1466	if (HAS_PCH_CPT(dev_priv->dev)) {
1467		if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1468			return false;
1469	} else if (IS_CHERRYVIEW(dev_priv->dev)) {
1470		if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1471			return false;
1472	} else {
1473		if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1474			return false;
1475	}
1476	return true;
1477}
1478
1479static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1480			      enum pipe pipe, u32 val)
1481{
1482	if ((val & LVDS_PORT_EN) == 0)
1483		return false;
1484
1485	if (HAS_PCH_CPT(dev_priv->dev)) {
1486		if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1487			return false;
1488	} else {
1489		if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1490			return false;
1491	}
1492	return true;
1493}
1494
1495static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1496			      enum pipe pipe, u32 val)
1497{
1498	if ((val & ADPA_DAC_ENABLE) == 0)
1499		return false;
1500	if (HAS_PCH_CPT(dev_priv->dev)) {
1501		if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1502			return false;
1503	} else {
1504		if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1505			return false;
1506	}
1507	return true;
1508}
1509
1510static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1511				   enum pipe pipe, int reg, u32 port_sel)
1512{
1513	u32 val = I915_READ(reg);
1514	I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1515	     "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1516	     reg, pipe_name(pipe));
1517
1518	I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1519	     && (val & DP_PIPEB_SELECT),
1520	     "IBX PCH dp port still using transcoder B\n");
1521}
1522
1523static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1524				     enum pipe pipe, int reg)
1525{
1526	u32 val = I915_READ(reg);
1527	I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1528	     "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1529	     reg, pipe_name(pipe));
1530
1531	I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1532	     && (val & SDVO_PIPE_B_SELECT),
1533	     "IBX PCH hdmi port still using transcoder B\n");
1534}
1535
1536static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1537				      enum pipe pipe)
1538{
1539	int reg;
1540	u32 val;
1541
1542	assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1543	assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1544	assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1545
1546	reg = PCH_ADPA;
1547	val = I915_READ(reg);
1548	I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1549	     "PCH VGA enabled on transcoder %c, should be disabled\n",
1550	     pipe_name(pipe));
1551
1552	reg = PCH_LVDS;
1553	val = I915_READ(reg);
1554	I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1555	     "PCH LVDS enabled on transcoder %c, should be disabled\n",
1556	     pipe_name(pipe));
1557
1558	assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1559	assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1560	assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1561}
1562
1563static void intel_init_dpio(struct drm_device *dev)
1564{
1565	struct drm_i915_private *dev_priv = dev->dev_private;
1566
1567	if (!IS_VALLEYVIEW(dev))
1568		return;
1569
1570	/*
1571	 * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1572	 * CHV x1 PHY (DP/HDMI D)
1573	 * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1574	 */
1575	if (IS_CHERRYVIEW(dev)) {
1576		DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1577		DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1578	} else {
1579		DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1580	}
1581}
1582
1583static void vlv_enable_pll(struct intel_crtc *crtc,
1584			   const struct intel_crtc_state *pipe_config)
1585{
1586	struct drm_device *dev = crtc->base.dev;
1587	struct drm_i915_private *dev_priv = dev->dev_private;
1588	int reg = DPLL(crtc->pipe);
1589	u32 dpll = pipe_config->dpll_hw_state.dpll;
1590
1591	assert_pipe_disabled(dev_priv, crtc->pipe);
1592
1593	/* No really, not for ILK+ */
1594	BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1595
1596	/* PLL is protected by panel, make sure we can write it */
1597	if (IS_MOBILE(dev_priv->dev))
1598		assert_panel_unlocked(dev_priv, crtc->pipe);
1599
1600	I915_WRITE(reg, dpll);
1601	POSTING_READ(reg);
1602	udelay(150);
1603
1604	if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1605		DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1606
1607	I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1608	POSTING_READ(DPLL_MD(crtc->pipe));
1609
1610	/* We do this three times for luck */
1611	I915_WRITE(reg, dpll);
1612	POSTING_READ(reg);
1613	udelay(150); /* wait for warmup */
1614	I915_WRITE(reg, dpll);
1615	POSTING_READ(reg);
1616	udelay(150); /* wait for warmup */
1617	I915_WRITE(reg, dpll);
1618	POSTING_READ(reg);
1619	udelay(150); /* wait for warmup */
1620}
1621
1622static void chv_enable_pll(struct intel_crtc *crtc,
1623			   const struct intel_crtc_state *pipe_config)
1624{
1625	struct drm_device *dev = crtc->base.dev;
1626	struct drm_i915_private *dev_priv = dev->dev_private;
1627	int pipe = crtc->pipe;
1628	enum dpio_channel port = vlv_pipe_to_channel(pipe);
1629	u32 tmp;
1630
1631	assert_pipe_disabled(dev_priv, crtc->pipe);
1632
1633	BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1634
1635	mutex_lock(&dev_priv->dpio_lock);
1636
1637	/* Enable back the 10bit clock to display controller */
1638	tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1639	tmp |= DPIO_DCLKP_EN;
1640	vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1641
1642	/*
1643	 * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1644	 */
1645	udelay(1);
1646
1647	/* Enable PLL */
1648	I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1649
1650	/* Check PLL is locked */
1651	if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1652		DRM_ERROR("PLL %d failed to lock\n", pipe);
1653
1654	/* not sure when this should be written */
1655	I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1656	POSTING_READ(DPLL_MD(pipe));
1657
1658	mutex_unlock(&dev_priv->dpio_lock);
1659}
1660
1661static int intel_num_dvo_pipes(struct drm_device *dev)
1662{
1663	struct intel_crtc *crtc;
1664	int count = 0;
1665
1666	for_each_intel_crtc(dev, crtc)
1667		count += crtc->active &&
1668			intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1669
1670	return count;
1671}
1672
1673static void i9xx_enable_pll(struct intel_crtc *crtc)
1674{
1675	struct drm_device *dev = crtc->base.dev;
1676	struct drm_i915_private *dev_priv = dev->dev_private;
1677	int reg = DPLL(crtc->pipe);
1678	u32 dpll = crtc->config->dpll_hw_state.dpll;
1679
1680	assert_pipe_disabled(dev_priv, crtc->pipe);
1681
1682	/* No really, not for ILK+ */
1683	BUG_ON(INTEL_INFO(dev)->gen >= 5);
1684
1685	/* PLL is protected by panel, make sure we can write it */
1686	if (IS_MOBILE(dev) && !IS_I830(dev))
1687		assert_panel_unlocked(dev_priv, crtc->pipe);
1688
1689	/* Enable DVO 2x clock on both PLLs if necessary */
1690	if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1691		/*
1692		 * It appears to be important that we don't enable this
1693		 * for the current pipe before otherwise configuring the
1694		 * PLL. No idea how this should be handled if multiple
1695		 * DVO outputs are enabled simultaneosly.
1696		 */
1697		dpll |= DPLL_DVO_2X_MODE;
1698		I915_WRITE(DPLL(!crtc->pipe),
1699			   I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1700	}
1701
1702	I915_WRITE(reg, dpll);
1703
1704	/* Wait for the clocks to stabilize. */
1705	POSTING_READ(reg);
1706	udelay(150);
1707
1708	if (INTEL_INFO(dev)->gen >= 4) {
1709		I915_WRITE(DPLL_MD(crtc->pipe),
1710			   crtc->config->dpll_hw_state.dpll_md);
1711	} else {
1712		/* The pixel multiplier can only be updated once the
1713		 * DPLL is enabled and the clocks are stable.
1714		 *
1715		 * So write it again.
1716		 */
1717		I915_WRITE(reg, dpll);
1718	}
1719
1720	/* We do this three times for luck */
1721	I915_WRITE(reg, dpll);
1722	POSTING_READ(reg);
1723	udelay(150); /* wait for warmup */
1724	I915_WRITE(reg, dpll);
1725	POSTING_READ(reg);
1726	udelay(150); /* wait for warmup */
1727	I915_WRITE(reg, dpll);
1728	POSTING_READ(reg);
1729	udelay(150); /* wait for warmup */
1730}
1731
1732/**
1733 * i9xx_disable_pll - disable a PLL
1734 * @dev_priv: i915 private structure
1735 * @pipe: pipe PLL to disable
1736 *
1737 * Disable the PLL for @pipe, making sure the pipe is off first.
1738 *
1739 * Note!  This is for pre-ILK only.
1740 */
1741static void i9xx_disable_pll(struct intel_crtc *crtc)
1742{
1743	struct drm_device *dev = crtc->base.dev;
1744	struct drm_i915_private *dev_priv = dev->dev_private;
1745	enum pipe pipe = crtc->pipe;
1746
1747	/* Disable DVO 2x clock on both PLLs if necessary */
1748	if (IS_I830(dev) &&
1749	    intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1750	    intel_num_dvo_pipes(dev) == 1) {
1751		I915_WRITE(DPLL(PIPE_B),
1752			   I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1753		I915_WRITE(DPLL(PIPE_A),
1754			   I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1755	}
1756
1757	/* Don't disable pipe or pipe PLLs if needed */
1758	if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1759	    (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1760		return;
1761
1762	/* Make sure the pipe isn't still relying on us */
1763	assert_pipe_disabled(dev_priv, pipe);
1764
1765	I915_WRITE(DPLL(pipe), 0);
1766	POSTING_READ(DPLL(pipe));
1767}
1768
1769static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1770{
1771	u32 val = 0;
1772
1773	/* Make sure the pipe isn't still relying on us */
1774	assert_pipe_disabled(dev_priv, pipe);
1775
1776	/*
1777	 * Leave integrated clock source and reference clock enabled for pipe B.
1778	 * The latter is needed for VGA hotplug / manual detection.
1779	 */
1780	if (pipe == PIPE_B)
1781		val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REFA_CLK_ENABLE_VLV;
1782	I915_WRITE(DPLL(pipe), val);
1783	POSTING_READ(DPLL(pipe));
1784
1785}
1786
1787static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1788{
1789	enum dpio_channel port = vlv_pipe_to_channel(pipe);
1790	u32 val;
1791
1792	/* Make sure the pipe isn't still relying on us */
1793	assert_pipe_disabled(dev_priv, pipe);
1794
1795	/* Set PLL en = 0 */
1796	val = DPLL_SSC_REF_CLOCK_CHV | DPLL_REFA_CLK_ENABLE_VLV;
1797	if (pipe != PIPE_A)
1798		val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1799	I915_WRITE(DPLL(pipe), val);
1800	POSTING_READ(DPLL(pipe));
1801
1802	mutex_lock(&dev_priv->dpio_lock);
1803
1804	/* Disable 10bit clock to display controller */
1805	val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1806	val &= ~DPIO_DCLKP_EN;
1807	vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1808
1809	/* disable left/right clock distribution */
1810	if (pipe != PIPE_B) {
1811		val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW5_CH0);
1812		val &= ~(CHV_BUFLEFTENA1_MASK | CHV_BUFRIGHTENA1_MASK);
1813		vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW5_CH0, val);
1814	} else {
1815		val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW1_CH1);
1816		val &= ~(CHV_BUFLEFTENA2_MASK | CHV_BUFRIGHTENA2_MASK);
1817		vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW1_CH1, val);
1818	}
1819
1820	mutex_unlock(&dev_priv->dpio_lock);
1821}
1822
1823void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1824		struct intel_digital_port *dport)
1825{
1826	u32 port_mask;
1827	int dpll_reg;
1828
1829	switch (dport->port) {
1830	case PORT_B:
1831		port_mask = DPLL_PORTB_READY_MASK;
1832		dpll_reg = DPLL(0);
1833		break;
1834	case PORT_C:
1835		port_mask = DPLL_PORTC_READY_MASK;
1836		dpll_reg = DPLL(0);
1837		break;
1838	case PORT_D:
1839		port_mask = DPLL_PORTD_READY_MASK;
1840		dpll_reg = DPIO_PHY_STATUS;
1841		break;
1842	default:
1843		BUG();
1844	}
1845
1846	if (wait_for((I915_READ(dpll_reg) & port_mask) == 0, 1000))
1847		WARN(1, "timed out waiting for port %c ready: 0x%08x\n",
1848		     port_name(dport->port), I915_READ(dpll_reg));
1849}
1850
1851static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1852{
1853	struct drm_device *dev = crtc->base.dev;
1854	struct drm_i915_private *dev_priv = dev->dev_private;
1855	struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1856
1857	if (WARN_ON(pll == NULL))
1858		return;
1859
1860	WARN_ON(!pll->config.crtc_mask);
1861	if (pll->active == 0) {
1862		DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1863		WARN_ON(pll->on);
1864		assert_shared_dpll_disabled(dev_priv, pll);
1865
1866		pll->mode_set(dev_priv, pll);
1867	}
1868}
1869
1870/**
1871 * intel_enable_shared_dpll - enable PCH PLL
1872 * @dev_priv: i915 private structure
1873 * @pipe: pipe PLL to enable
1874 *
1875 * The PCH PLL needs to be enabled before the PCH transcoder, since it
1876 * drives the transcoder clock.
1877 */
1878static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1879{
1880	struct drm_device *dev = crtc->base.dev;
1881	struct drm_i915_private *dev_priv = dev->dev_private;
1882	struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1883
1884	if (WARN_ON(pll == NULL))
1885		return;
1886
1887	if (WARN_ON(pll->config.crtc_mask == 0))
1888		return;
1889
1890	DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1891		      pll->name, pll->active, pll->on,
1892		      crtc->base.base.id);
1893
1894	if (pll->active++) {
1895		WARN_ON(!pll->on);
1896		assert_shared_dpll_enabled(dev_priv, pll);
1897		return;
1898	}
1899	WARN_ON(pll->on);
1900
1901	intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1902
1903	DRM_DEBUG_KMS("enabling %s\n", pll->name);
1904	pll->enable(dev_priv, pll);
1905	pll->on = true;
1906}
1907
1908static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1909{
1910	struct drm_device *dev = crtc->base.dev;
1911	struct drm_i915_private *dev_priv = dev->dev_private;
1912	struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1913
1914	/* PCH only available on ILK+ */
1915	BUG_ON(INTEL_INFO(dev)->gen < 5);
1916	if (WARN_ON(pll == NULL))
1917	       return;
1918
1919	if (WARN_ON(pll->config.crtc_mask == 0))
1920		return;
1921
1922	DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1923		      pll->name, pll->active, pll->on,
1924		      crtc->base.base.id);
1925
1926	if (WARN_ON(pll->active == 0)) {
1927		assert_shared_dpll_disabled(dev_priv, pll);
1928		return;
1929	}
1930
1931	assert_shared_dpll_enabled(dev_priv, pll);
1932	WARN_ON(!pll->on);
1933	if (--pll->active)
1934		return;
1935
1936	DRM_DEBUG_KMS("disabling %s\n", pll->name);
1937	pll->disable(dev_priv, pll);
1938	pll->on = false;
1939
1940	intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1941}
1942
1943static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1944					   enum pipe pipe)
1945{
1946	struct drm_device *dev = dev_priv->dev;
1947	struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1948	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1949	uint32_t reg, val, pipeconf_val;
1950
1951	/* PCH only available on ILK+ */
1952	BUG_ON(!HAS_PCH_SPLIT(dev));
1953
1954	/* Make sure PCH DPLL is enabled */
1955	assert_shared_dpll_enabled(dev_priv,
1956				   intel_crtc_to_shared_dpll(intel_crtc));
1957
1958	/* FDI must be feeding us bits for PCH ports */
1959	assert_fdi_tx_enabled(dev_priv, pipe);
1960	assert_fdi_rx_enabled(dev_priv, pipe);
1961
1962	if (HAS_PCH_CPT(dev)) {
1963		/* Workaround: Set the timing override bit before enabling the
1964		 * pch transcoder. */
1965		reg = TRANS_CHICKEN2(pipe);
1966		val = I915_READ(reg);
1967		val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1968		I915_WRITE(reg, val);
1969	}
1970
1971	reg = PCH_TRANSCONF(pipe);
1972	val = I915_READ(reg);
1973	pipeconf_val = I915_READ(PIPECONF(pipe));
1974
1975	if (HAS_PCH_IBX(dev_priv->dev)) {
1976		/*
1977		 * make the BPC in transcoder be consistent with
1978		 * that in pipeconf reg.
1979		 */
1980		val &= ~PIPECONF_BPC_MASK;
1981		val |= pipeconf_val & PIPECONF_BPC_MASK;
1982	}
1983
1984	val &= ~TRANS_INTERLACE_MASK;
1985	if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1986		if (HAS_PCH_IBX(dev_priv->dev) &&
1987		    intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1988			val |= TRANS_LEGACY_INTERLACED_ILK;
1989		else
1990			val |= TRANS_INTERLACED;
1991	else
1992		val |= TRANS_PROGRESSIVE;
1993
1994	I915_WRITE(reg, val | TRANS_ENABLE);
1995	if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1996		DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1997}
1998
1999static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
2000				      enum transcoder cpu_transcoder)
2001{
2002	u32 val, pipeconf_val;
2003
2004	/* PCH only available on ILK+ */
2005	BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
2006
2007	/* FDI must be feeding us bits for PCH ports */
2008	assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2009	assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2010
2011	/* Workaround: set timing override bit. */
2012	val = I915_READ(_TRANSA_CHICKEN2);
2013	val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2014	I915_WRITE(_TRANSA_CHICKEN2, val);
2015
2016	val = TRANS_ENABLE;
2017	pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2018
2019	if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2020	    PIPECONF_INTERLACED_ILK)
2021		val |= TRANS_INTERLACED;
2022	else
2023		val |= TRANS_PROGRESSIVE;
2024
2025	I915_WRITE(LPT_TRANSCONF, val);
2026	if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2027		DRM_ERROR("Failed to enable PCH transcoder\n");
2028}
2029
2030static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2031					    enum pipe pipe)
2032{
2033	struct drm_device *dev = dev_priv->dev;
2034	uint32_t reg, val;
2035
2036	/* FDI relies on the transcoder */
2037	assert_fdi_tx_disabled(dev_priv, pipe);
2038	assert_fdi_rx_disabled(dev_priv, pipe);
2039
2040	/* Ports must be off as well */
2041	assert_pch_ports_disabled(dev_priv, pipe);
2042
2043	reg = PCH_TRANSCONF(pipe);
2044	val = I915_READ(reg);
2045	val &= ~TRANS_ENABLE;
2046	I915_WRITE(reg, val);
2047	/* wait for PCH transcoder off, transcoder state */
2048	if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2049		DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2050
2051	if (!HAS_PCH_IBX(dev)) {
2052		/* Workaround: Clear the timing override chicken bit again. */
2053		reg = TRANS_CHICKEN2(pipe);
2054		val = I915_READ(reg);
2055		val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2056		I915_WRITE(reg, val);
2057	}
2058}
2059
2060static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2061{
2062	u32 val;
2063
2064	val = I915_READ(LPT_TRANSCONF);
2065	val &= ~TRANS_ENABLE;
2066	I915_WRITE(LPT_TRANSCONF, val);
2067	/* wait for PCH transcoder off, transcoder state */
2068	if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2069		DRM_ERROR("Failed to disable PCH transcoder\n");
2070
2071	/* Workaround: clear timing override bit. */
2072	val = I915_READ(_TRANSA_CHICKEN2);
2073	val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2074	I915_WRITE(_TRANSA_CHICKEN2, val);
2075}
2076
2077/**
2078 * intel_enable_pipe - enable a pipe, asserting requirements
2079 * @crtc: crtc responsible for the pipe
2080 *
2081 * Enable @crtc's pipe, making sure that various hardware specific requirements
2082 * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2083 */
2084static void intel_enable_pipe(struct intel_crtc *crtc)
2085{
2086	struct drm_device *dev = crtc->base.dev;
2087	struct drm_i915_private *dev_priv = dev->dev_private;
2088	enum pipe pipe = crtc->pipe;
2089	enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2090								      pipe);
2091	enum pipe pch_transcoder;
2092	int reg;
2093	u32 val;
2094
2095	assert_planes_disabled(dev_priv, pipe);
2096	assert_cursor_disabled(dev_priv, pipe);
2097	assert_sprites_disabled(dev_priv, pipe);
2098
2099	if (HAS_PCH_LPT(dev_priv->dev))
2100		pch_transcoder = TRANSCODER_A;
2101	else
2102		pch_transcoder = pipe;
2103
2104	/*
2105	 * A pipe without a PLL won't actually be able to drive bits from
2106	 * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2107	 * need the check.
2108	 */
2109	if (!HAS_PCH_SPLIT(dev_priv->dev))
2110		if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2111			assert_dsi_pll_enabled(dev_priv);
2112		else
2113			assert_pll_enabled(dev_priv, pipe);
2114	else {
2115		if (crtc->config->has_pch_encoder) {
2116			/* if driving the PCH, we need FDI enabled */
2117			assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2118			assert_fdi_tx_pll_enabled(dev_priv,
2119						  (enum pipe) cpu_transcoder);
2120		}
2121		/* FIXME: assert CPU port conditions for SNB+ */
2122	}
2123
2124	reg = PIPECONF(cpu_transcoder);
2125	val = I915_READ(reg);
2126	if (val & PIPECONF_ENABLE) {
2127		WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2128			  (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2129		return;
2130	}
2131
2132	I915_WRITE(reg, val | PIPECONF_ENABLE);
2133	POSTING_READ(reg);
2134}
2135
2136/**
2137 * intel_disable_pipe - disable a pipe, asserting requirements
2138 * @crtc: crtc whose pipes is to be disabled
2139 *
2140 * Disable the pipe of @crtc, making sure that various hardware
2141 * specific requirements are met, if applicable, e.g. plane
2142 * disabled, panel fitter off, etc.
2143 *
2144 * Will wait until the pipe has shut down before returning.
2145 */
2146static void intel_disable_pipe(struct intel_crtc *crtc)
2147{
2148	struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2149	enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2150	enum pipe pipe = crtc->pipe;
2151	int reg;
2152	u32 val;
2153
2154	/*
2155	 * Make sure planes won't keep trying to pump pixels to us,
2156	 * or we might hang the display.
2157	 */
2158	assert_planes_disabled(dev_priv, pipe);
2159	assert_cursor_disabled(dev_priv, pipe);
2160	assert_sprites_disabled(dev_priv, pipe);
2161
2162	reg = PIPECONF(cpu_transcoder);
2163	val = I915_READ(reg);
2164	if ((val & PIPECONF_ENABLE) == 0)
2165		return;
2166
2167	/*
2168	 * Double wide has implications for planes
2169	 * so best keep it disabled when not needed.
2170	 */
2171	if (crtc->config->double_wide)
2172		val &= ~PIPECONF_DOUBLE_WIDE;
2173
2174	/* Don't disable pipe or pipe PLLs if needed */
2175	if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2176	    !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2177		val &= ~PIPECONF_ENABLE;
2178
2179	I915_WRITE(reg, val);
2180	if ((val & PIPECONF_ENABLE) == 0)
2181		intel_wait_for_pipe_off(crtc);
2182}
2183
2184/*
2185 * Plane regs are double buffered, going from enabled->disabled needs a
2186 * trigger in order to latch.  The display address reg provides this.
2187 */
2188void intel_flush_primary_plane(struct drm_i915_private *dev_priv,
2189			       enum plane plane)
2190{
2191	struct drm_device *dev = dev_priv->dev;
2192	u32 reg = INTEL_INFO(dev)->gen >= 4 ? DSPSURF(plane) : DSPADDR(plane);
2193
2194	I915_WRITE(reg, I915_READ(reg));
2195	POSTING_READ(reg);
2196}
2197
2198/**
2199 * intel_enable_primary_hw_plane - enable the primary plane on a given pipe
2200 * @plane:  plane to be enabled
2201 * @crtc: crtc for the plane
2202 *
2203 * Enable @plane on @crtc, making sure that the pipe is running first.
2204 */
2205static void intel_enable_primary_hw_plane(struct drm_plane *plane,
2206					  struct drm_crtc *crtc)
2207{
2208	struct drm_device *dev = plane->dev;
2209	struct drm_i915_private *dev_priv = dev->dev_private;
2210	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2211
2212	/* If the pipe isn't enabled, we can't pump pixels and may hang */
2213	assert_pipe_enabled(dev_priv, intel_crtc->pipe);
2214
2215	if (intel_crtc->primary_enabled)
2216		return;
2217
2218	intel_crtc->primary_enabled = true;
2219
2220	dev_priv->display.update_primary_plane(crtc, plane->fb,
2221					       crtc->x, crtc->y);
2222
2223	/*
2224	 * BDW signals flip done immediately if the plane
2225	 * is disabled, even if the plane enable is already
2226	 * armed to occur at the next vblank :(
2227	 */
2228	if (IS_BROADWELL(dev))
2229		intel_wait_for_vblank(dev, intel_crtc->pipe);
2230}
2231
2232/**
2233 * intel_disable_primary_hw_plane - disable the primary hardware plane
2234 * @plane: plane to be disabled
2235 * @crtc: crtc for the plane
2236 *
2237 * Disable @plane on @crtc, making sure that the pipe is running first.
2238 */
2239static void intel_disable_primary_hw_plane(struct drm_plane *plane,
2240					   struct drm_crtc *crtc)
2241{
2242	struct drm_device *dev = plane->dev;
2243	struct drm_i915_private *dev_priv = dev->dev_private;
2244	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2245
2246	if (WARN_ON(!intel_crtc->active))
2247		return;
2248
2249	if (!intel_crtc->primary_enabled)
2250		return;
2251
2252	intel_crtc->primary_enabled = false;
2253
2254	dev_priv->display.update_primary_plane(crtc, plane->fb,
2255					       crtc->x, crtc->y);
2256}
2257
2258static bool need_vtd_wa(struct drm_device *dev)
2259{
2260#ifdef CONFIG_INTEL_IOMMU
2261	if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2262		return true;
2263#endif
2264	return false;
2265}
2266
2267unsigned int
2268intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2269		  uint64_t fb_format_modifier)
2270{
2271	unsigned int tile_height;
2272	uint32_t pixel_bytes;
2273
2274	switch (fb_format_modifier) {
2275	case DRM_FORMAT_MOD_NONE:
2276		tile_height = 1;
2277		break;
2278	case I915_FORMAT_MOD_X_TILED:
2279		tile_height = IS_GEN2(dev) ? 16 : 8;
2280		break;
2281	case I915_FORMAT_MOD_Y_TILED:
2282		tile_height = 32;
2283		break;
2284	case I915_FORMAT_MOD_Yf_TILED:
2285		pixel_bytes = drm_format_plane_cpp(pixel_format, 0);
2286		switch (pixel_bytes) {
2287		default:
2288		case 1:
2289			tile_height = 64;
2290			break;
2291		case 2:
2292		case 4:
2293			tile_height = 32;
2294			break;
2295		case 8:
2296			tile_height = 16;
2297			break;
2298		case 16:
2299			WARN_ONCE(1,
2300				  "128-bit pixels are not supported for display!");
2301			tile_height = 16;
2302			break;
2303		}
2304		break;
2305	default:
2306		MISSING_CASE(fb_format_modifier);
2307		tile_height = 1;
2308		break;
2309	}
2310
2311	return tile_height;
2312}
2313
2314unsigned int
2315intel_fb_align_height(struct drm_device *dev, unsigned int height,
2316		      uint32_t pixel_format, uint64_t fb_format_modifier)
2317{
2318	return ALIGN(height, intel_tile_height(dev, pixel_format,
2319					       fb_format_modifier));
2320}
2321
2322static int
2323intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2324			const struct drm_plane_state *plane_state)
2325{
2326	struct intel_rotation_info *info = &view->rotation_info;
2327
2328	*view = i915_ggtt_view_normal;
2329
2330	if (!plane_state)
2331		return 0;
2332
2333	if (!intel_rotation_90_or_270(plane_state->rotation))
2334		return 0;
2335
2336	*view = i915_ggtt_view_rotated;
2337
2338	info->height = fb->height;
2339	info->pixel_format = fb->pixel_format;
2340	info->pitch = fb->pitches[0];
2341	info->fb_modifier = fb->modifier[0];
2342
2343	if (!(info->fb_modifier == I915_FORMAT_MOD_Y_TILED ||
2344	      info->fb_modifier == I915_FORMAT_MOD_Yf_TILED)) {
2345		DRM_DEBUG_KMS(
2346			      "Y or Yf tiling is needed for 90/270 rotation!\n");
2347		return -EINVAL;
2348	}
2349
2350	return 0;
2351}
2352
2353int
2354intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2355			   struct drm_framebuffer *fb,
2356			   const struct drm_plane_state *plane_state,
2357			   struct intel_engine_cs *pipelined)
2358{
2359	struct drm_device *dev = fb->dev;
2360	struct drm_i915_private *dev_priv = dev->dev_private;
2361	struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2362	struct i915_ggtt_view view;
2363	u32 alignment;
2364	int ret;
2365
2366	WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2367
2368	switch (fb->modifier[0]) {
2369	case DRM_FORMAT_MOD_NONE:
2370		if (INTEL_INFO(dev)->gen >= 9)
2371			alignment = 256 * 1024;
2372		else if (IS_BROADWATER(dev) || IS_CRESTLINE(dev))
2373			alignment = 128 * 1024;
2374		else if (INTEL_INFO(dev)->gen >= 4)
2375			alignment = 4 * 1024;
2376		else
2377			alignment = 64 * 1024;
2378		break;
2379	case I915_FORMAT_MOD_X_TILED:
2380		if (INTEL_INFO(dev)->gen >= 9)
2381			alignment = 256 * 1024;
2382		else {
2383			/* pin() will align the object as required by fence */
2384			alignment = 0;
2385		}
2386		break;
2387	case I915_FORMAT_MOD_Y_TILED:
2388	case I915_FORMAT_MOD_Yf_TILED:
2389		if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2390			  "Y tiling bo slipped through, driver bug!\n"))
2391			return -EINVAL;
2392		alignment = 1 * 1024 * 1024;
2393		break;
2394	default:
2395		MISSING_CASE(fb->modifier[0]);
2396		return -EINVAL;
2397	}
2398
2399	ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2400	if (ret)
2401		return ret;
2402
2403	/* Note that the w/a also requires 64 PTE of padding following the
2404	 * bo. We currently fill all unused PTE with the shadow page and so
2405	 * we should always have valid PTE following the scanout preventing
2406	 * the VT-d warning.
2407	 */
2408	if (need_vtd_wa(dev) && alignment < 256 * 1024)
2409		alignment = 256 * 1024;
2410
2411	/*
2412	 * Global gtt pte registers are special registers which actually forward
2413	 * writes to a chunk of system memory. Which means that there is no risk
2414	 * that the register values disappear as soon as we call
2415	 * intel_runtime_pm_put(), so it is correct to wrap only the
2416	 * pin/unpin/fence and not more.
2417	 */
2418	intel_runtime_pm_get(dev_priv);
2419
2420	dev_priv->mm.interruptible = false;
2421	ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined,
2422						   &view);
2423	if (ret)
2424		goto err_interruptible;
2425
2426	/* Install a fence for tiled scan-out. Pre-i965 always needs a
2427	 * fence, whereas 965+ only requires a fence if using
2428	 * framebuffer compression.  For simplicity, we always install
2429	 * a fence as the cost is not that onerous.
2430	 */
2431	ret = i915_gem_object_get_fence(obj);
2432	if (ret)
2433		goto err_unpin;
2434
2435	i915_gem_object_pin_fence(obj);
2436
2437	dev_priv->mm.interruptible = true;
2438	intel_runtime_pm_put(dev_priv);
2439	return 0;
2440
2441err_unpin:
2442	i915_gem_object_unpin_from_display_plane(obj, &view);
2443err_interruptible:
2444	dev_priv->mm.interruptible = true;
2445	intel_runtime_pm_put(dev_priv);
2446	return ret;
2447}
2448
2449static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2450			       const struct drm_plane_state *plane_state)
2451{
2452	struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2453	struct i915_ggtt_view view;
2454	int ret;
2455
2456	WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2457
2458	ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2459	WARN_ONCE(ret, "Couldn't get view from plane state!");
2460
2461	i915_gem_object_unpin_fence(obj);
2462	i915_gem_object_unpin_from_display_plane(obj, &view);
2463}
2464
2465/* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2466 * is assumed to be a power-of-two. */
2467unsigned long intel_gen4_compute_page_offset(int *x, int *y,
2468					     unsigned int tiling_mode,
2469					     unsigned int cpp,
2470					     unsigned int pitch)
2471{
2472	if (tiling_mode != I915_TILING_NONE) {
2473		unsigned int tile_rows, tiles;
2474
2475		tile_rows = *y / 8;
2476		*y %= 8;
2477
2478		tiles = *x / (512/cpp);
2479		*x %= 512/cpp;
2480
2481		return tile_rows * pitch * 8 + tiles * 4096;
2482	} else {
2483		unsigned int offset;
2484
2485		offset = *y * pitch + *x * cpp;
2486		*y = 0;
2487		*x = (offset & 4095) / cpp;
2488		return offset & -4096;
2489	}
2490}
2491
2492static int i9xx_format_to_fourcc(int format)
2493{
2494	switch (format) {
2495	case DISPPLANE_8BPP:
2496		return DRM_FORMAT_C8;
2497	case DISPPLANE_BGRX555:
2498		return DRM_FORMAT_XRGB1555;
2499	case DISPPLANE_BGRX565:
2500		return DRM_FORMAT_RGB565;
2501	default:
2502	case DISPPLANE_BGRX888:
2503		return DRM_FORMAT_XRGB8888;
2504	case DISPPLANE_RGBX888:
2505		return DRM_FORMAT_XBGR8888;
2506	case DISPPLANE_BGRX101010:
2507		return DRM_FORMAT_XRGB2101010;
2508	case DISPPLANE_RGBX101010:
2509		return DRM_FORMAT_XBGR2101010;
2510	}
2511}
2512
2513static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2514{
2515	switch (format) {
2516	case PLANE_CTL_FORMAT_RGB_565:
2517		return DRM_FORMAT_RGB565;
2518	default:
2519	case PLANE_CTL_FORMAT_XRGB_8888:
2520		if (rgb_order) {
2521			if (alpha)
2522				return DRM_FORMAT_ABGR8888;
2523			else
2524				return DRM_FORMAT_XBGR8888;
2525		} else {
2526			if (alpha)
2527				return DRM_FORMAT_ARGB8888;
2528			else
2529				return DRM_FORMAT_XRGB8888;
2530		}
2531	case PLANE_CTL_FORMAT_XRGB_2101010:
2532		if (rgb_order)
2533			return DRM_FORMAT_XBGR2101010;
2534		else
2535			return DRM_FORMAT_XRGB2101010;
2536	}
2537}
2538
2539static bool
2540intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2541			      struct intel_initial_plane_config *plane_config)
2542{
2543	struct drm_device *dev = crtc->base.dev;
2544	struct drm_i915_gem_object *obj = NULL;
2545	struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2546	struct drm_framebuffer *fb = &plane_config->fb->base;
2547	u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2548	u32 size_aligned = round_up(plane_config->base + plane_config->size,
2549				    PAGE_SIZE);
2550
2551	size_aligned -= base_aligned;
2552
2553	if (plane_config->size == 0)
2554		return false;
2555
2556	obj = i915_gem_object_create_stolen_for_preallocated(dev,
2557							     base_aligned,
2558							     base_aligned,
2559							     size_aligned);
2560	if (!obj)
2561		return false;
2562
2563	obj->tiling_mode = plane_config->tiling;
2564	if (obj->tiling_mode == I915_TILING_X)
2565		obj->stride = fb->pitches[0];
2566
2567	mode_cmd.pixel_format = fb->pixel_format;
2568	mode_cmd.width = fb->width;
2569	mode_cmd.height = fb->height;
2570	mode_cmd.pitches[0] = fb->pitches[0];
2571	mode_cmd.modifier[0] = fb->modifier[0];
2572	mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2573
2574	mutex_lock(&dev->struct_mutex);
2575	if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2576				   &mode_cmd, obj)) {
2577		DRM_DEBUG_KMS("intel fb init failed\n");
2578		goto out_unref_obj;
2579	}
2580	mutex_unlock(&dev->struct_mutex);
2581
2582	DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2583	return true;
2584
2585out_unref_obj:
2586	drm_gem_object_unreference(&obj->base);
2587	mutex_unlock(&dev->struct_mutex);
2588	return false;
2589}
2590
2591/* Update plane->state->fb to match plane->fb after driver-internal updates */
2592static void
2593update_state_fb(struct drm_plane *plane)
2594{
2595	if (plane->fb == plane->state->fb)
2596		return;
2597
2598	if (plane->state->fb)
2599		drm_framebuffer_unreference(plane->state->fb);
2600	plane->state->fb = plane->fb;
2601	if (plane->state->fb)
2602		drm_framebuffer_reference(plane->state->fb);
2603}
2604
2605static void
2606intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2607			     struct intel_initial_plane_config *plane_config)
2608{
2609	struct drm_device *dev = intel_crtc->base.dev;
2610	struct drm_i915_private *dev_priv = dev->dev_private;
2611	struct drm_crtc *c;
2612	struct intel_crtc *i;
2613	struct drm_i915_gem_object *obj;
2614	struct drm_plane *primary = intel_crtc->base.primary;
2615	struct drm_framebuffer *fb;
2616
2617	if (!plane_config->fb)
2618		return;
2619
2620	if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2621		fb = &plane_config->fb->base;
2622		goto valid_fb;
2623	}
2624
2625	kfree(plane_config->fb);
2626
2627	/*
2628	 * Failed to alloc the obj, check to see if we should share
2629	 * an fb with another CRTC instead
2630	 */
2631	for_each_crtc(dev, c) {
2632		i = to_intel_crtc(c);
2633
2634		if (c == &intel_crtc->base)
2635			continue;
2636
2637		if (!i->active)
2638			continue;
2639
2640		fb = c->primary->fb;
2641		if (!fb)
2642			continue;
2643
2644		obj = intel_fb_obj(fb);
2645		if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2646			drm_framebuffer_reference(fb);
2647			goto valid_fb;
2648		}
2649	}
2650
2651	return;
2652
2653valid_fb:
2654	obj = intel_fb_obj(fb);
2655	if (obj->tiling_mode != I915_TILING_NONE)
2656		dev_priv->preserve_bios_swizzle = true;
2657
2658	primary->fb = fb;
2659	primary->state->crtc = &intel_crtc->base;
2660	primary->crtc = &intel_crtc->base;
2661	update_state_fb(primary);
2662	obj->frontbuffer_bits |= INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
2663}
2664
2665static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2666				      struct drm_framebuffer *fb,
2667				      int x, int y)
2668{
2669	struct drm_device *dev = crtc->dev;
2670	struct drm_i915_private *dev_priv = dev->dev_private;
2671	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2672	struct drm_i915_gem_object *obj;
2673	int plane = intel_crtc->plane;
2674	unsigned long linear_offset;
2675	u32 dspcntr;
2676	u32 reg = DSPCNTR(plane);
2677	int pixel_size;
2678
2679	if (!intel_crtc->primary_enabled) {
2680		I915_WRITE(reg, 0);
2681		if (INTEL_INFO(dev)->gen >= 4)
2682			I915_WRITE(DSPSURF(plane), 0);
2683		else
2684			I915_WRITE(DSPADDR(plane), 0);
2685		POSTING_READ(reg);
2686		return;
2687	}
2688
2689	obj = intel_fb_obj(fb);
2690	if (WARN_ON(obj == NULL))
2691		return;
2692
2693	pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2694
2695	dspcntr = DISPPLANE_GAMMA_ENABLE;
2696
2697	dspcntr |= DISPLAY_PLANE_ENABLE;
2698
2699	if (INTEL_INFO(dev)->gen < 4) {
2700		if (intel_crtc->pipe == PIPE_B)
2701			dspcntr |= DISPPLANE_SEL_PIPE_B;
2702
2703		/* pipesrc and dspsize control the size that is scaled from,
2704		 * which should always be the user's requested size.
2705		 */
2706		I915_WRITE(DSPSIZE(plane),
2707			   ((intel_crtc->config->pipe_src_h - 1) << 16) |
2708			   (intel_crtc->config->pipe_src_w - 1));
2709		I915_WRITE(DSPPOS(plane), 0);
2710	} else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2711		I915_WRITE(PRIMSIZE(plane),
2712			   ((intel_crtc->config->pipe_src_h - 1) << 16) |
2713			   (intel_crtc->config->pipe_src_w - 1));
2714		I915_WRITE(PRIMPOS(plane), 0);
2715		I915_WRITE(PRIMCNSTALPHA(plane), 0);
2716	}
2717
2718	switch (fb->pixel_format) {
2719	case DRM_FORMAT_C8:
2720		dspcntr |= DISPPLANE_8BPP;
2721		break;
2722	case DRM_FORMAT_XRGB1555:
2723	case DRM_FORMAT_ARGB1555:
2724		dspcntr |= DISPPLANE_BGRX555;
2725		break;
2726	case DRM_FORMAT_RGB565:
2727		dspcntr |= DISPPLANE_BGRX565;
2728		break;
2729	case DRM_FORMAT_XRGB8888:
2730	case DRM_FORMAT_ARGB8888:
2731		dspcntr |= DISPPLANE_BGRX888;
2732		break;
2733	case DRM_FORMAT_XBGR8888:
2734	case DRM_FORMAT_ABGR8888:
2735		dspcntr |= DISPPLANE_RGBX888;
2736		break;
2737	case DRM_FORMAT_XRGB2101010:
2738	case DRM_FORMAT_ARGB2101010:
2739		dspcntr |= DISPPLANE_BGRX101010;
2740		break;
2741	case DRM_FORMAT_XBGR2101010:
2742	case DRM_FORMAT_ABGR2101010:
2743		dspcntr |= DISPPLANE_RGBX101010;
2744		break;
2745	default:
2746		BUG();
2747	}
2748
2749	if (INTEL_INFO(dev)->gen >= 4 &&
2750	    obj->tiling_mode != I915_TILING_NONE)
2751		dspcntr |= DISPPLANE_TILED;
2752
2753	if (IS_G4X(dev))
2754		dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2755
2756	linear_offset = y * fb->pitches[0] + x * pixel_size;
2757
2758	if (INTEL_INFO(dev)->gen >= 4) {
2759		intel_crtc->dspaddr_offset =
2760			intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2761						       pixel_size,
2762						       fb->pitches[0]);
2763		linear_offset -= intel_crtc->dspaddr_offset;
2764	} else {
2765		intel_crtc->dspaddr_offset = linear_offset;
2766	}
2767
2768	if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2769		dspcntr |= DISPPLANE_ROTATE_180;
2770
2771		x += (intel_crtc->config->pipe_src_w - 1);
2772		y += (intel_crtc->config->pipe_src_h - 1);
2773
2774		/* Finding the last pixel of the last line of the display
2775		data and adding to linear_offset*/
2776		linear_offset +=
2777			(intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2778			(intel_crtc->config->pipe_src_w - 1) * pixel_size;
2779	}
2780
2781	I915_WRITE(reg, dspcntr);
2782
2783	I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2784	if (INTEL_INFO(dev)->gen >= 4) {
2785		I915_WRITE(DSPSURF(plane),
2786			   i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2787		I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2788		I915_WRITE(DSPLINOFF(plane), linear_offset);
2789	} else
2790		I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2791	POSTING_READ(reg);
2792}
2793
2794static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2795					  struct drm_framebuffer *fb,
2796					  int x, int y)
2797{
2798	struct drm_device *dev = crtc->dev;
2799	struct drm_i915_private *dev_priv = dev->dev_private;
2800	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2801	struct drm_i915_gem_object *obj;
2802	int plane = intel_crtc->plane;
2803	unsigned long linear_offset;
2804	u32 dspcntr;
2805	u32 reg = DSPCNTR(plane);
2806	int pixel_size;
2807
2808	if (!intel_crtc->primary_enabled) {
2809		I915_WRITE(reg, 0);
2810		I915_WRITE(DSPSURF(plane), 0);
2811		POSTING_READ(reg);
2812		return;
2813	}
2814
2815	obj = intel_fb_obj(fb);
2816	if (WARN_ON(obj == NULL))
2817		return;
2818
2819	pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2820
2821	dspcntr = DISPPLANE_GAMMA_ENABLE;
2822
2823	dspcntr |= DISPLAY_PLANE_ENABLE;
2824
2825	if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2826		dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2827
2828	switch (fb->pixel_format) {
2829	case DRM_FORMAT_C8:
2830		dspcntr |= DISPPLANE_8BPP;
2831		break;
2832	case DRM_FORMAT_RGB565:
2833		dspcntr |= DISPPLANE_BGRX565;
2834		break;
2835	case DRM_FORMAT_XRGB8888:
2836	case DRM_FORMAT_ARGB8888:
2837		dspcntr |= DISPPLANE_BGRX888;
2838		break;
2839	case DRM_FORMAT_XBGR8888:
2840	case DRM_FORMAT_ABGR8888:
2841		dspcntr |= DISPPLANE_RGBX888;
2842		break;
2843	case DRM_FORMAT_XRGB2101010:
2844	case DRM_FORMAT_ARGB2101010:
2845		dspcntr |= DISPPLANE_BGRX101010;
2846		break;
2847	case DRM_FORMAT_XBGR2101010:
2848	case DRM_FORMAT_ABGR2101010:
2849		dspcntr |= DISPPLANE_RGBX101010;
2850		break;
2851	default:
2852		BUG();
2853	}
2854
2855	if (obj->tiling_mode != I915_TILING_NONE)
2856		dspcntr |= DISPPLANE_TILED;
2857
2858	if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2859		dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2860
2861	linear_offset = y * fb->pitches[0] + x * pixel_size;
2862	intel_crtc->dspaddr_offset =
2863		intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2864					       pixel_size,
2865					       fb->pitches[0]);
2866	linear_offset -= intel_crtc->dspaddr_offset;
2867	if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2868		dspcntr |= DISPPLANE_ROTATE_180;
2869
2870		if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2871			x += (intel_crtc->config->pipe_src_w - 1);
2872			y += (intel_crtc->config->pipe_src_h - 1);
2873
2874			/* Finding the last pixel of the last line of the display
2875			data and adding to linear_offset*/
2876			linear_offset +=
2877				(intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2878				(intel_crtc->config->pipe_src_w - 1) * pixel_size;
2879		}
2880	}
2881
2882	I915_WRITE(reg, dspcntr);
2883
2884	I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2885	I915_WRITE(DSPSURF(plane),
2886		   i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2887	if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2888		I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2889	} else {
2890		I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2891		I915_WRITE(DSPLINOFF(plane), linear_offset);
2892	}
2893	POSTING_READ(reg);
2894}
2895
2896u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2897			      uint32_t pixel_format)
2898{
2899	u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2900
2901	/*
2902	 * The stride is either expressed as a multiple of 64 bytes
2903	 * chunks for linear buffers or in number of tiles for tiled
2904	 * buffers.
2905	 */
2906	switch (fb_modifier) {
2907	case DRM_FORMAT_MOD_NONE:
2908		return 64;
2909	case I915_FORMAT_MOD_X_TILED:
2910		if (INTEL_INFO(dev)->gen == 2)
2911			return 128;
2912		return 512;
2913	case I915_FORMAT_MOD_Y_TILED:
2914		/* No need to check for old gens and Y tiling since this is
2915		 * about the display engine and those will be blocked before
2916		 * we get here.
2917		 */
2918		return 128;
2919	case I915_FORMAT_MOD_Yf_TILED:
2920		if (bits_per_pixel == 8)
2921			return 64;
2922		else
2923			return 128;
2924	default:
2925		MISSING_CASE(fb_modifier);
2926		return 64;
2927	}
2928}
2929
2930unsigned long intel_plane_obj_offset(struct intel_plane *intel_plane,
2931				     struct drm_i915_gem_object *obj)
2932{
2933	const struct i915_ggtt_view *view = &i915_ggtt_view_normal;
2934
2935	if (intel_rotation_90_or_270(intel_plane->base.state->rotation))
2936		view = &i915_ggtt_view_rotated;
2937
2938	return i915_gem_obj_ggtt_offset_view(obj, view);
2939}
2940
2941static void skylake_update_primary_plane(struct drm_crtc *crtc,
2942					 struct drm_framebuffer *fb,
2943					 int x, int y)
2944{
2945	struct drm_device *dev = crtc->dev;
2946	struct drm_i915_private *dev_priv = dev->dev_private;
2947	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2948	struct drm_i915_gem_object *obj;
2949	int pipe = intel_crtc->pipe;
2950	u32 plane_ctl, stride_div;
2951	unsigned long surf_addr;
2952
2953	if (!intel_crtc->primary_enabled) {
2954		I915_WRITE(PLANE_CTL(pipe, 0), 0);
2955		I915_WRITE(PLANE_SURF(pipe, 0), 0);
2956		POSTING_READ(PLANE_CTL(pipe, 0));
2957		return;
2958	}
2959
2960	plane_ctl = PLANE_CTL_ENABLE |
2961		    PLANE_CTL_PIPE_GAMMA_ENABLE |
2962		    PLANE_CTL_PIPE_CSC_ENABLE;
2963
2964	switch (fb->pixel_format) {
2965	case DRM_FORMAT_RGB565:
2966		plane_ctl |= PLANE_CTL_FORMAT_RGB_565;
2967		break;
2968	case DRM_FORMAT_XRGB8888:
2969		plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2970		break;
2971	case DRM_FORMAT_ARGB8888:
2972		plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2973		plane_ctl |= PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2974		break;
2975	case DRM_FORMAT_XBGR8888:
2976		plane_ctl |= PLANE_CTL_ORDER_RGBX;
2977		plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2978		break;
2979	case DRM_FORMAT_ABGR8888:
2980		plane_ctl |= PLANE_CTL_ORDER_RGBX;
2981		plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2982		plane_ctl |= PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2983		break;
2984	case DRM_FORMAT_XRGB2101010:
2985		plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
2986		break;
2987	case DRM_FORMAT_XBGR2101010:
2988		plane_ctl |= PLANE_CTL_ORDER_RGBX;
2989		plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
2990		break;
2991	default:
2992		BUG();
2993	}
2994
2995	switch (fb->modifier[0]) {
2996	case DRM_FORMAT_MOD_NONE:
2997		break;
2998	case I915_FORMAT_MOD_X_TILED:
2999		plane_ctl |= PLANE_CTL_TILED_X;
3000		break;
3001	case I915_FORMAT_MOD_Y_TILED:
3002		plane_ctl |= PLANE_CTL_TILED_Y;
3003		break;
3004	case I915_FORMAT_MOD_Yf_TILED:
3005		plane_ctl |= PLANE_CTL_TILED_YF;
3006		break;
3007	default:
3008		MISSING_CASE(fb->modifier[0]);
3009	}
3010
3011	plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3012	if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180))
3013		plane_ctl |= PLANE_CTL_ROTATE_180;
3014
3015	obj = intel_fb_obj(fb);
3016	stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3017					       fb->pixel_format);
3018	surf_addr = intel_plane_obj_offset(to_intel_plane(crtc->primary), obj);
3019
3020	I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3021	I915_WRITE(PLANE_POS(pipe, 0), 0);
3022	I915_WRITE(PLANE_OFFSET(pipe, 0), (y << 16) | x);
3023	I915_WRITE(PLANE_SIZE(pipe, 0),
3024		   (intel_crtc->config->pipe_src_h - 1) << 16 |
3025		   (intel_crtc->config->pipe_src_w - 1));
3026	I915_WRITE(PLANE_STRIDE(pipe, 0), fb->pitches[0] / stride_div);
3027	I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3028
3029	POSTING_READ(PLANE_SURF(pipe, 0));
3030}
3031
3032/* Assume fb object is pinned & idle & fenced and just update base pointers */
3033static int
3034intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3035			   int x, int y, enum mode_set_atomic state)
3036{
3037	struct drm_device *dev = crtc->dev;
3038	struct drm_i915_private *dev_priv = dev->dev_private;
3039
3040	if (dev_priv->display.disable_fbc)
3041		dev_priv->display.disable_fbc(dev);
3042
3043	dev_priv->display.update_primary_plane(crtc, fb, x, y);
3044
3045	return 0;
3046}
3047
3048static void intel_complete_page_flips(struct drm_device *dev)
3049{
3050	struct drm_crtc *crtc;
3051
3052	for_each_crtc(dev, crtc) {
3053		struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3054		enum plane plane = intel_crtc->plane;
3055
3056		intel_prepare_page_flip(dev, plane);
3057		intel_finish_page_flip_plane(dev, plane);
3058	}
3059}
3060
3061static void intel_update_primary_planes(struct drm_device *dev)
3062{
3063	struct drm_i915_private *dev_priv = dev->dev_private;
3064	struct drm_crtc *crtc;
3065
3066	for_each_crtc(dev, crtc) {
3067		struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3068
3069		drm_modeset_lock(&crtc->mutex, NULL);
3070		/*
3071		 * FIXME: Once we have proper support for primary planes (and
3072		 * disabling them without disabling the entire crtc) allow again
3073		 * a NULL crtc->primary->fb.
3074		 */
3075		if (intel_crtc->active && crtc->primary->fb)
3076			dev_priv->display.update_primary_plane(crtc,
3077							       crtc->primary->fb,
3078							       crtc->x,
3079							       crtc->y);
3080		drm_modeset_unlock(&crtc->mutex);
3081	}
3082}
3083
3084void intel_prepare_reset(struct drm_device *dev)
3085{
3086	struct drm_i915_private *dev_priv = to_i915(dev);
3087	struct intel_crtc *crtc;
3088
3089	/* no reset support for gen2 */
3090	if (IS_GEN2(dev))
3091		return;
3092
3093	/* reset doesn't touch the display */
3094	if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3095		return;
3096
3097	drm_modeset_lock_all(dev);
3098
3099	/*
3100	 * Disabling the crtcs gracefully seems nicer. Also the
3101	 * g33 docs say we should at least disable all the planes.
3102	 */
3103	for_each_intel_crtc(dev, crtc) {
3104		if (crtc->active)
3105			dev_priv->display.crtc_disable(&crtc->base);
3106	}
3107}
3108
3109void intel_finish_reset(struct drm_device *dev)
3110{
3111	struct drm_i915_private *dev_priv = to_i915(dev);
3112
3113	/*
3114	 * Flips in the rings will be nuked by the reset,
3115	 * so complete all pending flips so that user space
3116	 * will get its events and not get stuck.
3117	 */
3118	intel_complete_page_flips(dev);
3119
3120	/* no reset support for gen2 */
3121	if (IS_GEN2(dev))
3122		return;
3123
3124	/* reset doesn't touch the display */
3125	if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3126		/*
3127		 * Flips in the rings have been nuked by the reset,
3128		 * so update the base address of all primary
3129		 * planes to the the last fb to make sure we're
3130		 * showing the correct fb after a reset.
3131		 */
3132		intel_update_primary_planes(dev);
3133		return;
3134	}
3135
3136	/*
3137	 * The display has been reset as well,
3138	 * so need a full re-initialization.
3139	 */
3140	intel_runtime_pm_disable_interrupts(dev_priv);
3141	intel_runtime_pm_enable_interrupts(dev_priv);
3142
3143	intel_modeset_init_hw(dev);
3144
3145	spin_lock_irq(&dev_priv->irq_lock);
3146	if (dev_priv->display.hpd_irq_setup)
3147		dev_priv->display.hpd_irq_setup(dev);
3148	spin_unlock_irq(&dev_priv->irq_lock);
3149
3150	intel_modeset_setup_hw_state(dev, true);
3151
3152	intel_hpd_init(dev_priv);
3153
3154	drm_modeset_unlock_all(dev);
3155}
3156
3157static int
3158intel_finish_fb(struct drm_framebuffer *old_fb)
3159{
3160	struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3161	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3162	bool was_interruptible = dev_priv->mm.interruptible;
3163	int ret;
3164
3165	/* Big Hammer, we also need to ensure that any pending
3166	 * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3167	 * current scanout is retired before unpinning the old
3168	 * framebuffer.
3169	 *
3170	 * This should only fail upon a hung GPU, in which case we
3171	 * can safely continue.
3172	 */
3173	dev_priv->mm.interruptible = false;
3174	ret = i915_gem_object_finish_gpu(obj);
3175	dev_priv->mm.interruptible = was_interruptible;
3176
3177	return ret;
3178}
3179
3180static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3181{
3182	struct drm_device *dev = crtc->dev;
3183	struct drm_i915_private *dev_priv = dev->dev_private;
3184	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3185	bool pending;
3186
3187	if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3188	    intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3189		return false;
3190
3191	spin_lock_irq(&dev->event_lock);
3192	pending = to_intel_crtc(crtc)->unpin_work != NULL;
3193	spin_unlock_irq(&dev->event_lock);
3194
3195	return pending;
3196}
3197
3198static void intel_update_pipe_size(struct intel_crtc *crtc)
3199{
3200	struct drm_device *dev = crtc->base.dev;
3201	struct drm_i915_private *dev_priv = dev->dev_private;
3202	const struct drm_display_mode *adjusted_mode;
3203
3204	if (!i915.fastboot)
3205		return;
3206
3207	/*
3208	 * Update pipe size and adjust fitter if needed: the reason for this is
3209	 * that in compute_mode_changes we check the native mode (not the pfit
3210	 * mode) to see if we can flip rather than do a full mode set. In the
3211	 * fastboot case, we'll flip, but if we don't update the pipesrc and
3212	 * pfit state, we'll end up with a big fb scanned out into the wrong
3213	 * sized surface.
3214	 *
3215	 * To fix this properly, we need to hoist the checks up into
3216	 * compute_mode_changes (or above), check the actual pfit state and
3217	 * whether the platform allows pfit disable with pipe active, and only
3218	 * then update the pipesrc and pfit state, even on the flip path.
3219	 */
3220
3221	adjusted_mode = &crtc->config->base.adjusted_mode;
3222
3223	I915_WRITE(PIPESRC(crtc->pipe),
3224		   ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3225		   (adjusted_mode->crtc_vdisplay - 1));
3226	if (!crtc->config->pch_pfit.enabled &&
3227	    (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3228	     intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3229		I915_WRITE(PF_CTL(crtc->pipe), 0);
3230		I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3231		I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3232	}
3233	crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3234	crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3235}
3236
3237static void intel_fdi_normal_train(struct drm_crtc *crtc)
3238{
3239	struct drm_device *dev = crtc->dev;
3240	struct drm_i915_private *dev_priv = dev->dev_private;
3241	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3242	int pipe = intel_crtc->pipe;
3243	u32 reg, temp;
3244
3245	/* enable normal train */
3246	reg = FDI_TX_CTL(pipe);
3247	temp = I915_READ(reg);
3248	if (IS_IVYBRIDGE(dev)) {
3249		temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3250		temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3251	} else {
3252		temp &= ~FDI_LINK_TRAIN_NONE;
3253		temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3254	}
3255	I915_WRITE(reg, temp);
3256
3257	reg = FDI_RX_CTL(pipe);
3258	temp = I915_READ(reg);
3259	if (HAS_PCH_CPT(dev)) {
3260		temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3261		temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3262	} else {
3263		temp &= ~FDI_LINK_TRAIN_NONE;
3264		temp |= FDI_LINK_TRAIN_NONE;
3265	}
3266	I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3267
3268	/* wait one idle pattern time */
3269	POSTING_READ(reg);
3270	udelay(1000);
3271
3272	/* IVB wants error correction enabled */
3273	if (IS_IVYBRIDGE(dev))
3274		I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3275			   FDI_FE_ERRC_ENABLE);
3276}
3277
3278/* The FDI link training functions for ILK/Ibexpeak. */
3279static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3280{
3281	struct drm_device *dev = crtc->dev;
3282	struct drm_i915_private *dev_priv = dev->dev_private;
3283	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3284	int pipe = intel_crtc->pipe;
3285	u32 reg, temp, tries;
3286
3287	/* FDI needs bits from pipe first */
3288	assert_pipe_enabled(dev_priv, pipe);
3289
3290	/* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3291	   for train result */
3292	reg = FDI_RX_IMR(pipe);
3293	temp = I915_READ(reg);
3294	temp &= ~FDI_RX_SYMBOL_LOCK;
3295	temp &= ~FDI_RX_BIT_LOCK;
3296	I915_WRITE(reg, temp);
3297	I915_READ(reg);
3298	udelay(150);
3299
3300	/* enable CPU FDI TX and PCH FDI RX */
3301	reg = FDI_TX_CTL(pipe);
3302	temp = I915_READ(reg);
3303	temp &= ~FDI_DP_PORT_WIDTH_MASK;
3304	temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3305	temp &= ~FDI_LINK_TRAIN_NONE;
3306	temp |= FDI_LINK_TRAIN_PATTERN_1;
3307	I915_WRITE(reg, temp | FDI_TX_ENABLE);
3308
3309	reg = FDI_RX_CTL(pipe);
3310	temp = I915_READ(reg);
3311	temp &= ~FDI_LINK_TRAIN_NONE;
3312	temp |= FDI_LINK_TRAIN_PATTERN_1;
3313	I915_WRITE(reg, temp | FDI_RX_ENABLE);
3314
3315	POSTING_READ(reg);
3316	udelay(150);
3317
3318	/* Ironlake workaround, enable clock pointer after FDI enable*/
3319	I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3320	I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3321		   FDI_RX_PHASE_SYNC_POINTER_EN);
3322
3323	reg = FDI_RX_IIR(pipe);
3324	for (tries = 0; tries < 5; tries++) {
3325		temp = I915_READ(reg);
3326		DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3327
3328		if ((temp & FDI_RX_BIT_LOCK)) {
3329			DRM_DEBUG_KMS("FDI train 1 done.\n");
3330			I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3331			break;
3332		}
3333	}
3334	if (tries == 5)
3335		DRM_ERROR("FDI train 1 fail!\n");
3336
3337	/* Train 2 */
3338	reg = FDI_TX_CTL(pipe);
3339	temp = I915_READ(reg);
3340	temp &= ~FDI_LINK_TRAIN_NONE;
3341	temp |= FDI_LINK_TRAIN_PATTERN_2;
3342	I915_WRITE(reg, temp);
3343
3344	reg = FDI_RX_CTL(pipe);
3345	temp = I915_READ(reg);
3346	temp &= ~FDI_LINK_TRAIN_NONE;
3347	temp |= FDI_LINK_TRAIN_PATTERN_2;
3348	I915_WRITE(reg, temp);
3349
3350	POSTING_READ(reg);
3351	udelay(150);
3352
3353	reg = FDI_RX_IIR(pipe);
3354	for (tries = 0; tries < 5; tries++) {
3355		temp = I915_READ(reg);
3356		DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3357
3358		if (temp & FDI_RX_SYMBOL_LOCK) {
3359			I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3360			DRM_DEBUG_KMS("FDI train 2 done.\n");
3361			break;
3362		}
3363	}
3364	if (tries == 5)
3365		DRM_ERROR("FDI train 2 fail!\n");
3366
3367	DRM_DEBUG_KMS("FDI train done\n");
3368
3369}
3370
3371static const int snb_b_fdi_train_param[] = {
3372	FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3373	FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3374	FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3375	FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3376};
3377
3378/* The FDI link training functions for SNB/Cougarpoint. */
3379static void gen6_fdi_link_train(struct drm_crtc *crtc)
3380{
3381	struct drm_device *dev = crtc->dev;
3382	struct drm_i915_private *dev_priv = dev->dev_private;
3383	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3384	int pipe = intel_crtc->pipe;
3385	u32 reg, temp, i, retry;
3386
3387	/* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3388	   for train result */
3389	reg = FDI_RX_IMR(pipe);
3390	temp = I915_READ(reg);
3391	temp &= ~FDI_RX_SYMBOL_LOCK;
3392	temp &= ~FDI_RX_BIT_LOCK;
3393	I915_WRITE(reg, temp);
3394
3395	POSTING_READ(reg);
3396	udelay(150);
3397
3398	/* enable CPU FDI TX and PCH FDI RX */
3399	reg = FDI_TX_CTL(pipe);
3400	temp = I915_READ(reg);
3401	temp &= ~FDI_DP_PORT_WIDTH_MASK;
3402	temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3403	temp &= ~FDI_LINK_TRAIN_NONE;
3404	temp |= FDI_LINK_TRAIN_PATTERN_1;
3405	temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3406	/* SNB-B */
3407	temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3408	I915_WRITE(reg, temp | FDI_TX_ENABLE);
3409
3410	I915_WRITE(FDI_RX_MISC(pipe),
3411		   FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3412
3413	reg = FDI_RX_CTL(pipe);
3414	temp = I915_READ(reg);
3415	if (HAS_PCH_CPT(dev)) {
3416		temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3417		temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3418	} else {
3419		temp &= ~FDI_LINK_TRAIN_NONE;
3420		temp |= FDI_LINK_TRAIN_PATTERN_1;
3421	}
3422	I915_WRITE(reg, temp | FDI_RX_ENABLE);
3423
3424	POSTING_READ(reg);
3425	udelay(150);
3426
3427	for (i = 0; i < 4; i++) {
3428		reg = FDI_TX_CTL(pipe);
3429		temp = I915_READ(reg);
3430		temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3431		temp |= snb_b_fdi_train_param[i];
3432		I915_WRITE(reg, temp);
3433
3434		POSTING_READ(reg);
3435		udelay(500);
3436
3437		for (retry = 0; retry < 5; retry++) {
3438			reg = FDI_RX_IIR(pipe);
3439			temp = I915_READ(reg);
3440			DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3441			if (temp & FDI_RX_BIT_LOCK) {
3442				I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3443				DRM_DEBUG_KMS("FDI train 1 done.\n");
3444				break;
3445			}
3446			udelay(50);
3447		}
3448		if (retry < 5)
3449			break;
3450	}
3451	if (i == 4)
3452		DRM_ERROR("FDI train 1 fail!\n");
3453
3454	/* Train 2 */
3455	reg = FDI_TX_CTL(pipe);
3456	temp = I915_READ(reg);
3457	temp &= ~FDI_LINK_TRAIN_NONE;
3458	temp |= FDI_LINK_TRAIN_PATTERN_2;
3459	if (IS_GEN6(dev)) {
3460		temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3461		/* SNB-B */
3462		temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3463	}
3464	I915_WRITE(reg, temp);
3465
3466	reg = FDI_RX_CTL(pipe);
3467	temp = I915_READ(reg);
3468	if (HAS_PCH_CPT(dev)) {
3469		temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3470		temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3471	} else {
3472		temp &= ~FDI_LINK_TRAIN_NONE;
3473		temp |= FDI_LINK_TRAIN_PATTERN_2;
3474	}
3475	I915_WRITE(reg, temp);
3476
3477	POSTING_READ(reg);
3478	udelay(150);
3479
3480	for (i = 0; i < 4; i++) {
3481		reg = FDI_TX_CTL(pipe);
3482		temp = I915_READ(reg);
3483		temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3484		temp |= snb_b_fdi_train_param[i];
3485		I915_WRITE(reg, temp);
3486
3487		POSTING_READ(reg);
3488		udelay(500);
3489
3490		for (retry = 0; retry < 5; retry++) {
3491			reg = FDI_RX_IIR(pipe);
3492			temp = I915_READ(reg);
3493			DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3494			if (temp & FDI_RX_SYMBOL_LOCK) {
3495				I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3496				DRM_DEBUG_KMS("FDI train 2 done.\n");
3497				break;
3498			}
3499			udelay(50);
3500		}
3501		if (retry < 5)
3502			break;
3503	}
3504	if (i == 4)
3505		DRM_ERROR("FDI train 2 fail!\n");
3506
3507	DRM_DEBUG_KMS("FDI train done.\n");
3508}
3509
3510/* Manual link training for Ivy Bridge A0 parts */
3511static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3512{
3513	struct drm_device *dev = crtc->dev;
3514	struct drm_i915_private *dev_priv = dev->dev_private;
3515	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3516	int pipe = intel_crtc->pipe;
3517	u32 reg, temp, i, j;
3518
3519	/* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3520	   for train result */
3521	reg = FDI_RX_IMR(pipe);
3522	temp = I915_READ(reg);
3523	temp &= ~FDI_RX_SYMBOL_LOCK;
3524	temp &= ~FDI_RX_BIT_LOCK;
3525	I915_WRITE(reg, temp);
3526
3527	POSTING_READ(reg);
3528	udelay(150);
3529
3530	DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3531		      I915_READ(FDI_RX_IIR(pipe)));
3532
3533	/* Try each vswing and preemphasis setting twice before moving on */
3534	for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3535		/* disable first in case we need to retry */
3536		reg = FDI_TX_CTL(pipe);
3537		temp = I915_READ(reg);
3538		temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3539		temp &= ~FDI_TX_ENABLE;
3540		I915_WRITE(reg, temp);
3541
3542		reg = FDI_RX_CTL(pipe);
3543		temp = I915_READ(reg);
3544		temp &= ~FDI_LINK_TRAIN_AUTO;
3545		temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3546		temp &= ~FDI_RX_ENABLE;
3547		I915_WRITE(reg, temp);
3548
3549		/* enable CPU FDI TX and PCH FDI RX */
3550		reg = FDI_TX_CTL(pipe);
3551		temp = I915_READ(reg);
3552		temp &= ~FDI_DP_PORT_WIDTH_MASK;
3553		temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3554		temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3555		temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3556		temp |= snb_b_fdi_train_param[j/2];
3557		temp |= FDI_COMPOSITE_SYNC;
3558		I915_WRITE(reg, temp | FDI_TX_ENABLE);
3559
3560		I915_WRITE(FDI_RX_MISC(pipe),
3561			   FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3562
3563		reg = FDI_RX_CTL(pipe);
3564		temp = I915_READ(reg);
3565		temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3566		temp |= FDI_COMPOSITE_SYNC;
3567		I915_WRITE(reg, temp | FDI_RX_ENABLE);
3568
3569		POSTING_READ(reg);
3570		udelay(1); /* should be 0.5us */
3571
3572		for (i = 0; i < 4; i++) {
3573			reg = FDI_RX_IIR(pipe);
3574			temp = I915_READ(reg);
3575			DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3576
3577			if (temp & FDI_RX_BIT_LOCK ||
3578			    (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3579				I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3580				DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3581					      i);
3582				break;
3583			}
3584			udelay(1); /* should be 0.5us */
3585		}
3586		if (i == 4) {
3587			DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3588			continue;
3589		}
3590
3591		/* Train 2 */
3592		reg = FDI_TX_CTL(pipe);
3593		temp = I915_READ(reg);
3594		temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3595		temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3596		I915_WRITE(reg, temp);
3597
3598		reg = FDI_RX_CTL(pipe);
3599		temp = I915_READ(reg);
3600		temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3601		temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3602		I915_WRITE(reg, temp);
3603
3604		POSTING_READ(reg);
3605		udelay(2); /* should be 1.5us */
3606
3607		for (i = 0; i < 4; i++) {
3608			reg = FDI_RX_IIR(pipe);
3609			temp = I915_READ(reg);
3610			DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3611
3612			if (temp & FDI_RX_SYMBOL_LOCK ||
3613			    (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3614				I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3615				DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3616					      i);
3617				goto train_done;
3618			}
3619			udelay(2); /* should be 1.5us */
3620		}
3621		if (i == 4)
3622			DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3623	}
3624
3625train_done:
3626	DRM_DEBUG_KMS("FDI train done.\n");
3627}
3628
3629static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3630{
3631	struct drm_device *dev = intel_crtc->base.dev;
3632	struct drm_i915_private *dev_priv = dev->dev_private;
3633	int pipe = intel_crtc->pipe;
3634	u32 reg, temp;
3635
3636
3637	/* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3638	reg = FDI_RX_CTL(pipe);
3639	temp = I915_READ(reg);
3640	temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3641	temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3642	temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3643	I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3644
3645	POSTING_READ(reg);
3646	udelay(200);
3647
3648	/* Switch from Rawclk to PCDclk */
3649	temp = I915_READ(reg);
3650	I915_WRITE(reg, temp | FDI_PCDCLK);
3651
3652	POSTING_READ(reg);
3653	udelay(200);
3654
3655	/* Enable CPU FDI TX PLL, always on for Ironlake */
3656	reg = FDI_TX_CTL(pipe);
3657	temp = I915_READ(reg);
3658	if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3659		I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3660
3661		POSTING_READ(reg);
3662		udelay(100);
3663	}
3664}
3665
3666static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3667{
3668	struct drm_device *dev = intel_crtc->base.dev;
3669	struct drm_i915_private *dev_priv = dev->dev_private;
3670	int pipe = intel_crtc->pipe;
3671	u32 reg, temp;
3672
3673	/* Switch from PCDclk to Rawclk */
3674	reg = FDI_RX_CTL(pipe);
3675	temp = I915_READ(reg);
3676	I915_WRITE(reg, temp & ~FDI_PCDCLK);
3677
3678	/* Disable CPU FDI TX PLL */
3679	reg = FDI_TX_CTL(pipe);
3680	temp = I915_READ(reg);
3681	I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3682
3683	POSTING_READ(reg);
3684	udelay(100);
3685
3686	reg = FDI_RX_CTL(pipe);
3687	temp = I915_READ(reg);
3688	I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3689
3690	/* Wait for the clocks to turn off. */
3691	POSTING_READ(reg);
3692	udelay(100);
3693}
3694
3695static void ironlake_fdi_disable(struct drm_crtc *crtc)
3696{
3697	struct drm_device *dev = crtc->dev;
3698	struct drm_i915_private *dev_priv = dev->dev_private;
3699	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3700	int pipe = intel_crtc->pipe;
3701	u32 reg, temp;
3702
3703	/* disable CPU FDI tx and PCH FDI rx */
3704	reg = FDI_TX_CTL(pipe);
3705	temp = I915_READ(reg);
3706	I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3707	POSTING_READ(reg);
3708
3709	reg = FDI_RX_CTL(pipe);
3710	temp = I915_READ(reg);
3711	temp &= ~(0x7 << 16);
3712	temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3713	I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3714
3715	POSTING_READ(reg);
3716	udelay(100);
3717
3718	/* Ironlake workaround, disable clock pointer after downing FDI */
3719	if (HAS_PCH_IBX(dev))
3720		I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3721
3722	/* still set train pattern 1 */
3723	reg = FDI_TX_CTL(pipe);
3724	temp = I915_READ(reg);
3725	temp &= ~FDI_LINK_TRAIN_NONE;
3726	temp |= FDI_LINK_TRAIN_PATTERN_1;
3727	I915_WRITE(reg, temp);
3728
3729	reg = FDI_RX_CTL(pipe);
3730	temp = I915_READ(reg);
3731	if (HAS_PCH_CPT(dev)) {
3732		temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3733		temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3734	} else {
3735		temp &= ~FDI_LINK_TRAIN_NONE;
3736		temp |= FDI_LINK_TRAIN_PATTERN_1;
3737	}
3738	/* BPC in FDI rx is consistent with that in PIPECONF */
3739	temp &= ~(0x07 << 16);
3740	temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3741	I915_WRITE(reg, temp);
3742
3743	POSTING_READ(reg);
3744	udelay(100);
3745}
3746
3747bool intel_has_pending_fb_unpin(struct drm_device *dev)
3748{
3749	struct intel_crtc *crtc;
3750
3751	/* Note that we don't need to be called with mode_config.lock here
3752	 * as our list of CRTC objects is static for the lifetime of the
3753	 * device and so cannot disappear as we iterate. Similarly, we can
3754	 * happily treat the predicates as racy, atomic checks as userspace
3755	 * cannot claim and pin a new fb without at least acquring the
3756	 * struct_mutex and so serialising with us.
3757	 */
3758	for_each_intel_crtc(dev, crtc) {
3759		if (atomic_read(&crtc->unpin_work_count) == 0)
3760			continue;
3761
3762		if (crtc->unpin_work)
3763			intel_wait_for_vblank(dev, crtc->pipe);
3764
3765		return true;
3766	}
3767
3768	return false;
3769}
3770
3771static void page_flip_completed(struct intel_crtc *intel_crtc)
3772{
3773	struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3774	struct intel_unpin_work *work = intel_crtc->unpin_work;
3775
3776	/* ensure that the unpin work is consistent wrt ->pending. */
3777	smp_rmb();
3778	intel_crtc->unpin_work = NULL;
3779
3780	if (work->event)
3781		drm_send_vblank_event(intel_crtc->base.dev,
3782				      intel_crtc->pipe,
3783				      work->event);
3784
3785	drm_crtc_vblank_put(&intel_crtc->base);
3786
3787	wake_up_all(&dev_priv->pending_flip_queue);
3788	queue_work(dev_priv->wq, &work->work);
3789
3790	trace_i915_flip_complete(intel_crtc->plane,
3791				 work->pending_flip_obj);
3792}
3793
3794void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3795{
3796	struct drm_device *dev = crtc->dev;
3797	struct drm_i915_private *dev_priv = dev->dev_private;
3798
3799	WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3800	if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3801				       !intel_crtc_has_pending_flip(crtc),
3802				       60*HZ) == 0)) {
3803		struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3804
3805		spin_lock_irq(&dev->event_lock);
3806		if (intel_crtc->unpin_work) {
3807			WARN_ONCE(1, "Removing stuck page flip\n");
3808			page_flip_completed(intel_crtc);
3809		}
3810		spin_unlock_irq(&dev->event_lock);
3811	}
3812
3813	if (crtc->primary->fb) {
3814		mutex_lock(&dev->struct_mutex);
3815		intel_finish_fb(crtc->primary->fb);
3816		mutex_unlock(&dev->struct_mutex);
3817	}
3818}
3819
3820/* Program iCLKIP clock to the desired frequency */
3821static void lpt_program_iclkip(struct drm_crtc *crtc)
3822{
3823	struct drm_device *dev = crtc->dev;
3824	struct drm_i915_private *dev_priv = dev->dev_private;
3825	int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3826	u32 divsel, phaseinc, auxdiv, phasedir = 0;
3827	u32 temp;
3828
3829	mutex_lock(&dev_priv->dpio_lock);
3830
3831	/* It is necessary to ungate the pixclk gate prior to programming
3832	 * the divisors, and gate it back when it is done.
3833	 */
3834	I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3835
3836	/* Disable SSCCTL */
3837	intel_sbi_write(dev_priv, SBI_SSCCTL6,
3838			intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3839				SBI_SSCCTL_DISABLE,
3840			SBI_ICLK);
3841
3842	/* 20MHz is a corner case which is out of range for the 7-bit divisor */
3843	if (clock == 20000) {
3844		auxdiv = 1;
3845		divsel = 0x41;
3846		phaseinc = 0x20;
3847	} else {
3848		/* The iCLK virtual clock root frequency is in MHz,
3849		 * but the adjusted_mode->crtc_clock in in KHz. To get the
3850		 * divisors, it is necessary to divide one by another, so we
3851		 * convert the virtual clock precision to KHz here for higher
3852		 * precision.
3853		 */
3854		u32 iclk_virtual_root_freq = 172800 * 1000;
3855		u32 iclk_pi_range = 64;
3856		u32 desired_divisor, msb_divisor_value, pi_value;
3857
3858		desired_divisor = (iclk_virtual_root_freq / clock);
3859		msb_divisor_value = desired_divisor / iclk_pi_range;
3860		pi_value = desired_divisor % iclk_pi_range;
3861
3862		auxdiv = 0;
3863		divsel = msb_divisor_value - 2;
3864		phaseinc = pi_value;
3865	}
3866
3867	/* This should not happen with any sane values */
3868	WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3869		~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3870	WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3871		~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3872
3873	DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3874			clock,
3875			auxdiv,
3876			divsel,
3877			phasedir,
3878			phaseinc);
3879
3880	/* Program SSCDIVINTPHASE6 */
3881	temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3882	temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3883	temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3884	temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3885	temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3886	temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3887	temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3888	intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3889
3890	/* Program SSCAUXDIV */
3891	temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3892	temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3893	temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3894	intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3895
3896	/* Enable modulator and associated divider */
3897	temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3898	temp &= ~SBI_SSCCTL_DISABLE;
3899	intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3900
3901	/* Wait for initialization time */
3902	udelay(24);
3903
3904	I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3905
3906	mutex_unlock(&dev_priv->dpio_lock);
3907}
3908
3909static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3910						enum pipe pch_transcoder)
3911{
3912	struct drm_device *dev = crtc->base.dev;
3913	struct drm_i915_private *dev_priv = dev->dev_private;
3914	enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3915
3916	I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3917		   I915_READ(HTOTAL(cpu_transcoder)));
3918	I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3919		   I915_READ(HBLANK(cpu_transcoder)));
3920	I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3921		   I915_READ(HSYNC(cpu_transcoder)));
3922
3923	I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3924		   I915_READ(VTOTAL(cpu_transcoder)));
3925	I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3926		   I915_READ(VBLANK(cpu_transcoder)));
3927	I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3928		   I915_READ(VSYNC(cpu_transcoder)));
3929	I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3930		   I915_READ(VSYNCSHIFT(cpu_transcoder)));
3931}
3932
3933static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
3934{
3935	struct drm_i915_private *dev_priv = dev->dev_private;
3936	uint32_t temp;
3937
3938	temp = I915_READ(SOUTH_CHICKEN1);
3939	if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
3940		return;
3941
3942	WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3943	WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3944
3945	temp &= ~FDI_BC_BIFURCATION_SELECT;
3946	if (enable)
3947		temp |= FDI_BC_BIFURCATION_SELECT;
3948
3949	DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
3950	I915_WRITE(SOUTH_CHICKEN1, temp);
3951	POSTING_READ(SOUTH_CHICKEN1);
3952}
3953
3954static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
3955{
3956	struct drm_device *dev = intel_crtc->base.dev;
3957
3958	switch (intel_crtc->pipe) {
3959	case PIPE_A:
3960		break;
3961	case PIPE_B:
3962		if (intel_crtc->config->fdi_lanes > 2)
3963			cpt_set_fdi_bc_bifurcation(dev, false);
3964		else
3965			cpt_set_fdi_bc_bifurcation(dev, true);
3966
3967		break;
3968	case PIPE_C:
3969		cpt_set_fdi_bc_bifurcation(dev, true);
3970
3971		break;
3972	default:
3973		BUG();
3974	}
3975}
3976
3977/*
3978 * Enable PCH resources required for PCH ports:
3979 *   - PCH PLLs
3980 *   - FDI training & RX/TX
3981 *   - update transcoder timings
3982 *   - DP transcoding bits
3983 *   - transcoder
3984 */
3985static void ironlake_pch_enable(struct drm_crtc *crtc)
3986{
3987	struct drm_device *dev = crtc->dev;
3988	struct drm_i915_private *dev_priv = dev->dev_private;
3989	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3990	int pipe = intel_crtc->pipe;
3991	u32 reg, temp;
3992
3993	assert_pch_transcoder_disabled(dev_priv, pipe);
3994
3995	if (IS_IVYBRIDGE(dev))
3996		ivybridge_update_fdi_bc_bifurcation(intel_crtc);
3997
3998	/* Write the TU size bits before fdi link training, so that error
3999	 * detection works. */
4000	I915_WRITE(FDI_RX_TUSIZE1(pipe),
4001		   I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4002
4003	/* For PCH output, training FDI link */
4004	dev_priv->display.fdi_link_train(crtc);
4005
4006	/* We need to program the right clock selection before writing the pixel
4007	 * mutliplier into the DPLL. */
4008	if (HAS_PCH_CPT(dev)) {
4009		u32 sel;
4010
4011		temp = I915_READ(PCH_DPLL_SEL);
4012		temp |= TRANS_DPLL_ENABLE(pipe);
4013		sel = TRANS_DPLLB_SEL(pipe);
4014		if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4015			temp |= sel;
4016		else
4017			temp &= ~sel;
4018		I915_WRITE(PCH_DPLL_SEL, temp);
4019	}
4020
4021	/* XXX: pch pll's can be enabled any time before we enable the PCH
4022	 * transcoder, and we actually should do this to not upset any PCH
4023	 * transcoder that already use the clock when we share it.
4024	 *
4025	 * Note that enable_shared_dpll tries to do the right thing, but
4026	 * get_shared_dpll unconditionally resets the pll - we need that to have
4027	 * the right LVDS enable sequence. */
4028	intel_enable_shared_dpll(intel_crtc);
4029
4030	/* set transcoder timing, panel must allow it */
4031	assert_panel_unlocked(dev_priv, pipe);
4032	ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4033
4034	intel_fdi_normal_train(crtc);
4035
4036	/* For PCH DP, enable TRANS_DP_CTL */
4037	if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4038		u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4039		reg = TRANS_DP_CTL(pipe);
4040		temp = I915_READ(reg);
4041		temp &= ~(TRANS_DP_PORT_SEL_MASK |
4042			  TRANS_DP_SYNC_MASK |
4043			  TRANS_DP_BPC_MASK);
4044		temp |= (TRANS_DP_OUTPUT_ENABLE |
4045			 TRANS_DP_ENH_FRAMING);
4046		temp |= bpc << 9; /* same format but at 11:9 */
4047
4048		if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
4049			temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4050		if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
4051			temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4052
4053		switch (intel_trans_dp_port_sel(crtc)) {
4054		case PCH_DP_B:
4055			temp |= TRANS_DP_PORT_SEL_B;
4056			break;
4057		case PCH_DP_C:
4058			temp |= TRANS_DP_PORT_SEL_C;
4059			break;
4060		case PCH_DP_D:
4061			temp |= TRANS_DP_PORT_SEL_D;
4062			break;
4063		default:
4064			BUG();
4065		}
4066
4067		I915_WRITE(reg, temp);
4068	}
4069
4070	ironlake_enable_pch_transcoder(dev_priv, pipe);
4071}
4072
4073static void lpt_pch_enable(struct drm_crtc *crtc)
4074{
4075	struct drm_device *dev = crtc->dev;
4076	struct drm_i915_private *dev_priv = dev->dev_private;
4077	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4078	enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4079
4080	assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4081
4082	lpt_program_iclkip(crtc);
4083
4084	/* Set transcoder timing. */
4085	ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4086
4087	lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4088}
4089
4090void intel_put_shared_dpll(struct intel_crtc *crtc)
4091{
4092	struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
4093
4094	if (pll == NULL)
4095		return;
4096
4097	if (!(pll->config.crtc_mask & (1 << crtc->pipe))) {
4098		WARN(1, "bad %s crtc mask\n", pll->name);
4099		return;
4100	}
4101
4102	pll->config.crtc_mask &= ~(1 << crtc->pipe);
4103	if (pll->config.crtc_mask == 0) {
4104		WARN_ON(pll->on);
4105		WARN_ON(pll->active);
4106	}
4107
4108	crtc->config->shared_dpll = DPLL_ID_PRIVATE;
4109}
4110
4111struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4112						struct intel_crtc_state *crtc_state)
4113{
4114	struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4115	struct intel_shared_dpll *pll;
4116	enum intel_dpll_id i;
4117
4118	if (HAS_PCH_IBX(dev_priv->dev)) {
4119		/* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4120		i = (enum intel_dpll_id) crtc->pipe;
4121		pll = &dev_priv->shared_dplls[i];
4122
4123		DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4124			      crtc->base.base.id, pll->name);
4125
4126		WARN_ON(pll->new_config->crtc_mask);
4127
4128		goto found;
4129	}
4130
4131	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4132		pll = &dev_priv->shared_dplls[i];
4133
4134		/* Only want to check enabled timings first */
4135		if (pll->new_config->crtc_mask == 0)
4136			continue;
4137
4138		if (memcmp(&crtc_state->dpll_hw_state,
4139			   &pll->new_config->hw_state,
4140			   sizeof(pll->new_config->hw_state)) == 0) {
4141			DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4142				      crtc->base.base.id, pll->name,
4143				      pll->new_config->crtc_mask,
4144				      pll->active);
4145			goto found;
4146		}
4147	}
4148
4149	/* Ok no matching timings, maybe there's a free one? */
4150	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4151		pll = &dev_priv->shared_dplls[i];
4152		if (pll->new_config->crtc_mask == 0) {
4153			DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4154				      crtc->base.base.id, pll->name);
4155			goto found;
4156		}
4157	}
4158
4159	return NULL;
4160
4161found:
4162	if (pll->new_config->crtc_mask == 0)
4163		pll->new_config->hw_state = crtc_state->dpll_hw_state;
4164
4165	crtc_state->shared_dpll = i;
4166	DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4167			 pipe_name(crtc->pipe));
4168
4169	pll->new_config->crtc_mask |= 1 << crtc->pipe;
4170
4171	return pll;
4172}
4173
4174/**
4175 * intel_shared_dpll_start_config - start a new PLL staged config
4176 * @dev_priv: DRM device
4177 * @clear_pipes: mask of pipes that will have their PLLs freed
4178 *
4179 * Starts a new PLL staged config, copying the current config but
4180 * releasing the references of pipes specified in clear_pipes.
4181 */
4182static int intel_shared_dpll_start_config(struct drm_i915_private *dev_priv,
4183					  unsigned clear_pipes)
4184{
4185	struct intel_shared_dpll *pll;
4186	enum intel_dpll_id i;
4187
4188	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4189		pll = &dev_priv->shared_dplls[i];
4190
4191		pll->new_config = kmemdup(&pll->config, sizeof pll->config,
4192					  GFP_KERNEL);
4193		if (!pll->new_config)
4194			goto cleanup;
4195
4196		pll->new_config->crtc_mask &= ~clear_pipes;
4197	}
4198
4199	return 0;
4200
4201cleanup:
4202	while (--i >= 0) {
4203		pll = &dev_priv->shared_dplls[i];
4204		kfree(pll->new_config);
4205		pll->new_config = NULL;
4206	}
4207
4208	return -ENOMEM;
4209}
4210
4211static void intel_shared_dpll_commit(struct drm_i915_private *dev_priv)
4212{
4213	struct intel_shared_dpll *pll;
4214	enum intel_dpll_id i;
4215
4216	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4217		pll = &dev_priv->shared_dplls[i];
4218
4219		WARN_ON(pll->new_config == &pll->config);
4220
4221		pll->config = *pll->new_config;
4222		kfree(pll->new_config);
4223		pll->new_config = NULL;
4224	}
4225}
4226
4227static void intel_shared_dpll_abort_config(struct drm_i915_private *dev_priv)
4228{
4229	struct intel_shared_dpll *pll;
4230	enum intel_dpll_id i;
4231
4232	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4233		pll = &dev_priv->shared_dplls[i];
4234
4235		WARN_ON(pll->new_config == &pll->config);
4236
4237		kfree(pll->new_config);
4238		pll->new_config = NULL;
4239	}
4240}
4241
4242static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4243{
4244	struct drm_i915_private *dev_priv = dev->dev_private;
4245	int dslreg = PIPEDSL(pipe);
4246	u32 temp;
4247
4248	temp = I915_READ(dslreg);
4249	udelay(500);
4250	if (wait_for(I915_READ(dslreg) != temp, 5)) {
4251		if (wait_for(I915_READ(dslreg) != temp, 5))
4252			DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4253	}
4254}
4255
4256static void skylake_pfit_enable(struct intel_crtc *crtc)
4257{
4258	struct drm_device *dev = crtc->base.dev;
4259	struct drm_i915_private *dev_priv = dev->dev_private;
4260	int pipe = crtc->pipe;
4261
4262	if (crtc->config->pch_pfit.enabled) {
4263		I915_WRITE(PS_CTL(pipe), PS_ENABLE);
4264		I915_WRITE(PS_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4265		I915_WRITE(PS_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4266	}
4267}
4268
4269static void ironlake_pfit_enable(struct intel_crtc *crtc)
4270{
4271	struct drm_device *dev = crtc->base.dev;
4272	struct drm_i915_private *dev_priv = dev->dev_private;
4273	int pipe = crtc->pipe;
4274
4275	if (crtc->config->pch_pfit.enabled) {
4276		/* Force use of hard-coded filter coefficients
4277		 * as some pre-programmed values are broken,
4278		 * e.g. x201.
4279		 */
4280		if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4281			I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4282						 PF_PIPE_SEL_IVB(pipe));
4283		else
4284			I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4285		I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4286		I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4287	}
4288}
4289
4290static void intel_enable_sprite_planes(struct drm_crtc *crtc)
4291{
4292	struct drm_device *dev = crtc->dev;
4293	enum pipe pipe = to_intel_crtc(crtc)->pipe;
4294	struct drm_plane *plane;
4295	struct intel_plane *intel_plane;
4296
4297	drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4298		intel_plane = to_intel_plane(plane);
4299		if (intel_plane->pipe == pipe)
4300			intel_plane_restore(&intel_plane->base);
4301	}
4302}
4303
4304/*
4305 * Disable a plane internally without actually modifying the plane's state.
4306 * This will allow us to easily restore the plane later by just reprogramming
4307 * its state.
4308 */
4309static void disable_plane_internal(struct drm_plane *plane)
4310{
4311	struct intel_plane *intel_plane = to_intel_plane(plane);
4312	struct drm_plane_state *state =
4313		plane->funcs->atomic_duplicate_state(plane);
4314	struct intel_plane_state *intel_state = to_intel_plane_state(state);
4315
4316	intel_state->visible = false;
4317	intel_plane->commit_plane(plane, intel_state);
4318
4319	intel_plane_destroy_state(plane, state);
4320}
4321
4322static void intel_disable_sprite_planes(struct drm_crtc *crtc)
4323{
4324	struct drm_device *dev = crtc->dev;
4325	enum pipe pipe = to_intel_crtc(crtc)->pipe;
4326	struct drm_plane *plane;
4327	struct intel_plane *intel_plane;
4328
4329	drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4330		intel_plane = to_intel_plane(plane);
4331		if (plane->fb && intel_plane->pipe == pipe)
4332			disable_plane_internal(plane);
4333	}
4334}
4335
4336void hsw_enable_ips(struct intel_crtc *crtc)
4337{
4338	struct drm_device *dev = crtc->base.dev;
4339	struct drm_i915_private *dev_priv = dev->dev_private;
4340
4341	if (!crtc->config->ips_enabled)
4342		return;
4343
4344	/* We can only enable IPS after we enable a plane and wait for a vblank */
4345	intel_wait_for_vblank(dev, crtc->pipe);
4346
4347	assert_plane_enabled(dev_priv, crtc->plane);
4348	if (IS_BROADWELL(dev)) {
4349		mutex_lock(&dev_priv->rps.hw_lock);
4350		WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4351		mutex_unlock(&dev_priv->rps.hw_lock);
4352		/* Quoting Art Runyan: "its not safe to expect any particular
4353		 * value in IPS_CTL bit 31 after enabling IPS through the
4354		 * mailbox." Moreover, the mailbox may return a bogus state,
4355		 * so we need to just enable it and continue on.
4356		 */
4357	} else {
4358		I915_WRITE(IPS_CTL, IPS_ENABLE);
4359		/* The bit only becomes 1 in the next vblank, so this wait here
4360		 * is essentially intel_wait_for_vblank. If we don't have this
4361		 * and don't wait for vblanks until the end of crtc_enable, then
4362		 * the HW state readout code will complain that the expected
4363		 * IPS_CTL value is not the one we read. */
4364		if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4365			DRM_ERROR("Timed out waiting for IPS enable\n");
4366	}
4367}
4368
4369void hsw_disable_ips(struct intel_crtc *crtc)
4370{
4371	struct drm_device *dev = crtc->base.dev;
4372	struct drm_i915_private *dev_priv = dev->dev_private;
4373
4374	if (!crtc->config->ips_enabled)
4375		return;
4376
4377	assert_plane_enabled(dev_priv, crtc->plane);
4378	if (IS_BROADWELL(dev)) {
4379		mutex_lock(&dev_priv->rps.hw_lock);
4380		WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4381		mutex_unlock(&dev_priv->rps.hw_lock);
4382		/* wait for pcode to finish disabling IPS, which may take up to 42ms */
4383		if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4384			DRM_ERROR("Timed out waiting for IPS disable\n");
4385	} else {
4386		I915_WRITE(IPS_CTL, 0);
4387		POSTING_READ(IPS_CTL);
4388	}
4389
4390	/* We need to wait for a vblank before we can disable the plane. */
4391	intel_wait_for_vblank(dev, crtc->pipe);
4392}
4393
4394/** Loads the palette/gamma unit for the CRTC with the prepared values */
4395static void intel_crtc_load_lut(struct drm_crtc *crtc)
4396{
4397	struct drm_device *dev = crtc->dev;
4398	struct drm_i915_private *dev_priv = dev->dev_private;
4399	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4400	enum pipe pipe = intel_crtc->pipe;
4401	int palreg = PALETTE(pipe);
4402	int i;
4403	bool reenable_ips = false;
4404
4405	/* The clocks have to be on to load the palette. */
4406	if (!crtc->state->enable || !intel_crtc->active)
4407		return;
4408
4409	if (!HAS_PCH_SPLIT(dev_priv->dev)) {
4410		if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4411			assert_dsi_pll_enabled(dev_priv);
4412		else
4413			assert_pll_enabled(dev_priv, pipe);
4414	}
4415
4416	/* use legacy palette for Ironlake */
4417	if (!HAS_GMCH_DISPLAY(dev))
4418		palreg = LGC_PALETTE(pipe);
4419
4420	/* Workaround : Do not read or write the pipe palette/gamma data while
4421	 * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4422	 */
4423	if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4424	    ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4425	     GAMMA_MODE_MODE_SPLIT)) {
4426		hsw_disable_ips(intel_crtc);
4427		reenable_ips = true;
4428	}
4429
4430	for (i = 0; i < 256; i++) {
4431		I915_WRITE(palreg + 4 * i,
4432			   (intel_crtc->lut_r[i] << 16) |
4433			   (intel_crtc->lut_g[i] << 8) |
4434			   intel_crtc->lut_b[i]);
4435	}
4436
4437	if (reenable_ips)
4438		hsw_enable_ips(intel_crtc);
4439}
4440
4441static void intel_crtc_dpms_overlay(struct intel_crtc *intel_crtc, bool enable)
4442{
4443	if (!enable && intel_crtc->overlay) {
4444		struct drm_device *dev = intel_crtc->base.dev;
4445		struct drm_i915_private *dev_priv = dev->dev_private;
4446
4447		mutex_lock(&dev->struct_mutex);
4448		dev_priv->mm.interruptible = false;
4449		(void) intel_overlay_switch_off(intel_crtc->overlay);
4450		dev_priv->mm.interruptible = true;
4451		mutex_unlock(&dev->struct_mutex);
4452	}
4453
4454	/* Let userspace switch the overlay on again. In most cases userspace
4455	 * has to recompute where to put it anyway.
4456	 */
4457}
4458
4459static void intel_crtc_enable_planes(struct drm_crtc *crtc)
4460{
4461	struct drm_device *dev = crtc->dev;
4462	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4463	int pipe = intel_crtc->pipe;
4464
4465	intel_enable_primary_hw_plane(crtc->primary, crtc);
4466	intel_enable_sprite_planes(crtc);
4467	intel_crtc_update_cursor(crtc, true);
4468	intel_crtc_dpms_overlay(intel_crtc, true);
4469
4470	hsw_enable_ips(intel_crtc);
4471
4472	mutex_lock(&dev->struct_mutex);
4473	intel_fbc_update(dev);
4474	mutex_unlock(&dev->struct_mutex);
4475
4476	/*
4477	 * FIXME: Once we grow proper nuclear flip support out of this we need
4478	 * to compute the mask of flip planes precisely. For the time being
4479	 * consider this a flip from a NULL plane.
4480	 */
4481	intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4482}
4483
4484static void intel_crtc_disable_planes(struct drm_crtc *crtc)
4485{
4486	struct drm_device *dev = crtc->dev;
4487	struct drm_i915_private *dev_priv = dev->dev_private;
4488	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4489	int pipe = intel_crtc->pipe;
4490
4491	intel_crtc_wait_for_pending_flips(crtc);
4492
4493	if (dev_priv->fbc.crtc == intel_crtc)
4494		intel_fbc_disable(dev);
4495
4496	hsw_disable_ips(intel_crtc);
4497
4498	intel_crtc_dpms_overlay(intel_crtc, false);
4499	intel_crtc_update_cursor(crtc, false);
4500	intel_disable_sprite_planes(crtc);
4501	intel_disable_primary_hw_plane(crtc->primary, crtc);
4502
4503	/*
4504	 * FIXME: Once we grow proper nuclear flip support out of this we need
4505	 * to compute the mask of flip planes precisely. For the time being
4506	 * consider this a flip to a NULL plane.
4507	 */
4508	intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4509}
4510
4511static void ironlake_crtc_enable(struct drm_crtc *crtc)
4512{
4513	struct drm_device *dev = crtc->dev;
4514	struct drm_i915_private *dev_priv = dev->dev_private;
4515	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4516	struct intel_encoder *encoder;
4517	int pipe = intel_crtc->pipe;
4518
4519	WARN_ON(!crtc->state->enable);
4520
4521	if (intel_crtc->active)
4522		return;
4523
4524	if (intel_crtc->config->has_pch_encoder)
4525		intel_prepare_shared_dpll(intel_crtc);
4526
4527	if (intel_crtc->config->has_dp_encoder)
4528		intel_dp_set_m_n(intel_crtc, M1_N1);
4529
4530	intel_set_pipe_timings(intel_crtc);
4531
4532	if (intel_crtc->config->has_pch_encoder) {
4533		intel_cpu_transcoder_set_m_n(intel_crtc,
4534				     &intel_crtc->config->fdi_m_n, NULL);
4535	}
4536
4537	ironlake_set_pipeconf(crtc);
4538
4539	intel_crtc->active = true;
4540
4541	intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4542	intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4543
4544	for_each_encoder_on_crtc(dev, crtc, encoder)
4545		if (encoder->pre_enable)
4546			encoder->pre_enable(encoder);
4547
4548	if (intel_crtc->config->has_pch_encoder) {
4549		/* Note: FDI PLL enabling _must_ be done before we enable the
4550		 * cpu pipes, hence this is separate from all the other fdi/pch
4551		 * enabling. */
4552		ironlake_fdi_pll_enable(intel_crtc);
4553	} else {
4554		assert_fdi_tx_disabled(dev_priv, pipe);
4555		assert_fdi_rx_disabled(dev_priv, pipe);
4556	}
4557
4558	ironlake_pfit_enable(intel_crtc);
4559
4560	/*
4561	 * On ILK+ LUT must be loaded before the pipe is running but with
4562	 * clocks enabled
4563	 */
4564	intel_crtc_load_lut(crtc);
4565
4566	intel_update_watermarks(crtc);
4567	intel_enable_pipe(intel_crtc);
4568
4569	if (intel_crtc->config->has_pch_encoder)
4570		ironlake_pch_enable(crtc);
4571
4572	assert_vblank_disabled(crtc);
4573	drm_crtc_vblank_on(crtc);
4574
4575	for_each_encoder_on_crtc(dev, crtc, encoder)
4576		encoder->enable(encoder);
4577
4578	if (HAS_PCH_CPT(dev))
4579		cpt_verify_modeset(dev, intel_crtc->pipe);
4580
4581	intel_crtc_enable_planes(crtc);
4582}
4583
4584/* IPS only exists on ULT machines and is tied to pipe A. */
4585static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4586{
4587	return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4588}
4589
4590/*
4591 * This implements the workaround described in the "notes" section of the mode
4592 * set sequence documentation. When going from no pipes or single pipe to
4593 * multiple pipes, and planes are enabled after the pipe, we need to wait at
4594 * least 2 vblanks on the first pipe before enabling planes on the second pipe.
4595 */
4596static void haswell_mode_set_planes_workaround(struct intel_crtc *crtc)
4597{
4598	struct drm_device *dev = crtc->base.dev;
4599	struct intel_crtc *crtc_it, *other_active_crtc = NULL;
4600
4601	/* We want to get the other_active_crtc only if there's only 1 other
4602	 * active crtc. */
4603	for_each_intel_crtc(dev, crtc_it) {
4604		if (!crtc_it->active || crtc_it == crtc)
4605			continue;
4606
4607		if (other_active_crtc)
4608			return;
4609
4610		other_active_crtc = crtc_it;
4611	}
4612	if (!other_active_crtc)
4613		return;
4614
4615	intel_wait_for_vblank(dev, other_active_crtc->pipe);
4616	intel_wait_for_vblank(dev, other_active_crtc->pipe);
4617}
4618
4619static void haswell_crtc_enable(struct drm_crtc *crtc)
4620{
4621	struct drm_device *dev = crtc->dev;
4622	struct drm_i915_private *dev_priv = dev->dev_private;
4623	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4624	struct intel_encoder *encoder;
4625	int pipe = intel_crtc->pipe;
4626
4627	WARN_ON(!crtc->state->enable);
4628
4629	if (intel_crtc->active)
4630		return;
4631
4632	if (intel_crtc_to_shared_dpll(intel_crtc))
4633		intel_enable_shared_dpll(intel_crtc);
4634
4635	if (intel_crtc->config->has_dp_encoder)
4636		intel_dp_set_m_n(intel_crtc, M1_N1);
4637
4638	intel_set_pipe_timings(intel_crtc);
4639
4640	if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4641		I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4642			   intel_crtc->config->pixel_multiplier - 1);
4643	}
4644
4645	if (intel_crtc->config->has_pch_encoder) {
4646		intel_cpu_transcoder_set_m_n(intel_crtc,
4647				     &intel_crtc->config->fdi_m_n, NULL);
4648	}
4649
4650	haswell_set_pipeconf(crtc);
4651
4652	intel_set_pipe_csc(crtc);
4653
4654	intel_crtc->active = true;
4655
4656	intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4657	for_each_encoder_on_crtc(dev, crtc, encoder)
4658		if (encoder->pre_enable)
4659			encoder->pre_enable(encoder);
4660
4661	if (intel_crtc->config->has_pch_encoder) {
4662		intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4663						      true);
4664		dev_priv->display.fdi_link_train(crtc);
4665	}
4666
4667	intel_ddi_enable_pipe_clock(intel_crtc);
4668
4669	if (IS_SKYLAKE(dev))
4670		skylake_pfit_enable(intel_crtc);
4671	else
4672		ironlake_pfit_enable(intel_crtc);
4673
4674	/*
4675	 * On ILK+ LUT must be loaded before the pipe is running but with
4676	 * clocks enabled
4677	 */
4678	intel_crtc_load_lut(crtc);
4679
4680	intel_ddi_set_pipe_settings(crtc);
4681	intel_ddi_enable_transcoder_func(crtc);
4682
4683	intel_update_watermarks(crtc);
4684	intel_enable_pipe(intel_crtc);
4685
4686	if (intel_crtc->config->has_pch_encoder)
4687		lpt_pch_enable(crtc);
4688
4689	if (intel_crtc->config->dp_encoder_is_mst)
4690		intel_ddi_set_vc_payload_alloc(crtc, true);
4691
4692	assert_vblank_disabled(crtc);
4693	drm_crtc_vblank_on(crtc);
4694
4695	for_each_encoder_on_crtc(dev, crtc, encoder) {
4696		encoder->enable(encoder);
4697		intel_opregion_notify_encoder(encoder, true);
4698	}
4699
4700	/* If we change the relative order between pipe/planes enabling, we need
4701	 * to change the workaround. */
4702	haswell_mode_set_planes_workaround(intel_crtc);
4703	intel_crtc_enable_planes(crtc);
4704}
4705
4706static void skylake_pfit_disable(struct intel_crtc *crtc)
4707{
4708	struct drm_device *dev = crtc->base.dev;
4709	struct drm_i915_private *dev_priv = dev->dev_private;
4710	int pipe = crtc->pipe;
4711
4712	/* To avoid upsetting the power well on haswell only disable the pfit if
4713	 * it's in use. The hw state code will make sure we get this right. */
4714	if (crtc->config->pch_pfit.enabled) {
4715		I915_WRITE(PS_CTL(pipe), 0);
4716		I915_WRITE(PS_WIN_POS(pipe), 0);
4717		I915_WRITE(PS_WIN_SZ(pipe), 0);
4718	}
4719}
4720
4721static void ironlake_pfit_disable(struct intel_crtc *crtc)
4722{
4723	struct drm_device *dev = crtc->base.dev;
4724	struct drm_i915_private *dev_priv = dev->dev_private;
4725	int pipe = crtc->pipe;
4726
4727	/* To avoid upsetting the power well on haswell only disable the pfit if
4728	 * it's in use. The hw state code will make sure we get this right. */
4729	if (crtc->config->pch_pfit.enabled) {
4730		I915_WRITE(PF_CTL(pipe), 0);
4731		I915_WRITE(PF_WIN_POS(pipe), 0);
4732		I915_WRITE(PF_WIN_SZ(pipe), 0);
4733	}
4734}
4735
4736static void ironlake_crtc_disable(struct drm_crtc *crtc)
4737{
4738	struct drm_device *dev = crtc->dev;
4739	struct drm_i915_private *dev_priv = dev->dev_private;
4740	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4741	struct intel_encoder *encoder;
4742	int pipe = intel_crtc->pipe;
4743	u32 reg, temp;
4744
4745	if (!intel_crtc->active)
4746		return;
4747
4748	intel_crtc_disable_planes(crtc);
4749
4750	for_each_encoder_on_crtc(dev, crtc, encoder)
4751		encoder->disable(encoder);
4752
4753	drm_crtc_vblank_off(crtc);
4754	assert_vblank_disabled(crtc);
4755
4756	if (intel_crtc->config->has_pch_encoder)
4757		intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4758
4759	intel_disable_pipe(intel_crtc);
4760
4761	ironlake_pfit_disable(intel_crtc);
4762
4763	for_each_encoder_on_crtc(dev, crtc, encoder)
4764		if (encoder->post_disable)
4765			encoder->post_disable(encoder);
4766
4767	if (intel_crtc->config->has_pch_encoder) {
4768		ironlake_fdi_disable(crtc);
4769
4770		ironlake_disable_pch_transcoder(dev_priv, pipe);
4771
4772		if (HAS_PCH_CPT(dev)) {
4773			/* disable TRANS_DP_CTL */
4774			reg = TRANS_DP_CTL(pipe);
4775			temp = I915_READ(reg);
4776			temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4777				  TRANS_DP_PORT_SEL_MASK);
4778			temp |= TRANS_DP_PORT_SEL_NONE;
4779			I915_WRITE(reg, temp);
4780
4781			/* disable DPLL_SEL */
4782			temp = I915_READ(PCH_DPLL_SEL);
4783			temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4784			I915_WRITE(PCH_DPLL_SEL, temp);
4785		}
4786
4787		/* disable PCH DPLL */
4788		intel_disable_shared_dpll(intel_crtc);
4789
4790		ironlake_fdi_pll_disable(intel_crtc);
4791	}
4792
4793	intel_crtc->active = false;
4794	intel_update_watermarks(crtc);
4795
4796	mutex_lock(&dev->struct_mutex);
4797	intel_fbc_update(dev);
4798	mutex_unlock(&dev->struct_mutex);
4799}
4800
4801static void haswell_crtc_disable(struct drm_crtc *crtc)
4802{
4803	struct drm_device *dev = crtc->dev;
4804	struct drm_i915_private *dev_priv = dev->dev_private;
4805	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4806	struct intel_encoder *encoder;
4807	enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4808
4809	if (!intel_crtc->active)
4810		return;
4811
4812	intel_crtc_disable_planes(crtc);
4813
4814	for_each_encoder_on_crtc(dev, crtc, encoder) {
4815		intel_opregion_notify_encoder(encoder, false);
4816		encoder->disable(encoder);
4817	}
4818
4819	drm_crtc_vblank_off(crtc);
4820	assert_vblank_disabled(crtc);
4821
4822	if (intel_crtc->config->has_pch_encoder)
4823		intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4824						      false);
4825	intel_disable_pipe(intel_crtc);
4826
4827	if (intel_crtc->config->dp_encoder_is_mst)
4828		intel_ddi_set_vc_payload_alloc(crtc, false);
4829
4830	intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
4831
4832	if (IS_SKYLAKE(dev))
4833		skylake_pfit_disable(intel_crtc);
4834	else
4835		ironlake_pfit_disable(intel_crtc);
4836
4837	intel_ddi_disable_pipe_clock(intel_crtc);
4838
4839	if (intel_crtc->config->has_pch_encoder) {
4840		lpt_disable_pch_transcoder(dev_priv);
4841		intel_ddi_fdi_disable(crtc);
4842	}
4843
4844	for_each_encoder_on_crtc(dev, crtc, encoder)
4845		if (encoder->post_disable)
4846			encoder->post_disable(encoder);
4847
4848	intel_crtc->active = false;
4849	intel_update_watermarks(crtc);
4850
4851	mutex_lock(&dev->struct_mutex);
4852	intel_fbc_update(dev);
4853	mutex_unlock(&dev->struct_mutex);
4854
4855	if (intel_crtc_to_shared_dpll(intel_crtc))
4856		intel_disable_shared_dpll(intel_crtc);
4857}
4858
4859static void ironlake_crtc_off(struct drm_crtc *crtc)
4860{
4861	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4862	intel_put_shared_dpll(intel_crtc);
4863}
4864
4865
4866static void i9xx_pfit_enable(struct intel_crtc *crtc)
4867{
4868	struct drm_device *dev = crtc->base.dev;
4869	struct drm_i915_private *dev_priv = dev->dev_private;
4870	struct intel_crtc_state *pipe_config = crtc->config;
4871
4872	if (!pipe_config->gmch_pfit.control)
4873		return;
4874
4875	/*
4876	 * The panel fitter should only be adjusted whilst the pipe is disabled,
4877	 * according to register description and PRM.
4878	 */
4879	WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
4880	assert_pipe_disabled(dev_priv, crtc->pipe);
4881
4882	I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
4883	I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
4884
4885	/* Border color in case we don't scale up to the full screen. Black by
4886	 * default, change to something else for debugging. */
4887	I915_WRITE(BCLRPAT(crtc->pipe), 0);
4888}
4889
4890static enum intel_display_power_domain port_to_power_domain(enum port port)
4891{
4892	switch (port) {
4893	case PORT_A:
4894		return POWER_DOMAIN_PORT_DDI_A_4_LANES;
4895	case PORT_B:
4896		return POWER_DOMAIN_PORT_DDI_B_4_LANES;
4897	case PORT_C:
4898		return POWER_DOMAIN_PORT_DDI_C_4_LANES;
4899	case PORT_D:
4900		return POWER_DOMAIN_PORT_DDI_D_4_LANES;
4901	default:
4902		WARN_ON_ONCE(1);
4903		return POWER_DOMAIN_PORT_OTHER;
4904	}
4905}
4906
4907#define for_each_power_domain(domain, mask)				\
4908	for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)	\
4909		if ((1 << (domain)) & (mask))
4910
4911enum intel_display_power_domain
4912intel_display_port_power_domain(struct intel_encoder *intel_encoder)
4913{
4914	struct drm_device *dev = intel_encoder->base.dev;
4915	struct intel_digital_port *intel_dig_port;
4916
4917	switch (intel_encoder->type) {
4918	case INTEL_OUTPUT_UNKNOWN:
4919		/* Only DDI platforms should ever use this output type */
4920		WARN_ON_ONCE(!HAS_DDI(dev));
4921	case INTEL_OUTPUT_DISPLAYPORT:
4922	case INTEL_OUTPUT_HDMI:
4923	case INTEL_OUTPUT_EDP:
4924		intel_dig_port = enc_to_dig_port(&intel_encoder->base);
4925		return port_to_power_domain(intel_dig_port->port);
4926	case INTEL_OUTPUT_DP_MST:
4927		intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
4928		return port_to_power_domain(intel_dig_port->port);
4929	case INTEL_OUTPUT_ANALOG:
4930		return POWER_DOMAIN_PORT_CRT;
4931	case INTEL_OUTPUT_DSI:
4932		return POWER_DOMAIN_PORT_DSI;
4933	default:
4934		return POWER_DOMAIN_PORT_OTHER;
4935	}
4936}
4937
4938static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
4939{
4940	struct drm_device *dev = crtc->dev;
4941	struct intel_encoder *intel_encoder;
4942	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4943	enum pipe pipe = intel_crtc->pipe;
4944	unsigned long mask;
4945	enum transcoder transcoder;
4946
4947	transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
4948
4949	mask = BIT(POWER_DOMAIN_PIPE(pipe));
4950	mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
4951	if (intel_crtc->config->pch_pfit.enabled ||
4952	    intel_crtc->config->pch_pfit.force_thru)
4953		mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
4954
4955	for_each_encoder_on_crtc(dev, crtc, intel_encoder)
4956		mask |= BIT(intel_display_port_power_domain(intel_encoder));
4957
4958	return mask;
4959}
4960
4961static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
4962{
4963	struct drm_device *dev = state->dev;
4964	struct drm_i915_private *dev_priv = dev->dev_private;
4965	unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
4966	struct intel_crtc *crtc;
4967
4968	/*
4969	 * First get all needed power domains, then put all unneeded, to avoid
4970	 * any unnecessary toggling of the power wells.
4971	 */
4972	for_each_intel_crtc(dev, crtc) {
4973		enum intel_display_power_domain domain;
4974
4975		if (!crtc->base.state->enable)
4976			continue;
4977
4978		pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
4979
4980		for_each_power_domain(domain, pipe_domains[crtc->pipe])
4981			intel_display_power_get(dev_priv, domain);
4982	}
4983
4984	if (dev_priv->display.modeset_global_resources)
4985		dev_priv->display.modeset_global_resources(state);
4986
4987	for_each_intel_crtc(dev, crtc) {
4988		enum intel_display_power_domain domain;
4989
4990		for_each_power_domain(domain, crtc->enabled_power_domains)
4991			intel_display_power_put(dev_priv, domain);
4992
4993		crtc->enabled_power_domains = pipe_domains[crtc->pipe];
4994	}
4995
4996	intel_display_set_init_power(dev_priv, false);
4997}
4998
4999/* returns HPLL frequency in kHz */
5000static int valleyview_get_vco(struct drm_i915_private *dev_priv)
5001{
5002	int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
5003
5004	/* Obtain SKU information */
5005	mutex_lock(&dev_priv->dpio_lock);
5006	hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
5007		CCK_FUSE_HPLL_FREQ_MASK;
5008	mutex_unlock(&dev_priv->dpio_lock);
5009
5010	return vco_freq[hpll_freq] * 1000;
5011}
5012
5013static void vlv_update_cdclk(struct drm_device *dev)
5014{
5015	struct drm_i915_private *dev_priv = dev->dev_private;
5016
5017	dev_priv->vlv_cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5018	DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5019			 dev_priv->vlv_cdclk_freq);
5020
5021	/*
5022	 * Program the gmbus_freq based on the cdclk frequency.
5023	 * BSpec erroneously claims we should aim for 4MHz, but
5024	 * in fact 1MHz is the correct frequency.
5025	 */
5026	I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->vlv_cdclk_freq, 1000));
5027}
5028
5029/* Adjust CDclk dividers to allow high res or save power if possible */
5030static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5031{
5032	struct drm_i915_private *dev_priv = dev->dev_private;
5033	u32 val, cmd;
5034
5035	WARN_ON(dev_priv->display.get_display_clock_speed(dev) != dev_priv->vlv_cdclk_freq);
5036
5037	if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5038		cmd = 2;
5039	else if (cdclk == 266667)
5040		cmd = 1;
5041	else
5042		cmd = 0;
5043
5044	mutex_lock(&dev_priv->rps.hw_lock);
5045	val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5046	val &= ~DSPFREQGUAR_MASK;
5047	val |= (cmd << DSPFREQGUAR_SHIFT);
5048	vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5049	if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5050		      DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5051		     50)) {
5052		DRM_ERROR("timed out waiting for CDclk change\n");
5053	}
5054	mutex_unlock(&dev_priv->rps.hw_lock);
5055
5056	if (cdclk == 400000) {
5057		u32 divider;
5058
5059		divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5060
5061		mutex_lock(&dev_priv->dpio_lock);
5062		/* adjust cdclk divider */
5063		val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5064		val &= ~DISPLAY_FREQUENCY_VALUES;
5065		val |= divider;
5066		vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5067
5068		if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5069			      DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5070			     50))
5071			DRM_ERROR("timed out waiting for CDclk change\n");
5072		mutex_unlock(&dev_priv->dpio_lock);
5073	}
5074
5075	mutex_lock(&dev_priv->dpio_lock);
5076	/* adjust self-refresh exit latency value */
5077	val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5078	val &= ~0x7f;
5079
5080	/*
5081	 * For high bandwidth configs, we set a higher latency in the bunit
5082	 * so that the core display fetch happens in time to avoid underruns.
5083	 */
5084	if (cdclk == 400000)
5085		val |= 4500 / 250; /* 4.5 usec */
5086	else
5087		val |= 3000 / 250; /* 3.0 usec */
5088	vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5089	mutex_unlock(&dev_priv->dpio_lock);
5090
5091	vlv_update_cdclk(dev);
5092}
5093
5094static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5095{
5096	struct drm_i915_private *dev_priv = dev->dev_private;
5097	u32 val, cmd;
5098
5099	WARN_ON(dev_priv->display.get_display_clock_speed(dev) != dev_priv->vlv_cdclk_freq);
5100
5101	switch (cdclk) {
5102	case 333333:
5103	case 320000:
5104	case 266667:
5105	case 200000:
5106		break;
5107	default:
5108		MISSING_CASE(cdclk);
5109		return;
5110	}
5111
5112	/*
5113	 * Specs are full of misinformation, but testing on actual
5114	 * hardware has shown that we just need to write the desired
5115	 * CCK divider into the Punit register.
5116	 */
5117	cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5118
5119	mutex_lock(&dev_priv->rps.hw_lock);
5120	val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5121	val &= ~DSPFREQGUAR_MASK_CHV;
5122	val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5123	vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5124	if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5125		      DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5126		     50)) {
5127		DRM_ERROR("timed out waiting for CDclk change\n");
5128	}
5129	mutex_unlock(&dev_priv->rps.hw_lock);
5130
5131	vlv_update_cdclk(dev);
5132}
5133
5134static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5135				 int max_pixclk)
5136{
5137	int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5138	int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5139
5140	/*
5141	 * Really only a few cases to deal with, as only 4 CDclks are supported:
5142	 *   200MHz
5143	 *   267MHz
5144	 *   320/333MHz (depends on HPLL freq)
5145	 *   400MHz (VLV only)
5146	 * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5147	 * of the lower bin and adjust if needed.
5148	 *
5149	 * We seem to get an unstable or solid color picture at 200MHz.
5150	 * Not sure what's wrong. For now use 200MHz only when all pipes
5151	 * are off.
5152	 */
5153	if (!IS_CHERRYVIEW(dev_priv) &&
5154	    max_pixclk > freq_320*limit/100)
5155		return 400000;
5156	else if (max_pixclk > 266667*limit/100)
5157		return freq_320;
5158	else if (max_pixclk > 0)
5159		return 266667;
5160	else
5161		return 200000;
5162}
5163
5164/* compute the max pixel clock for new configuration */
5165static int intel_mode_max_pixclk(struct drm_i915_private *dev_priv)
5166{
5167	struct drm_device *dev = dev_priv->dev;
5168	struct intel_crtc *intel_crtc;
5169	int max_pixclk = 0;
5170
5171	for_each_intel_crtc(dev, intel_crtc) {
5172		if (intel_crtc->new_enabled)
5173			max_pixclk = max(max_pixclk,
5174					 intel_crtc->new_config->base.adjusted_mode.crtc_clock);
5175	}
5176
5177	return max_pixclk;
5178}
5179
5180static void valleyview_modeset_global_pipes(struct drm_device *dev,
5181					    unsigned *prepare_pipes)
5182{
5183	struct drm_i915_private *dev_priv = dev->dev_private;
5184	struct intel_crtc *intel_crtc;
5185	int max_pixclk = intel_mode_max_pixclk(dev_priv);
5186
5187	if (valleyview_calc_cdclk(dev_priv, max_pixclk) ==
5188	    dev_priv->vlv_cdclk_freq)
5189		return;
5190
5191	/* disable/enable all currently active pipes while we change cdclk */
5192	for_each_intel_crtc(dev, intel_crtc)
5193		if (intel_crtc->base.state->enable)
5194			*prepare_pipes |= (1 << intel_crtc->pipe);
5195}
5196
5197static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5198{
5199	unsigned int credits, default_credits;
5200
5201	if (IS_CHERRYVIEW(dev_priv))
5202		default_credits = PFI_CREDIT(12);
5203	else
5204		default_credits = PFI_CREDIT(8);
5205
5206	if (DIV_ROUND_CLOSEST(dev_priv->vlv_cdclk_freq, 1000) >= dev_priv->rps.cz_freq) {
5207		/* CHV suggested value is 31 or 63 */
5208		if (IS_CHERRYVIEW(dev_priv))
5209			credits = PFI_CREDIT_31;
5210		else
5211			credits = PFI_CREDIT(15);
5212	} else {
5213		credits = default_credits;
5214	}
5215
5216	/*
5217	 * WA - write default credits before re-programming
5218	 * FIXME: should we also set the resend bit here?
5219	 */
5220	I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5221		   default_credits);
5222
5223	I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5224		   credits | PFI_CREDIT_RESEND);
5225
5226	/*
5227	 * FIXME is this guaranteed to clear
5228	 * immediately or should we poll for it?
5229	 */
5230	WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5231}
5232
5233static void valleyview_modeset_global_resources(struct drm_atomic_state *state)
5234{
5235	struct drm_device *dev = state->dev;
5236	struct drm_i915_private *dev_priv = dev->dev_private;
5237	int max_pixclk = intel_mode_max_pixclk(dev_priv);
5238	int req_cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
5239
5240	if (req_cdclk != dev_priv->vlv_cdclk_freq) {
5241		/*
5242		 * FIXME: We can end up here with all power domains off, yet
5243		 * with a CDCLK frequency other than the minimum. To account
5244		 * for this take the PIPE-A power domain, which covers the HW
5245		 * blocks needed for the following programming. This can be
5246		 * removed once it's guaranteed that we get here either with
5247		 * the minimum CDCLK set, or the required power domains
5248		 * enabled.
5249		 */
5250		intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5251
5252		if (IS_CHERRYVIEW(dev))
5253			cherryview_set_cdclk(dev, req_cdclk);
5254		else
5255			valleyview_set_cdclk(dev, req_cdclk);
5256
5257		vlv_program_pfi_credits(dev_priv);
5258
5259		intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5260	}
5261}
5262
5263static void valleyview_crtc_enable(struct drm_crtc *crtc)
5264{
5265	struct drm_device *dev = crtc->dev;
5266	struct drm_i915_private *dev_priv = to_i915(dev);
5267	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5268	struct intel_encoder *encoder;
5269	int pipe = intel_crtc->pipe;
5270	bool is_dsi;
5271
5272	WARN_ON(!crtc->state->enable);
5273
5274	if (intel_crtc->active)
5275		return;
5276
5277	is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
5278
5279	if (!is_dsi) {
5280		if (IS_CHERRYVIEW(dev))
5281			chv_prepare_pll(intel_crtc, intel_crtc->config);
5282		else
5283			vlv_prepare_pll(intel_crtc, intel_crtc->config);
5284	}
5285
5286	if (intel_crtc->config->has_dp_encoder)
5287		intel_dp_set_m_n(intel_crtc, M1_N1);
5288
5289	intel_set_pipe_timings(intel_crtc);
5290
5291	if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
5292		struct drm_i915_private *dev_priv = dev->dev_private;
5293
5294		I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5295		I915_WRITE(CHV_CANVAS(pipe), 0);
5296	}
5297
5298	i9xx_set_pipeconf(intel_crtc);
5299
5300	intel_crtc->active = true;
5301
5302	intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5303
5304	for_each_encoder_on_crtc(dev, crtc, encoder)
5305		if (encoder->pre_pll_enable)
5306			encoder->pre_pll_enable(encoder);
5307
5308	if (!is_dsi) {
5309		if (IS_CHERRYVIEW(dev))
5310			chv_enable_pll(intel_crtc, intel_crtc->config);
5311		else
5312			vlv_enable_pll(intel_crtc, intel_crtc->config);
5313	}
5314
5315	for_each_encoder_on_crtc(dev, crtc, encoder)
5316		if (encoder->pre_enable)
5317			encoder->pre_enable(encoder);
5318
5319	i9xx_pfit_enable(intel_crtc);
5320
5321	intel_crtc_load_lut(crtc);
5322
5323	intel_update_watermarks(crtc);
5324	intel_enable_pipe(intel_crtc);
5325
5326	assert_vblank_disabled(crtc);
5327	drm_crtc_vblank_on(crtc);
5328
5329	for_each_encoder_on_crtc(dev, crtc, encoder)
5330		encoder->enable(encoder);
5331
5332	intel_crtc_enable_planes(crtc);
5333
5334	/* Underruns don't raise interrupts, so check manually. */
5335	i9xx_check_fifo_underruns(dev_priv);
5336}
5337
5338static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5339{
5340	struct drm_device *dev = crtc->base.dev;
5341	struct drm_i915_private *dev_priv = dev->dev_private;
5342
5343	I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5344	I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5345}
5346
5347static void i9xx_crtc_enable(struct drm_crtc *crtc)
5348{
5349	struct drm_device *dev = crtc->dev;
5350	struct drm_i915_private *dev_priv = to_i915(dev);
5351	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5352	struct intel_encoder *encoder;
5353	int pipe = intel_crtc->pipe;
5354
5355	WARN_ON(!crtc->state->enable);
5356
5357	if (intel_crtc->active)
5358		return;
5359
5360	i9xx_set_pll_dividers(intel_crtc);
5361
5362	if (intel_crtc->config->has_dp_encoder)
5363		intel_dp_set_m_n(intel_crtc, M1_N1);
5364
5365	intel_set_pipe_timings(intel_crtc);
5366
5367	i9xx_set_pipeconf(intel_crtc);
5368
5369	intel_crtc->active = true;
5370
5371	if (!IS_GEN2(dev))
5372		intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5373
5374	for_each_encoder_on_crtc(dev, crtc, encoder)
5375		if (encoder->pre_enable)
5376			encoder->pre_enable(encoder);
5377
5378	i9xx_enable_pll(intel_crtc);
5379
5380	i9xx_pfit_enable(intel_crtc);
5381
5382	intel_crtc_load_lut(crtc);
5383
5384	intel_update_watermarks(crtc);
5385	intel_enable_pipe(intel_crtc);
5386
5387	assert_vblank_disabled(crtc);
5388	drm_crtc_vblank_on(crtc);
5389
5390	for_each_encoder_on_crtc(dev, crtc, encoder)
5391		encoder->enable(encoder);
5392
5393	intel_crtc_enable_planes(crtc);
5394
5395	/*
5396	 * Gen2 reports pipe underruns whenever all planes are disabled.
5397	 * So don't enable underrun reporting before at least some planes
5398	 * are enabled.
5399	 * FIXME: Need to fix the logic to work when we turn off all planes
5400	 * but leave the pipe running.
5401	 */
5402	if (IS_GEN2(dev))
5403		intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5404
5405	/* Underruns don't raise interrupts, so check manually. */
5406	i9xx_check_fifo_underruns(dev_priv);
5407}
5408
5409static void i9xx_pfit_disable(struct intel_crtc *crtc)
5410{
5411	struct drm_device *dev = crtc->base.dev;
5412	struct drm_i915_private *dev_priv = dev->dev_private;
5413
5414	if (!crtc->config->gmch_pfit.control)
5415		return;
5416
5417	assert_pipe_disabled(dev_priv, crtc->pipe);
5418
5419	DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5420			 I915_READ(PFIT_CONTROL));
5421	I915_WRITE(PFIT_CONTROL, 0);
5422}
5423
5424static void i9xx_crtc_disable(struct drm_crtc *crtc)
5425{
5426	struct drm_device *dev = crtc->dev;
5427	struct drm_i915_private *dev_priv = dev->dev_private;
5428	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5429	struct intel_encoder *encoder;
5430	int pipe = intel_crtc->pipe;
5431
5432	if (!intel_crtc->active)
5433		return;
5434
5435	/*
5436	 * Gen2 reports pipe underruns whenever all planes are disabled.
5437	 * So diasble underrun reporting before all the planes get disabled.
5438	 * FIXME: Need to fix the logic to work when we turn off all planes
5439	 * but leave the pipe running.
5440	 */
5441	if (IS_GEN2(dev))
5442		intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5443
5444	/*
5445	 * Vblank time updates from the shadow to live plane control register
5446	 * are blocked if the memory self-refresh mode is active at that
5447	 * moment. So to make sure the plane gets truly disabled, disable
5448	 * first the self-refresh mode. The self-refresh enable bit in turn
5449	 * will be checked/applied by the HW only at the next frame start
5450	 * event which is after the vblank start event, so we need to have a
5451	 * wait-for-vblank between disabling the plane and the pipe.
5452	 */
5453	intel_set_memory_cxsr(dev_priv, false);
5454	intel_crtc_disable_planes(crtc);
5455
5456	/*
5457	 * On gen2 planes are double buffered but the pipe isn't, so we must
5458	 * wait for planes to fully turn off before disabling the pipe.
5459	 * We also need to wait on all gmch platforms because of the
5460	 * self-refresh mode constraint explained above.
5461	 */
5462	intel_wait_for_vblank(dev, pipe);
5463
5464	for_each_encoder_on_crtc(dev, crtc, encoder)
5465		encoder->disable(encoder);
5466
5467	drm_crtc_vblank_off(crtc);
5468	assert_vblank_disabled(crtc);
5469
5470	intel_disable_pipe(intel_crtc);
5471
5472	i9xx_pfit_disable(intel_crtc);
5473
5474	for_each_encoder_on_crtc(dev, crtc, encoder)
5475		if (encoder->post_disable)
5476			encoder->post_disable(encoder);
5477
5478	if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
5479		if (IS_CHERRYVIEW(dev))
5480			chv_disable_pll(dev_priv, pipe);
5481		else if (IS_VALLEYVIEW(dev))
5482			vlv_disable_pll(dev_priv, pipe);
5483		else
5484			i9xx_disable_pll(intel_crtc);
5485	}
5486
5487	if (!IS_GEN2(dev))
5488		intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5489
5490	intel_crtc->active = false;
5491	intel_update_watermarks(crtc);
5492
5493	mutex_lock(&dev->struct_mutex);
5494	intel_fbc_update(dev);
5495	mutex_unlock(&dev->struct_mutex);
5496}
5497
5498static void i9xx_crtc_off(struct drm_crtc *crtc)
5499{
5500}
5501
5502/* Master function to enable/disable CRTC and corresponding power wells */
5503void intel_crtc_control(struct drm_crtc *crtc, bool enable)
5504{
5505	struct drm_device *dev = crtc->dev;
5506	struct drm_i915_private *dev_priv = dev->dev_private;
5507	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5508	enum intel_display_power_domain domain;
5509	unsigned long domains;
5510
5511	if (enable) {
5512		if (!intel_crtc->active) {
5513			domains = get_crtc_power_domains(crtc);
5514			for_each_power_domain(domain, domains)
5515				intel_display_power_get(dev_priv, domain);
5516			intel_crtc->enabled_power_domains = domains;
5517
5518			dev_priv->display.crtc_enable(crtc);
5519		}
5520	} else {
5521		if (intel_crtc->active) {
5522			dev_priv->display.crtc_disable(crtc);
5523
5524			domains = intel_crtc->enabled_power_domains;
5525			for_each_power_domain(domain, domains)
5526				intel_display_power_put(dev_priv, domain);
5527			intel_crtc->enabled_power_domains = 0;
5528		}
5529	}
5530}
5531
5532/**
5533 * Sets the power management mode of the pipe and plane.
5534 */
5535void intel_crtc_update_dpms(struct drm_crtc *crtc)
5536{
5537	struct drm_device *dev = crtc->dev;
5538	struct intel_encoder *intel_encoder;
5539	bool enable = false;
5540
5541	for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5542		enable |= intel_encoder->connectors_active;
5543
5544	intel_crtc_control(crtc, enable);
5545}
5546
5547static void intel_crtc_disable(struct drm_crtc *crtc)
5548{
5549	struct drm_device *dev = crtc->dev;
5550	struct drm_connector *connector;
5551	struct drm_i915_private *dev_priv = dev->dev_private;
5552
5553	/* crtc should still be enabled when we disable it. */
5554	WARN_ON(!crtc->state->enable);
5555
5556	dev_priv->display.crtc_disable(crtc);
5557	dev_priv->display.off(crtc);
5558
5559	crtc->primary->funcs->disable_plane(crtc->primary);
5560
5561	/* Update computed state. */
5562	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
5563		if (!connector->encoder || !connector->encoder->crtc)
5564			continue;
5565
5566		if (connector->encoder->crtc != crtc)
5567			continue;
5568
5569		connector->dpms = DRM_MODE_DPMS_OFF;
5570		to_intel_encoder(connector->encoder)->connectors_active = false;
5571	}
5572}
5573
5574void intel_encoder_destroy(struct drm_encoder *encoder)
5575{
5576	struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5577
5578	drm_encoder_cleanup(encoder);
5579	kfree(intel_encoder);
5580}
5581
5582/* Simple dpms helper for encoders with just one connector, no cloning and only
5583 * one kind of off state. It clamps all !ON modes to fully OFF and changes the
5584 * state of the entire output pipe. */
5585static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
5586{
5587	if (mode == DRM_MODE_DPMS_ON) {
5588		encoder->connectors_active = true;
5589
5590		intel_crtc_update_dpms(encoder->base.crtc);
5591	} else {
5592		encoder->connectors_active = false;
5593
5594		intel_crtc_update_dpms(encoder->base.crtc);
5595	}
5596}
5597
5598/* Cross check the actual hw state with our own modeset state tracking (and it's
5599 * internal consistency). */
5600static void intel_connector_check_state(struct intel_connector *connector)
5601{
5602	if (connector->get_hw_state(connector)) {
5603		struct intel_encoder *encoder = connector->encoder;
5604		struct drm_crtc *crtc;
5605		bool encoder_enabled;
5606		enum pipe pipe;
5607
5608		DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
5609			      connector->base.base.id,
5610			      connector->base.name);
5611
5612		I915_STATE_WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
5613		     "wrong connector dpms state\n");
5614		I915_STATE_WARN(connector->base.encoder != &encoder->base,
5615		     "active connector not linked to encoder\n");
5616
5617		if (encoder) {
5618			I915_STATE_WARN(!encoder->connectors_active,
5619			     "encoder->connectors_active not set\n");
5620
5621			encoder_enabled = encoder->get_hw_state(encoder, &pipe);
5622			I915_STATE_WARN(!encoder_enabled, "encoder not enabled\n");
5623			if (I915_STATE_WARN_ON(!encoder->base.crtc))
5624				return;
5625
5626			crtc = encoder->base.crtc;
5627
5628			I915_STATE_WARN(!crtc->state->enable,
5629					"crtc not enabled\n");
5630			I915_STATE_WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
5631			I915_STATE_WARN(pipe != to_intel_crtc(crtc)->pipe,
5632			     "encoder active on the wrong pipe\n");
5633		}
5634	}
5635}
5636
5637int intel_connector_init(struct intel_connector *connector)
5638{
5639	struct drm_connector_state *connector_state;
5640
5641	connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
5642	if (!connector_state)
5643		return -ENOMEM;
5644
5645	connector->base.state = connector_state;
5646	return 0;
5647}
5648
5649struct intel_connector *intel_connector_alloc(void)
5650{
5651	struct intel_connector *connector;
5652
5653	connector = kzalloc(sizeof *connector, GFP_KERNEL);
5654	if (!connector)
5655		return NULL;
5656
5657	if (intel_connector_init(connector) < 0) {
5658		kfree(connector);
5659		return NULL;
5660	}
5661
5662	return connector;
5663}
5664
5665/* Even simpler default implementation, if there's really no special case to
5666 * consider. */
5667void intel_connector_dpms(struct drm_connector *connector, int mode)
5668{
5669	/* All the simple cases only support two dpms states. */
5670	if (mode != DRM_MODE_DPMS_ON)
5671		mode = DRM_MODE_DPMS_OFF;
5672
5673	if (mode == connector->dpms)
5674		return;
5675
5676	connector->dpms = mode;
5677
5678	/* Only need to change hw state when actually enabled */
5679	if (connector->encoder)
5680		intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
5681
5682	intel_modeset_check_state(connector->dev);
5683}
5684
5685/* Simple connector->get_hw_state implementation for encoders that support only
5686 * one connector and no cloning and hence the encoder state determines the state
5687 * of the connector. */
5688bool intel_connector_get_hw_state(struct intel_connector *connector)
5689{
5690	enum pipe pipe = 0;
5691	struct intel_encoder *encoder = connector->encoder;
5692
5693	return encoder->get_hw_state(encoder, &pipe);
5694}
5695
5696static int pipe_required_fdi_lanes(struct drm_device *dev, enum pipe pipe)
5697{
5698	struct intel_crtc *crtc =
5699		to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
5700
5701	if (crtc->base.state->enable &&
5702	    crtc->config->has_pch_encoder)
5703		return crtc->config->fdi_lanes;
5704
5705	return 0;
5706}
5707
5708static bool ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
5709				     struct intel_crtc_state *pipe_config)
5710{
5711	DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
5712		      pipe_name(pipe), pipe_config->fdi_lanes);
5713	if (pipe_config->fdi_lanes > 4) {
5714		DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
5715			      pipe_name(pipe), pipe_config->fdi_lanes);
5716		return false;
5717	}
5718
5719	if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
5720		if (pipe_config->fdi_lanes > 2) {
5721			DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
5722				      pipe_config->fdi_lanes);
5723			return false;
5724		} else {
5725			return true;
5726		}
5727	}
5728
5729	if (INTEL_INFO(dev)->num_pipes == 2)
5730		return true;
5731
5732	/* Ivybridge 3 pipe is really complicated */
5733	switch (pipe) {
5734	case PIPE_A:
5735		return true;
5736	case PIPE_B:
5737		if (pipe_config->fdi_lanes > 2 &&
5738		    pipe_required_fdi_lanes(dev, PIPE_C) > 0) {
5739			DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
5740				      pipe_name(pipe), pipe_config->fdi_lanes);
5741			return false;
5742		}
5743		return true;
5744	case PIPE_C:
5745		if (pipe_config->fdi_lanes > 2) {
5746			DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
5747				      pipe_name(pipe), pipe_config->fdi_lanes);
5748			return false;
5749		}
5750		if (pipe_required_fdi_lanes(dev, PIPE_B) > 2) {
5751			DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
5752			return false;
5753		}
5754		return true;
5755	default:
5756		BUG();
5757	}
5758}
5759
5760#define RETRY 1
5761static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
5762				       struct intel_crtc_state *pipe_config)
5763{
5764	struct drm_device *dev = intel_crtc->base.dev;
5765	struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
5766	int lane, link_bw, fdi_dotclock;
5767	bool setup_ok, needs_recompute = false;
5768
5769retry:
5770	/* FDI is a binary signal running at ~2.7GHz, encoding
5771	 * each output octet as 10 bits. The actual frequency
5772	 * is stored as a divider into a 100MHz clock, and the
5773	 * mode pixel clock is stored in units of 1KHz.
5774	 * Hence the bw of each lane in terms of the mode signal
5775	 * is:
5776	 */
5777	link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
5778
5779	fdi_dotclock = adjusted_mode->crtc_clock;
5780
5781	lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
5782					   pipe_config->pipe_bpp);
5783
5784	pipe_config->fdi_lanes = lane;
5785
5786	intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
5787			       link_bw, &pipe_config->fdi_m_n);
5788
5789	setup_ok = ironlake_check_fdi_lanes(intel_crtc->base.dev,
5790					    intel_crtc->pipe, pipe_config);
5791	if (!setup_ok && pipe_config->pipe_bpp > 6*3) {
5792		pipe_config->pipe_bpp -= 2*3;
5793		DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
5794			      pipe_config->pipe_bpp);
5795		needs_recompute = true;
5796		pipe_config->bw_constrained = true;
5797
5798		goto retry;
5799	}
5800
5801	if (needs_recompute)
5802		return RETRY;
5803
5804	return setup_ok ? 0 : -EINVAL;
5805}
5806
5807static void hsw_compute_ips_config(struct intel_crtc *crtc,
5808				   struct intel_crtc_state *pipe_config)
5809{
5810	pipe_config->ips_enabled = i915.enable_ips &&
5811				   hsw_crtc_supports_ips(crtc) &&
5812				   pipe_config->pipe_bpp <= 24;
5813}
5814
5815static int intel_crtc_compute_config(struct intel_crtc *crtc,
5816				     struct intel_crtc_state *pipe_config)
5817{
5818	struct drm_device *dev = crtc->base.dev;
5819	struct drm_i915_private *dev_priv = dev->dev_private;
5820	struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
5821
5822	/* FIXME should check pixel clock limits on all platforms */
5823	if (INTEL_INFO(dev)->gen < 4) {
5824		int clock_limit =
5825			dev_priv->display.get_display_clock_speed(dev);
5826
5827		/*
5828		 * Enable pixel doubling when the dot clock
5829		 * is > 90% of the (display) core speed.
5830		 *
5831		 * GDG double wide on either pipe,
5832		 * otherwise pipe A only.
5833		 */
5834		if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
5835		    adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
5836			clock_limit *= 2;
5837			pipe_config->double_wide = true;
5838		}
5839
5840		if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
5841			return -EINVAL;
5842	}
5843
5844	/*
5845	 * Pipe horizontal size must be even in:
5846	 * - DVO ganged mode
5847	 * - LVDS dual channel mode
5848	 * - Double wide pipe
5849	 */
5850	if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
5851	     intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
5852		pipe_config->pipe_src_w &= ~1;
5853
5854	/* Cantiga+ cannot handle modes with a hsync front porch of 0.
5855	 * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
5856	 */
5857	if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
5858		adjusted_mode->hsync_start == adjusted_mode->hdisplay)
5859		return -EINVAL;
5860
5861	if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)) && pipe_config->pipe_bpp > 10*3) {
5862		pipe_config->pipe_bpp = 10*3; /* 12bpc is gen5+ */
5863	} else if (INTEL_INFO(dev)->gen <= 4 && pipe_config->pipe_bpp > 8*3) {
5864		/* only a 8bpc pipe, with 6bpc dither through the panel fitter
5865		 * for lvds. */
5866		pipe_config->pipe_bpp = 8*3;
5867	}
5868
5869	if (HAS_IPS(dev))
5870		hsw_compute_ips_config(crtc, pipe_config);
5871
5872	if (pipe_config->has_pch_encoder)
5873		return ironlake_fdi_compute_config(crtc, pipe_config);
5874
5875	return 0;
5876}
5877
5878static int valleyview_get_display_clock_speed(struct drm_device *dev)
5879{
5880	struct drm_i915_private *dev_priv = dev->dev_private;
5881	u32 val;
5882	int divider;
5883
5884	if (dev_priv->hpll_freq == 0)
5885		dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
5886
5887	mutex_lock(&dev_priv->dpio_lock);
5888	val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5889	mutex_unlock(&dev_priv->dpio_lock);
5890
5891	divider = val & DISPLAY_FREQUENCY_VALUES;
5892
5893	WARN((val & DISPLAY_FREQUENCY_STATUS) !=
5894	     (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5895	     "cdclk change in progress\n");
5896
5897	return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
5898}
5899
5900static int i945_get_display_clock_speed(struct drm_device *dev)
5901{
5902	return 400000;
5903}
5904
5905static int i915_get_display_clock_speed(struct drm_device *dev)
5906{
5907	return 333000;
5908}
5909
5910static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
5911{
5912	return 200000;
5913}
5914
5915static int pnv_get_display_clock_speed(struct drm_device *dev)
5916{
5917	u16 gcfgc = 0;
5918
5919	pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5920
5921	switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5922	case GC_DISPLAY_CLOCK_267_MHZ_PNV:
5923		return 267000;
5924	case GC_DISPLAY_CLOCK_333_MHZ_PNV:
5925		return 333000;
5926	case GC_DISPLAY_CLOCK_444_MHZ_PNV:
5927		return 444000;
5928	case GC_DISPLAY_CLOCK_200_MHZ_PNV:
5929		return 200000;
5930	default:
5931		DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
5932	case GC_DISPLAY_CLOCK_133_MHZ_PNV:
5933		return 133000;
5934	case GC_DISPLAY_CLOCK_167_MHZ_PNV:
5935		return 167000;
5936	}
5937}
5938
5939static int i915gm_get_display_clock_speed(struct drm_device *dev)
5940{
5941	u16 gcfgc = 0;
5942
5943	pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5944
5945	if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
5946		return 133000;
5947	else {
5948		switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5949		case GC_DISPLAY_CLOCK_333_MHZ:
5950			return 333000;
5951		default:
5952		case GC_DISPLAY_CLOCK_190_200_MHZ:
5953			return 190000;
5954		}
5955	}
5956}
5957
5958static int i865_get_display_clock_speed(struct drm_device *dev)
5959{
5960	return 266000;
5961}
5962
5963static int i855_get_display_clock_speed(struct drm_device *dev)
5964{
5965	u16 hpllcc = 0;
5966	/* Assume that the hardware is in the high speed state.  This
5967	 * should be the default.
5968	 */
5969	switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
5970	case GC_CLOCK_133_200:
5971	case GC_CLOCK_100_200:
5972		return 200000;
5973	case GC_CLOCK_166_250:
5974		return 250000;
5975	case GC_CLOCK_100_133:
5976		return 133000;
5977	}
5978
5979	/* Shouldn't happen */
5980	return 0;
5981}
5982
5983static int i830_get_display_clock_speed(struct drm_device *dev)
5984{
5985	return 133000;
5986}
5987
5988static void
5989intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
5990{
5991	while (*num > DATA_LINK_M_N_MASK ||
5992	       *den > DATA_LINK_M_N_MASK) {
5993		*num >>= 1;
5994		*den >>= 1;
5995	}
5996}
5997
5998static void compute_m_n(unsigned int m, unsigned int n,
5999			uint32_t *ret_m, uint32_t *ret_n)
6000{
6001	*ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6002	*ret_m = div_u64((uint64_t) m * *ret_n, n);
6003	intel_reduce_m_n_ratio(ret_m, ret_n);
6004}
6005
6006void
6007intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6008		       int pixel_clock, int link_clock,
6009		       struct intel_link_m_n *m_n)
6010{
6011	m_n->tu = 64;
6012
6013	compute_m_n(bits_per_pixel * pixel_clock,
6014		    link_clock * nlanes * 8,
6015		    &m_n->gmch_m, &m_n->gmch_n);
6016
6017	compute_m_n(pixel_clock, link_clock,
6018		    &m_n->link_m, &m_n->link_n);
6019}
6020
6021static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6022{
6023	if (i915.panel_use_ssc >= 0)
6024		return i915.panel_use_ssc != 0;
6025	return dev_priv->vbt.lvds_use_ssc
6026		&& !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6027}
6028
6029static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
6030			   int num_connectors)
6031{
6032	struct drm_device *dev = crtc_state->base.crtc->dev;
6033	struct drm_i915_private *dev_priv = dev->dev_private;
6034	int refclk;
6035
6036	WARN_ON(!crtc_state->base.state);
6037
6038	if (IS_VALLEYVIEW(dev)) {
6039		refclk = 100000;
6040	} else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6041	    intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
6042		refclk = dev_priv->vbt.lvds_ssc_freq;
6043		DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
6044	} else if (!IS_GEN2(dev)) {
6045		refclk = 96000;
6046	} else {
6047		refclk = 48000;
6048	}
6049
6050	return refclk;
6051}
6052
6053static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6054{
6055	return (1 << dpll->n) << 16 | dpll->m2;
6056}
6057
6058static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6059{
6060	return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6061}
6062
6063static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6064				     struct intel_crtc_state *crtc_state,
6065				     intel_clock_t *reduced_clock)
6066{
6067	struct drm_device *dev = crtc->base.dev;
6068	u32 fp, fp2 = 0;
6069
6070	if (IS_PINEVIEW(dev)) {
6071		fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6072		if (reduced_clock)
6073			fp2 = pnv_dpll_compute_fp(reduced_clock);
6074	} else {
6075		fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6076		if (reduced_clock)
6077			fp2 = i9xx_dpll_compute_fp(reduced_clock);
6078	}
6079
6080	crtc_state->dpll_hw_state.fp0 = fp;
6081
6082	crtc->lowfreq_avail = false;
6083	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6084	    reduced_clock) {
6085		crtc_state->dpll_hw_state.fp1 = fp2;
6086		crtc->lowfreq_avail = true;
6087	} else {
6088		crtc_state->dpll_hw_state.fp1 = fp;
6089	}
6090}
6091
6092static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6093		pipe)
6094{
6095	u32 reg_val;
6096
6097	/*
6098	 * PLLB opamp always calibrates to max value of 0x3f, force enable it
6099	 * and set it to a reasonable value instead.
6100	 */
6101	reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6102	reg_val &= 0xffffff00;
6103	reg_val |= 0x00000030;
6104	vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6105
6106	reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6107	reg_val &= 0x8cffffff;
6108	reg_val = 0x8c000000;
6109	vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6110
6111	reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6112	reg_val &= 0xffffff00;
6113	vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6114
6115	reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6116	reg_val &= 0x00ffffff;
6117	reg_val |= 0xb0000000;
6118	vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6119}
6120
6121static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6122					 struct intel_link_m_n *m_n)
6123{
6124	struct drm_device *dev = crtc->base.dev;
6125	struct drm_i915_private *dev_priv = dev->dev_private;
6126	int pipe = crtc->pipe;
6127
6128	I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6129	I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6130	I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6131	I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6132}
6133
6134static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6135					 struct intel_link_m_n *m_n,
6136					 struct intel_link_m_n *m2_n2)
6137{
6138	struct drm_device *dev = crtc->base.dev;
6139	struct drm_i915_private *dev_priv = dev->dev_private;
6140	int pipe = crtc->pipe;
6141	enum transcoder transcoder = crtc->config->cpu_transcoder;
6142
6143	if (INTEL_INFO(dev)->gen >= 5) {
6144		I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6145		I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6146		I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6147		I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6148		/* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6149		 * for gen < 8) and if DRRS is supported (to make sure the
6150		 * registers are not unnecessarily accessed).
6151		 */
6152		if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
6153			crtc->config->has_drrs) {
6154			I915_WRITE(PIPE_DATA_M2(transcoder),
6155					TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6156			I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6157			I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6158			I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6159		}
6160	} else {
6161		I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6162		I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6163		I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6164		I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6165	}
6166}
6167
6168void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6169{
6170	struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6171
6172	if (m_n == M1_N1) {
6173		dp_m_n = &crtc->config->dp_m_n;
6174		dp_m2_n2 = &crtc->config->dp_m2_n2;
6175	} else if (m_n == M2_N2) {
6176
6177		/*
6178		 * M2_N2 registers are not supported. Hence m2_n2 divider value
6179		 * needs to be programmed into M1_N1.
6180		 */
6181		dp_m_n = &crtc->config->dp_m2_n2;
6182	} else {
6183		DRM_ERROR("Unsupported divider value\n");
6184		return;
6185	}
6186
6187	if (crtc->config->has_pch_encoder)
6188		intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6189	else
6190		intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6191}
6192
6193static void vlv_update_pll(struct intel_crtc *crtc,
6194			   struct intel_crtc_state *pipe_config)
6195{
6196	u32 dpll, dpll_md;
6197
6198	/*
6199	 * Enable DPIO clock input. We should never disable the reference
6200	 * clock for pipe B, since VGA hotplug / manual detection depends
6201	 * on it.
6202	 */
6203	dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REFA_CLK_ENABLE_VLV |
6204		DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_CLOCK_VLV;
6205	/* We should never disable this, set it here for state tracking */
6206	if (crtc->pipe == PIPE_B)
6207		dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6208	dpll |= DPLL_VCO_ENABLE;
6209	pipe_config->dpll_hw_state.dpll = dpll;
6210
6211	dpll_md = (pipe_config->pixel_multiplier - 1)
6212		<< DPLL_MD_UDI_MULTIPLIER_SHIFT;
6213	pipe_config->dpll_hw_state.dpll_md = dpll_md;
6214}
6215
6216static void vlv_prepare_pll(struct intel_crtc *crtc,
6217			    const struct intel_crtc_state *pipe_config)
6218{
6219	struct drm_device *dev = crtc->base.dev;
6220	struct drm_i915_private *dev_priv = dev->dev_private;
6221	int pipe = crtc->pipe;
6222	u32 mdiv;
6223	u32 bestn, bestm1, bestm2, bestp1, bestp2;
6224	u32 coreclk, reg_val;
6225
6226	mutex_lock(&dev_priv->dpio_lock);
6227
6228	bestn = pipe_config->dpll.n;
6229	bestm1 = pipe_config->dpll.m1;
6230	bestm2 = pipe_config->dpll.m2;
6231	bestp1 = pipe_config->dpll.p1;
6232	bestp2 = pipe_config->dpll.p2;
6233
6234	/* See eDP HDMI DPIO driver vbios notes doc */
6235
6236	/* PLL B needs special handling */
6237	if (pipe == PIPE_B)
6238		vlv_pllb_recal_opamp(dev_priv, pipe);
6239
6240	/* Set up Tx target for periodic Rcomp update */
6241	vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6242
6243	/* Disable target IRef on PLL */
6244	reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6245	reg_val &= 0x00ffffff;
6246	vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6247
6248	/* Disable fast lock */
6249	vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6250
6251	/* Set idtafcrecal before PLL is enabled */
6252	mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6253	mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6254	mdiv |= ((bestn << DPIO_N_SHIFT));
6255	mdiv |= (1 << DPIO_K_SHIFT);
6256
6257	/*
6258	 * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6259	 * but we don't support that).
6260	 * Note: don't use the DAC post divider as it seems unstable.
6261	 */
6262	mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6263	vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6264
6265	mdiv |= DPIO_ENABLE_CALIBRATION;
6266	vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6267
6268	/* Set HBR and RBR LPF coefficients */
6269	if (pipe_config->port_clock == 162000 ||
6270	    intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
6271	    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
6272		vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6273				 0x009f0003);
6274	else
6275		vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6276				 0x00d0000f);
6277
6278	if (pipe_config->has_dp_encoder) {
6279		/* Use SSC source */
6280		if (pipe == PIPE_A)
6281			vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6282					 0x0df40000);
6283		else
6284			vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6285					 0x0df70000);
6286	} else { /* HDMI or VGA */
6287		/* Use bend source */
6288		if (pipe == PIPE_A)
6289			vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6290					 0x0df70000);
6291		else
6292			vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6293					 0x0df40000);
6294	}
6295
6296	coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6297	coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6298	if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
6299	    intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
6300		coreclk |= 0x01000000;
6301	vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6302
6303	vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6304	mutex_unlock(&dev_priv->dpio_lock);
6305}
6306
6307static void chv_update_pll(struct intel_crtc *crtc,
6308			   struct intel_crtc_state *pipe_config)
6309{
6310	pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLOCK_CHV |
6311		DPLL_REFA_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
6312		DPLL_VCO_ENABLE;
6313	if (crtc->pipe != PIPE_A)
6314		pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6315
6316	pipe_config->dpll_hw_state.dpll_md =
6317		(pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6318}
6319
6320static void chv_prepare_pll(struct intel_crtc *crtc,
6321			    const struct intel_crtc_state *pipe_config)
6322{
6323	struct drm_device *dev = crtc->base.dev;
6324	struct drm_i915_private *dev_priv = dev->dev_private;
6325	int pipe = crtc->pipe;
6326	int dpll_reg = DPLL(crtc->pipe);
6327	enum dpio_channel port = vlv_pipe_to_channel(pipe);
6328	u32 loopfilter, tribuf_calcntr;
6329	u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6330	u32 dpio_val;
6331	int vco;
6332
6333	bestn = pipe_config->dpll.n;
6334	bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6335	bestm1 = pipe_config->dpll.m1;
6336	bestm2 = pipe_config->dpll.m2 >> 22;
6337	bestp1 = pipe_config->dpll.p1;
6338	bestp2 = pipe_config->dpll.p2;
6339	vco = pipe_config->dpll.vco;
6340	dpio_val = 0;
6341	loopfilter = 0;
6342
6343	/*
6344	 * Enable Refclk and SSC
6345	 */
6346	I915_WRITE(dpll_reg,
6347		   pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6348
6349	mutex_lock(&dev_priv->dpio_lock);
6350
6351	/* p1 and p2 divider */
6352	vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6353			5 << DPIO_CHV_S1_DIV_SHIFT |
6354			bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6355			bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6356			1 << DPIO_CHV_K_DIV_SHIFT);
6357
6358	/* Feedback post-divider - m2 */
6359	vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6360
6361	/* Feedback refclk divider - n and m1 */
6362	vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6363			DPIO_CHV_M1_DIV_BY_2 |
6364			1 << DPIO_CHV_N_DIV_SHIFT);
6365
6366	/* M2 fraction division */
6367	if (bestm2_frac)
6368		vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6369
6370	/* M2 fraction division enable */
6371	dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6372	dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6373	dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6374	if (bestm2_frac)
6375		dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6376	vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6377
6378	/* Program digital lock detect threshold */
6379	dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6380	dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6381					DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6382	dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6383	if (!bestm2_frac)
6384		dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6385	vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6386
6387	/* Loop filter */
6388	if (vco == 5400000) {
6389		loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6390		loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6391		loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6392		tribuf_calcntr = 0x9;
6393	} else if (vco <= 6200000) {
6394		loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6395		loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6396		loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6397		tribuf_calcntr = 0x9;
6398	} else if (vco <= 6480000) {
6399		loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6400		loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6401		loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6402		tribuf_calcntr = 0x8;
6403	} else {
6404		/* Not supported. Apply the same limits as in the max case */
6405		loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6406		loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6407		loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6408		tribuf_calcntr = 0;
6409	}
6410	vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6411
6412	dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6413	dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6414	dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6415	vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6416
6417	/* AFC Recal */
6418	vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6419			vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6420			DPIO_AFC_RECAL);
6421
6422	mutex_unlock(&dev_priv->dpio_lock);
6423}
6424
6425/**
6426 * vlv_force_pll_on - forcibly enable just the PLL
6427 * @dev_priv: i915 private structure
6428 * @pipe: pipe PLL to enable
6429 * @dpll: PLL configuration
6430 *
6431 * Enable the PLL for @pipe using the supplied @dpll config. To be used
6432 * in cases where we need the PLL enabled even when @pipe is not going to
6433 * be enabled.
6434 */
6435void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
6436		      const struct dpll *dpll)
6437{
6438	struct intel_crtc *crtc =
6439		to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
6440	struct intel_crtc_state pipe_config = {
6441		.base.crtc = &crtc->base,
6442		.pixel_multiplier = 1,
6443		.dpll = *dpll,
6444	};
6445
6446	if (IS_CHERRYVIEW(dev)) {
6447		chv_update_pll(crtc, &pipe_config);
6448		chv_prepare_pll(crtc, &pipe_config);
6449		chv_enable_pll(crtc, &pipe_config);
6450	} else {
6451		vlv_update_pll(crtc, &pipe_config);
6452		vlv_prepare_pll(crtc, &pipe_config);
6453		vlv_enable_pll(crtc, &pipe_config);
6454	}
6455}
6456
6457/**
6458 * vlv_force_pll_off - forcibly disable just the PLL
6459 * @dev_priv: i915 private structure
6460 * @pipe: pipe PLL to disable
6461 *
6462 * Disable the PLL for @pipe. To be used in cases where we need
6463 * the PLL enabled even when @pipe is not going to be enabled.
6464 */
6465void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
6466{
6467	if (IS_CHERRYVIEW(dev))
6468		chv_disable_pll(to_i915(dev), pipe);
6469	else
6470		vlv_disable_pll(to_i915(dev), pipe);
6471}
6472
6473static void i9xx_update_pll(struct intel_crtc *crtc,
6474			    struct intel_crtc_state *crtc_state,
6475			    intel_clock_t *reduced_clock,
6476			    int num_connectors)
6477{
6478	struct drm_device *dev = crtc->base.dev;
6479	struct drm_i915_private *dev_priv = dev->dev_private;
6480	u32 dpll;
6481	bool is_sdvo;
6482	struct dpll *clock = &crtc_state->dpll;
6483
6484	i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6485
6486	is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
6487		intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
6488
6489	dpll = DPLL_VGA_MODE_DIS;
6490
6491	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
6492		dpll |= DPLLB_MODE_LVDS;
6493	else
6494		dpll |= DPLLB_MODE_DAC_SERIAL;
6495
6496	if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
6497		dpll |= (crtc_state->pixel_multiplier - 1)
6498			<< SDVO_MULTIPLIER_SHIFT_HIRES;
6499	}
6500
6501	if (is_sdvo)
6502		dpll |= DPLL_SDVO_HIGH_SPEED;
6503
6504	if (crtc_state->has_dp_encoder)
6505		dpll |= DPLL_SDVO_HIGH_SPEED;
6506
6507	/* compute bitmask from p1 value */
6508	if (IS_PINEVIEW(dev))
6509		dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6510	else {
6511		dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6512		if (IS_G4X(dev) && reduced_clock)
6513			dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6514	}
6515	switch (clock->p2) {
6516	case 5:
6517		dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6518		break;
6519	case 7:
6520		dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6521		break;
6522	case 10:
6523		dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6524		break;
6525	case 14:
6526		dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6527		break;
6528	}
6529	if (INTEL_INFO(dev)->gen >= 4)
6530		dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6531
6532	if (crtc_state->sdvo_tv_clock)
6533		dpll |= PLL_REF_INPUT_TVCLKINBC;
6534	else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6535		 intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6536		dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6537	else
6538		dpll |= PLL_REF_INPUT_DREFCLK;
6539
6540	dpll |= DPLL_VCO_ENABLE;
6541	crtc_state->dpll_hw_state.dpll = dpll;
6542
6543	if (INTEL_INFO(dev)->gen >= 4) {
6544		u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6545			<< DPLL_MD_UDI_MULTIPLIER_SHIFT;
6546		crtc_state->dpll_hw_state.dpll_md = dpll_md;
6547	}
6548}
6549
6550static void i8xx_update_pll(struct intel_crtc *crtc,
6551			    struct intel_crtc_state *crtc_state,
6552			    intel_clock_t *reduced_clock,
6553			    int num_connectors)
6554{
6555	struct drm_device *dev = crtc->base.dev;
6556	struct drm_i915_private *dev_priv = dev->dev_private;
6557	u32 dpll;
6558	struct dpll *clock = &crtc_state->dpll;
6559
6560	i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6561
6562	dpll = DPLL_VGA_MODE_DIS;
6563
6564	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
6565		dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6566	} else {
6567		if (clock->p1 == 2)
6568			dpll |= PLL_P1_DIVIDE_BY_TWO;
6569		else
6570			dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6571		if (clock->p2 == 4)
6572			dpll |= PLL_P2_DIVIDE_BY_4;
6573	}
6574
6575	if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
6576		dpll |= DPLL_DVO_2X_MODE;
6577
6578	if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6579		 intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6580		dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6581	else
6582		dpll |= PLL_REF_INPUT_DREFCLK;
6583
6584	dpll |= DPLL_VCO_ENABLE;
6585	crtc_state->dpll_hw_state.dpll = dpll;
6586}
6587
6588static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
6589{
6590	struct drm_device *dev = intel_crtc->base.dev;
6591	struct drm_i915_private *dev_priv = dev->dev_private;
6592	enum pipe pipe = intel_crtc->pipe;
6593	enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
6594	struct drm_display_mode *adjusted_mode =
6595		&intel_crtc->config->base.adjusted_mode;
6596	uint32_t crtc_vtotal, crtc_vblank_end;
6597	int vsyncshift = 0;
6598
6599	/* We need to be careful not to changed the adjusted mode, for otherwise
6600	 * the hw state checker will get angry at the mismatch. */
6601	crtc_vtotal = adjusted_mode->crtc_vtotal;
6602	crtc_vblank_end = adjusted_mode->crtc_vblank_end;
6603
6604	if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
6605		/* the chip adds 2 halflines automatically */
6606		crtc_vtotal -= 1;
6607		crtc_vblank_end -= 1;
6608
6609		if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
6610			vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
6611		else
6612			vsyncshift = adjusted_mode->crtc_hsync_start -
6613				adjusted_mode->crtc_htotal / 2;
6614		if (vsyncshift < 0)
6615			vsyncshift += adjusted_mode->crtc_htotal;
6616	}
6617
6618	if (INTEL_INFO(dev)->gen > 3)
6619		I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
6620
6621	I915_WRITE(HTOTAL(cpu_transcoder),
6622		   (adjusted_mode->crtc_hdisplay - 1) |
6623		   ((adjusted_mode->crtc_htotal - 1) << 16));
6624	I915_WRITE(HBLANK(cpu_transcoder),
6625		   (adjusted_mode->crtc_hblank_start - 1) |
6626		   ((adjusted_mode->crtc_hblank_end - 1) << 16));
6627	I915_WRITE(HSYNC(cpu_transcoder),
6628		   (adjusted_mode->crtc_hsync_start - 1) |
6629		   ((adjusted_mode->crtc_hsync_end - 1) << 16));
6630
6631	I915_WRITE(VTOTAL(cpu_transcoder),
6632		   (adjusted_mode->crtc_vdisplay - 1) |
6633		   ((crtc_vtotal - 1) << 16));
6634	I915_WRITE(VBLANK(cpu_transcoder),
6635		   (adjusted_mode->crtc_vblank_start - 1) |
6636		   ((crtc_vblank_end - 1) << 16));
6637	I915_WRITE(VSYNC(cpu_transcoder),
6638		   (adjusted_mode->crtc_vsync_start - 1) |
6639		   ((adjusted_mode->crtc_vsync_end - 1) << 16));
6640
6641	/* Workaround: when the EDP input selection is B, the VTOTAL_B must be
6642	 * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
6643	 * documented on the DDI_FUNC_CTL register description, EDP Input Select
6644	 * bits. */
6645	if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
6646	    (pipe == PIPE_B || pipe == PIPE_C))
6647		I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
6648
6649	/* pipesrc controls the size that is scaled from, which should
6650	 * always be the user's requested size.
6651	 */
6652	I915_WRITE(PIPESRC(pipe),
6653		   ((intel_crtc->config->pipe_src_w - 1) << 16) |
6654		   (intel_crtc->config->pipe_src_h - 1));
6655}
6656
6657static void intel_get_pipe_timings(struct intel_crtc *crtc,
6658				   struct intel_crtc_state *pipe_config)
6659{
6660	struct drm_device *dev = crtc->base.dev;
6661	struct drm_i915_private *dev_priv = dev->dev_private;
6662	enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6663	uint32_t tmp;
6664
6665	tmp = I915_READ(HTOTAL(cpu_transcoder));
6666	pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
6667	pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
6668	tmp = I915_READ(HBLANK(cpu_transcoder));
6669	pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
6670	pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
6671	tmp = I915_READ(HSYNC(cpu_transcoder));
6672	pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
6673	pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
6674
6675	tmp = I915_READ(VTOTAL(cpu_transcoder));
6676	pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
6677	pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
6678	tmp = I915_READ(VBLANK(cpu_transcoder));
6679	pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
6680	pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
6681	tmp = I915_READ(VSYNC(cpu_transcoder));
6682	pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
6683	pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
6684
6685	if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
6686		pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
6687		pipe_config->base.adjusted_mode.crtc_vtotal += 1;
6688		pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
6689	}
6690
6691	tmp = I915_READ(PIPESRC(crtc->pipe));
6692	pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
6693	pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
6694
6695	pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
6696	pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
6697}
6698
6699void intel_mode_from_pipe_config(struct drm_display_mode *mode,
6700				 struct intel_crtc_state *pipe_config)
6701{
6702	mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
6703	mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
6704	mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
6705	mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
6706
6707	mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
6708	mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
6709	mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
6710	mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
6711
6712	mode->flags = pipe_config->base.adjusted_mode.flags;
6713
6714	mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
6715	mode->flags |= pipe_config->base.adjusted_mode.flags;
6716}
6717
6718static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
6719{
6720	struct drm_device *dev = intel_crtc->base.dev;
6721	struct drm_i915_private *dev_priv = dev->dev_private;
6722	uint32_t pipeconf;
6723
6724	pipeconf = 0;
6725
6726	if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
6727	    (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
6728		pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
6729
6730	if (intel_crtc->config->double_wide)
6731		pipeconf |= PIPECONF_DOUBLE_WIDE;
6732
6733	/* only g4x and later have fancy bpc/dither controls */
6734	if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
6735		/* Bspec claims that we can't use dithering for 30bpp pipes. */
6736		if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
6737			pipeconf |= PIPECONF_DITHER_EN |
6738				    PIPECONF_DITHER_TYPE_SP;
6739
6740		switch (intel_crtc->config->pipe_bpp) {
6741		case 18:
6742			pipeconf |= PIPECONF_6BPC;
6743			break;
6744		case 24:
6745			pipeconf |= PIPECONF_8BPC;
6746			break;
6747		case 30:
6748			pipeconf |= PIPECONF_10BPC;
6749			break;
6750		default:
6751			/* Case prevented by intel_choose_pipe_bpp_dither. */
6752			BUG();
6753		}
6754	}
6755
6756	if (HAS_PIPE_CXSR(dev)) {
6757		if (intel_crtc->lowfreq_avail) {
6758			DRM_DEBUG_KMS("enabling CxSR downclocking\n");
6759			pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
6760		} else {
6761			DRM_DEBUG_KMS("disabling CxSR downclocking\n");
6762		}
6763	}
6764
6765	if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
6766		if (INTEL_INFO(dev)->gen < 4 ||
6767		    intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
6768			pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
6769		else
6770			pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
6771	} else
6772		pipeconf |= PIPECONF_PROGRESSIVE;
6773
6774	if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
6775		pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
6776
6777	I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
6778	POSTING_READ(PIPECONF(intel_crtc->pipe));
6779}
6780
6781static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
6782				   struct intel_crtc_state *crtc_state)
6783{
6784	struct drm_device *dev = crtc->base.dev;
6785	struct drm_i915_private *dev_priv = dev->dev_private;
6786	int refclk, num_connectors = 0;
6787	intel_clock_t clock, reduced_clock;
6788	bool ok, has_reduced_clock = false;
6789	bool is_lvds = false, is_dsi = false;
6790	struct intel_encoder *encoder;
6791	const intel_limit_t *limit;
6792	struct drm_atomic_state *state = crtc_state->base.state;
6793	struct drm_connector_state *connector_state;
6794	int i;
6795
6796	for (i = 0; i < state->num_connector; i++) {
6797		if (!state->connectors[i])
6798			continue;
6799
6800		connector_state = state->connector_states[i];
6801		if (connector_state->crtc != &crtc->base)
6802			continue;
6803
6804		encoder = to_intel_encoder(connector_state->best_encoder);
6805
6806		switch (encoder->type) {
6807		case INTEL_OUTPUT_LVDS:
6808			is_lvds = true;
6809			break;
6810		case INTEL_OUTPUT_DSI:
6811			is_dsi = true;
6812			break;
6813		default:
6814			break;
6815		}
6816
6817		num_connectors++;
6818	}
6819
6820	if (is_dsi)
6821		return 0;
6822
6823	if (!crtc_state->clock_set) {
6824		refclk = i9xx_get_refclk(crtc_state, num_connectors);
6825
6826		/*
6827		 * Returns a set of divisors for the desired target clock with
6828		 * the given refclk, or FALSE.  The returned values represent
6829		 * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
6830		 * 2) / p1 / p2.
6831		 */
6832		limit = intel_limit(crtc_state, refclk);
6833		ok = dev_priv->display.find_dpll(limit, crtc_state,
6834						 crtc_state->port_clock,
6835						 refclk, NULL, &clock);
6836		if (!ok) {
6837			DRM_ERROR("Couldn't find PLL settings for mode!\n");
6838			return -EINVAL;
6839		}
6840
6841		if (is_lvds && dev_priv->lvds_downclock_avail) {
6842			/*
6843			 * Ensure we match the reduced clock's P to the target
6844			 * clock.  If the clocks don't match, we can't switch
6845			 * the display clock by using the FP0/FP1. In such case
6846			 * we will disable the LVDS downclock feature.
6847			 */
6848			has_reduced_clock =
6849				dev_priv->display.find_dpll(limit, crtc_state,
6850							    dev_priv->lvds_downclock,
6851							    refclk, &clock,
6852							    &reduced_clock);
6853		}
6854		/* Compat-code for transition, will disappear. */
6855		crtc_state->dpll.n = clock.n;
6856		crtc_state->dpll.m1 = clock.m1;
6857		crtc_state->dpll.m2 = clock.m2;
6858		crtc_state->dpll.p1 = clock.p1;
6859		crtc_state->dpll.p2 = clock.p2;
6860	}
6861
6862	if (IS_GEN2(dev)) {
6863		i8xx_update_pll(crtc, crtc_state,
6864				has_reduced_clock ? &reduced_clock : NULL,
6865				num_connectors);
6866	} else if (IS_CHERRYVIEW(dev)) {
6867		chv_update_pll(crtc, crtc_state);
6868	} else if (IS_VALLEYVIEW(dev)) {
6869		vlv_update_pll(crtc, crtc_state);
6870	} else {
6871		i9xx_update_pll(crtc, crtc_state,
6872				has_reduced_clock ? &reduced_clock : NULL,
6873				num_connectors);
6874	}
6875
6876	return 0;
6877}
6878
6879static void i9xx_get_pfit_config(struct intel_crtc *crtc,
6880				 struct intel_crtc_state *pipe_config)
6881{
6882	struct drm_device *dev = crtc->base.dev;
6883	struct drm_i915_private *dev_priv = dev->dev_private;
6884	uint32_t tmp;
6885
6886	if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
6887		return;
6888
6889	tmp = I915_READ(PFIT_CONTROL);
6890	if (!(tmp & PFIT_ENABLE))
6891		return;
6892
6893	/* Check whether the pfit is attached to our pipe. */
6894	if (INTEL_INFO(dev)->gen < 4) {
6895		if (crtc->pipe != PIPE_B)
6896			return;
6897	} else {
6898		if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
6899			return;
6900	}
6901
6902	pipe_config->gmch_pfit.control = tmp;
6903	pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
6904	if (INTEL_INFO(dev)->gen < 5)
6905		pipe_config->gmch_pfit.lvds_border_bits =
6906			I915_READ(LVDS) & LVDS_BORDER_ENABLE;
6907}
6908
6909static void vlv_crtc_clock_get(struct intel_crtc *crtc,
6910			       struct intel_crtc_state *pipe_config)
6911{
6912	struct drm_device *dev = crtc->base.dev;
6913	struct drm_i915_private *dev_priv = dev->dev_private;
6914	int pipe = pipe_config->cpu_transcoder;
6915	intel_clock_t clock;
6916	u32 mdiv;
6917	int refclk = 100000;
6918
6919	/* In case of MIPI DPLL will not even be used */
6920	if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
6921		return;
6922
6923	mutex_lock(&dev_priv->dpio_lock);
6924	mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
6925	mutex_unlock(&dev_priv->dpio_lock);
6926
6927	clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
6928	clock.m2 = mdiv & DPIO_M2DIV_MASK;
6929	clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
6930	clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
6931	clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
6932
6933	vlv_clock(refclk, &clock);
6934
6935	/* clock.dot is the fast clock */
6936	pipe_config->port_clock = clock.dot / 5;
6937}
6938
6939static void
6940i9xx_get_initial_plane_config(struct intel_crtc *crtc,
6941			      struct intel_initial_plane_config *plane_config)
6942{
6943	struct drm_device *dev = crtc->base.dev;
6944	struct drm_i915_private *dev_priv = dev->dev_private;
6945	u32 val, base, offset;
6946	int pipe = crtc->pipe, plane = crtc->plane;
6947	int fourcc, pixel_format;
6948	unsigned int aligned_height;
6949	struct drm_framebuffer *fb;
6950	struct intel_framebuffer *intel_fb;
6951
6952	val = I915_READ(DSPCNTR(plane));
6953	if (!(val & DISPLAY_PLANE_ENABLE))
6954		return;
6955
6956	intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
6957	if (!intel_fb) {
6958		DRM_DEBUG_KMS("failed to alloc fb\n");
6959		return;
6960	}
6961
6962	fb = &intel_fb->base;
6963
6964	if (INTEL_INFO(dev)->gen >= 4) {
6965		if (val & DISPPLANE_TILED) {
6966			plane_config->tiling = I915_TILING_X;
6967			fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
6968		}
6969	}
6970
6971	pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
6972	fourcc = i9xx_format_to_fourcc(pixel_format);
6973	fb->pixel_format = fourcc;
6974	fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
6975
6976	if (INTEL_INFO(dev)->gen >= 4) {
6977		if (plane_config->tiling)
6978			offset = I915_READ(DSPTILEOFF(plane));
6979		else
6980			offset = I915_READ(DSPLINOFF(plane));
6981		base = I915_READ(DSPSURF(plane)) & 0xfffff000;
6982	} else {
6983		base = I915_READ(DSPADDR(plane));
6984	}
6985	plane_config->base = base;
6986
6987	val = I915_READ(PIPESRC(pipe));
6988	fb->width = ((val >> 16) & 0xfff) + 1;
6989	fb->height = ((val >> 0) & 0xfff) + 1;
6990
6991	val = I915_READ(DSPSTRIDE(pipe));
6992	fb->pitches[0] = val & 0xffffffc0;
6993
6994	aligned_height = intel_fb_align_height(dev, fb->height,
6995					       fb->pixel_format,
6996					       fb->modifier[0]);
6997
6998	plane_config->size = fb->pitches[0] * aligned_height;
6999
7000	DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7001		      pipe_name(pipe), plane, fb->width, fb->height,
7002		      fb->bits_per_pixel, base, fb->pitches[0],
7003		      plane_config->size);
7004
7005	plane_config->fb = intel_fb;
7006}
7007
7008static void chv_crtc_clock_get(struct intel_crtc *crtc,
7009			       struct intel_crtc_state *pipe_config)
7010{
7011	struct drm_device *dev = crtc->base.dev;
7012	struct drm_i915_private *dev_priv = dev->dev_private;
7013	int pipe = pipe_config->cpu_transcoder;
7014	enum dpio_channel port = vlv_pipe_to_channel(pipe);
7015	intel_clock_t clock;
7016	u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
7017	int refclk = 100000;
7018
7019	mutex_lock(&dev_priv->dpio_lock);
7020	cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7021	pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7022	pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7023	pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7024	mutex_unlock(&dev_priv->dpio_lock);
7025
7026	clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7027	clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
7028	clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7029	clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7030	clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7031
7032	chv_clock(refclk, &clock);
7033
7034	/* clock.dot is the fast clock */
7035	pipe_config->port_clock = clock.dot / 5;
7036}
7037
7038static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7039				 struct intel_crtc_state *pipe_config)
7040{
7041	struct drm_device *dev = crtc->base.dev;
7042	struct drm_i915_private *dev_priv = dev->dev_private;
7043	uint32_t tmp;
7044
7045	if (!intel_display_power_is_enabled(dev_priv,
7046					    POWER_DOMAIN_PIPE(crtc->pipe)))
7047		return false;
7048
7049	pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7050	pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7051
7052	tmp = I915_READ(PIPECONF(crtc->pipe));
7053	if (!(tmp & PIPECONF_ENABLE))
7054		return false;
7055
7056	if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7057		switch (tmp & PIPECONF_BPC_MASK) {
7058		case PIPECONF_6BPC:
7059			pipe_config->pipe_bpp = 18;
7060			break;
7061		case PIPECONF_8BPC:
7062			pipe_config->pipe_bpp = 24;
7063			break;
7064		case PIPECONF_10BPC:
7065			pipe_config->pipe_bpp = 30;
7066			break;
7067		default:
7068			break;
7069		}
7070	}
7071
7072	if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
7073		pipe_config->limited_color_range = true;
7074
7075	if (INTEL_INFO(dev)->gen < 4)
7076		pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7077
7078	intel_get_pipe_timings(crtc, pipe_config);
7079
7080	i9xx_get_pfit_config(crtc, pipe_config);
7081
7082	if (INTEL_INFO(dev)->gen >= 4) {
7083		tmp = I915_READ(DPLL_MD(crtc->pipe));
7084		pipe_config->pixel_multiplier =
7085			((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7086			 >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7087		pipe_config->dpll_hw_state.dpll_md = tmp;
7088	} else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7089		tmp = I915_READ(DPLL(crtc->pipe));
7090		pipe_config->pixel_multiplier =
7091			((tmp & SDVO_MULTIPLIER_MASK)
7092			 >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7093	} else {
7094		/* Note that on i915G/GM the pixel multiplier is in the sdvo
7095		 * port and will be fixed up in the encoder->get_config
7096		 * function. */
7097		pipe_config->pixel_multiplier = 1;
7098	}
7099	pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7100	if (!IS_VALLEYVIEW(dev)) {
7101		/*
7102		 * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7103		 * on 830. Filter it out here so that we don't
7104		 * report errors due to that.
7105		 */
7106		if (IS_I830(dev))
7107			pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7108
7109		pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7110		pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7111	} else {
7112		/* Mask out read-only status bits. */
7113		pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7114						     DPLL_PORTC_READY_MASK |
7115						     DPLL_PORTB_READY_MASK);
7116	}
7117
7118	if (IS_CHERRYVIEW(dev))
7119		chv_crtc_clock_get(crtc, pipe_config);
7120	else if (IS_VALLEYVIEW(dev))
7121		vlv_crtc_clock_get(crtc, pipe_config);
7122	else
7123		i9xx_crtc_clock_get(crtc, pipe_config);
7124
7125	return true;
7126}
7127
7128static void ironlake_init_pch_refclk(struct drm_device *dev)
7129{
7130	struct drm_i915_private *dev_priv = dev->dev_private;
7131	struct intel_encoder *encoder;
7132	u32 val, final;
7133	bool has_lvds = false;
7134	bool has_cpu_edp = false;
7135	bool has_panel = false;
7136	bool has_ck505 = false;
7137	bool can_ssc = false;
7138
7139	/* We need to take the global config into account */
7140	for_each_intel_encoder(dev, encoder) {
7141		switch (encoder->type) {
7142		case INTEL_OUTPUT_LVDS:
7143			has_panel = true;
7144			has_lvds = true;
7145			break;
7146		case INTEL_OUTPUT_EDP:
7147			has_panel = true;
7148			if (enc_to_dig_port(&encoder->base)->port == PORT_A)
7149				has_cpu_edp = true;
7150			break;
7151		default:
7152			break;
7153		}
7154	}
7155
7156	if (HAS_PCH_IBX(dev)) {
7157		has_ck505 = dev_priv->vbt.display_clock_mode;
7158		can_ssc = has_ck505;
7159	} else {
7160		has_ck505 = false;
7161		can_ssc = true;
7162	}
7163
7164	DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
7165		      has_panel, has_lvds, has_ck505);
7166
7167	/* Ironlake: try to setup display ref clock before DPLL
7168	 * enabling. This is only under driver's control after
7169	 * PCH B stepping, previous chipset stepping should be
7170	 * ignoring this setting.
7171	 */
7172	val = I915_READ(PCH_DREF_CONTROL);
7173
7174	/* As we must carefully and slowly disable/enable each source in turn,
7175	 * compute the final state we want first and check if we need to
7176	 * make any changes at all.
7177	 */
7178	final = val;
7179	final &= ~DREF_NONSPREAD_SOURCE_MASK;
7180	if (has_ck505)
7181		final |= DREF_NONSPREAD_CK505_ENABLE;
7182	else
7183		final |= DREF_NONSPREAD_SOURCE_ENABLE;
7184
7185	final &= ~DREF_SSC_SOURCE_MASK;
7186	final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7187	final &= ~DREF_SSC1_ENABLE;
7188
7189	if (has_panel) {
7190		final |= DREF_SSC_SOURCE_ENABLE;
7191
7192		if (intel_panel_use_ssc(dev_priv) && can_ssc)
7193			final |= DREF_SSC1_ENABLE;
7194
7195		if (has_cpu_edp) {
7196			if (intel_panel_use_ssc(dev_priv) && can_ssc)
7197				final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7198			else
7199				final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7200		} else
7201			final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7202	} else {
7203		final |= DREF_SSC_SOURCE_DISABLE;
7204		final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7205	}
7206
7207	if (final == val)
7208		return;
7209
7210	/* Always enable nonspread source */
7211	val &= ~DREF_NONSPREAD_SOURCE_MASK;
7212
7213	if (has_ck505)
7214		val |= DREF_NONSPREAD_CK505_ENABLE;
7215	else
7216		val |= DREF_NONSPREAD_SOURCE_ENABLE;
7217
7218	if (has_panel) {
7219		val &= ~DREF_SSC_SOURCE_MASK;
7220		val |= DREF_SSC_SOURCE_ENABLE;
7221
7222		/* SSC must be turned on before enabling the CPU output  */
7223		if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7224			DRM_DEBUG_KMS("Using SSC on panel\n");
7225			val |= DREF_SSC1_ENABLE;
7226		} else
7227			val &= ~DREF_SSC1_ENABLE;
7228
7229		/* Get SSC going before enabling the outputs */
7230		I915_WRITE(PCH_DREF_CONTROL, val);
7231		POSTING_READ(PCH_DREF_CONTROL);
7232		udelay(200);
7233
7234		val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7235
7236		/* Enable CPU source on CPU attached eDP */
7237		if (has_cpu_edp) {
7238			if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7239				DRM_DEBUG_KMS("Using SSC on eDP\n");
7240				val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7241			} else
7242				val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7243		} else
7244			val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7245
7246		I915_WRITE(PCH_DREF_CONTROL, val);
7247		POSTING_READ(PCH_DREF_CONTROL);
7248		udelay(200);
7249	} else {
7250		DRM_DEBUG_KMS("Disabling SSC entirely\n");
7251
7252		val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7253
7254		/* Turn off CPU output */
7255		val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7256
7257		I915_WRITE(PCH_DREF_CONTROL, val);
7258		POSTING_READ(PCH_DREF_CONTROL);
7259		udelay(200);
7260
7261		/* Turn off the SSC source */
7262		val &= ~DREF_SSC_SOURCE_MASK;
7263		val |= DREF_SSC_SOURCE_DISABLE;
7264
7265		/* Turn off SSC1 */
7266		val &= ~DREF_SSC1_ENABLE;
7267
7268		I915_WRITE(PCH_DREF_CONTROL, val);
7269		POSTING_READ(PCH_DREF_CONTROL);
7270		udelay(200);
7271	}
7272
7273	BUG_ON(val != final);
7274}
7275
7276static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7277{
7278	uint32_t tmp;
7279
7280	tmp = I915_READ(SOUTH_CHICKEN2);
7281	tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7282	I915_WRITE(SOUTH_CHICKEN2, tmp);
7283
7284	if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
7285			       FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7286		DRM_ERROR("FDI mPHY reset assert timeout\n");
7287
7288	tmp = I915_READ(SOUTH_CHICKEN2);
7289	tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7290	I915_WRITE(SOUTH_CHICKEN2, tmp);
7291
7292	if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
7293				FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7294		DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7295}
7296
7297/* WaMPhyProgramming:hsw */
7298static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7299{
7300	uint32_t tmp;
7301
7302	tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7303	tmp &= ~(0xFF << 24);
7304	tmp |= (0x12 << 24);
7305	intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7306
7307	tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7308	tmp |= (1 << 11);
7309	intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7310
7311	tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7312	tmp |= (1 << 11);
7313	intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7314
7315	tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7316	tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7317	intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7318
7319	tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7320	tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7321	intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7322
7323	tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7324	tmp &= ~(7 << 13);
7325	tmp |= (5 << 13);
7326	intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7327
7328	tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7329	tmp &= ~(7 << 13);
7330	tmp |= (5 << 13);
7331	intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7332
7333	tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7334	tmp &= ~0xFF;
7335	tmp |= 0x1C;
7336	intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7337
7338	tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7339	tmp &= ~0xFF;
7340	tmp |= 0x1C;
7341	intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7342
7343	tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7344	tmp &= ~(0xFF << 16);
7345	tmp |= (0x1C << 16);
7346	intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7347
7348	tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7349	tmp &= ~(0xFF << 16);
7350	tmp |= (0x1C << 16);
7351	intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7352
7353	tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7354	tmp |= (1 << 27);
7355	intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7356
7357	tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7358	tmp |= (1 << 27);
7359	intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7360
7361	tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7362	tmp &= ~(0xF << 28);
7363	tmp |= (4 << 28);
7364	intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7365
7366	tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7367	tmp &= ~(0xF << 28);
7368	tmp |= (4 << 28);
7369	intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7370}
7371
7372/* Implements 3 different sequences from BSpec chapter "Display iCLK
7373 * Programming" based on the parameters passed:
7374 * - Sequence to enable CLKOUT_DP
7375 * - Sequence to enable CLKOUT_DP without spread
7376 * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7377 */
7378static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
7379				 bool with_fdi)
7380{
7381	struct drm_i915_private *dev_priv = dev->dev_private;
7382	uint32_t reg, tmp;
7383
7384	if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7385		with_spread = true;
7386	if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
7387		 with_fdi, "LP PCH doesn't have FDI\n"))
7388		with_fdi = false;
7389
7390	mutex_lock(&dev_priv->dpio_lock);
7391
7392	tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7393	tmp &= ~SBI_SSCCTL_DISABLE;
7394	tmp |= SBI_SSCCTL_PATHALT;
7395	intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7396
7397	udelay(24);
7398
7399	if (with_spread) {
7400		tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7401		tmp &= ~SBI_SSCCTL_PATHALT;
7402		intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7403
7404		if (with_fdi) {
7405			lpt_reset_fdi_mphy(dev_priv);
7406			lpt_program_fdi_mphy(dev_priv);
7407		}
7408	}
7409
7410	reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7411	       SBI_GEN0 : SBI_DBUFF0;
7412	tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7413	tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7414	intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7415
7416	mutex_unlock(&dev_priv->dpio_lock);
7417}
7418
7419/* Sequence to disable CLKOUT_DP */
7420static void lpt_disable_clkout_dp(struct drm_device *dev)
7421{
7422	struct drm_i915_private *dev_priv = dev->dev_private;
7423	uint32_t reg, tmp;
7424
7425	mutex_lock(&dev_priv->dpio_lock);
7426
7427	reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7428	       SBI_GEN0 : SBI_DBUFF0;
7429	tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7430	tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7431	intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7432
7433	tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7434	if (!(tmp & SBI_SSCCTL_DISABLE)) {
7435		if (!(tmp & SBI_SSCCTL_PATHALT)) {
7436			tmp |= SBI_SSCCTL_PATHALT;
7437			intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7438			udelay(32);
7439		}
7440		tmp |= SBI_SSCCTL_DISABLE;
7441		intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7442	}
7443
7444	mutex_unlock(&dev_priv->dpio_lock);
7445}
7446
7447static void lpt_init_pch_refclk(struct drm_device *dev)
7448{
7449	struct intel_encoder *encoder;
7450	bool has_vga = false;
7451
7452	for_each_intel_encoder(dev, encoder) {
7453		switch (encoder->type) {
7454		case INTEL_OUTPUT_ANALOG:
7455			has_vga = true;
7456			break;
7457		default:
7458			break;
7459		}
7460	}
7461
7462	if (has_vga)
7463		lpt_enable_clkout_dp(dev, true, true);
7464	else
7465		lpt_disable_clkout_dp(dev);
7466}
7467
7468/*
7469 * Initialize reference clocks when the driver loads
7470 */
7471void intel_init_pch_refclk(struct drm_device *dev)
7472{
7473	if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
7474		ironlake_init_pch_refclk(dev);
7475	else if (HAS_PCH_LPT(dev))
7476		lpt_init_pch_refclk(dev);
7477}
7478
7479static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
7480{
7481	struct drm_device *dev = crtc_state->base.crtc->dev;
7482	struct drm_i915_private *dev_priv = dev->dev_private;
7483	struct drm_atomic_state *state = crtc_state->base.state;
7484	struct drm_connector_state *connector_state;
7485	struct intel_encoder *encoder;
7486	int num_connectors = 0, i;
7487	bool is_lvds = false;
7488
7489	for (i = 0; i < state->num_connector; i++) {
7490		if (!state->connectors[i])
7491			continue;
7492
7493		connector_state = state->connector_states[i];
7494		if (connector_state->crtc != crtc_state->base.crtc)
7495			continue;
7496
7497		encoder = to_intel_encoder(connector_state->best_encoder);
7498
7499		switch (encoder->type) {
7500		case INTEL_OUTPUT_LVDS:
7501			is_lvds = true;
7502			break;
7503		default:
7504			break;
7505		}
7506		num_connectors++;
7507	}
7508
7509	if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7510		DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
7511			      dev_priv->vbt.lvds_ssc_freq);
7512		return dev_priv->vbt.lvds_ssc_freq;
7513	}
7514
7515	return 120000;
7516}
7517
7518static void ironlake_set_pipeconf(struct drm_crtc *crtc)
7519{
7520	struct drm_i915_private *dev_priv = crtc->dev->dev_private;
7521	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7522	int pipe = intel_crtc->pipe;
7523	uint32_t val;
7524
7525	val = 0;
7526
7527	switch (intel_crtc->config->pipe_bpp) {
7528	case 18:
7529		val |= PIPECONF_6BPC;
7530		break;
7531	case 24:
7532		val |= PIPECONF_8BPC;
7533		break;
7534	case 30:
7535		val |= PIPECONF_10BPC;
7536		break;
7537	case 36:
7538		val |= PIPECONF_12BPC;
7539		break;
7540	default:
7541		/* Case prevented by intel_choose_pipe_bpp_dither. */
7542		BUG();
7543	}
7544
7545	if (intel_crtc->config->dither)
7546		val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
7547
7548	if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
7549		val |= PIPECONF_INTERLACED_ILK;
7550	else
7551		val |= PIPECONF_PROGRESSIVE;
7552
7553	if (intel_crtc->config->limited_color_range)
7554		val |= PIPECONF_COLOR_RANGE_SELECT;
7555
7556	I915_WRITE(PIPECONF(pipe), val);
7557	POSTING_READ(PIPECONF(pipe));
7558}
7559
7560/*
7561 * Set up the pipe CSC unit.
7562 *
7563 * Currently only full range RGB to limited range RGB conversion
7564 * is supported, but eventually this should handle various
7565 * RGB<->YCbCr scenarios as well.
7566 */
7567static void intel_set_pipe_csc(struct drm_crtc *crtc)
7568{
7569	struct drm_device *dev = crtc->dev;
7570	struct drm_i915_private *dev_priv = dev->dev_private;
7571	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7572	int pipe = intel_crtc->pipe;
7573	uint16_t coeff = 0x7800; /* 1.0 */
7574
7575	/*
7576	 * TODO: Check what kind of values actually come out of the pipe
7577	 * with these coeff/postoff values and adjust to get the best
7578	 * accuracy. Perhaps we even need to take the bpc value into
7579	 * consideration.
7580	 */
7581
7582	if (intel_crtc->config->limited_color_range)
7583		coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
7584
7585	/*
7586	 * GY/GU and RY/RU should be the other way around according
7587	 * to BSpec, but reality doesn't agree. Just set them up in
7588	 * a way that results in the correct picture.
7589	 */
7590	I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
7591	I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
7592
7593	I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
7594	I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
7595
7596	I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
7597	I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
7598
7599	I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
7600	I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
7601	I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
7602
7603	if (INTEL_INFO(dev)->gen > 6) {
7604		uint16_t postoff = 0;
7605
7606		if (intel_crtc->config->limited_color_range)
7607			postoff = (16 * (1 << 12) / 255) & 0x1fff;
7608
7609		I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
7610		I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
7611		I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
7612
7613		I915_WRITE(PIPE_CSC_MODE(pipe), 0);
7614	} else {
7615		uint32_t mode = CSC_MODE_YUV_TO_RGB;
7616
7617		if (intel_crtc->config->limited_color_range)
7618			mode |= CSC_BLACK_SCREEN_OFFSET;
7619
7620		I915_WRITE(PIPE_CSC_MODE(pipe), mode);
7621	}
7622}
7623
7624static void haswell_set_pipeconf(struct drm_crtc *crtc)
7625{
7626	struct drm_device *dev = crtc->dev;
7627	struct drm_i915_private *dev_priv = dev->dev_private;
7628	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7629	enum pipe pipe = intel_crtc->pipe;
7630	enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7631	uint32_t val;
7632
7633	val = 0;
7634
7635	if (IS_HASWELL(dev) && intel_crtc->config->dither)
7636		val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
7637
7638	if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
7639		val |= PIPECONF_INTERLACED_ILK;
7640	else
7641		val |= PIPECONF_PROGRESSIVE;
7642
7643	I915_WRITE(PIPECONF(cpu_transcoder), val);
7644	POSTING_READ(PIPECONF(cpu_transcoder));
7645
7646	I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
7647	POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
7648
7649	if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
7650		val = 0;
7651
7652		switch (intel_crtc->config->pipe_bpp) {
7653		case 18:
7654			val |= PIPEMISC_DITHER_6_BPC;
7655			break;
7656		case 24:
7657			val |= PIPEMISC_DITHER_8_BPC;
7658			break;
7659		case 30:
7660			val |= PIPEMISC_DITHER_10_BPC;
7661			break;
7662		case 36:
7663			val |= PIPEMISC_DITHER_12_BPC;
7664			break;
7665		default:
7666			/* Case prevented by pipe_config_set_bpp. */
7667			BUG();
7668		}
7669
7670		if (intel_crtc->config->dither)
7671			val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
7672
7673		I915_WRITE(PIPEMISC(pipe), val);
7674	}
7675}
7676
7677static bool ironlake_compute_clocks(struct drm_crtc *crtc,
7678				    struct intel_crtc_state *crtc_state,
7679				    intel_clock_t *clock,
7680				    bool *has_reduced_clock,
7681				    intel_clock_t *reduced_clock)
7682{
7683	struct drm_device *dev = crtc->dev;
7684	struct drm_i915_private *dev_priv = dev->dev_private;
7685	int refclk;
7686	const intel_limit_t *limit;
7687	bool ret, is_lvds = false;
7688
7689	is_lvds = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS);
7690
7691	refclk = ironlake_get_refclk(crtc_state);
7692
7693	/*
7694	 * Returns a set of divisors for the desired target clock with the given
7695	 * refclk, or FALSE.  The returned values represent the clock equation:
7696	 * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
7697	 */
7698	limit = intel_limit(crtc_state, refclk);
7699	ret = dev_priv->display.find_dpll(limit, crtc_state,
7700					  crtc_state->port_clock,
7701					  refclk, NULL, clock);
7702	if (!ret)
7703		return false;
7704
7705	if (is_lvds && dev_priv->lvds_downclock_avail) {
7706		/*
7707		 * Ensure we match the reduced clock's P to the target clock.
7708		 * If the clocks don't match, we can't switch the display clock
7709		 * by using the FP0/FP1. In such case we will disable the LVDS
7710		 * downclock feature.
7711		*/
7712		*has_reduced_clock =
7713			dev_priv->display.find_dpll(limit, crtc_state,
7714						    dev_priv->lvds_downclock,
7715						    refclk, clock,
7716						    reduced_clock);
7717	}
7718
7719	return true;
7720}
7721
7722int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
7723{
7724	/*
7725	 * Account for spread spectrum to avoid
7726	 * oversubscribing the link. Max center spread
7727	 * is 2.5%; use 5% for safety's sake.
7728	 */
7729	u32 bps = target_clock * bpp * 21 / 20;
7730	return DIV_ROUND_UP(bps, link_bw * 8);
7731}
7732
7733static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
7734{
7735	return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
7736}
7737
7738static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
7739				      struct intel_crtc_state *crtc_state,
7740				      u32 *fp,
7741				      intel_clock_t *reduced_clock, u32 *fp2)
7742{
7743	struct drm_crtc *crtc = &intel_crtc->base;
7744	struct drm_device *dev = crtc->dev;
7745	struct drm_i915_private *dev_priv = dev->dev_private;
7746	struct drm_atomic_state *state = crtc_state->base.state;
7747	struct drm_connector_state *connector_state;
7748	struct intel_encoder *encoder;
7749	uint32_t dpll;
7750	int factor, num_connectors = 0, i;
7751	bool is_lvds = false, is_sdvo = false;
7752
7753	for (i = 0; i < state->num_connector; i++) {
7754		if (!state->connectors[i])
7755			continue;
7756
7757		connector_state = state->connector_states[i];
7758		if (connector_state->crtc != crtc_state->base.crtc)
7759			continue;
7760
7761		encoder = to_intel_encoder(connector_state->best_encoder);
7762
7763		switch (encoder->type) {
7764		case INTEL_OUTPUT_LVDS:
7765			is_lvds = true;
7766			break;
7767		case INTEL_OUTPUT_SDVO:
7768		case INTEL_OUTPUT_HDMI:
7769			is_sdvo = true;
7770			break;
7771		default:
7772			break;
7773		}
7774
7775		num_connectors++;
7776	}
7777
7778	/* Enable autotuning of the PLL clock (if permissible) */
7779	factor = 21;
7780	if (is_lvds) {
7781		if ((intel_panel_use_ssc(dev_priv) &&
7782		     dev_priv->vbt.lvds_ssc_freq == 100000) ||
7783		    (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
7784			factor = 25;
7785	} else if (crtc_state->sdvo_tv_clock)
7786		factor = 20;
7787
7788	if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
7789		*fp |= FP_CB_TUNE;
7790
7791	if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
7792		*fp2 |= FP_CB_TUNE;
7793
7794	dpll = 0;
7795
7796	if (is_lvds)
7797		dpll |= DPLLB_MODE_LVDS;
7798	else
7799		dpll |= DPLLB_MODE_DAC_SERIAL;
7800
7801	dpll |= (crtc_state->pixel_multiplier - 1)
7802		<< PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
7803
7804	if (is_sdvo)
7805		dpll |= DPLL_SDVO_HIGH_SPEED;
7806	if (crtc_state->has_dp_encoder)
7807		dpll |= DPLL_SDVO_HIGH_SPEED;
7808
7809	/* compute bitmask from p1 value */
7810	dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7811	/* also FPA1 */
7812	dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7813
7814	switch (crtc_state->dpll.p2) {
7815	case 5:
7816		dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7817		break;
7818	case 7:
7819		dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7820		break;
7821	case 10:
7822		dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7823		break;
7824	case 14:
7825		dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7826		break;
7827	}
7828
7829	if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7830		dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7831	else
7832		dpll |= PLL_REF_INPUT_DREFCLK;
7833
7834	return dpll | DPLL_VCO_ENABLE;
7835}
7836
7837static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
7838				       struct intel_crtc_state *crtc_state)
7839{
7840	struct drm_device *dev = crtc->base.dev;
7841	intel_clock_t clock, reduced_clock;
7842	u32 dpll = 0, fp = 0, fp2 = 0;
7843	bool ok, has_reduced_clock = false;
7844	bool is_lvds = false;
7845	struct intel_shared_dpll *pll;
7846
7847	is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
7848
7849	WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
7850	     "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
7851
7852	ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
7853				     &has_reduced_clock, &reduced_clock);
7854	if (!ok && !crtc_state->clock_set) {
7855		DRM_ERROR("Couldn't find PLL settings for mode!\n");
7856		return -EINVAL;
7857	}
7858	/* Compat-code for transition, will disappear. */
7859	if (!crtc_state->clock_set) {
7860		crtc_state->dpll.n = clock.n;
7861		crtc_state->dpll.m1 = clock.m1;
7862		crtc_state->dpll.m2 = clock.m2;
7863		crtc_state->dpll.p1 = clock.p1;
7864		crtc_state->dpll.p2 = clock.p2;
7865	}
7866
7867	/* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
7868	if (crtc_state->has_pch_encoder) {
7869		fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7870		if (has_reduced_clock)
7871			fp2 = i9xx_dpll_compute_fp(&reduced_clock);
7872
7873		dpll = ironlake_compute_dpll(crtc, crtc_state,
7874					     &fp, &reduced_clock,
7875					     has_reduced_clock ? &fp2 : NULL);
7876
7877		crtc_state->dpll_hw_state.dpll = dpll;
7878		crtc_state->dpll_hw_state.fp0 = fp;
7879		if (has_reduced_clock)
7880			crtc_state->dpll_hw_state.fp1 = fp2;
7881		else
7882			crtc_state->dpll_hw_state.fp1 = fp;
7883
7884		pll = intel_get_shared_dpll(crtc, crtc_state);
7885		if (pll == NULL) {
7886			DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
7887					 pipe_name(crtc->pipe));
7888			return -EINVAL;
7889		}
7890	}
7891
7892	if (is_lvds && has_reduced_clock)
7893		crtc->lowfreq_avail = true;
7894	else
7895		crtc->lowfreq_avail = false;
7896
7897	return 0;
7898}
7899
7900static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
7901					 struct intel_link_m_n *m_n)
7902{
7903	struct drm_device *dev = crtc->base.dev;
7904	struct drm_i915_private *dev_priv = dev->dev_private;
7905	enum pipe pipe = crtc->pipe;
7906
7907	m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
7908	m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
7909	m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
7910		& ~TU_SIZE_MASK;
7911	m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
7912	m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
7913		    & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7914}
7915
7916static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
7917					 enum transcoder transcoder,
7918					 struct intel_link_m_n *m_n,
7919					 struct intel_link_m_n *m2_n2)
7920{
7921	struct drm_device *dev = crtc->base.dev;
7922	struct drm_i915_private *dev_priv = dev->dev_private;
7923	enum pipe pipe = crtc->pipe;
7924
7925	if (INTEL_INFO(dev)->gen >= 5) {
7926		m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
7927		m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
7928		m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
7929			& ~TU_SIZE_MASK;
7930		m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
7931		m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
7932			    & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7933		/* Read M2_N2 registers only for gen < 8 (M2_N2 available for
7934		 * gen < 8) and if DRRS is supported (to make sure the
7935		 * registers are not unnecessarily read).
7936		 */
7937		if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
7938			crtc->config->has_drrs) {
7939			m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
7940			m2_n2->link_n =	I915_READ(PIPE_LINK_N2(transcoder));
7941			m2_n2->gmch_m =	I915_READ(PIPE_DATA_M2(transcoder))
7942					& ~TU_SIZE_MASK;
7943			m2_n2->gmch_n =	I915_READ(PIPE_DATA_N2(transcoder));
7944			m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
7945					& TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7946		}
7947	} else {
7948		m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
7949		m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
7950		m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
7951			& ~TU_SIZE_MASK;
7952		m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
7953		m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
7954			    & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7955	}
7956}
7957
7958void intel_dp_get_m_n(struct intel_crtc *crtc,
7959		      struct intel_crtc_state *pipe_config)
7960{
7961	if (pipe_config->has_pch_encoder)
7962		intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
7963	else
7964		intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7965					     &pipe_config->dp_m_n,
7966					     &pipe_config->dp_m2_n2);
7967}
7968
7969static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
7970					struct intel_crtc_state *pipe_config)
7971{
7972	intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7973				     &pipe_config->fdi_m_n, NULL);
7974}
7975
7976static void skylake_get_pfit_config(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	uint32_t tmp;
7982
7983	tmp = I915_READ(PS_CTL(crtc->pipe));
7984
7985	if (tmp & PS_ENABLE) {
7986		pipe_config->pch_pfit.enabled = true;
7987		pipe_config->pch_pfit.pos = I915_READ(PS_WIN_POS(crtc->pipe));
7988		pipe_config->pch_pfit.size = I915_READ(PS_WIN_SZ(crtc->pipe));
7989	}
7990}
7991
7992static void
7993skylake_get_initial_plane_config(struct intel_crtc *crtc,
7994				 struct intel_initial_plane_config *plane_config)
7995{
7996	struct drm_device *dev = crtc->base.dev;
7997	struct drm_i915_private *dev_priv = dev->dev_private;
7998	u32 val, base, offset, stride_mult, tiling;
7999	int pipe = crtc->pipe;
8000	int fourcc, pixel_format;
8001	unsigned int aligned_height;
8002	struct drm_framebuffer *fb;
8003	struct intel_framebuffer *intel_fb;
8004
8005	intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8006	if (!intel_fb) {
8007		DRM_DEBUG_KMS("failed to alloc fb\n");
8008		return;
8009	}
8010
8011	fb = &intel_fb->base;
8012
8013	val = I915_READ(PLANE_CTL(pipe, 0));
8014	if (!(val & PLANE_CTL_ENABLE))
8015		goto error;
8016
8017	pixel_format = val & PLANE_CTL_FORMAT_MASK;
8018	fourcc = skl_format_to_fourcc(pixel_format,
8019				      val & PLANE_CTL_ORDER_RGBX,
8020				      val & PLANE_CTL_ALPHA_MASK);
8021	fb->pixel_format = fourcc;
8022	fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8023
8024	tiling = val & PLANE_CTL_TILED_MASK;
8025	switch (tiling) {
8026	case PLANE_CTL_TILED_LINEAR:
8027		fb->modifier[0] = DRM_FORMAT_MOD_NONE;
8028		break;
8029	case PLANE_CTL_TILED_X:
8030		plane_config->tiling = I915_TILING_X;
8031		fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8032		break;
8033	case PLANE_CTL_TILED_Y:
8034		fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
8035		break;
8036	case PLANE_CTL_TILED_YF:
8037		fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
8038		break;
8039	default:
8040		MISSING_CASE(tiling);
8041		goto error;
8042	}
8043
8044	base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
8045	plane_config->base = base;
8046
8047	offset = I915_READ(PLANE_OFFSET(pipe, 0));
8048
8049	val = I915_READ(PLANE_SIZE(pipe, 0));
8050	fb->height = ((val >> 16) & 0xfff) + 1;
8051	fb->width = ((val >> 0) & 0x1fff) + 1;
8052
8053	val = I915_READ(PLANE_STRIDE(pipe, 0));
8054	stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
8055						fb->pixel_format);
8056	fb->pitches[0] = (val & 0x3ff) * stride_mult;
8057
8058	aligned_height = intel_fb_align_height(dev, fb->height,
8059					       fb->pixel_format,
8060					       fb->modifier[0]);
8061
8062	plane_config->size = fb->pitches[0] * aligned_height;
8063
8064	DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8065		      pipe_name(pipe), fb->width, fb->height,
8066		      fb->bits_per_pixel, base, fb->pitches[0],
8067		      plane_config->size);
8068
8069	plane_config->fb = intel_fb;
8070	return;
8071
8072error:
8073	kfree(fb);
8074}
8075
8076static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8077				     struct intel_crtc_state *pipe_config)
8078{
8079	struct drm_device *dev = crtc->base.dev;
8080	struct drm_i915_private *dev_priv = dev->dev_private;
8081	uint32_t tmp;
8082
8083	tmp = I915_READ(PF_CTL(crtc->pipe));
8084
8085	if (tmp & PF_ENABLE) {
8086		pipe_config->pch_pfit.enabled = true;
8087		pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8088		pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8089
8090		/* We currently do not free assignements of panel fitters on
8091		 * ivb/hsw (since we don't use the higher upscaling modes which
8092		 * differentiates them) so just WARN about this case for now. */
8093		if (IS_GEN7(dev)) {
8094			WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8095				PF_PIPE_SEL_IVB(crtc->pipe));
8096		}
8097	}
8098}
8099
8100static void
8101ironlake_get_initial_plane_config(struct intel_crtc *crtc,
8102				  struct intel_initial_plane_config *plane_config)
8103{
8104	struct drm_device *dev = crtc->base.dev;
8105	struct drm_i915_private *dev_priv = dev->dev_private;
8106	u32 val, base, offset;
8107	int pipe = crtc->pipe;
8108	int fourcc, pixel_format;
8109	unsigned int aligned_height;
8110	struct drm_framebuffer *fb;
8111	struct intel_framebuffer *intel_fb;
8112
8113	val = I915_READ(DSPCNTR(pipe));
8114	if (!(val & DISPLAY_PLANE_ENABLE))
8115		return;
8116
8117	intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8118	if (!intel_fb) {
8119		DRM_DEBUG_KMS("failed to alloc fb\n");
8120		return;
8121	}
8122
8123	fb = &intel_fb->base;
8124
8125	if (INTEL_INFO(dev)->gen >= 4) {
8126		if (val & DISPPLANE_TILED) {
8127			plane_config->tiling = I915_TILING_X;
8128			fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8129		}
8130	}
8131
8132	pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8133	fourcc = i9xx_format_to_fourcc(pixel_format);
8134	fb->pixel_format = fourcc;
8135	fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8136
8137	base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
8138	if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
8139		offset = I915_READ(DSPOFFSET(pipe));
8140	} else {
8141		if (plane_config->tiling)
8142			offset = I915_READ(DSPTILEOFF(pipe));
8143		else
8144			offset = I915_READ(DSPLINOFF(pipe));
8145	}
8146	plane_config->base = base;
8147
8148	val = I915_READ(PIPESRC(pipe));
8149	fb->width = ((val >> 16) & 0xfff) + 1;
8150	fb->height = ((val >> 0) & 0xfff) + 1;
8151
8152	val = I915_READ(DSPSTRIDE(pipe));
8153	fb->pitches[0] = val & 0xffffffc0;
8154
8155	aligned_height = intel_fb_align_height(dev, fb->height,
8156					       fb->pixel_format,
8157					       fb->modifier[0]);
8158
8159	plane_config->size = fb->pitches[0] * aligned_height;
8160
8161	DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8162		      pipe_name(pipe), fb->width, fb->height,
8163		      fb->bits_per_pixel, base, fb->pitches[0],
8164		      plane_config->size);
8165
8166	plane_config->fb = intel_fb;
8167}
8168
8169static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8170				     struct intel_crtc_state *pipe_config)
8171{
8172	struct drm_device *dev = crtc->base.dev;
8173	struct drm_i915_private *dev_priv = dev->dev_private;
8174	uint32_t tmp;
8175
8176	if (!intel_display_power_is_enabled(dev_priv,
8177					    POWER_DOMAIN_PIPE(crtc->pipe)))
8178		return false;
8179
8180	pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8181	pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8182
8183	tmp = I915_READ(PIPECONF(crtc->pipe));
8184	if (!(tmp & PIPECONF_ENABLE))
8185		return false;
8186
8187	switch (tmp & PIPECONF_BPC_MASK) {
8188	case PIPECONF_6BPC:
8189		pipe_config->pipe_bpp = 18;
8190		break;
8191	case PIPECONF_8BPC:
8192		pipe_config->pipe_bpp = 24;
8193		break;
8194	case PIPECONF_10BPC:
8195		pipe_config->pipe_bpp = 30;
8196		break;
8197	case PIPECONF_12BPC:
8198		pipe_config->pipe_bpp = 36;
8199		break;
8200	default:
8201		break;
8202	}
8203
8204	if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8205		pipe_config->limited_color_range = true;
8206
8207	if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8208		struct intel_shared_dpll *pll;
8209
8210		pipe_config->has_pch_encoder = true;
8211
8212		tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8213		pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8214					  FDI_DP_PORT_WIDTH_SHIFT) + 1;
8215
8216		ironlake_get_fdi_m_n_config(crtc, pipe_config);
8217
8218		if (HAS_PCH_IBX(dev_priv->dev)) {
8219			pipe_config->shared_dpll =
8220				(enum intel_dpll_id) crtc->pipe;
8221		} else {
8222			tmp = I915_READ(PCH_DPLL_SEL);
8223			if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8224				pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
8225			else
8226				pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
8227		}
8228
8229		pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
8230
8231		WARN_ON(!pll->get_hw_state(dev_priv, pll,
8232					   &pipe_config->dpll_hw_state));
8233
8234		tmp = pipe_config->dpll_hw_state.dpll;
8235		pipe_config->pixel_multiplier =
8236			((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8237			 >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8238
8239		ironlake_pch_clock_get(crtc, pipe_config);
8240	} else {
8241		pipe_config->pixel_multiplier = 1;
8242	}
8243
8244	intel_get_pipe_timings(crtc, pipe_config);
8245
8246	ironlake_get_pfit_config(crtc, pipe_config);
8247
8248	return true;
8249}
8250
8251static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8252{
8253	struct drm_device *dev = dev_priv->dev;
8254	struct intel_crtc *crtc;
8255
8256	for_each_intel_crtc(dev, crtc)
8257		I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8258		     pipe_name(crtc->pipe));
8259
8260	I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
8261	I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8262	I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8263	I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8264	I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
8265	I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8266	     "CPU PWM1 enabled\n");
8267	if (IS_HASWELL(dev))
8268		I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8269		     "CPU PWM2 enabled\n");
8270	I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8271	     "PCH PWM1 enabled\n");
8272	I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8273	     "Utility pin enabled\n");
8274	I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8275
8276	/*
8277	 * In theory we can still leave IRQs enabled, as long as only the HPD
8278	 * interrupts remain enabled. We used to check for that, but since it's
8279	 * gen-specific and since we only disable LCPLL after we fully disable
8280	 * the interrupts, the check below should be enough.
8281	 */
8282	I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8283}
8284
8285static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8286{
8287	struct drm_device *dev = dev_priv->dev;
8288
8289	if (IS_HASWELL(dev))
8290		return I915_READ(D_COMP_HSW);
8291	else
8292		return I915_READ(D_COMP_BDW);
8293}
8294
8295static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8296{
8297	struct drm_device *dev = dev_priv->dev;
8298
8299	if (IS_HASWELL(dev)) {
8300		mutex_lock(&dev_priv->rps.hw_lock);
8301		if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8302					    val))
8303			DRM_ERROR("Failed to write to D_COMP\n");
8304		mutex_unlock(&dev_priv->rps.hw_lock);
8305	} else {
8306		I915_WRITE(D_COMP_BDW, val);
8307		POSTING_READ(D_COMP_BDW);
8308	}
8309}
8310
8311/*
8312 * This function implements pieces of two sequences from BSpec:
8313 * - Sequence for display software to disable LCPLL
8314 * - Sequence for display software to allow package C8+
8315 * The steps implemented here are just the steps that actually touch the LCPLL
8316 * register. Callers should take care of disabling all the display engine
8317 * functions, doing the mode unset, fixing interrupts, etc.
8318 */
8319static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8320			      bool switch_to_fclk, bool allow_power_down)
8321{
8322	uint32_t val;
8323
8324	assert_can_disable_lcpll(dev_priv);
8325
8326	val = I915_READ(LCPLL_CTL);
8327
8328	if (switch_to_fclk) {
8329		val |= LCPLL_CD_SOURCE_FCLK;
8330		I915_WRITE(LCPLL_CTL, val);
8331
8332		if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
8333				       LCPLL_CD_SOURCE_FCLK_DONE, 1))
8334			DRM_ERROR("Switching to FCLK failed\n");
8335
8336		val = I915_READ(LCPLL_CTL);
8337	}
8338
8339	val |= LCPLL_PLL_DISABLE;
8340	I915_WRITE(LCPLL_CTL, val);
8341	POSTING_READ(LCPLL_CTL);
8342
8343	if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
8344		DRM_ERROR("LCPLL still locked\n");
8345
8346	val = hsw_read_dcomp(dev_priv);
8347	val |= D_COMP_COMP_DISABLE;
8348	hsw_write_dcomp(dev_priv, val);
8349	ndelay(100);
8350
8351	if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8352		     1))
8353		DRM_ERROR("D_COMP RCOMP still in progress\n");
8354
8355	if (allow_power_down) {
8356		val = I915_READ(LCPLL_CTL);
8357		val |= LCPLL_POWER_DOWN_ALLOW;
8358		I915_WRITE(LCPLL_CTL, val);
8359		POSTING_READ(LCPLL_CTL);
8360	}
8361}
8362
8363/*
8364 * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8365 * source.
8366 */
8367static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8368{
8369	uint32_t val;
8370
8371	val = I915_READ(LCPLL_CTL);
8372
8373	if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8374		    LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8375		return;
8376
8377	/*
8378	 * Make sure we're not on PC8 state before disabling PC8, otherwise
8379	 * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8380	 */
8381	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8382
8383	if (val & LCPLL_POWER_DOWN_ALLOW) {
8384		val &= ~LCPLL_POWER_DOWN_ALLOW;
8385		I915_WRITE(LCPLL_CTL, val);
8386		POSTING_READ(LCPLL_CTL);
8387	}
8388
8389	val = hsw_read_dcomp(dev_priv);
8390	val |= D_COMP_COMP_FORCE;
8391	val &= ~D_COMP_COMP_DISABLE;
8392	hsw_write_dcomp(dev_priv, val);
8393
8394	val = I915_READ(LCPLL_CTL);
8395	val &= ~LCPLL_PLL_DISABLE;
8396	I915_WRITE(LCPLL_CTL, val);
8397
8398	if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
8399		DRM_ERROR("LCPLL not locked yet\n");
8400
8401	if (val & LCPLL_CD_SOURCE_FCLK) {
8402		val = I915_READ(LCPLL_CTL);
8403		val &= ~LCPLL_CD_SOURCE_FCLK;
8404		I915_WRITE(LCPLL_CTL, val);
8405
8406		if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
8407					LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8408			DRM_ERROR("Switching back to LCPLL failed\n");
8409	}
8410
8411	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8412}
8413
8414/*
8415 * Package states C8 and deeper are really deep PC states that can only be
8416 * reached when all the devices on the system allow it, so even if the graphics
8417 * device allows PC8+, it doesn't mean the system will actually get to these
8418 * states. Our driver only allows PC8+ when going into runtime PM.
8419 *
8420 * The requirements for PC8+ are that all the outputs are disabled, the power
8421 * well is disabled and most interrupts are disabled, and these are also
8422 * requirements for runtime PM. When these conditions are met, we manually do
8423 * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8424 * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8425 * hang the machine.
8426 *
8427 * When we really reach PC8 or deeper states (not just when we allow it) we lose
8428 * the state of some registers, so when we come back from PC8+ we need to
8429 * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8430 * need to take care of the registers kept by RC6. Notice that this happens even
8431 * if we don't put the device in PCI D3 state (which is what currently happens
8432 * because of the runtime PM support).
8433 *
8434 * For more, read "Display Sequences for Package C8" on the hardware
8435 * documentation.
8436 */
8437void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8438{
8439	struct drm_device *dev = dev_priv->dev;
8440	uint32_t val;
8441
8442	DRM_DEBUG_KMS("Enabling package C8+\n");
8443
8444	if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
8445		val = I915_READ(SOUTH_DSPCLK_GATE_D);
8446		val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8447		I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8448	}
8449
8450	lpt_disable_clkout_dp(dev);
8451	hsw_disable_lcpll(dev_priv, true, true);
8452}
8453
8454void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8455{
8456	struct drm_device *dev = dev_priv->dev;
8457	uint32_t val;
8458
8459	DRM_DEBUG_KMS("Disabling package C8+\n");
8460
8461	hsw_restore_lcpll(dev_priv);
8462	lpt_init_pch_refclk(dev);
8463
8464	if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
8465		val = I915_READ(SOUTH_DSPCLK_GATE_D);
8466		val |= PCH_LP_PARTITION_LEVEL_DISABLE;
8467		I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8468	}
8469
8470	intel_prepare_ddi(dev);
8471}
8472
8473static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
8474				      struct intel_crtc_state *crtc_state)
8475{
8476	if (!intel_ddi_pll_select(crtc, crtc_state))
8477		return -EINVAL;
8478
8479	crtc->lowfreq_avail = false;
8480
8481	return 0;
8482}
8483
8484static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
8485				enum port port,
8486				struct intel_crtc_state *pipe_config)
8487{
8488	u32 temp, dpll_ctl1;
8489
8490	temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
8491	pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
8492
8493	switch (pipe_config->ddi_pll_sel) {
8494	case SKL_DPLL0:
8495		/*
8496		 * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
8497		 * of the shared DPLL framework and thus needs to be read out
8498		 * separately
8499		 */
8500		dpll_ctl1 = I915_READ(DPLL_CTRL1);
8501		pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
8502		break;
8503	case SKL_DPLL1:
8504		pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
8505		break;
8506	case SKL_DPLL2:
8507		pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
8508		break;
8509	case SKL_DPLL3:
8510		pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
8511		break;
8512	}
8513}
8514
8515static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
8516				enum port port,
8517				struct intel_crtc_state *pipe_config)
8518{
8519	pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
8520
8521	switch (pipe_config->ddi_pll_sel) {
8522	case PORT_CLK_SEL_WRPLL1:
8523		pipe_config->shared_dpll = DPLL_ID_WRPLL1;
8524		break;
8525	case PORT_CLK_SEL_WRPLL2:
8526		pipe_config->shared_dpll = DPLL_ID_WRPLL2;
8527		break;
8528	}
8529}
8530
8531static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
8532				       struct intel_crtc_state *pipe_config)
8533{
8534	struct drm_device *dev = crtc->base.dev;
8535	struct drm_i915_private *dev_priv = dev->dev_private;
8536	struct intel_shared_dpll *pll;
8537	enum port port;
8538	uint32_t tmp;
8539
8540	tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
8541
8542	port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
8543
8544	if (IS_SKYLAKE(dev))
8545		skylake_get_ddi_pll(dev_priv, port, pipe_config);
8546	else
8547		haswell_get_ddi_pll(dev_priv, port, pipe_config);
8548
8549	if (pipe_config->shared_dpll >= 0) {
8550		pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
8551
8552		WARN_ON(!pll->get_hw_state(dev_priv, pll,
8553					   &pipe_config->dpll_hw_state));
8554	}
8555
8556	/*
8557	 * Haswell has only FDI/PCH transcoder A. It is which is connected to
8558	 * DDI E. So just check whether this pipe is wired to DDI E and whether
8559	 * the PCH transcoder is on.
8560	 */
8561	if (INTEL_INFO(dev)->gen < 9 &&
8562	    (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
8563		pipe_config->has_pch_encoder = true;
8564
8565		tmp = I915_READ(FDI_RX_CTL(PIPE_A));
8566		pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8567					  FDI_DP_PORT_WIDTH_SHIFT) + 1;
8568
8569		ironlake_get_fdi_m_n_config(crtc, pipe_config);
8570	}
8571}
8572
8573static bool haswell_get_pipe_config(struct intel_crtc *crtc,
8574				    struct intel_crtc_state *pipe_config)
8575{
8576	struct drm_device *dev = crtc->base.dev;
8577	struct drm_i915_private *dev_priv = dev->dev_private;
8578	enum intel_display_power_domain pfit_domain;
8579	uint32_t tmp;
8580
8581	if (!intel_display_power_is_enabled(dev_priv,
8582					 POWER_DOMAIN_PIPE(crtc->pipe)))
8583		return false;
8584
8585	pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8586	pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8587
8588	tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
8589	if (tmp & TRANS_DDI_FUNC_ENABLE) {
8590		enum pipe trans_edp_pipe;
8591		switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
8592		default:
8593			WARN(1, "unknown pipe linked to edp transcoder\n");
8594		case TRANS_DDI_EDP_INPUT_A_ONOFF:
8595		case TRANS_DDI_EDP_INPUT_A_ON:
8596			trans_edp_pipe = PIPE_A;
8597			break;
8598		case TRANS_DDI_EDP_INPUT_B_ONOFF:
8599			trans_edp_pipe = PIPE_B;
8600			break;
8601		case TRANS_DDI_EDP_INPUT_C_ONOFF:
8602			trans_edp_pipe = PIPE_C;
8603			break;
8604		}
8605
8606		if (trans_edp_pipe == crtc->pipe)
8607			pipe_config->cpu_transcoder = TRANSCODER_EDP;
8608	}
8609
8610	if (!intel_display_power_is_enabled(dev_priv,
8611			POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
8612		return false;
8613
8614	tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
8615	if (!(tmp & PIPECONF_ENABLE))
8616		return false;
8617
8618	haswell_get_ddi_port_state(crtc, pipe_config);
8619
8620	intel_get_pipe_timings(crtc, pipe_config);
8621
8622	pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
8623	if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
8624		if (IS_SKYLAKE(dev))
8625			skylake_get_pfit_config(crtc, pipe_config);
8626		else
8627			ironlake_get_pfit_config(crtc, pipe_config);
8628	}
8629
8630	if (IS_HASWELL(dev))
8631		pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
8632			(I915_READ(IPS_CTL) & IPS_ENABLE);
8633
8634	if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
8635		pipe_config->pixel_multiplier =
8636			I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
8637	} else {
8638		pipe_config->pixel_multiplier = 1;
8639	}
8640
8641	return true;
8642}
8643
8644static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
8645{
8646	struct drm_device *dev = crtc->dev;
8647	struct drm_i915_private *dev_priv = dev->dev_private;
8648	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8649	uint32_t cntl = 0, size = 0;
8650
8651	if (base) {
8652		unsigned int width = intel_crtc->base.cursor->state->crtc_w;
8653		unsigned int height = intel_crtc->base.cursor->state->crtc_h;
8654		unsigned int stride = roundup_pow_of_two(width) * 4;
8655
8656		switch (stride) {
8657		default:
8658			WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
8659				  width, stride);
8660			stride = 256;
8661			/* fallthrough */
8662		case 256:
8663		case 512:
8664		case 1024:
8665		case 2048:
8666			break;
8667		}
8668
8669		cntl |= CURSOR_ENABLE |
8670			CURSOR_GAMMA_ENABLE |
8671			CURSOR_FORMAT_ARGB |
8672			CURSOR_STRIDE(stride);
8673
8674		size = (height << 12) | width;
8675	}
8676
8677	if (intel_crtc->cursor_cntl != 0 &&
8678	    (intel_crtc->cursor_base != base ||
8679	     intel_crtc->cursor_size != size ||
8680	     intel_crtc->cursor_cntl != cntl)) {
8681		/* On these chipsets we can only modify the base/size/stride
8682		 * whilst the cursor is disabled.
8683		 */
8684		I915_WRITE(_CURACNTR, 0);
8685		POSTING_READ(_CURACNTR);
8686		intel_crtc->cursor_cntl = 0;
8687	}
8688
8689	if (intel_crtc->cursor_base != base) {
8690		I915_WRITE(_CURABASE, base);
8691		intel_crtc->cursor_base = base;
8692	}
8693
8694	if (intel_crtc->cursor_size != size) {
8695		I915_WRITE(CURSIZE, size);
8696		intel_crtc->cursor_size = size;
8697	}
8698
8699	if (intel_crtc->cursor_cntl != cntl) {
8700		I915_WRITE(_CURACNTR, cntl);
8701		POSTING_READ(_CURACNTR);
8702		intel_crtc->cursor_cntl = cntl;
8703	}
8704}
8705
8706static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
8707{
8708	struct drm_device *dev = crtc->dev;
8709	struct drm_i915_private *dev_priv = dev->dev_private;
8710	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8711	int pipe = intel_crtc->pipe;
8712	uint32_t cntl;
8713
8714	cntl = 0;
8715	if (base) {
8716		cntl = MCURSOR_GAMMA_ENABLE;
8717		switch (intel_crtc->base.cursor->state->crtc_w) {
8718			case 64:
8719				cntl |= CURSOR_MODE_64_ARGB_AX;
8720				break;
8721			case 128:
8722				cntl |= CURSOR_MODE_128_ARGB_AX;
8723				break;
8724			case 256:
8725				cntl |= CURSOR_MODE_256_ARGB_AX;
8726				break;
8727			default:
8728				MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
8729				return;
8730		}
8731		cntl |= pipe << 28; /* Connect to correct pipe */
8732
8733		if (IS_HASWELL(dev) || IS_BROADWELL(dev))
8734			cntl |= CURSOR_PIPE_CSC_ENABLE;
8735	}
8736
8737	if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
8738		cntl |= CURSOR_ROTATE_180;
8739
8740	if (intel_crtc->cursor_cntl != cntl) {
8741		I915_WRITE(CURCNTR(pipe), cntl);
8742		POSTING_READ(CURCNTR(pipe));
8743		intel_crtc->cursor_cntl = cntl;
8744	}
8745
8746	/* and commit changes on next vblank */
8747	I915_WRITE(CURBASE(pipe), base);
8748	POSTING_READ(CURBASE(pipe));
8749
8750	intel_crtc->cursor_base = base;
8751}
8752
8753/* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
8754static void intel_crtc_update_cursor(struct drm_crtc *crtc,
8755				     bool on)
8756{
8757	struct drm_device *dev = crtc->dev;
8758	struct drm_i915_private *dev_priv = dev->dev_private;
8759	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8760	int pipe = intel_crtc->pipe;
8761	int x = crtc->cursor_x;
8762	int y = crtc->cursor_y;
8763	u32 base = 0, pos = 0;
8764
8765	if (on)
8766		base = intel_crtc->cursor_addr;
8767
8768	if (x >= intel_crtc->config->pipe_src_w)
8769		base = 0;
8770
8771	if (y >= intel_crtc->config->pipe_src_h)
8772		base = 0;
8773
8774	if (x < 0) {
8775		if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
8776			base = 0;
8777
8778		pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
8779		x = -x;
8780	}
8781	pos |= x << CURSOR_X_SHIFT;
8782
8783	if (y < 0) {
8784		if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
8785			base = 0;
8786
8787		pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
8788		y = -y;
8789	}
8790	pos |= y << CURSOR_Y_SHIFT;
8791
8792	if (base == 0 && intel_crtc->cursor_base == 0)
8793		return;
8794
8795	I915_WRITE(CURPOS(pipe), pos);
8796
8797	/* ILK+ do this automagically */
8798	if (HAS_GMCH_DISPLAY(dev) &&
8799	    crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
8800		base += (intel_crtc->base.cursor->state->crtc_h *
8801			intel_crtc->base.cursor->state->crtc_w - 1) * 4;
8802	}
8803
8804	if (IS_845G(dev) || IS_I865G(dev))
8805		i845_update_cursor(crtc, base);
8806	else
8807		i9xx_update_cursor(crtc, base);
8808}
8809
8810static bool cursor_size_ok(struct drm_device *dev,
8811			   uint32_t width, uint32_t height)
8812{
8813	if (width == 0 || height == 0)
8814		return false;
8815
8816	/*
8817	 * 845g/865g are special in that they are only limited by
8818	 * the width of their cursors, the height is arbitrary up to
8819	 * the precision of the register. Everything else requires
8820	 * square cursors, limited to a few power-of-two sizes.
8821	 */
8822	if (IS_845G(dev) || IS_I865G(dev)) {
8823		if ((width & 63) != 0)
8824			return false;
8825
8826		if (width > (IS_845G(dev) ? 64 : 512))
8827			return false;
8828
8829		if (height > 1023)
8830			return false;
8831	} else {
8832		switch (width | height) {
8833		case 256:
8834		case 128:
8835			if (IS_GEN2(dev))
8836				return false;
8837		case 64:
8838			break;
8839		default:
8840			return false;
8841		}
8842	}
8843
8844	return true;
8845}
8846
8847static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
8848				 u16 *blue, uint32_t start, uint32_t size)
8849{
8850	int end = (start + size > 256) ? 256 : start + size, i;
8851	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8852
8853	for (i = start; i < end; i++) {
8854		intel_crtc->lut_r[i] = red[i] >> 8;
8855		intel_crtc->lut_g[i] = green[i] >> 8;
8856		intel_crtc->lut_b[i] = blue[i] >> 8;
8857	}
8858
8859	intel_crtc_load_lut(crtc);
8860}
8861
8862/* VESA 640x480x72Hz mode to set on the pipe */
8863static struct drm_display_mode load_detect_mode = {
8864	DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
8865		 704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
8866};
8867
8868struct drm_framebuffer *
8869__intel_framebuffer_create(struct drm_device *dev,
8870			   struct drm_mode_fb_cmd2 *mode_cmd,
8871			   struct drm_i915_gem_object *obj)
8872{
8873	struct intel_framebuffer *intel_fb;
8874	int ret;
8875
8876	intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8877	if (!intel_fb) {
8878		drm_gem_object_unreference(&obj->base);
8879		return ERR_PTR(-ENOMEM);
8880	}
8881
8882	ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
8883	if (ret)
8884		goto err;
8885
8886	return &intel_fb->base;
8887err:
8888	drm_gem_object_unreference(&obj->base);
8889	kfree(intel_fb);
8890
8891	return ERR_PTR(ret);
8892}
8893
8894static struct drm_framebuffer *
8895intel_framebuffer_create(struct drm_device *dev,
8896			 struct drm_mode_fb_cmd2 *mode_cmd,
8897			 struct drm_i915_gem_object *obj)
8898{
8899	struct drm_framebuffer *fb;
8900	int ret;
8901
8902	ret = i915_mutex_lock_interruptible(dev);
8903	if (ret)
8904		return ERR_PTR(ret);
8905	fb = __intel_framebuffer_create(dev, mode_cmd, obj);
8906	mutex_unlock(&dev->struct_mutex);
8907
8908	return fb;
8909}
8910
8911static u32
8912intel_framebuffer_pitch_for_width(int width, int bpp)
8913{
8914	u32 pitch = DIV_ROUND_UP(width * bpp, 8);
8915	return ALIGN(pitch, 64);
8916}
8917
8918static u32
8919intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
8920{
8921	u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
8922	return PAGE_ALIGN(pitch * mode->vdisplay);
8923}
8924
8925static struct drm_framebuffer *
8926intel_framebuffer_create_for_mode(struct drm_device *dev,
8927				  struct drm_display_mode *mode,
8928				  int depth, int bpp)
8929{
8930	struct drm_i915_gem_object *obj;
8931	struct drm_mode_fb_cmd2 mode_cmd = { 0 };
8932
8933	obj = i915_gem_alloc_object(dev,
8934				    intel_framebuffer_size_for_mode(mode, bpp));
8935	if (obj == NULL)
8936		return ERR_PTR(-ENOMEM);
8937
8938	mode_cmd.width = mode->hdisplay;
8939	mode_cmd.height = mode->vdisplay;
8940	mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
8941								bpp);
8942	mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
8943
8944	return intel_framebuffer_create(dev, &mode_cmd, obj);
8945}
8946
8947static struct drm_framebuffer *
8948mode_fits_in_fbdev(struct drm_device *dev,
8949		   struct drm_display_mode *mode)
8950{
8951#ifdef CONFIG_DRM_I915_FBDEV
8952	struct drm_i915_private *dev_priv = dev->dev_private;
8953	struct drm_i915_gem_object *obj;
8954	struct drm_framebuffer *fb;
8955
8956	if (!dev_priv->fbdev)
8957		return NULL;
8958
8959	if (!dev_priv->fbdev->fb)
8960		return NULL;
8961
8962	obj = dev_priv->fbdev->fb->obj;
8963	BUG_ON(!obj);
8964
8965	fb = &dev_priv->fbdev->fb->base;
8966	if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
8967							       fb->bits_per_pixel))
8968		return NULL;
8969
8970	if (obj->base.size < mode->vdisplay * fb->pitches[0])
8971		return NULL;
8972
8973	return fb;
8974#else
8975	return NULL;
8976#endif
8977}
8978
8979bool intel_get_load_detect_pipe(struct drm_connector *connector,
8980				struct drm_display_mode *mode,
8981				struct intel_load_detect_pipe *old,
8982				struct drm_modeset_acquire_ctx *ctx)
8983{
8984	struct intel_crtc *intel_crtc;
8985	struct intel_encoder *intel_encoder =
8986		intel_attached_encoder(connector);
8987	struct drm_crtc *possible_crtc;
8988	struct drm_encoder *encoder = &intel_encoder->base;
8989	struct drm_crtc *crtc = NULL;
8990	struct drm_device *dev = encoder->dev;
8991	struct drm_framebuffer *fb;
8992	struct drm_mode_config *config = &dev->mode_config;
8993	struct drm_atomic_state *state = NULL;
8994	struct drm_connector_state *connector_state;
8995	int ret, i = -1;
8996
8997	DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8998		      connector->base.id, connector->name,
8999		      encoder->base.id, encoder->name);
9000
9001retry:
9002	ret = drm_modeset_lock(&config->connection_mutex, ctx);
9003	if (ret)
9004		goto fail_unlock;
9005
9006	/*
9007	 * Algorithm gets a little messy:
9008	 *
9009	 *   - if the connector already has an assigned crtc, use it (but make
9010	 *     sure it's on first)
9011	 *
9012	 *   - try to find the first unused crtc that can drive this connector,
9013	 *     and use that if we find one
9014	 */
9015
9016	/* See if we already have a CRTC for this connector */
9017	if (encoder->crtc) {
9018		crtc = encoder->crtc;
9019
9020		ret = drm_modeset_lock(&crtc->mutex, ctx);
9021		if (ret)
9022			goto fail_unlock;
9023		ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9024		if (ret)
9025			goto fail_unlock;
9026
9027		old->dpms_mode = connector->dpms;
9028		old->load_detect_temp = false;
9029
9030		/* Make sure the crtc and connector are running */
9031		if (connector->dpms != DRM_MODE_DPMS_ON)
9032			connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
9033
9034		return true;
9035	}
9036
9037	/* Find an unused one (if possible) */
9038	for_each_crtc(dev, possible_crtc) {
9039		i++;
9040		if (!(encoder->possible_crtcs & (1 << i)))
9041			continue;
9042		if (possible_crtc->state->enable)
9043			continue;
9044		/* This can occur when applying the pipe A quirk on resume. */
9045		if (to_intel_crtc(possible_crtc)->new_enabled)
9046			continue;
9047
9048		crtc = possible_crtc;
9049		break;
9050	}
9051
9052	/*
9053	 * If we didn't find an unused CRTC, don't use any.
9054	 */
9055	if (!crtc) {
9056		DRM_DEBUG_KMS("no pipe available for load-detect\n");
9057		goto fail_unlock;
9058	}
9059
9060	ret = drm_modeset_lock(&crtc->mutex, ctx);
9061	if (ret)
9062		goto fail_unlock;
9063	ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9064	if (ret)
9065		goto fail_unlock;
9066	intel_encoder->new_crtc = to_intel_crtc(crtc);
9067	to_intel_connector(connector)->new_encoder = intel_encoder;
9068
9069	intel_crtc = to_intel_crtc(crtc);
9070	intel_crtc->new_enabled = true;
9071	intel_crtc->new_config = intel_crtc->config;
9072	old->dpms_mode = connector->dpms;
9073	old->load_detect_temp = true;
9074	old->release_fb = NULL;
9075
9076	state = drm_atomic_state_alloc(dev);
9077	if (!state)
9078		return false;
9079
9080	state->acquire_ctx = ctx;
9081
9082	connector_state = drm_atomic_get_connector_state(state, connector);
9083	if (IS_ERR(connector_state)) {
9084		ret = PTR_ERR(connector_state);
9085		goto fail;
9086	}
9087
9088	connector_state->crtc = crtc;
9089	connector_state->best_encoder = &intel_encoder->base;
9090
9091	if (!mode)
9092		mode = &load_detect_mode;
9093
9094	/* We need a framebuffer large enough to accommodate all accesses
9095	 * that the plane may generate whilst we perform load detection.
9096	 * We can not rely on the fbcon either being present (we get called
9097	 * during its initialisation to detect all boot displays, or it may
9098	 * not even exist) or that it is large enough to satisfy the
9099	 * requested mode.
9100	 */
9101	fb = mode_fits_in_fbdev(dev, mode);
9102	if (fb == NULL) {
9103		DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
9104		fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
9105		old->release_fb = fb;
9106	} else
9107		DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
9108	if (IS_ERR(fb)) {
9109		DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
9110		goto fail;
9111	}
9112
9113	if (intel_set_mode(crtc, mode, 0, 0, fb, state)) {
9114		DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9115		if (old->release_fb)
9116			old->release_fb->funcs->destroy(old->release_fb);
9117		goto fail;
9118	}
9119	crtc->primary->crtc = crtc;
9120
9121	/* let the connector get through one full cycle before testing */
9122	intel_wait_for_vblank(dev, intel_crtc->pipe);
9123	return true;
9124
9125 fail:
9126	intel_crtc->new_enabled = crtc->state->enable;
9127	if (intel_crtc->new_enabled)
9128		intel_crtc->new_config = intel_crtc->config;
9129	else
9130		intel_crtc->new_config = NULL;
9131fail_unlock:
9132	if (state) {
9133		drm_atomic_state_free(state);
9134		state = NULL;
9135	}
9136
9137	if (ret == -EDEADLK) {
9138		drm_modeset_backoff(ctx);
9139		goto retry;
9140	}
9141
9142	return false;
9143}
9144
9145void intel_release_load_detect_pipe(struct drm_connector *connector,
9146				    struct intel_load_detect_pipe *old,
9147				    struct drm_modeset_acquire_ctx *ctx)
9148{
9149	struct drm_device *dev = connector->dev;
9150	struct intel_encoder *intel_encoder =
9151		intel_attached_encoder(connector);
9152	struct drm_encoder *encoder = &intel_encoder->base;
9153	struct drm_crtc *crtc = encoder->crtc;
9154	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9155	struct drm_atomic_state *state;
9156	struct drm_connector_state *connector_state;
9157
9158	DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9159		      connector->base.id, connector->name,
9160		      encoder->base.id, encoder->name);
9161
9162	if (old->load_detect_temp) {
9163		state = drm_atomic_state_alloc(dev);
9164		if (!state)
9165			goto fail;
9166
9167		state->acquire_ctx = ctx;
9168
9169		connector_state = drm_atomic_get_connector_state(state, connector);
9170		if (IS_ERR(connector_state))
9171			goto fail;
9172
9173		to_intel_connector(connector)->new_encoder = NULL;
9174		intel_encoder->new_crtc = NULL;
9175		intel_crtc->new_enabled = false;
9176		intel_crtc->new_config = NULL;
9177
9178		connector_state->best_encoder = NULL;
9179		connector_state->crtc = NULL;
9180
9181		intel_set_mode(crtc, NULL, 0, 0, NULL, state);
9182
9183		drm_atomic_state_free(state);
9184
9185		if (old->release_fb) {
9186			drm_framebuffer_unregister_private(old->release_fb);
9187			drm_framebuffer_unreference(old->release_fb);
9188		}
9189
9190		return;
9191	}
9192
9193	/* Switch crtc and encoder back off if necessary */
9194	if (old->dpms_mode != DRM_MODE_DPMS_ON)
9195		connector->funcs->dpms(connector, old->dpms_mode);
9196
9197	return;
9198fail:
9199	DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
9200	drm_atomic_state_free(state);
9201}
9202
9203static int i9xx_pll_refclk(struct drm_device *dev,
9204			   const struct intel_crtc_state *pipe_config)
9205{
9206	struct drm_i915_private *dev_priv = dev->dev_private;
9207	u32 dpll = pipe_config->dpll_hw_state.dpll;
9208
9209	if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
9210		return dev_priv->vbt.lvds_ssc_freq;
9211	else if (HAS_PCH_SPLIT(dev))
9212		return 120000;
9213	else if (!IS_GEN2(dev))
9214		return 96000;
9215	else
9216		return 48000;
9217}
9218
9219/* Returns the clock of the currently programmed mode of the given pipe. */
9220static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
9221				struct intel_crtc_state *pipe_config)
9222{
9223	struct drm_device *dev = crtc->base.dev;
9224	struct drm_i915_private *dev_priv = dev->dev_private;
9225	int pipe = pipe_config->cpu_transcoder;
9226	u32 dpll = pipe_config->dpll_hw_state.dpll;
9227	u32 fp;
9228	intel_clock_t clock;
9229	int refclk = i9xx_pll_refclk(dev, pipe_config);
9230
9231	if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
9232		fp = pipe_config->dpll_hw_state.fp0;
9233	else
9234		fp = pipe_config->dpll_hw_state.fp1;
9235
9236	clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
9237	if (IS_PINEVIEW(dev)) {
9238		clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
9239		clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
9240	} else {
9241		clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
9242		clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
9243	}
9244
9245	if (!IS_GEN2(dev)) {
9246		if (IS_PINEVIEW(dev))
9247			clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
9248				DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
9249		else
9250			clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
9251			       DPLL_FPA01_P1_POST_DIV_SHIFT);
9252
9253		switch (dpll & DPLL_MODE_MASK) {
9254		case DPLLB_MODE_DAC_SERIAL:
9255			clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
9256				5 : 10;
9257			break;
9258		case DPLLB_MODE_LVDS:
9259			clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
9260				7 : 14;
9261			break;
9262		default:
9263			DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
9264				  "mode\n", (int)(dpll & DPLL_MODE_MASK));
9265			return;
9266		}
9267
9268		if (IS_PINEVIEW(dev))
9269			pineview_clock(refclk, &clock);
9270		else
9271			i9xx_clock(refclk, &clock);
9272	} else {
9273		u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
9274		bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
9275
9276		if (is_lvds) {
9277			clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
9278				       DPLL_FPA01_P1_POST_DIV_SHIFT);
9279
9280			if (lvds & LVDS_CLKB_POWER_UP)
9281				clock.p2 = 7;
9282			else
9283				clock.p2 = 14;
9284		} else {
9285			if (dpll & PLL_P1_DIVIDE_BY_TWO)
9286				clock.p1 = 2;
9287			else {
9288				clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
9289					    DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
9290			}
9291			if (dpll & PLL_P2_DIVIDE_BY_4)
9292				clock.p2 = 4;
9293			else
9294				clock.p2 = 2;
9295		}
9296
9297		i9xx_clock(refclk, &clock);
9298	}
9299
9300	/*
9301	 * This value includes pixel_multiplier. We will use
9302	 * port_clock to compute adjusted_mode.crtc_clock in the
9303	 * encoder's get_config() function.
9304	 */
9305	pipe_config->port_clock = clock.dot;
9306}
9307
9308int intel_dotclock_calculate(int link_freq,
9309			     const struct intel_link_m_n *m_n)
9310{
9311	/*
9312	 * The calculation for the data clock is:
9313	 * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
9314	 * But we want to avoid losing precison if possible, so:
9315	 * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
9316	 *
9317	 * and the link clock is simpler:
9318	 * link_clock = (m * link_clock) / n
9319	 */
9320
9321	if (!m_n->link_n)
9322		return 0;
9323
9324	return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
9325}
9326
9327static void ironlake_pch_clock_get(struct intel_crtc *crtc,
9328				   struct intel_crtc_state *pipe_config)
9329{
9330	struct drm_device *dev = crtc->base.dev;
9331
9332	/* read out port_clock from the DPLL */
9333	i9xx_crtc_clock_get(crtc, pipe_config);
9334
9335	/*
9336	 * This value does not include pixel_multiplier.
9337	 * We will check that port_clock and adjusted_mode.crtc_clock
9338	 * agree once we know their relationship in the encoder's
9339	 * get_config() function.
9340	 */
9341	pipe_config->base.adjusted_mode.crtc_clock =
9342		intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
9343					 &pipe_config->fdi_m_n);
9344}
9345
9346/** Returns the currently programmed mode of the given pipe. */
9347struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
9348					     struct drm_crtc *crtc)
9349{
9350	struct drm_i915_private *dev_priv = dev->dev_private;
9351	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9352	enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9353	struct drm_display_mode *mode;
9354	struct intel_crtc_state pipe_config;
9355	int htot = I915_READ(HTOTAL(cpu_transcoder));
9356	int hsync = I915_READ(HSYNC(cpu_transcoder));
9357	int vtot = I915_READ(VTOTAL(cpu_transcoder));
9358	int vsync = I915_READ(VSYNC(cpu_transcoder));
9359	enum pipe pipe = intel_crtc->pipe;
9360
9361	mode = kzalloc(sizeof(*mode), GFP_KERNEL);
9362	if (!mode)
9363		return NULL;
9364
9365	/*
9366	 * Construct a pipe_config sufficient for getting the clock info
9367	 * back out of crtc_clock_get.
9368	 *
9369	 * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
9370	 * to use a real value here instead.
9371	 */
9372	pipe_config.cpu_transcoder = (enum transcoder) pipe;
9373	pipe_config.pixel_multiplier = 1;
9374	pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
9375	pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
9376	pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
9377	i9xx_crtc_clock_get(intel_crtc, &pipe_config);
9378
9379	mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
9380	mode->hdisplay = (htot & 0xffff) + 1;
9381	mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
9382	mode->hsync_start = (hsync & 0xffff) + 1;
9383	mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
9384	mode->vdisplay = (vtot & 0xffff) + 1;
9385	mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
9386	mode->vsync_start = (vsync & 0xffff) + 1;
9387	mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
9388
9389	drm_mode_set_name(mode);
9390
9391	return mode;
9392}
9393
9394static void intel_decrease_pllclock(struct drm_crtc *crtc)
9395{
9396	struct drm_device *dev = crtc->dev;
9397	struct drm_i915_private *dev_priv = dev->dev_private;
9398	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9399
9400	if (!HAS_GMCH_DISPLAY(dev))
9401		return;
9402
9403	if (!dev_priv->lvds_downclock_avail)
9404		return;
9405
9406	/*
9407	 * Since this is called by a timer, we should never get here in
9408	 * the manual case.
9409	 */
9410	if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
9411		int pipe = intel_crtc->pipe;
9412		int dpll_reg = DPLL(pipe);
9413		int dpll;
9414
9415		DRM_DEBUG_DRIVER("downclocking LVDS\n");
9416
9417		assert_panel_unlocked(dev_priv, pipe);
9418
9419		dpll = I915_READ(dpll_reg);
9420		dpll |= DISPLAY_RATE_SELECT_FPA1;
9421		I915_WRITE(dpll_reg, dpll);
9422		intel_wait_for_vblank(dev, pipe);
9423		dpll = I915_READ(dpll_reg);
9424		if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
9425			DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
9426	}
9427
9428}
9429
9430void intel_mark_busy(struct drm_device *dev)
9431{
9432	struct drm_i915_private *dev_priv = dev->dev_private;
9433
9434	if (dev_priv->mm.busy)
9435		return;
9436
9437	intel_runtime_pm_get(dev_priv);
9438	i915_update_gfx_val(dev_priv);
9439	if (INTEL_INFO(dev)->gen >= 6)
9440		gen6_rps_busy(dev_priv);
9441	dev_priv->mm.busy = true;
9442}
9443
9444void intel_mark_idle(struct drm_device *dev)
9445{
9446	struct drm_i915_private *dev_priv = dev->dev_private;
9447	struct drm_crtc *crtc;
9448
9449	if (!dev_priv->mm.busy)
9450		return;
9451
9452	dev_priv->mm.busy = false;
9453
9454	for_each_crtc(dev, crtc) {
9455		if (!crtc->primary->fb)
9456			continue;
9457
9458		intel_decrease_pllclock(crtc);
9459	}
9460
9461	if (INTEL_INFO(dev)->gen >= 6)
9462		gen6_rps_idle(dev->dev_private);
9463
9464	intel_runtime_pm_put(dev_priv);
9465}
9466
9467static void intel_crtc_set_state(struct intel_crtc *crtc,
9468				 struct intel_crtc_state *crtc_state)
9469{
9470	kfree(crtc->config);
9471	crtc->config = crtc_state;
9472	crtc->base.state = &crtc_state->base;
9473}
9474
9475static void intel_crtc_destroy(struct drm_crtc *crtc)
9476{
9477	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9478	struct drm_device *dev = crtc->dev;
9479	struct intel_unpin_work *work;
9480
9481	spin_lock_irq(&dev->event_lock);
9482	work = intel_crtc->unpin_work;
9483	intel_crtc->unpin_work = NULL;
9484	spin_unlock_irq(&dev->event_lock);
9485
9486	if (work) {
9487		cancel_work_sync(&work->work);
9488		kfree(work);
9489	}
9490
9491	intel_crtc_set_state(intel_crtc, NULL);
9492	drm_crtc_cleanup(crtc);
9493
9494	kfree(intel_crtc);
9495}
9496
9497static void intel_unpin_work_fn(struct work_struct *__work)
9498{
9499	struct intel_unpin_work *work =
9500		container_of(__work, struct intel_unpin_work, work);
9501	struct drm_device *dev = work->crtc->dev;
9502	enum pipe pipe = to_intel_crtc(work->crtc)->pipe;
9503
9504	mutex_lock(&dev->struct_mutex);
9505	intel_unpin_fb_obj(work->old_fb, work->crtc->primary->state);
9506	drm_gem_object_unreference(&work->pending_flip_obj->base);
9507
9508	intel_fbc_update(dev);
9509
9510	if (work->flip_queued_req)
9511		i915_gem_request_assign(&work->flip_queued_req, NULL);
9512	mutex_unlock(&dev->struct_mutex);
9513
9514	intel_frontbuffer_flip_complete(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
9515	drm_framebuffer_unreference(work->old_fb);
9516
9517	BUG_ON(atomic_read(&to_intel_crtc(work->crtc)->unpin_work_count) == 0);
9518	atomic_dec(&to_intel_crtc(work->crtc)->unpin_work_count);
9519
9520	kfree(work);
9521}
9522
9523static void do_intel_finish_page_flip(struct drm_device *dev,
9524				      struct drm_crtc *crtc)
9525{
9526	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9527	struct intel_unpin_work *work;
9528	unsigned long flags;
9529
9530	/* Ignore early vblank irqs */
9531	if (intel_crtc == NULL)
9532		return;
9533
9534	/*
9535	 * This is called both by irq handlers and the reset code (to complete
9536	 * lost pageflips) so needs the full irqsave spinlocks.
9537	 */
9538	spin_lock_irqsave(&dev->event_lock, flags);
9539	work = intel_crtc->unpin_work;
9540
9541	/* Ensure we don't miss a work->pending update ... */
9542	smp_rmb();
9543
9544	if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
9545		spin_unlock_irqrestore(&dev->event_lock, flags);
9546		return;
9547	}
9548
9549	page_flip_completed(intel_crtc);
9550
9551	spin_unlock_irqrestore(&dev->event_lock, flags);
9552}
9553
9554void intel_finish_page_flip(struct drm_device *dev, int pipe)
9555{
9556	struct drm_i915_private *dev_priv = dev->dev_private;
9557	struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
9558
9559	do_intel_finish_page_flip(dev, crtc);
9560}
9561
9562void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
9563{
9564	struct drm_i915_private *dev_priv = dev->dev_private;
9565	struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
9566
9567	do_intel_finish_page_flip(dev, crtc);
9568}
9569
9570/* Is 'a' after or equal to 'b'? */
9571static bool g4x_flip_count_after_eq(u32 a, u32 b)
9572{
9573	return !((a - b) & 0x80000000);
9574}
9575
9576static bool page_flip_finished(struct intel_crtc *crtc)
9577{
9578	struct drm_device *dev = crtc->base.dev;
9579	struct drm_i915_private *dev_priv = dev->dev_private;
9580
9581	if (i915_reset_in_progress(&dev_priv->gpu_error) ||
9582	    crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
9583		return true;
9584
9585	/*
9586	 * The relevant registers doen't exist on pre-ctg.
9587	 * As the flip done interrupt doesn't trigger for mmio
9588	 * flips on gmch platforms, a flip count check isn't
9589	 * really needed there. But since ctg has the registers,
9590	 * include it in the check anyway.
9591	 */
9592	if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
9593		return true;
9594
9595	/*
9596	 * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
9597	 * used the same base address. In that case the mmio flip might
9598	 * have completed, but the CS hasn't even executed the flip yet.
9599	 *
9600	 * A flip count check isn't enough as the CS might have updated
9601	 * the base address just after start of vblank, but before we
9602	 * managed to process the interrupt. This means we'd complete the
9603	 * CS flip too soon.
9604	 *
9605	 * Combining both checks should get us a good enough result. It may
9606	 * still happen that the CS flip has been executed, but has not
9607	 * yet actually completed. But in case the base address is the same
9608	 * anyway, we don't really care.
9609	 */
9610	return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
9611		crtc->unpin_work->gtt_offset &&
9612		g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
9613				    crtc->unpin_work->flip_count);
9614}
9615
9616void intel_prepare_page_flip(struct drm_device *dev, int plane)
9617{
9618	struct drm_i915_private *dev_priv = dev->dev_private;
9619	struct intel_crtc *intel_crtc =
9620		to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
9621	unsigned long flags;
9622
9623
9624	/*
9625	 * This is called both by irq handlers and the reset code (to complete
9626	 * lost pageflips) so needs the full irqsave spinlocks.
9627	 *
9628	 * NB: An MMIO update of the plane base pointer will also
9629	 * generate a page-flip completion irq, i.e. every modeset
9630	 * is also accompanied by a spurious intel_prepare_page_flip().
9631	 */
9632	spin_lock_irqsave(&dev->event_lock, flags);
9633	if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
9634		atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
9635	spin_unlock_irqrestore(&dev->event_lock, flags);
9636}
9637
9638static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
9639{
9640	/* Ensure that the work item is consistent when activating it ... */
9641	smp_wmb();
9642	atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
9643	/* and that it is marked active as soon as the irq could fire. */
9644	smp_wmb();
9645}
9646
9647static int intel_gen2_queue_flip(struct drm_device *dev,
9648				 struct drm_crtc *crtc,
9649				 struct drm_framebuffer *fb,
9650				 struct drm_i915_gem_object *obj,
9651				 struct intel_engine_cs *ring,
9652				 uint32_t flags)
9653{
9654	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9655	u32 flip_mask;
9656	int ret;
9657
9658	ret = intel_ring_begin(ring, 6);
9659	if (ret)
9660		return ret;
9661
9662	/* Can't queue multiple flips, so wait for the previous
9663	 * one to finish before executing the next.
9664	 */
9665	if (intel_crtc->plane)
9666		flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
9667	else
9668		flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
9669	intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
9670	intel_ring_emit(ring, MI_NOOP);
9671	intel_ring_emit(ring, MI_DISPLAY_FLIP |
9672			MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9673	intel_ring_emit(ring, fb->pitches[0]);
9674	intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9675	intel_ring_emit(ring, 0); /* aux display base address, unused */
9676
9677	intel_mark_page_flip_active(intel_crtc);
9678	__intel_ring_advance(ring);
9679	return 0;
9680}
9681
9682static int intel_gen3_queue_flip(struct drm_device *dev,
9683				 struct drm_crtc *crtc,
9684				 struct drm_framebuffer *fb,
9685				 struct drm_i915_gem_object *obj,
9686				 struct intel_engine_cs *ring,
9687				 uint32_t flags)
9688{
9689	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9690	u32 flip_mask;
9691	int ret;
9692
9693	ret = intel_ring_begin(ring, 6);
9694	if (ret)
9695		return ret;
9696
9697	if (intel_crtc->plane)
9698		flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
9699	else
9700		flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
9701	intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
9702	intel_ring_emit(ring, MI_NOOP);
9703	intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
9704			MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9705	intel_ring_emit(ring, fb->pitches[0]);
9706	intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9707	intel_ring_emit(ring, MI_NOOP);
9708
9709	intel_mark_page_flip_active(intel_crtc);
9710	__intel_ring_advance(ring);
9711	return 0;
9712}
9713
9714static int intel_gen4_queue_flip(struct drm_device *dev,
9715				 struct drm_crtc *crtc,
9716				 struct drm_framebuffer *fb,
9717				 struct drm_i915_gem_object *obj,
9718				 struct intel_engine_cs *ring,
9719				 uint32_t flags)
9720{
9721	struct drm_i915_private *dev_priv = dev->dev_private;
9722	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9723	uint32_t pf, pipesrc;
9724	int ret;
9725
9726	ret = intel_ring_begin(ring, 4);
9727	if (ret)
9728		return ret;
9729
9730	/* i965+ uses the linear or tiled offsets from the
9731	 * Display Registers (which do not change across a page-flip)
9732	 * so we need only reprogram the base address.
9733	 */
9734	intel_ring_emit(ring, MI_DISPLAY_FLIP |
9735			MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9736	intel_ring_emit(ring, fb->pitches[0]);
9737	intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
9738			obj->tiling_mode);
9739
9740	/* XXX Enabling the panel-fitter across page-flip is so far
9741	 * untested on non-native modes, so ignore it for now.
9742	 * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
9743	 */
9744	pf = 0;
9745	pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9746	intel_ring_emit(ring, pf | pipesrc);
9747
9748	intel_mark_page_flip_active(intel_crtc);
9749	__intel_ring_advance(ring);
9750	return 0;
9751}
9752
9753static int intel_gen6_queue_flip(struct drm_device *dev,
9754				 struct drm_crtc *crtc,
9755				 struct drm_framebuffer *fb,
9756				 struct drm_i915_gem_object *obj,
9757				 struct intel_engine_cs *ring,
9758				 uint32_t flags)
9759{
9760	struct drm_i915_private *dev_priv = dev->dev_private;
9761	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9762	uint32_t pf, pipesrc;
9763	int ret;
9764
9765	ret = intel_ring_begin(ring, 4);
9766	if (ret)
9767		return ret;
9768
9769	intel_ring_emit(ring, MI_DISPLAY_FLIP |
9770			MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9771	intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
9772	intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9773
9774	/* Contrary to the suggestions in the documentation,
9775	 * "Enable Panel Fitter" does not seem to be required when page
9776	 * flipping with a non-native mode, and worse causes a normal
9777	 * modeset to fail.
9778	 * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
9779	 */
9780	pf = 0;
9781	pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9782	intel_ring_emit(ring, pf | pipesrc);
9783
9784	intel_mark_page_flip_active(intel_crtc);
9785	__intel_ring_advance(ring);
9786	return 0;
9787}
9788
9789static int intel_gen7_queue_flip(struct drm_device *dev,
9790				 struct drm_crtc *crtc,
9791				 struct drm_framebuffer *fb,
9792				 struct drm_i915_gem_object *obj,
9793				 struct intel_engine_cs *ring,
9794				 uint32_t flags)
9795{
9796	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9797	uint32_t plane_bit = 0;
9798	int len, ret;
9799
9800	switch (intel_crtc->plane) {
9801	case PLANE_A:
9802		plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
9803		break;
9804	case PLANE_B:
9805		plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
9806		break;
9807	case PLANE_C:
9808		plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
9809		break;
9810	default:
9811		WARN_ONCE(1, "unknown plane in flip command\n");
9812		return -ENODEV;
9813	}
9814
9815	len = 4;
9816	if (ring->id == RCS) {
9817		len += 6;
9818		/*
9819		 * On Gen 8, SRM is now taking an extra dword to accommodate
9820		 * 48bits addresses, and we need a NOOP for the batch size to
9821		 * stay even.
9822		 */
9823		if (IS_GEN8(dev))
9824			len += 2;
9825	}
9826
9827	/*
9828	 * BSpec MI_DISPLAY_FLIP for IVB:
9829	 * "The full packet must be contained within the same cache line."
9830	 *
9831	 * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
9832	 * cacheline, if we ever start emitting more commands before
9833	 * the MI_DISPLAY_FLIP we may need to first emit everything else,
9834	 * then do the cacheline alignment, and finally emit the
9835	 * MI_DISPLAY_FLIP.
9836	 */
9837	ret = intel_ring_cacheline_align(ring);
9838	if (ret)
9839		return ret;
9840
9841	ret = intel_ring_begin(ring, len);
9842	if (ret)
9843		return ret;
9844
9845	/* Unmask the flip-done completion message. Note that the bspec says that
9846	 * we should do this for both the BCS and RCS, and that we must not unmask
9847	 * more than one flip event at any time (or ensure that one flip message
9848	 * can be sent by waiting for flip-done prior to queueing new flips).
9849	 * Experimentation says that BCS works despite DERRMR masking all
9850	 * flip-done completion events and that unmasking all planes at once
9851	 * for the RCS also doesn't appear to drop events. Setting the DERRMR
9852	 * to zero does lead to lockups within MI_DISPLAY_FLIP.
9853	 */
9854	if (ring->id == RCS) {
9855		intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
9856		intel_ring_emit(ring, DERRMR);
9857		intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
9858					DERRMR_PIPEB_PRI_FLIP_DONE |
9859					DERRMR_PIPEC_PRI_FLIP_DONE));
9860		if (IS_GEN8(dev))
9861			intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
9862					      MI_SRM_LRM_GLOBAL_GTT);
9863		else
9864			intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
9865					      MI_SRM_LRM_GLOBAL_GTT);
9866		intel_ring_emit(ring, DERRMR);
9867		intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
9868		if (IS_GEN8(dev)) {
9869			intel_ring_emit(ring, 0);
9870			intel_ring_emit(ring, MI_NOOP);
9871		}
9872	}
9873
9874	intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
9875	intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
9876	intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9877	intel_ring_emit(ring, (MI_NOOP));
9878
9879	intel_mark_page_flip_active(intel_crtc);
9880	__intel_ring_advance(ring);
9881	return 0;
9882}
9883
9884static bool use_mmio_flip(struct intel_engine_cs *ring,
9885			  struct drm_i915_gem_object *obj)
9886{
9887	/*
9888	 * This is not being used for older platforms, because
9889	 * non-availability of flip done interrupt forces us to use
9890	 * CS flips. Older platforms derive flip done using some clever
9891	 * tricks involving the flip_pending status bits and vblank irqs.
9892	 * So using MMIO flips there would disrupt this mechanism.
9893	 */
9894
9895	if (ring == NULL)
9896		return true;
9897
9898	if (INTEL_INFO(ring->dev)->gen < 5)
9899		return false;
9900
9901	if (i915.use_mmio_flip < 0)
9902		return false;
9903	else if (i915.use_mmio_flip > 0)
9904		return true;
9905	else if (i915.enable_execlists)
9906		return true;
9907	else
9908		return ring != i915_gem_request_get_ring(obj->last_read_req);
9909}
9910
9911static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
9912{
9913	struct drm_device *dev = intel_crtc->base.dev;
9914	struct drm_i915_private *dev_priv = dev->dev_private;
9915	struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
9916	struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
9917	struct drm_i915_gem_object *obj = intel_fb->obj;
9918	const enum pipe pipe = intel_crtc->pipe;
9919	u32 ctl, stride;
9920
9921	ctl = I915_READ(PLANE_CTL(pipe, 0));
9922	ctl &= ~PLANE_CTL_TILED_MASK;
9923	if (obj->tiling_mode == I915_TILING_X)
9924		ctl |= PLANE_CTL_TILED_X;
9925
9926	/*
9927	 * The stride is either expressed as a multiple of 64 bytes chunks for
9928	 * linear buffers or in number of tiles for tiled buffers.
9929	 */
9930	stride = fb->pitches[0] >> 6;
9931	if (obj->tiling_mode == I915_TILING_X)
9932		stride = fb->pitches[0] >> 9; /* X tiles are 512 bytes wide */
9933
9934	/*
9935	 * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
9936	 * PLANE_SURF updates, the update is then guaranteed to be atomic.
9937	 */
9938	I915_WRITE(PLANE_CTL(pipe, 0), ctl);
9939	I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
9940
9941	I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
9942	POSTING_READ(PLANE_SURF(pipe, 0));
9943}
9944
9945static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
9946{
9947	struct drm_device *dev = intel_crtc->base.dev;
9948	struct drm_i915_private *dev_priv = dev->dev_private;
9949	struct intel_framebuffer *intel_fb =
9950		to_intel_framebuffer(intel_crtc->base.primary->fb);
9951	struct drm_i915_gem_object *obj = intel_fb->obj;
9952	u32 dspcntr;
9953	u32 reg;
9954
9955	reg = DSPCNTR(intel_crtc->plane);
9956	dspcntr = I915_READ(reg);
9957
9958	if (obj->tiling_mode != I915_TILING_NONE)
9959		dspcntr |= DISPPLANE_TILED;
9960	else
9961		dspcntr &= ~DISPPLANE_TILED;
9962
9963	I915_WRITE(reg, dspcntr);
9964
9965	I915_WRITE(DSPSURF(intel_crtc->plane),
9966		   intel_crtc->unpin_work->gtt_offset);
9967	POSTING_READ(DSPSURF(intel_crtc->plane));
9968
9969}
9970
9971/*
9972 * XXX: This is the temporary way to update the plane registers until we get
9973 * around to using the usual plane update functions for MMIO flips
9974 */
9975static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
9976{
9977	struct drm_device *dev = intel_crtc->base.dev;
9978	bool atomic_update;
9979	u32 start_vbl_count;
9980
9981	intel_mark_page_flip_active(intel_crtc);
9982
9983	atomic_update = intel_pipe_update_start(intel_crtc, &start_vbl_count);
9984
9985	if (INTEL_INFO(dev)->gen >= 9)
9986		skl_do_mmio_flip(intel_crtc);
9987	else
9988		/* use_mmio_flip() retricts MMIO flips to ilk+ */
9989		ilk_do_mmio_flip(intel_crtc);
9990
9991	if (atomic_update)
9992		intel_pipe_update_end(intel_crtc, start_vbl_count);
9993}
9994
9995static void intel_mmio_flip_work_func(struct work_struct *work)
9996{
9997	struct intel_crtc *crtc =
9998		container_of(work, struct intel_crtc, mmio_flip.work);
9999	struct intel_mmio_flip *mmio_flip;
10000
10001	mmio_flip = &crtc->mmio_flip;
10002	if (mmio_flip->req)
10003		WARN_ON(__i915_wait_request(mmio_flip->req,
10004					    crtc->reset_counter,
10005					    false, NULL, NULL) != 0);
10006
10007	intel_do_mmio_flip(crtc);
10008	if (mmio_flip->req) {
10009		mutex_lock(&crtc->base.dev->struct_mutex);
10010		i915_gem_request_assign(&mmio_flip->req, NULL);
10011		mutex_unlock(&crtc->base.dev->struct_mutex);
10012	}
10013}
10014
10015static int intel_queue_mmio_flip(struct drm_device *dev,
10016				 struct drm_crtc *crtc,
10017				 struct drm_framebuffer *fb,
10018				 struct drm_i915_gem_object *obj,
10019				 struct intel_engine_cs *ring,
10020				 uint32_t flags)
10021{
10022	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10023
10024	i915_gem_request_assign(&intel_crtc->mmio_flip.req,
10025				obj->last_write_req);
10026
10027	schedule_work(&intel_crtc->mmio_flip.work);
10028
10029	return 0;
10030}
10031
10032static int intel_default_queue_flip(struct drm_device *dev,
10033				    struct drm_crtc *crtc,
10034				    struct drm_framebuffer *fb,
10035				    struct drm_i915_gem_object *obj,
10036				    struct intel_engine_cs *ring,
10037				    uint32_t flags)
10038{
10039	return -ENODEV;
10040}
10041
10042static bool __intel_pageflip_stall_check(struct drm_device *dev,
10043					 struct drm_crtc *crtc)
10044{
10045	struct drm_i915_private *dev_priv = dev->dev_private;
10046	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10047	struct intel_unpin_work *work = intel_crtc->unpin_work;
10048	u32 addr;
10049
10050	if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
10051		return true;
10052
10053	if (!work->enable_stall_check)
10054		return false;
10055
10056	if (work->flip_ready_vblank == 0) {
10057		if (work->flip_queued_req &&
10058		    !i915_gem_request_completed(work->flip_queued_req, true))
10059			return false;
10060
10061		work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
10062	}
10063
10064	if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
10065		return false;
10066
10067	/* Potential stall - if we see that the flip has happened,
10068	 * assume a missed interrupt. */
10069	if (INTEL_INFO(dev)->gen >= 4)
10070		addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
10071	else
10072		addr = I915_READ(DSPADDR(intel_crtc->plane));
10073
10074	/* There is a potential issue here with a false positive after a flip
10075	 * to the same address. We could address this by checking for a
10076	 * non-incrementing frame counter.
10077	 */
10078	return addr == work->gtt_offset;
10079}
10080
10081void intel_check_page_flip(struct drm_device *dev, int pipe)
10082{
10083	struct drm_i915_private *dev_priv = dev->dev_private;
10084	struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10085	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10086
10087	WARN_ON(!in_interrupt());
10088
10089	if (crtc == NULL)
10090		return;
10091
10092	spin_lock(&dev->event_lock);
10093	if (intel_crtc->unpin_work && __intel_pageflip_stall_check(dev, crtc)) {
10094		WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
10095			 intel_crtc->unpin_work->flip_queued_vblank,
10096			 drm_vblank_count(dev, pipe));
10097		page_flip_completed(intel_crtc);
10098	}
10099	spin_unlock(&dev->event_lock);
10100}
10101
10102static int intel_crtc_page_flip(struct drm_crtc *crtc,
10103				struct drm_framebuffer *fb,
10104				struct drm_pending_vblank_event *event,
10105				uint32_t page_flip_flags)
10106{
10107	struct drm_device *dev = crtc->dev;
10108	struct drm_i915_private *dev_priv = dev->dev_private;
10109	struct drm_framebuffer *old_fb = crtc->primary->fb;
10110	struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10111	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10112	struct drm_plane *primary = crtc->primary;
10113	enum pipe pipe = intel_crtc->pipe;
10114	struct intel_unpin_work *work;
10115	struct intel_engine_cs *ring;
10116	int ret;
10117
10118	/*
10119	 * drm_mode_page_flip_ioctl() should already catch this, but double
10120	 * check to be safe.  In the future we may enable pageflipping from
10121	 * a disabled primary plane.
10122	 */
10123	if (WARN_ON(intel_fb_obj(old_fb) == NULL))
10124		return -EBUSY;
10125
10126	/* Can't change pixel format via MI display flips. */
10127	if (fb->pixel_format != crtc->primary->fb->pixel_format)
10128		return -EINVAL;
10129
10130	/*
10131	 * TILEOFF/LINOFF registers can't be changed via MI display flips.
10132	 * Note that pitch changes could also affect these register.
10133	 */
10134	if (INTEL_INFO(dev)->gen > 3 &&
10135	    (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
10136	     fb->pitches[0] != crtc->primary->fb->pitches[0]))
10137		return -EINVAL;
10138
10139	if (i915_terminally_wedged(&dev_priv->gpu_error))
10140		goto out_hang;
10141
10142	work = kzalloc(sizeof(*work), GFP_KERNEL);
10143	if (work == NULL)
10144		return -ENOMEM;
10145
10146	work->event = event;
10147	work->crtc = crtc;
10148	work->old_fb = old_fb;
10149	INIT_WORK(&work->work, intel_unpin_work_fn);
10150
10151	ret = drm_crtc_vblank_get(crtc);
10152	if (ret)
10153		goto free_work;
10154
10155	/* We borrow the event spin lock for protecting unpin_work */
10156	spin_lock_irq(&dev->event_lock);
10157	if (intel_crtc->unpin_work) {
10158		/* Before declaring the flip queue wedged, check if
10159		 * the hardware completed the operation behind our backs.
10160		 */
10161		if (__intel_pageflip_stall_check(dev, crtc)) {
10162			DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
10163			page_flip_completed(intel_crtc);
10164		} else {
10165			DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
10166			spin_unlock_irq(&dev->event_lock);
10167
10168			drm_crtc_vblank_put(crtc);
10169			kfree(work);
10170			return -EBUSY;
10171		}
10172	}
10173	intel_crtc->unpin_work = work;
10174	spin_unlock_irq(&dev->event_lock);
10175
10176	if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
10177		flush_workqueue(dev_priv->wq);
10178
10179	/* Reference the objects for the scheduled work. */
10180	drm_framebuffer_reference(work->old_fb);
10181	drm_gem_object_reference(&obj->base);
10182
10183	crtc->primary->fb = fb;
10184	update_state_fb(crtc->primary);
10185
10186	work->pending_flip_obj = obj;
10187
10188	ret = i915_mutex_lock_interruptible(dev);
10189	if (ret)
10190		goto cleanup;
10191
10192	atomic_inc(&intel_crtc->unpin_work_count);
10193	intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
10194
10195	if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
10196		work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
10197
10198	if (IS_VALLEYVIEW(dev)) {
10199		ring = &dev_priv->ring[BCS];
10200		if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
10201			/* vlv: DISPLAY_FLIP fails to change tiling */
10202			ring = NULL;
10203	} else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
10204		ring = &dev_priv->ring[BCS];
10205	} else if (INTEL_INFO(dev)->gen >= 7) {
10206		ring = i915_gem_request_get_ring(obj->last_read_req);
10207		if (ring == NULL || ring->id != RCS)
10208			ring = &dev_priv->ring[BCS];
10209	} else {
10210		ring = &dev_priv->ring[RCS];
10211	}
10212
10213	ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
10214					 crtc->primary->state, ring);
10215	if (ret)
10216		goto cleanup_pending;
10217
10218	work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
10219						  + intel_crtc->dspaddr_offset;
10220
10221	if (use_mmio_flip(ring, obj)) {
10222		ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
10223					    page_flip_flags);
10224		if (ret)
10225			goto cleanup_unpin;
10226
10227		i915_gem_request_assign(&work->flip_queued_req,
10228					obj->last_write_req);
10229	} else {
10230		ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, ring,
10231						   page_flip_flags);
10232		if (ret)
10233			goto cleanup_unpin;
10234
10235		i915_gem_request_assign(&work->flip_queued_req,
10236					intel_ring_get_request(ring));
10237	}
10238
10239	work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
10240	work->enable_stall_check = true;
10241
10242	i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
10243			  INTEL_FRONTBUFFER_PRIMARY(pipe));
10244
10245	intel_fbc_disable(dev);
10246	intel_frontbuffer_flip_prepare(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
10247	mutex_unlock(&dev->struct_mutex);
10248
10249	trace_i915_flip_request(intel_crtc->plane, obj);
10250
10251	return 0;
10252
10253cleanup_unpin:
10254	intel_unpin_fb_obj(fb, crtc->primary->state);
10255cleanup_pending:
10256	atomic_dec(&intel_crtc->unpin_work_count);
10257	mutex_unlock(&dev->struct_mutex);
10258cleanup:
10259	crtc->primary->fb = old_fb;
10260	update_state_fb(crtc->primary);
10261
10262	drm_gem_object_unreference_unlocked(&obj->base);
10263	drm_framebuffer_unreference(work->old_fb);
10264
10265	spin_lock_irq(&dev->event_lock);
10266	intel_crtc->unpin_work = NULL;
10267	spin_unlock_irq(&dev->event_lock);
10268
10269	drm_crtc_vblank_put(crtc);
10270free_work:
10271	kfree(work);
10272
10273	if (ret == -EIO) {
10274out_hang:
10275		ret = intel_plane_restore(primary);
10276		if (ret == 0 && event) {
10277			spin_lock_irq(&dev->event_lock);
10278			drm_send_vblank_event(dev, pipe, event);
10279			spin_unlock_irq(&dev->event_lock);
10280		}
10281	}
10282	return ret;
10283}
10284
10285static struct drm_crtc_helper_funcs intel_helper_funcs = {
10286	.mode_set_base_atomic = intel_pipe_set_base_atomic,
10287	.load_lut = intel_crtc_load_lut,
10288	.atomic_begin = intel_begin_crtc_commit,
10289	.atomic_flush = intel_finish_crtc_commit,
10290};
10291
10292/**
10293 * intel_modeset_update_staged_output_state
10294 *
10295 * Updates the staged output configuration state, e.g. after we've read out the
10296 * current hw state.
10297 */
10298static void intel_modeset_update_staged_output_state(struct drm_device *dev)
10299{
10300	struct intel_crtc *crtc;
10301	struct intel_encoder *encoder;
10302	struct intel_connector *connector;
10303
10304	for_each_intel_connector(dev, connector) {
10305		connector->new_encoder =
10306			to_intel_encoder(connector->base.encoder);
10307	}
10308
10309	for_each_intel_encoder(dev, encoder) {
10310		encoder->new_crtc =
10311			to_intel_crtc(encoder->base.crtc);
10312	}
10313
10314	for_each_intel_crtc(dev, crtc) {
10315		crtc->new_enabled = crtc->base.state->enable;
10316
10317		if (crtc->new_enabled)
10318			crtc->new_config = crtc->config;
10319		else
10320			crtc->new_config = NULL;
10321	}
10322}
10323
10324/* Transitional helper to copy current connector/encoder state to
10325 * connector->state. This is needed so that code that is partially
10326 * converted to atomic does the right thing.
10327 */
10328static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10329{
10330	struct intel_connector *connector;
10331
10332	for_each_intel_connector(dev, connector) {
10333		if (connector->base.encoder) {
10334			connector->base.state->best_encoder =
10335				connector->base.encoder;
10336			connector->base.state->crtc =
10337				connector->base.encoder->crtc;
10338		} else {
10339			connector->base.state->best_encoder = NULL;
10340			connector->base.state->crtc = NULL;
10341		}
10342	}
10343}
10344
10345/**
10346 * intel_modeset_commit_output_state
10347 *
10348 * This function copies the stage display pipe configuration to the real one.
10349 */
10350static void intel_modeset_commit_output_state(struct drm_device *dev)
10351{
10352	struct intel_crtc *crtc;
10353	struct intel_encoder *encoder;
10354	struct intel_connector *connector;
10355
10356	for_each_intel_connector(dev, connector) {
10357		connector->base.encoder = &connector->new_encoder->base;
10358	}
10359
10360	for_each_intel_encoder(dev, encoder) {
10361		encoder->base.crtc = &encoder->new_crtc->base;
10362	}
10363
10364	for_each_intel_crtc(dev, crtc) {
10365		crtc->base.state->enable = crtc->new_enabled;
10366		crtc->base.enabled = crtc->new_enabled;
10367	}
10368
10369	intel_modeset_update_connector_atomic_state(dev);
10370}
10371
10372static void
10373connected_sink_compute_bpp(struct intel_connector *connector,
10374			   struct intel_crtc_state *pipe_config)
10375{
10376	int bpp = pipe_config->pipe_bpp;
10377
10378	DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10379		connector->base.base.id,
10380		connector->base.name);
10381
10382	/* Don't use an invalid EDID bpc value */
10383	if (connector->base.display_info.bpc &&
10384	    connector->base.display_info.bpc * 3 < bpp) {
10385		DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10386			      bpp, connector->base.display_info.bpc*3);
10387		pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
10388	}
10389
10390	/* Clamp bpp to default limit on screens without EDID 1.4 */
10391	if (connector->base.display_info.bpc == 0) {
10392		int type = connector->base.connector_type;
10393		int clamp_bpp = 24;
10394
10395		/* Fall back to 18 bpp when DP sink capability is unknown. */
10396		if (type == DRM_MODE_CONNECTOR_DisplayPort ||
10397		    type == DRM_MODE_CONNECTOR_eDP)
10398			clamp_bpp = 18;
10399
10400		if (bpp > clamp_bpp) {
10401			DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
10402				      bpp, clamp_bpp);
10403			pipe_config->pipe_bpp = clamp_bpp;
10404		}
10405	}
10406}
10407
10408static int
10409compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10410			  struct drm_framebuffer *fb,
10411			  struct intel_crtc_state *pipe_config)
10412{
10413	struct drm_device *dev = crtc->base.dev;
10414	struct drm_atomic_state *state;
10415	struct intel_connector *connector;
10416	int bpp, i;
10417
10418	switch (fb->pixel_format) {
10419	case DRM_FORMAT_C8:
10420		bpp = 8*3; /* since we go through a colormap */
10421		break;
10422	case DRM_FORMAT_XRGB1555:
10423	case DRM_FORMAT_ARGB1555:
10424		/* checked in intel_framebuffer_init already */
10425		if (WARN_ON(INTEL_INFO(dev)->gen > 3))
10426			return -EINVAL;
10427	case DRM_FORMAT_RGB565:
10428		bpp = 6*3; /* min is 18bpp */
10429		break;
10430	case DRM_FORMAT_XBGR8888:
10431	case DRM_FORMAT_ABGR8888:
10432		/* checked in intel_framebuffer_init already */
10433		if (WARN_ON(INTEL_INFO(dev)->gen < 4))
10434			return -EINVAL;
10435	case DRM_FORMAT_XRGB8888:
10436	case DRM_FORMAT_ARGB8888:
10437		bpp = 8*3;
10438		break;
10439	case DRM_FORMAT_XRGB2101010:
10440	case DRM_FORMAT_ARGB2101010:
10441	case DRM_FORMAT_XBGR2101010:
10442	case DRM_FORMAT_ABGR2101010:
10443		/* checked in intel_framebuffer_init already */
10444		if (WARN_ON(INTEL_INFO(dev)->gen < 4))
10445			return -EINVAL;
10446		bpp = 10*3;
10447		break;
10448	/* TODO: gen4+ supports 16 bpc floating point, too. */
10449	default:
10450		DRM_DEBUG_KMS("unsupported depth\n");
10451		return -EINVAL;
10452	}
10453
10454	pipe_config->pipe_bpp = bpp;
10455
10456	state = pipe_config->base.state;
10457
10458	/* Clamp display bpp to EDID value */
10459	for (i = 0; i < state->num_connector; i++) {
10460		if (!state->connectors[i])
10461			continue;
10462
10463		connector = to_intel_connector(state->connectors[i]);
10464		if (state->connector_states[i]->crtc != &crtc->base)
10465			continue;
10466
10467		connected_sink_compute_bpp(connector, pipe_config);
10468	}
10469
10470	return bpp;
10471}
10472
10473static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10474{
10475	DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10476			"type: 0x%x flags: 0x%x\n",
10477		mode->crtc_clock,
10478		mode->crtc_hdisplay, mode->crtc_hsync_start,
10479		mode->crtc_hsync_end, mode->crtc_htotal,
10480		mode->crtc_vdisplay, mode->crtc_vsync_start,
10481		mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10482}
10483
10484static void intel_dump_pipe_config(struct intel_crtc *crtc,
10485				   struct intel_crtc_state *pipe_config,
10486				   const char *context)
10487{
10488	DRM_DEBUG_KMS("[CRTC:%d]%s config for pipe %c\n", crtc->base.base.id,
10489		      context, pipe_name(crtc->pipe));
10490
10491	DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
10492	DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
10493		      pipe_config->pipe_bpp, pipe_config->dither);
10494	DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10495		      pipe_config->has_pch_encoder,
10496		      pipe_config->fdi_lanes,
10497		      pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
10498		      pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
10499		      pipe_config->fdi_m_n.tu);
10500	DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10501		      pipe_config->has_dp_encoder,
10502		      pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
10503		      pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
10504		      pipe_config->dp_m_n.tu);
10505
10506	DRM_DEBUG_KMS("dp: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
10507		      pipe_config->has_dp_encoder,
10508		      pipe_config->dp_m2_n2.gmch_m,
10509		      pipe_config->dp_m2_n2.gmch_n,
10510		      pipe_config->dp_m2_n2.link_m,
10511		      pipe_config->dp_m2_n2.link_n,
10512		      pipe_config->dp_m2_n2.tu);
10513
10514	DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10515		      pipe_config->has_audio,
10516		      pipe_config->has_infoframe);
10517
10518	DRM_DEBUG_KMS("requested mode:\n");
10519	drm_mode_debug_printmodeline(&pipe_config->base.mode);
10520	DRM_DEBUG_KMS("adjusted mode:\n");
10521	drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10522	intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10523	DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
10524	DRM_DEBUG_KMS("pipe src size: %dx%d\n",
10525		      pipe_config->pipe_src_w, pipe_config->pipe_src_h);
10526	DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10527		      pipe_config->gmch_pfit.control,
10528		      pipe_config->gmch_pfit.pgm_ratios,
10529		      pipe_config->gmch_pfit.lvds_border_bits);
10530	DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10531		      pipe_config->pch_pfit.pos,
10532		      pipe_config->pch_pfit.size,
10533		      pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
10534	DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
10535	DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
10536}
10537
10538static bool encoders_cloneable(const struct intel_encoder *a,
10539			       const struct intel_encoder *b)
10540{
10541	/* masks could be asymmetric, so check both ways */
10542	return a == b || (a->cloneable & (1 << b->type) &&
10543			  b->cloneable & (1 << a->type));
10544}
10545
10546static bool check_single_encoder_cloning(struct intel_crtc *crtc,
10547					 struct intel_encoder *encoder)
10548{
10549	struct drm_device *dev = crtc->base.dev;
10550	struct intel_encoder *source_encoder;
10551
10552	for_each_intel_encoder(dev, source_encoder) {
10553		if (source_encoder->new_crtc != crtc)
10554			continue;
10555
10556		if (!encoders_cloneable(encoder, source_encoder))
10557			return false;
10558	}
10559
10560	return true;
10561}
10562
10563static bool check_encoder_cloning(struct intel_crtc *crtc)
10564{
10565	struct drm_device *dev = crtc->base.dev;
10566	struct intel_encoder *encoder;
10567
10568	for_each_intel_encoder(dev, encoder) {
10569		if (encoder->new_crtc != crtc)
10570			continue;
10571
10572		if (!check_single_encoder_cloning(crtc, encoder))
10573			return false;
10574	}
10575
10576	return true;
10577}
10578
10579static bool check_digital_port_conflicts(struct drm_device *dev)
10580{
10581	struct intel_connector *connector;
10582	unsigned int used_ports = 0;
10583
10584	/*
10585	 * Walk the connector list instead of the encoder
10586	 * list to detect the problem on ddi platforms
10587	 * where there's just one encoder per digital port.
10588	 */
10589	for_each_intel_connector(dev, connector) {
10590		struct intel_encoder *encoder = connector->new_encoder;
10591
10592		if (!encoder)
10593			continue;
10594
10595		WARN_ON(!encoder->new_crtc);
10596
10597		switch (encoder->type) {
10598			unsigned int port_mask;
10599		case INTEL_OUTPUT_UNKNOWN:
10600			if (WARN_ON(!HAS_DDI(dev)))
10601				break;
10602		case INTEL_OUTPUT_DISPLAYPORT:
10603		case INTEL_OUTPUT_HDMI:
10604		case INTEL_OUTPUT_EDP:
10605			port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
10606
10607			/* the same port mustn't appear more than once */
10608			if (used_ports & port_mask)
10609				return false;
10610
10611			used_ports |= port_mask;
10612		default:
10613			break;
10614		}
10615	}
10616
10617	return true;
10618}
10619
10620static void
10621clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10622{
10623	struct drm_crtc_state tmp_state;
10624
10625	/* Clear only the intel specific part of the crtc state */
10626	tmp_state = crtc_state->base;
10627	memset(crtc_state, 0, sizeof *crtc_state);
10628	crtc_state->base = tmp_state;
10629}
10630
10631static struct intel_crtc_state *
10632intel_modeset_pipe_config(struct drm_crtc *crtc,
10633			  struct drm_framebuffer *fb,
10634			  struct drm_display_mode *mode,
10635			  struct drm_atomic_state *state)
10636{
10637	struct drm_device *dev = crtc->dev;
10638	struct intel_encoder *encoder;
10639	struct intel_connector *connector;
10640	struct drm_connector_state *connector_state;
10641	struct intel_crtc_state *pipe_config;
10642	int plane_bpp, ret = -EINVAL;
10643	int i;
10644	bool retry = true;
10645
10646	if (!check_encoder_cloning(to_intel_crtc(crtc))) {
10647		DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10648		return ERR_PTR(-EINVAL);
10649	}
10650
10651	if (!check_digital_port_conflicts(dev)) {
10652		DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
10653		return ERR_PTR(-EINVAL);
10654	}
10655
10656	pipe_config = intel_atomic_get_crtc_state(state, to_intel_crtc(crtc));
10657	if (IS_ERR(pipe_config))
10658		return pipe_config;
10659
10660	clear_intel_crtc_state(pipe_config);
10661
10662	pipe_config->base.crtc = crtc;
10663	drm_mode_copy(&pipe_config->base.adjusted_mode, mode);
10664	drm_mode_copy(&pipe_config->base.mode, mode);
10665
10666	pipe_config->cpu_transcoder =
10667		(enum transcoder) to_intel_crtc(crtc)->pipe;
10668	pipe_config->shared_dpll = DPLL_ID_PRIVATE;
10669
10670	/*
10671	 * Sanitize sync polarity flags based on requested ones. If neither
10672	 * positive or negative polarity is requested, treat this as meaning
10673	 * negative polarity.
10674	 */
10675	if (!(pipe_config->base.adjusted_mode.flags &
10676	      (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10677		pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10678
10679	if (!(pipe_config->base.adjusted_mode.flags &
10680	      (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10681		pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10682
10683	/* Compute a starting value for pipe_config->pipe_bpp taking the source
10684	 * plane pixel format and any sink constraints into account. Returns the
10685	 * source plane bpp so that dithering can be selected on mismatches
10686	 * after encoders and crtc also have had their say. */
10687	plane_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10688					      fb, pipe_config);
10689	if (plane_bpp < 0)
10690		goto fail;
10691
10692	/*
10693	 * Determine the real pipe dimensions. Note that stereo modes can
10694	 * increase the actual pipe size due to the frame doubling and
10695	 * insertion of additional space for blanks between the frame. This
10696	 * is stored in the crtc timings. We use the requested mode to do this
10697	 * computation to clearly distinguish it from the adjusted mode, which
10698	 * can be changed by the connectors in the below retry loop.
10699	 */
10700	drm_crtc_get_hv_timing(&pipe_config->base.mode,
10701			       &pipe_config->pipe_src_w,
10702			       &pipe_config->pipe_src_h);
10703
10704encoder_retry:
10705	/* Ensure the port clock defaults are reset when retrying. */
10706	pipe_config->port_clock = 0;
10707	pipe_config->pixel_multiplier = 1;
10708
10709	/* Fill in default crtc timings, allow encoders to overwrite them. */
10710	drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10711			      CRTC_STEREO_DOUBLE);
10712
10713	/* Pass our mode to the connectors and the CRTC to give them a chance to
10714	 * adjust it according to limitations or connector properties, and also
10715	 * a chance to reject the mode entirely.
10716	 */
10717	for (i = 0; i < state->num_connector; i++) {
10718		connector = to_intel_connector(state->connectors[i]);
10719		if (!connector)
10720			continue;
10721
10722		connector_state = state->connector_states[i];
10723		if (connector_state->crtc != crtc)
10724			continue;
10725
10726		encoder = to_intel_encoder(connector_state->best_encoder);
10727
10728		if (!(encoder->compute_config(encoder, pipe_config))) {
10729			DRM_DEBUG_KMS("Encoder config failure\n");
10730			goto fail;
10731		}
10732	}
10733
10734	/* Set default port clock if not overwritten by the encoder. Needs to be
10735	 * done afterwards in case the encoder adjusts the mode. */
10736	if (!pipe_config->port_clock)
10737		pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
10738			* pipe_config->pixel_multiplier;
10739
10740	ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
10741	if (ret < 0) {
10742		DRM_DEBUG_KMS("CRTC fixup failed\n");
10743		goto fail;
10744	}
10745
10746	if (ret == RETRY) {
10747		if (WARN(!retry, "loop in pipe configuration computation\n")) {
10748			ret = -EINVAL;
10749			goto fail;
10750		}
10751
10752		DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
10753		retry = false;
10754		goto encoder_retry;
10755	}
10756
10757	pipe_config->dither = pipe_config->pipe_bpp != plane_bpp;
10758	DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
10759		      plane_bpp, pipe_config->pipe_bpp, pipe_config->dither);
10760
10761	return pipe_config;
10762fail:
10763	return ERR_PTR(ret);
10764}
10765
10766/* Computes which crtcs are affected and sets the relevant bits in the mask. For
10767 * simplicity we use the crtc's pipe number (because it's easier to obtain). */
10768static void
10769intel_modeset_affected_pipes(struct drm_crtc *crtc, unsigned *modeset_pipes,
10770			     unsigned *prepare_pipes, unsigned *disable_pipes)
10771{
10772	struct intel_crtc *intel_crtc;
10773	struct drm_device *dev = crtc->dev;
10774	struct intel_encoder *encoder;
10775	struct intel_connector *connector;
10776	struct drm_crtc *tmp_crtc;
10777
10778	*disable_pipes = *modeset_pipes = *prepare_pipes = 0;
10779
10780	/* Check which crtcs have changed outputs connected to them, these need
10781	 * to be part of the prepare_pipes mask. We don't (yet) support global
10782	 * modeset across multiple crtcs, so modeset_pipes will only have one
10783	 * bit set at most. */
10784	for_each_intel_connector(dev, connector) {
10785		if (connector->base.encoder == &connector->new_encoder->base)
10786			continue;
10787
10788		if (connector->base.encoder) {
10789			tmp_crtc = connector->base.encoder->crtc;
10790
10791			*prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
10792		}
10793
10794		if (connector->new_encoder)
10795			*prepare_pipes |=
10796				1 << connector->new_encoder->new_crtc->pipe;
10797	}
10798
10799	for_each_intel_encoder(dev, encoder) {
10800		if (encoder->base.crtc == &encoder->new_crtc->base)
10801			continue;
10802
10803		if (encoder->base.crtc) {
10804			tmp_crtc = encoder->base.crtc;
10805
10806			*prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
10807		}
10808
10809		if (encoder->new_crtc)
10810			*prepare_pipes |= 1 << encoder->new_crtc->pipe;
10811	}
10812
10813	/* Check for pipes that will be enabled/disabled ... */
10814	for_each_intel_crtc(dev, intel_crtc) {
10815		if (intel_crtc->base.state->enable == intel_crtc->new_enabled)
10816			continue;
10817
10818		if (!intel_crtc->new_enabled)
10819			*disable_pipes |= 1 << intel_crtc->pipe;
10820		else
10821			*prepare_pipes |= 1 << intel_crtc->pipe;
10822	}
10823
10824
10825	/* set_mode is also used to update properties on life display pipes. */
10826	intel_crtc = to_intel_crtc(crtc);
10827	if (intel_crtc->new_enabled)
10828		*prepare_pipes |= 1 << intel_crtc->pipe;
10829
10830	/*
10831	 * For simplicity do a full modeset on any pipe where the output routing
10832	 * changed. We could be more clever, but that would require us to be
10833	 * more careful with calling the relevant encoder->mode_set functions.
10834	 */
10835	if (*prepare_pipes)
10836		*modeset_pipes = *prepare_pipes;
10837
10838	/* ... and mask these out. */
10839	*modeset_pipes &= ~(*disable_pipes);
10840	*prepare_pipes &= ~(*disable_pipes);
10841
10842	/*
10843	 * HACK: We don't (yet) fully support global modesets. intel_set_config
10844	 * obies this rule, but the modeset restore mode of
10845	 * intel_modeset_setup_hw_state does not.
10846	 */
10847	*modeset_pipes &= 1 << intel_crtc->pipe;
10848	*prepare_pipes &= 1 << intel_crtc->pipe;
10849
10850	DRM_DEBUG_KMS("set mode pipe masks: modeset: %x, prepare: %x, disable: %x\n",
10851		      *modeset_pipes, *prepare_pipes, *disable_pipes);
10852}
10853
10854static bool intel_crtc_in_use(struct drm_crtc *crtc)
10855{
10856	struct drm_encoder *encoder;
10857	struct drm_device *dev = crtc->dev;
10858
10859	list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
10860		if (encoder->crtc == crtc)
10861			return true;
10862
10863	return false;
10864}
10865
10866static void
10867intel_modeset_update_state(struct drm_device *dev, unsigned prepare_pipes)
10868{
10869	struct drm_i915_private *dev_priv = dev->dev_private;
10870	struct intel_encoder *intel_encoder;
10871	struct intel_crtc *intel_crtc;
10872	struct drm_connector *connector;
10873
10874	intel_shared_dpll_commit(dev_priv);
10875
10876	for_each_intel_encoder(dev, intel_encoder) {
10877		if (!intel_encoder->base.crtc)
10878			continue;
10879
10880		intel_crtc = to_intel_crtc(intel_encoder->base.crtc);
10881
10882		if (prepare_pipes & (1 << intel_crtc->pipe))
10883			intel_encoder->connectors_active = false;
10884	}
10885
10886	intel_modeset_commit_output_state(dev);
10887
10888	/* Double check state. */
10889	for_each_intel_crtc(dev, intel_crtc) {
10890		WARN_ON(intel_crtc->base.state->enable != intel_crtc_in_use(&intel_crtc->base));
10891		WARN_ON(intel_crtc->new_config &&
10892			intel_crtc->new_config != intel_crtc->config);
10893		WARN_ON(intel_crtc->base.state->enable != !!intel_crtc->new_config);
10894	}
10895
10896	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
10897		if (!connector->encoder || !connector->encoder->crtc)
10898			continue;
10899
10900		intel_crtc = to_intel_crtc(connector->encoder->crtc);
10901
10902		if (prepare_pipes & (1 << intel_crtc->pipe)) {
10903			struct drm_property *dpms_property =
10904				dev->mode_config.dpms_property;
10905
10906			connector->dpms = DRM_MODE_DPMS_ON;
10907			drm_object_property_set_value(&connector->base,
10908							 dpms_property,
10909							 DRM_MODE_DPMS_ON);
10910
10911			intel_encoder = to_intel_encoder(connector->encoder);
10912			intel_encoder->connectors_active = true;
10913		}
10914	}
10915
10916}
10917
10918static bool intel_fuzzy_clock_check(int clock1, int clock2)
10919{
10920	int diff;
10921
10922	if (clock1 == clock2)
10923		return true;
10924
10925	if (!clock1 || !clock2)
10926		return false;
10927
10928	diff = abs(clock1 - clock2);
10929
10930	if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
10931		return true;
10932
10933	return false;
10934}
10935
10936#define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
10937	list_for_each_entry((intel_crtc), \
10938			    &(dev)->mode_config.crtc_list, \
10939			    base.head) \
10940		if (mask & (1 <<(intel_crtc)->pipe))
10941
10942static bool
10943intel_pipe_config_compare(struct drm_device *dev,
10944			  struct intel_crtc_state *current_config,
10945			  struct intel_crtc_state *pipe_config)
10946{
10947#define PIPE_CONF_CHECK_X(name)	\
10948	if (current_config->name != pipe_config->name) { \
10949		DRM_ERROR("mismatch in " #name " " \
10950			  "(expected 0x%08x, found 0x%08x)\n", \
10951			  current_config->name, \
10952			  pipe_config->name); \
10953		return false; \
10954	}
10955
10956#define PIPE_CONF_CHECK_I(name)	\
10957	if (current_config->name != pipe_config->name) { \
10958		DRM_ERROR("mismatch in " #name " " \
10959			  "(expected %i, found %i)\n", \
10960			  current_config->name, \
10961			  pipe_config->name); \
10962		return false; \
10963	}
10964
10965/* This is required for BDW+ where there is only one set of registers for
10966 * switching between high and low RR.
10967 * This macro can be used whenever a comparison has to be made between one
10968 * hw state and multiple sw state variables.
10969 */
10970#define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
10971	if ((current_config->name != pipe_config->name) && \
10972		(current_config->alt_name != pipe_config->name)) { \
10973			DRM_ERROR("mismatch in " #name " " \
10974				  "(expected %i or %i, found %i)\n", \
10975				  current_config->name, \
10976				  current_config->alt_name, \
10977				  pipe_config->name); \
10978			return false; \
10979	}
10980
10981#define PIPE_CONF_CHECK_FLAGS(name, mask)	\
10982	if ((current_config->name ^ pipe_config->name) & (mask)) { \
10983		DRM_ERROR("mismatch in " #name "(" #mask ") "	   \
10984			  "(expected %i, found %i)\n", \
10985			  current_config->name & (mask), \
10986			  pipe_config->name & (mask)); \
10987		return false; \
10988	}
10989
10990#define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
10991	if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
10992		DRM_ERROR("mismatch in " #name " " \
10993			  "(expected %i, found %i)\n", \
10994			  current_config->name, \
10995			  pipe_config->name); \
10996		return false; \
10997	}
10998
10999#define PIPE_CONF_QUIRK(quirk)	\
11000	((current_config->quirks | pipe_config->quirks) & (quirk))
11001
11002	PIPE_CONF_CHECK_I(cpu_transcoder);
11003
11004	PIPE_CONF_CHECK_I(has_pch_encoder);
11005	PIPE_CONF_CHECK_I(fdi_lanes);
11006	PIPE_CONF_CHECK_I(fdi_m_n.gmch_m);
11007	PIPE_CONF_CHECK_I(fdi_m_n.gmch_n);
11008	PIPE_CONF_CHECK_I(fdi_m_n.link_m);
11009	PIPE_CONF_CHECK_I(fdi_m_n.link_n);
11010	PIPE_CONF_CHECK_I(fdi_m_n.tu);
11011
11012	PIPE_CONF_CHECK_I(has_dp_encoder);
11013
11014	if (INTEL_INFO(dev)->gen < 8) {
11015		PIPE_CONF_CHECK_I(dp_m_n.gmch_m);
11016		PIPE_CONF_CHECK_I(dp_m_n.gmch_n);
11017		PIPE_CONF_CHECK_I(dp_m_n.link_m);
11018		PIPE_CONF_CHECK_I(dp_m_n.link_n);
11019		PIPE_CONF_CHECK_I(dp_m_n.tu);
11020
11021		if (current_config->has_drrs) {
11022			PIPE_CONF_CHECK_I(dp_m2_n2.gmch_m);
11023			PIPE_CONF_CHECK_I(dp_m2_n2.gmch_n);
11024			PIPE_CONF_CHECK_I(dp_m2_n2.link_m);
11025			PIPE_CONF_CHECK_I(dp_m2_n2.link_n);
11026			PIPE_CONF_CHECK_I(dp_m2_n2.tu);
11027		}
11028	} else {
11029		PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_m, dp_m2_n2.gmch_m);
11030		PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_n, dp_m2_n2.gmch_n);
11031		PIPE_CONF_CHECK_I_ALT(dp_m_n.link_m, dp_m2_n2.link_m);
11032		PIPE_CONF_CHECK_I_ALT(dp_m_n.link_n, dp_m2_n2.link_n);
11033		PIPE_CONF_CHECK_I_ALT(dp_m_n.tu, dp_m2_n2.tu);
11034	}
11035
11036	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11037	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11038	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11039	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11040	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11041	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11042
11043	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11044	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11045	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11046	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11047	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11048	PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11049
11050	PIPE_CONF_CHECK_I(pixel_multiplier);
11051	PIPE_CONF_CHECK_I(has_hdmi_sink);
11052	if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
11053	    IS_VALLEYVIEW(dev))
11054		PIPE_CONF_CHECK_I(limited_color_range);
11055	PIPE_CONF_CHECK_I(has_infoframe);
11056
11057	PIPE_CONF_CHECK_I(has_audio);
11058
11059	PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11060			      DRM_MODE_FLAG_INTERLACE);
11061
11062	if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11063		PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11064				      DRM_MODE_FLAG_PHSYNC);
11065		PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11066				      DRM_MODE_FLAG_NHSYNC);
11067		PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11068				      DRM_MODE_FLAG_PVSYNC);
11069		PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11070				      DRM_MODE_FLAG_NVSYNC);
11071	}
11072
11073	PIPE_CONF_CHECK_I(pipe_src_w);
11074	PIPE_CONF_CHECK_I(pipe_src_h);
11075
11076	/*
11077	 * FIXME: BIOS likes to set up a cloned config with lvds+external
11078	 * screen. Since we don't yet re-compute the pipe config when moving
11079	 * just the lvds port away to another pipe the sw tracking won't match.
11080	 *
11081	 * Proper atomic modesets with recomputed global state will fix this.
11082	 * Until then just don't check gmch state for inherited modes.
11083	 */
11084	if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
11085		PIPE_CONF_CHECK_I(gmch_pfit.control);
11086		/* pfit ratios are autocomputed by the hw on gen4+ */
11087		if (INTEL_INFO(dev)->gen < 4)
11088			PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
11089		PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
11090	}
11091
11092	PIPE_CONF_CHECK_I(pch_pfit.enabled);
11093	if (current_config->pch_pfit.enabled) {
11094		PIPE_CONF_CHECK_I(pch_pfit.pos);
11095		PIPE_CONF_CHECK_I(pch_pfit.size);
11096	}
11097
11098	/* BDW+ don't expose a synchronous way to read the state */
11099	if (IS_HASWELL(dev))
11100		PIPE_CONF_CHECK_I(ips_enabled);
11101
11102	PIPE_CONF_CHECK_I(double_wide);
11103
11104	PIPE_CONF_CHECK_X(ddi_pll_sel);
11105
11106	PIPE_CONF_CHECK_I(shared_dpll);
11107	PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11108	PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11109	PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11110	PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11111	PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11112	PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11113	PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11114	PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11115
11116	if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
11117		PIPE_CONF_CHECK_I(pipe_bpp);
11118
11119	PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11120	PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11121
11122#undef PIPE_CONF_CHECK_X
11123#undef PIPE_CONF_CHECK_I
11124#undef PIPE_CONF_CHECK_I_ALT
11125#undef PIPE_CONF_CHECK_FLAGS
11126#undef PIPE_CONF_CHECK_CLOCK_FUZZY
11127#undef PIPE_CONF_QUIRK
11128
11129	return true;
11130}
11131
11132static void check_wm_state(struct drm_device *dev)
11133{
11134	struct drm_i915_private *dev_priv = dev->dev_private;
11135	struct skl_ddb_allocation hw_ddb, *sw_ddb;
11136	struct intel_crtc *intel_crtc;
11137	int plane;
11138
11139	if (INTEL_INFO(dev)->gen < 9)
11140		return;
11141
11142	skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11143	sw_ddb = &dev_priv->wm.skl_hw.ddb;
11144
11145	for_each_intel_crtc(dev, intel_crtc) {
11146		struct skl_ddb_entry *hw_entry, *sw_entry;
11147		const enum pipe pipe = intel_crtc->pipe;
11148
11149		if (!intel_crtc->active)
11150			continue;
11151
11152		/* planes */
11153		for_each_plane(dev_priv, pipe, plane) {
11154			hw_entry = &hw_ddb.plane[pipe][plane];
11155			sw_entry = &sw_ddb->plane[pipe][plane];
11156
11157			if (skl_ddb_entry_equal(hw_entry, sw_entry))
11158				continue;
11159
11160			DRM_ERROR("mismatch in DDB state pipe %c plane %d "
11161				  "(expected (%u,%u), found (%u,%u))\n",
11162				  pipe_name(pipe), plane + 1,
11163				  sw_entry->start, sw_entry->end,
11164				  hw_entry->start, hw_entry->end);
11165		}
11166
11167		/* cursor */
11168		hw_entry = &hw_ddb.cursor[pipe];
11169		sw_entry = &sw_ddb->cursor[pipe];
11170
11171		if (skl_ddb_entry_equal(hw_entry, sw_entry))
11172			continue;
11173
11174		DRM_ERROR("mismatch in DDB state pipe %c cursor "
11175			  "(expected (%u,%u), found (%u,%u))\n",
11176			  pipe_name(pipe),
11177			  sw_entry->start, sw_entry->end,
11178			  hw_entry->start, hw_entry->end);
11179	}
11180}
11181
11182static void
11183check_connector_state(struct drm_device *dev)
11184{
11185	struct intel_connector *connector;
11186
11187	for_each_intel_connector(dev, connector) {
11188		/* This also checks the encoder/connector hw state with the
11189		 * ->get_hw_state callbacks. */
11190		intel_connector_check_state(connector);
11191
11192		I915_STATE_WARN(&connector->new_encoder->base != connector->base.encoder,
11193		     "connector's staged encoder doesn't match current encoder\n");
11194	}
11195}
11196
11197static void
11198check_encoder_state(struct drm_device *dev)
11199{
11200	struct intel_encoder *encoder;
11201	struct intel_connector *connector;
11202
11203	for_each_intel_encoder(dev, encoder) {
11204		bool enabled = false;
11205		bool active = false;
11206		enum pipe pipe, tracked_pipe;
11207
11208		DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11209			      encoder->base.base.id,
11210			      encoder->base.name);
11211
11212		I915_STATE_WARN(&encoder->new_crtc->base != encoder->base.crtc,
11213		     "encoder's stage crtc doesn't match current crtc\n");
11214		I915_STATE_WARN(encoder->connectors_active && !encoder->base.crtc,
11215		     "encoder's active_connectors set, but no crtc\n");
11216
11217		for_each_intel_connector(dev, connector) {
11218			if (connector->base.encoder != &encoder->base)
11219				continue;
11220			enabled = true;
11221			if (connector->base.dpms != DRM_MODE_DPMS_OFF)
11222				active = true;
11223		}
11224
11225		I915_STATE_WARN(!!encoder->base.crtc != enabled,
11226		     "encoder's enabled state mismatch "
11227		     "(expected %i, found %i)\n",
11228		     !!encoder->base.crtc, enabled);
11229		I915_STATE_WARN(active && !encoder->base.crtc,
11230		     "active encoder with no crtc\n");
11231
11232		I915_STATE_WARN(encoder->connectors_active != active,
11233		     "encoder's computed active state doesn't match tracked active state "
11234		     "(expected %i, found %i)\n", active, encoder->connectors_active);
11235
11236		active = encoder->get_hw_state(encoder, &pipe);
11237		I915_STATE_WARN(active != encoder->connectors_active,
11238		     "encoder's hw state doesn't match sw tracking "
11239		     "(expected %i, found %i)\n",
11240		     encoder->connectors_active, active);
11241
11242		if (!encoder->base.crtc)
11243			continue;
11244
11245		tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
11246		I915_STATE_WARN(active && pipe != tracked_pipe,
11247		     "active encoder's pipe doesn't match"
11248		     "(expected %i, found %i)\n",
11249		     tracked_pipe, pipe);
11250
11251	}
11252}
11253
11254static void
11255check_crtc_state(struct drm_device *dev)
11256{
11257	struct drm_i915_private *dev_priv = dev->dev_private;
11258	struct intel_crtc *crtc;
11259	struct intel_encoder *encoder;
11260	struct intel_crtc_state pipe_config;
11261
11262	for_each_intel_crtc(dev, crtc) {
11263		bool enabled = false;
11264		bool active = false;
11265
11266		memset(&pipe_config, 0, sizeof(pipe_config));
11267
11268		DRM_DEBUG_KMS("[CRTC:%d]\n",
11269			      crtc->base.base.id);
11270
11271		I915_STATE_WARN(crtc->active && !crtc->base.state->enable,
11272		     "active crtc, but not enabled in sw tracking\n");
11273
11274		for_each_intel_encoder(dev, encoder) {
11275			if (encoder->base.crtc != &crtc->base)
11276				continue;
11277			enabled = true;
11278			if (encoder->connectors_active)
11279				active = true;
11280		}
11281
11282		I915_STATE_WARN(active != crtc->active,
11283		     "crtc's computed active state doesn't match tracked active state "
11284		     "(expected %i, found %i)\n", active, crtc->active);
11285		I915_STATE_WARN(enabled != crtc->base.state->enable,
11286		     "crtc's computed enabled state doesn't match tracked enabled state "
11287		     "(expected %i, found %i)\n", enabled,
11288				crtc->base.state->enable);
11289
11290		active = dev_priv->display.get_pipe_config(crtc,
11291							   &pipe_config);
11292
11293		/* hw state is inconsistent with the pipe quirk */
11294		if ((crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
11295		    (crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
11296			active = crtc->active;
11297
11298		for_each_intel_encoder(dev, encoder) {
11299			enum pipe pipe;
11300			if (encoder->base.crtc != &crtc->base)
11301				continue;
11302			if (encoder->get_hw_state(encoder, &pipe))
11303				encoder->get_config(encoder, &pipe_config);
11304		}
11305
11306		I915_STATE_WARN(crtc->active != active,
11307		     "crtc active state doesn't match with hw state "
11308		     "(expected %i, found %i)\n", crtc->active, active);
11309
11310		if (active &&
11311		    !intel_pipe_config_compare(dev, crtc->config, &pipe_config)) {
11312			I915_STATE_WARN(1, "pipe state doesn't match!\n");
11313			intel_dump_pipe_config(crtc, &pipe_config,
11314					       "[hw state]");
11315			intel_dump_pipe_config(crtc, crtc->config,
11316					       "[sw state]");
11317		}
11318	}
11319}
11320
11321static void
11322check_shared_dpll_state(struct drm_device *dev)
11323{
11324	struct drm_i915_private *dev_priv = dev->dev_private;
11325	struct intel_crtc *crtc;
11326	struct intel_dpll_hw_state dpll_hw_state;
11327	int i;
11328
11329	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
11330		struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
11331		int enabled_crtcs = 0, active_crtcs = 0;
11332		bool active;
11333
11334		memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11335
11336		DRM_DEBUG_KMS("%s\n", pll->name);
11337
11338		active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
11339
11340		I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
11341		     "more active pll users than references: %i vs %i\n",
11342		     pll->active, hweight32(pll->config.crtc_mask));
11343		I915_STATE_WARN(pll->active && !pll->on,
11344		     "pll in active use but not on in sw tracking\n");
11345		I915_STATE_WARN(pll->on && !pll->active,
11346		     "pll in on but not on in use in sw tracking\n");
11347		I915_STATE_WARN(pll->on != active,
11348		     "pll on state mismatch (expected %i, found %i)\n",
11349		     pll->on, active);
11350
11351		for_each_intel_crtc(dev, crtc) {
11352			if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
11353				enabled_crtcs++;
11354			if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
11355				active_crtcs++;
11356		}
11357		I915_STATE_WARN(pll->active != active_crtcs,
11358		     "pll active crtcs mismatch (expected %i, found %i)\n",
11359		     pll->active, active_crtcs);
11360		I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
11361		     "pll enabled crtcs mismatch (expected %i, found %i)\n",
11362		     hweight32(pll->config.crtc_mask), enabled_crtcs);
11363
11364		I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
11365				       sizeof(dpll_hw_state)),
11366		     "pll hw state mismatch\n");
11367	}
11368}
11369
11370void
11371intel_modeset_check_state(struct drm_device *dev)
11372{
11373	check_wm_state(dev);
11374	check_connector_state(dev);
11375	check_encoder_state(dev);
11376	check_crtc_state(dev);
11377	check_shared_dpll_state(dev);
11378}
11379
11380void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
11381				     int dotclock)
11382{
11383	/*
11384	 * FDI already provided one idea for the dotclock.
11385	 * Yell if the encoder disagrees.
11386	 */
11387	WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
11388	     "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11389	     pipe_config->base.adjusted_mode.crtc_clock, dotclock);
11390}
11391
11392static void update_scanline_offset(struct intel_crtc *crtc)
11393{
11394	struct drm_device *dev = crtc->base.dev;
11395
11396	/*
11397	 * The scanline counter increments at the leading edge of hsync.
11398	 *
11399	 * On most platforms it starts counting from vtotal-1 on the
11400	 * first active line. That means the scanline counter value is
11401	 * always one less than what we would expect. Ie. just after
11402	 * start of vblank, which also occurs at start of hsync (on the
11403	 * last active line), the scanline counter will read vblank_start-1.
11404	 *
11405	 * On gen2 the scanline counter starts counting from 1 instead
11406	 * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11407	 * to keep the value positive), instead of adding one.
11408	 *
11409	 * On HSW+ the behaviour of the scanline counter depends on the output
11410	 * type. For DP ports it behaves like most other platforms, but on HDMI
11411	 * there's an extra 1 line difference. So we need to add two instead of
11412	 * one to the value.
11413	 */
11414	if (IS_GEN2(dev)) {
11415		const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
11416		int vtotal;
11417
11418		vtotal = mode->crtc_vtotal;
11419		if (mode->flags & DRM_MODE_FLAG_INTERLACE)
11420			vtotal /= 2;
11421
11422		crtc->scanline_offset = vtotal - 1;
11423	} else if (HAS_DDI(dev) &&
11424		   intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
11425		crtc->scanline_offset = 2;
11426	} else
11427		crtc->scanline_offset = 1;
11428}
11429
11430static struct intel_crtc_state *
11431intel_modeset_compute_config(struct drm_crtc *crtc,
11432			     struct drm_display_mode *mode,
11433			     struct drm_framebuffer *fb,
11434			     struct drm_atomic_state *state,
11435			     unsigned *modeset_pipes,
11436			     unsigned *prepare_pipes,
11437			     unsigned *disable_pipes)
11438{
11439	struct drm_device *dev = crtc->dev;
11440	struct intel_crtc_state *pipe_config = NULL;
11441	struct intel_crtc *intel_crtc;
11442	int ret = 0;
11443
11444	ret = drm_atomic_add_affected_connectors(state, crtc);
11445	if (ret)
11446		return ERR_PTR(ret);
11447
11448	intel_modeset_affected_pipes(crtc, modeset_pipes,
11449				     prepare_pipes, disable_pipes);
11450
11451	for_each_intel_crtc_masked(dev, *disable_pipes, intel_crtc) {
11452		pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
11453		if (IS_ERR(pipe_config))
11454			return pipe_config;
11455
11456		pipe_config->base.enable = false;
11457	}
11458
11459	/*
11460	 * Note this needs changes when we start tracking multiple modes
11461	 * and crtcs.  At that point we'll need to compute the whole config
11462	 * (i.e. one pipe_config for each crtc) rather than just the one
11463	 * for this crtc.
11464	 */
11465	for_each_intel_crtc_masked(dev, *modeset_pipes, intel_crtc) {
11466		/* FIXME: For now we still expect modeset_pipes has at most
11467		 * one bit set. */
11468		if (WARN_ON(&intel_crtc->base != crtc))
11469			continue;
11470
11471		pipe_config = intel_modeset_pipe_config(crtc, fb, mode, state);
11472		if (IS_ERR(pipe_config))
11473			return pipe_config;
11474
11475		intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
11476				       "[modeset]");
11477	}
11478
11479	return intel_atomic_get_crtc_state(state, to_intel_crtc(crtc));;
11480}
11481
11482static int __intel_set_mode_setup_plls(struct drm_device *dev,
11483				       unsigned modeset_pipes,
11484				       unsigned disable_pipes)
11485{
11486	struct drm_i915_private *dev_priv = to_i915(dev);
11487	unsigned clear_pipes = modeset_pipes | disable_pipes;
11488	struct intel_crtc *intel_crtc;
11489	int ret = 0;
11490
11491	if (!dev_priv->display.crtc_compute_clock)
11492		return 0;
11493
11494	ret = intel_shared_dpll_start_config(dev_priv, clear_pipes);
11495	if (ret)
11496		goto done;
11497
11498	for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
11499		struct intel_crtc_state *state = intel_crtc->new_config;
11500		ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11501							   state);
11502		if (ret) {
11503			intel_shared_dpll_abort_config(dev_priv);
11504			goto done;
11505		}
11506	}
11507
11508done:
11509	return ret;
11510}
11511
11512static int __intel_set_mode(struct drm_crtc *crtc,
11513			    struct drm_display_mode *mode,
11514			    int x, int y, struct drm_framebuffer *fb,
11515			    struct intel_crtc_state *pipe_config,
11516			    unsigned modeset_pipes,
11517			    unsigned prepare_pipes,
11518			    unsigned disable_pipes)
11519{
11520	struct drm_device *dev = crtc->dev;
11521	struct drm_i915_private *dev_priv = dev->dev_private;
11522	struct drm_display_mode *saved_mode;
11523	struct intel_crtc_state *crtc_state_copy = NULL;
11524	struct intel_crtc *intel_crtc;
11525	int ret = 0;
11526
11527	saved_mode = kmalloc(sizeof(*saved_mode), GFP_KERNEL);
11528	if (!saved_mode)
11529		return -ENOMEM;
11530
11531	crtc_state_copy = kmalloc(sizeof(*crtc_state_copy), GFP_KERNEL);
11532	if (!crtc_state_copy) {
11533		ret = -ENOMEM;
11534		goto done;
11535	}
11536
11537	*saved_mode = crtc->mode;
11538
11539	if (modeset_pipes)
11540		to_intel_crtc(crtc)->new_config = pipe_config;
11541
11542	/*
11543	 * See if the config requires any additional preparation, e.g.
11544	 * to adjust global state with pipes off.  We need to do this
11545	 * here so we can get the modeset_pipe updated config for the new
11546	 * mode set on this crtc.  For other crtcs we need to use the
11547	 * adjusted_mode bits in the crtc directly.
11548	 */
11549	if (IS_VALLEYVIEW(dev)) {
11550		valleyview_modeset_global_pipes(dev, &prepare_pipes);
11551
11552		/* may have added more to prepare_pipes than we should */
11553		prepare_pipes &= ~disable_pipes;
11554	}
11555
11556	ret = __intel_set_mode_setup_plls(dev, modeset_pipes, disable_pipes);
11557	if (ret)
11558		goto done;
11559
11560	for_each_intel_crtc_masked(dev, disable_pipes, intel_crtc)
11561		intel_crtc_disable(&intel_crtc->base);
11562
11563	for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
11564		if (intel_crtc->base.state->enable)
11565			dev_priv->display.crtc_disable(&intel_crtc->base);
11566	}
11567
11568	/* crtc->mode is already used by the ->mode_set callbacks, hence we need
11569	 * to set it here already despite that we pass it down the callchain.
11570	 *
11571	 * Note we'll need to fix this up when we start tracking multiple
11572	 * pipes; here we assume a single modeset_pipe and only track the
11573	 * single crtc and mode.
11574	 */
11575	if (modeset_pipes) {
11576		crtc->mode = *mode;
11577		/* mode_set/enable/disable functions rely on a correct pipe
11578		 * config. */
11579		intel_crtc_set_state(to_intel_crtc(crtc), pipe_config);
11580
11581		/*
11582		 * Calculate and store various constants which
11583		 * are later needed by vblank and swap-completion
11584		 * timestamping. They are derived from true hwmode.
11585		 */
11586		drm_calc_timestamping_constants(crtc,
11587						&pipe_config->base.adjusted_mode);
11588	}
11589
11590	/* Only after disabling all output pipelines that will be changed can we
11591	 * update the the output configuration. */
11592	intel_modeset_update_state(dev, prepare_pipes);
11593
11594	modeset_update_crtc_power_domains(pipe_config->base.state);
11595
11596	/* Set up the DPLL and any encoders state that needs to adjust or depend
11597	 * on the DPLL.
11598	 */
11599	for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
11600		struct drm_plane *primary = intel_crtc->base.primary;
11601		int vdisplay, hdisplay;
11602
11603		drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
11604		ret = primary->funcs->update_plane(primary, &intel_crtc->base,
11605						   fb, 0, 0,
11606						   hdisplay, vdisplay,
11607						   x << 16, y << 16,
11608						   hdisplay << 16, vdisplay << 16);
11609	}
11610
11611	/* Now enable the clocks, plane, pipe, and connectors that we set up. */
11612	for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
11613		update_scanline_offset(intel_crtc);
11614
11615		dev_priv->display.crtc_enable(&intel_crtc->base);
11616	}
11617
11618	/* FIXME: add subpixel order */
11619done:
11620	if (ret && crtc->state->enable)
11621		crtc->mode = *saved_mode;
11622
11623	if (ret == 0 && pipe_config) {
11624		struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11625
11626		/* The pipe_config will be freed with the atomic state, so
11627		 * make a copy. */
11628		memcpy(crtc_state_copy, intel_crtc->config,
11629		       sizeof *crtc_state_copy);
11630		intel_crtc->config = crtc_state_copy;
11631		intel_crtc->base.state = &crtc_state_copy->base;
11632
11633		if (modeset_pipes)
11634			intel_crtc->new_config = intel_crtc->config;
11635	} else {
11636		kfree(crtc_state_copy);
11637	}
11638
11639	kfree(saved_mode);
11640	return ret;
11641}
11642
11643static int intel_set_mode_pipes(struct drm_crtc *crtc,
11644				struct drm_display_mode *mode,
11645				int x, int y, struct drm_framebuffer *fb,
11646				struct intel_crtc_state *pipe_config,
11647				unsigned modeset_pipes,
11648				unsigned prepare_pipes,
11649				unsigned disable_pipes)
11650{
11651	int ret;
11652
11653	ret = __intel_set_mode(crtc, mode, x, y, fb, pipe_config, modeset_pipes,
11654			       prepare_pipes, disable_pipes);
11655
11656	if (ret == 0)
11657		intel_modeset_check_state(crtc->dev);
11658
11659	return ret;
11660}
11661
11662static int intel_set_mode(struct drm_crtc *crtc,
11663			  struct drm_display_mode *mode,
11664			  int x, int y, struct drm_framebuffer *fb,
11665			  struct drm_atomic_state *state)
11666{
11667	struct intel_crtc_state *pipe_config;
11668	unsigned modeset_pipes, prepare_pipes, disable_pipes;
11669	int ret = 0;
11670
11671	pipe_config = intel_modeset_compute_config(crtc, mode, fb, state,
11672						   &modeset_pipes,
11673						   &prepare_pipes,
11674						   &disable_pipes);
11675
11676	if (IS_ERR(pipe_config)) {
11677		ret = PTR_ERR(pipe_config);
11678		goto out;
11679	}
11680
11681	ret = intel_set_mode_pipes(crtc, mode, x, y, fb, pipe_config,
11682				   modeset_pipes, prepare_pipes,
11683				   disable_pipes);
11684	if (ret)
11685		goto out;
11686
11687out:
11688	return ret;
11689}
11690
11691void intel_crtc_restore_mode(struct drm_crtc *crtc)
11692{
11693	struct drm_device *dev = crtc->dev;
11694	struct drm_atomic_state *state;
11695	struct intel_encoder *encoder;
11696	struct intel_connector *connector;
11697	struct drm_connector_state *connector_state;
11698
11699	state = drm_atomic_state_alloc(dev);
11700	if (!state) {
11701		DRM_DEBUG_KMS("[CRTC:%d] mode restore failed, out of memory",
11702			      crtc->base.id);
11703		return;
11704	}
11705
11706	state->acquire_ctx = dev->mode_config.acquire_ctx;
11707
11708	/* The force restore path in the HW readout code relies on the staged
11709	 * config still keeping the user requested config while the actual
11710	 * state has been overwritten by the configuration read from HW. We
11711	 * need to copy the staged config to the atomic state, otherwise the
11712	 * mode set will just reapply the state the HW is already in. */
11713	for_each_intel_encoder(dev, encoder) {
11714		if (&encoder->new_crtc->base != crtc)
11715			continue;
11716
11717		for_each_intel_connector(dev, connector) {
11718			if (connector->new_encoder != encoder)
11719				continue;
11720
11721			connector_state = drm_atomic_get_connector_state(state, &connector->base);
11722			if (IS_ERR(connector_state)) {
11723				DRM_DEBUG_KMS("Failed to add [CONNECTOR:%d:%s] to state: %ld\n",
11724					      connector->base.base.id,
11725					      connector->base.name,
11726					      PTR_ERR(connector_state));
11727				continue;
11728			}
11729
11730			connector_state->crtc = crtc;
11731			connector_state->best_encoder = &encoder->base;
11732		}
11733	}
11734
11735	intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y, crtc->primary->fb,
11736		       state);
11737
11738	drm_atomic_state_free(state);
11739}
11740
11741#undef for_each_intel_crtc_masked
11742
11743static void intel_set_config_free(struct intel_set_config *config)
11744{
11745	if (!config)
11746		return;
11747
11748	kfree(config->save_connector_encoders);
11749	kfree(config->save_encoder_crtcs);
11750	kfree(config->save_crtc_enabled);
11751	kfree(config);
11752}
11753
11754static int intel_set_config_save_state(struct drm_device *dev,
11755				       struct intel_set_config *config)
11756{
11757	struct drm_crtc *crtc;
11758	struct drm_encoder *encoder;
11759	struct drm_connector *connector;
11760	int count;
11761
11762	config->save_crtc_enabled =
11763		kcalloc(dev->mode_config.num_crtc,
11764			sizeof(bool), GFP_KERNEL);
11765	if (!config->save_crtc_enabled)
11766		return -ENOMEM;
11767
11768	config->save_encoder_crtcs =
11769		kcalloc(dev->mode_config.num_encoder,
11770			sizeof(struct drm_crtc *), GFP_KERNEL);
11771	if (!config->save_encoder_crtcs)
11772		return -ENOMEM;
11773
11774	config->save_connector_encoders =
11775		kcalloc(dev->mode_config.num_connector,
11776			sizeof(struct drm_encoder *), GFP_KERNEL);
11777	if (!config->save_connector_encoders)
11778		return -ENOMEM;
11779
11780	/* Copy data. Note that driver private data is not affected.
11781	 * Should anything bad happen only the expected state is
11782	 * restored, not the drivers personal bookkeeping.
11783	 */
11784	count = 0;
11785	for_each_crtc(dev, crtc) {
11786		config->save_crtc_enabled[count++] = crtc->state->enable;
11787	}
11788
11789	count = 0;
11790	list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
11791		config->save_encoder_crtcs[count++] = encoder->crtc;
11792	}
11793
11794	count = 0;
11795	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
11796		config->save_connector_encoders[count++] = connector->encoder;
11797	}
11798
11799	return 0;
11800}
11801
11802static void intel_set_config_restore_state(struct drm_device *dev,
11803					   struct intel_set_config *config)
11804{
11805	struct intel_crtc *crtc;
11806	struct intel_encoder *encoder;
11807	struct intel_connector *connector;
11808	int count;
11809
11810	count = 0;
11811	for_each_intel_crtc(dev, crtc) {
11812		crtc->new_enabled = config->save_crtc_enabled[count++];
11813
11814		if (crtc->new_enabled)
11815			crtc->new_config = crtc->config;
11816		else
11817			crtc->new_config = NULL;
11818	}
11819
11820	count = 0;
11821	for_each_intel_encoder(dev, encoder) {
11822		encoder->new_crtc =
11823			to_intel_crtc(config->save_encoder_crtcs[count++]);
11824	}
11825
11826	count = 0;
11827	for_each_intel_connector(dev, connector) {
11828		connector->new_encoder =
11829			to_intel_encoder(config->save_connector_encoders[count++]);
11830	}
11831}
11832
11833static bool
11834is_crtc_connector_off(struct drm_mode_set *set)
11835{
11836	int i;
11837
11838	if (set->num_connectors == 0)
11839		return false;
11840
11841	if (WARN_ON(set->connectors == NULL))
11842		return false;
11843
11844	for (i = 0; i < set->num_connectors; i++)
11845		if (set->connectors[i]->encoder &&
11846		    set->connectors[i]->encoder->crtc == set->crtc &&
11847		    set->connectors[i]->dpms != DRM_MODE_DPMS_ON)
11848			return true;
11849
11850	return false;
11851}
11852
11853static void
11854intel_set_config_compute_mode_changes(struct drm_mode_set *set,
11855				      struct intel_set_config *config)
11856{
11857
11858	/* We should be able to check here if the fb has the same properties
11859	 * and then just flip_or_move it */
11860	if (is_crtc_connector_off(set)) {
11861		config->mode_changed = true;
11862	} else if (set->crtc->primary->fb != set->fb) {
11863		/*
11864		 * If we have no fb, we can only flip as long as the crtc is
11865		 * active, otherwise we need a full mode set.  The crtc may
11866		 * be active if we've only disabled the primary plane, or
11867		 * in fastboot situations.
11868		 */
11869		if (set->crtc->primary->fb == NULL) {
11870			struct intel_crtc *intel_crtc =
11871				to_intel_crtc(set->crtc);
11872
11873			if (intel_crtc->active) {
11874				DRM_DEBUG_KMS("crtc has no fb, will flip\n");
11875				config->fb_changed = true;
11876			} else {
11877				DRM_DEBUG_KMS("inactive crtc, full mode set\n");
11878				config->mode_changed = true;
11879			}
11880		} else if (set->fb == NULL) {
11881			config->mode_changed = true;
11882		} else if (set->fb->pixel_format !=
11883			   set->crtc->primary->fb->pixel_format) {
11884			config->mode_changed = true;
11885		} else {
11886			config->fb_changed = true;
11887		}
11888	}
11889
11890	if (set->fb && (set->x != set->crtc->x || set->y != set->crtc->y))
11891		config->fb_changed = true;
11892
11893	if (set->mode && !drm_mode_equal(set->mode, &set->crtc->mode)) {
11894		DRM_DEBUG_KMS("modes are different, full mode set\n");
11895		drm_mode_debug_printmodeline(&set->crtc->mode);
11896		drm_mode_debug_printmodeline(set->mode);
11897		config->mode_changed = true;
11898	}
11899
11900	DRM_DEBUG_KMS("computed changes for [CRTC:%d], mode_changed=%d, fb_changed=%d\n",
11901			set->crtc->base.id, config->mode_changed, config->fb_changed);
11902}
11903
11904static int
11905intel_modeset_stage_output_state(struct drm_device *dev,
11906				 struct drm_mode_set *set,
11907				 struct intel_set_config *config,
11908				 struct drm_atomic_state *state)
11909{
11910	struct intel_connector *connector;
11911	struct drm_connector_state *connector_state;
11912	struct intel_encoder *encoder;
11913	struct intel_crtc *crtc;
11914	int ro;
11915
11916	/* The upper layers ensure that we either disable a crtc or have a list
11917	 * of connectors. For paranoia, double-check this. */
11918	WARN_ON(!set->fb && (set->num_connectors != 0));
11919	WARN_ON(set->fb && (set->num_connectors == 0));
11920
11921	for_each_intel_connector(dev, connector) {
11922		/* Otherwise traverse passed in connector list and get encoders
11923		 * for them. */
11924		for (ro = 0; ro < set->num_connectors; ro++) {
11925			if (set->connectors[ro] == &connector->base) {
11926				connector->new_encoder = intel_find_encoder(connector, to_intel_crtc(set->crtc)->pipe);
11927				break;
11928			}
11929		}
11930
11931		/* If we disable the crtc, disable all its connectors. Also, if
11932		 * the connector is on the changing crtc but not on the new
11933		 * connector list, disable it. */
11934		if ((!set->fb || ro == set->num_connectors) &&
11935		    connector->base.encoder &&
11936		    connector->base.encoder->crtc == set->crtc) {
11937			connector->new_encoder = NULL;
11938
11939			DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
11940				connector->base.base.id,
11941				connector->base.name);
11942		}
11943
11944
11945		if (&connector->new_encoder->base != connector->base.encoder) {
11946			DRM_DEBUG_KMS("[CONNECTOR:%d:%s] encoder changed, full mode switch\n",
11947				      connector->base.base.id,
11948				      connector->base.name);
11949			config->mode_changed = true;
11950		}
11951	}
11952	/* connector->new_encoder is now updated for all connectors. */
11953
11954	/* Update crtc of enabled connectors. */
11955	for_each_intel_connector(dev, connector) {
11956		struct drm_crtc *new_crtc;
11957
11958		if (!connector->new_encoder)
11959			continue;
11960
11961		new_crtc = connector->new_encoder->base.crtc;
11962
11963		for (ro = 0; ro < set->num_connectors; ro++) {
11964			if (set->connectors[ro] == &connector->base)
11965				new_crtc = set->crtc;
11966		}
11967
11968		/* Make sure the new CRTC will work with the encoder */
11969		if (!drm_encoder_crtc_ok(&connector->new_encoder->base,
11970					 new_crtc)) {
11971			return -EINVAL;
11972		}
11973		connector->new_encoder->new_crtc = to_intel_crtc(new_crtc);
11974
11975		connector_state =
11976			drm_atomic_get_connector_state(state, &connector->base);
11977		if (IS_ERR(connector_state))
11978			return PTR_ERR(connector_state);
11979
11980		connector_state->crtc = new_crtc;
11981		connector_state->best_encoder = &connector->new_encoder->base;
11982
11983		DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
11984			connector->base.base.id,
11985			connector->base.name,
11986			new_crtc->base.id);
11987	}
11988
11989	/* Check for any encoders that needs to be disabled. */
11990	for_each_intel_encoder(dev, encoder) {
11991		int num_connectors = 0;
11992		for_each_intel_connector(dev, connector) {
11993			if (connector->new_encoder == encoder) {
11994				WARN_ON(!connector->new_encoder->new_crtc);
11995				num_connectors++;
11996			}
11997		}
11998
11999		if (num_connectors == 0)
12000			encoder->new_crtc = NULL;
12001		else if (num_connectors > 1)
12002			return -EINVAL;
12003
12004		/* Only now check for crtc changes so we don't miss encoders
12005		 * that will be disabled. */
12006		if (&encoder->new_crtc->base != encoder->base.crtc) {
12007			DRM_DEBUG_KMS("[ENCODER:%d:%s] crtc changed, full mode switch\n",
12008				      encoder->base.base.id,
12009				      encoder->base.name);
12010			config->mode_changed = true;
12011		}
12012	}
12013	/* Now we've also updated encoder->new_crtc for all encoders. */
12014	for_each_intel_connector(dev, connector) {
12015		connector_state =
12016			drm_atomic_get_connector_state(state, &connector->base);
12017		if (IS_ERR(connector_state))
12018			return PTR_ERR(connector_state);
12019
12020		if (connector->new_encoder) {
12021			if (connector->new_encoder != connector->encoder)
12022				connector->encoder = connector->new_encoder;
12023		} else {
12024			connector_state->crtc = NULL;
12025		}
12026	}
12027	for_each_intel_crtc(dev, crtc) {
12028		crtc->new_enabled = false;
12029
12030		for_each_intel_encoder(dev, encoder) {
12031			if (encoder->new_crtc == crtc) {
12032				crtc->new_enabled = true;
12033				break;
12034			}
12035		}
12036
12037		if (crtc->new_enabled != crtc->base.state->enable) {
12038			DRM_DEBUG_KMS("[CRTC:%d] %sabled, full mode switch\n",
12039				      crtc->base.base.id,
12040				      crtc->new_enabled ? "en" : "dis");
12041			config->mode_changed = true;
12042		}
12043
12044		if (crtc->new_enabled)
12045			crtc->new_config = crtc->config;
12046		else
12047			crtc->new_config = NULL;
12048	}
12049
12050	return 0;
12051}
12052
12053static void disable_crtc_nofb(struct intel_crtc *crtc)
12054{
12055	struct drm_device *dev = crtc->base.dev;
12056	struct intel_encoder *encoder;
12057	struct intel_connector *connector;
12058
12059	DRM_DEBUG_KMS("Trying to restore without FB -> disabling pipe %c\n",
12060		      pipe_name(crtc->pipe));
12061
12062	for_each_intel_connector(dev, connector) {
12063		if (connector->new_encoder &&
12064		    connector->new_encoder->new_crtc == crtc)
12065			connector->new_encoder = NULL;
12066	}
12067
12068	for_each_intel_encoder(dev, encoder) {
12069		if (encoder->new_crtc == crtc)
12070			encoder->new_crtc = NULL;
12071	}
12072
12073	crtc->new_enabled = false;
12074	crtc->new_config = NULL;
12075}
12076
12077static int intel_crtc_set_config(struct drm_mode_set *set)
12078{
12079	struct drm_device *dev;
12080	struct drm_mode_set save_set;
12081	struct drm_atomic_state *state = NULL;
12082	struct intel_set_config *config;
12083	struct intel_crtc_state *pipe_config;
12084	unsigned modeset_pipes, prepare_pipes, disable_pipes;
12085	int ret;
12086
12087	BUG_ON(!set);
12088	BUG_ON(!set->crtc);
12089	BUG_ON(!set->crtc->helper_private);
12090
12091	/* Enforce sane interface api - has been abused by the fb helper. */
12092	BUG_ON(!set->mode && set->fb);
12093	BUG_ON(set->fb && set->num_connectors == 0);
12094
12095	if (set->fb) {
12096		DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
12097				set->crtc->base.id, set->fb->base.id,
12098				(int)set->num_connectors, set->x, set->y);
12099	} else {
12100		DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
12101	}
12102
12103	dev = set->crtc->dev;
12104
12105	ret = -ENOMEM;
12106	config = kzalloc(sizeof(*config), GFP_KERNEL);
12107	if (!config)
12108		goto out_config;
12109
12110	ret = intel_set_config_save_state(dev, config);
12111	if (ret)
12112		goto out_config;
12113
12114	save_set.crtc = set->crtc;
12115	save_set.mode = &set->crtc->mode;
12116	save_set.x = set->crtc->x;
12117	save_set.y = set->crtc->y;
12118	save_set.fb = set->crtc->primary->fb;
12119
12120	/* Compute whether we need a full modeset, only an fb base update or no
12121	 * change at all. In the future we might also check whether only the
12122	 * mode changed, e.g. for LVDS where we only change the panel fitter in
12123	 * such cases. */
12124	intel_set_config_compute_mode_changes(set, config);
12125
12126	state = drm_atomic_state_alloc(dev);
12127	if (!state) {
12128		ret = -ENOMEM;
12129		goto out_config;
12130	}
12131
12132	state->acquire_ctx = dev->mode_config.acquire_ctx;
12133
12134	ret = intel_modeset_stage_output_state(dev, set, config, state);
12135	if (ret)
12136		goto fail;
12137
12138	pipe_config = intel_modeset_compute_config(set->crtc, set->mode,
12139						   set->fb, state,
12140						   &modeset_pipes,
12141						   &prepare_pipes,
12142						   &disable_pipes);
12143	if (IS_ERR(pipe_config)) {
12144		ret = PTR_ERR(pipe_config);
12145		goto fail;
12146	} else if (pipe_config) {
12147		if (pipe_config->has_audio !=
12148		    to_intel_crtc(set->crtc)->config->has_audio)
12149			config->mode_changed = true;
12150
12151		/*
12152		 * Note we have an issue here with infoframes: current code
12153		 * only updates them on the full mode set path per hw
12154		 * requirements.  So here we should be checking for any
12155		 * required changes and forcing a mode set.
12156		 */
12157	}
12158
12159	intel_update_pipe_size(to_intel_crtc(set->crtc));
12160
12161	if (config->mode_changed) {
12162		ret = intel_set_mode_pipes(set->crtc, set->mode,
12163					   set->x, set->y, set->fb, pipe_config,
12164					   modeset_pipes, prepare_pipes,
12165					   disable_pipes);
12166	} else if (config->fb_changed) {
12167		struct intel_crtc *intel_crtc = to_intel_crtc(set->crtc);
12168		struct drm_plane *primary = set->crtc->primary;
12169		int vdisplay, hdisplay;
12170
12171		drm_crtc_get_hv_timing(set->mode, &hdisplay, &vdisplay);
12172		ret = primary->funcs->update_plane(primary, set->crtc, set->fb,
12173						   0, 0, hdisplay, vdisplay,
12174						   set->x << 16, set->y << 16,
12175						   hdisplay << 16, vdisplay << 16);
12176
12177		/*
12178		 * We need to make sure the primary plane is re-enabled if it
12179		 * has previously been turned off.
12180		 */
12181		if (!intel_crtc->primary_enabled && ret == 0) {
12182			WARN_ON(!intel_crtc->active);
12183			intel_enable_primary_hw_plane(set->crtc->primary, set->crtc);
12184		}
12185
12186		/*
12187		 * In the fastboot case this may be our only check of the
12188		 * state after boot.  It would be better to only do it on
12189		 * the first update, but we don't have a nice way of doing that
12190		 * (and really, set_config isn't used much for high freq page
12191		 * flipping, so increasing its cost here shouldn't be a big
12192		 * deal).
12193		 */
12194		if (i915.fastboot && ret == 0)
12195			intel_modeset_check_state(set->crtc->dev);
12196	}
12197
12198	if (ret) {
12199		DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
12200			      set->crtc->base.id, ret);
12201fail:
12202		intel_set_config_restore_state(dev, config);
12203
12204		drm_atomic_state_clear(state);
12205
12206		/*
12207		 * HACK: if the pipe was on, but we didn't have a framebuffer,
12208		 * force the pipe off to avoid oopsing in the modeset code
12209		 * due to fb==NULL. This should only happen during boot since
12210		 * we don't yet reconstruct the FB from the hardware state.
12211		 */
12212		if (to_intel_crtc(save_set.crtc)->new_enabled && !save_set.fb)
12213			disable_crtc_nofb(to_intel_crtc(save_set.crtc));
12214
12215		/* Try to restore the config */
12216		if (config->mode_changed &&
12217		    intel_set_mode(save_set.crtc, save_set.mode,
12218				   save_set.x, save_set.y, save_set.fb,
12219				   state))
12220			DRM_ERROR("failed to restore config after modeset failure\n");
12221	}
12222
12223out_config:
12224	if (state)
12225		drm_atomic_state_free(state);
12226
12227	intel_set_config_free(config);
12228	return ret;
12229}
12230
12231static const struct drm_crtc_funcs intel_crtc_funcs = {
12232	.gamma_set = intel_crtc_gamma_set,
12233	.set_config = intel_crtc_set_config,
12234	.destroy = intel_crtc_destroy,
12235	.page_flip = intel_crtc_page_flip,
12236	.atomic_duplicate_state = intel_crtc_duplicate_state,
12237	.atomic_destroy_state = intel_crtc_destroy_state,
12238};
12239
12240static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
12241				      struct intel_shared_dpll *pll,
12242				      struct intel_dpll_hw_state *hw_state)
12243{
12244	uint32_t val;
12245
12246	if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
12247		return false;
12248
12249	val = I915_READ(PCH_DPLL(pll->id));
12250	hw_state->dpll = val;
12251	hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
12252	hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
12253
12254	return val & DPLL_VCO_ENABLE;
12255}
12256
12257static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
12258				  struct intel_shared_dpll *pll)
12259{
12260	I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
12261	I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
12262}
12263
12264static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
12265				struct intel_shared_dpll *pll)
12266{
12267	/* PCH refclock must be enabled first */
12268	ibx_assert_pch_refclk_enabled(dev_priv);
12269
12270	I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
12271
12272	/* Wait for the clocks to stabilize. */
12273	POSTING_READ(PCH_DPLL(pll->id));
12274	udelay(150);
12275
12276	/* The pixel multiplier can only be updated once the
12277	 * DPLL is enabled and the clocks are stable.
12278	 *
12279	 * So write it again.
12280	 */
12281	I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
12282	POSTING_READ(PCH_DPLL(pll->id));
12283	udelay(200);
12284}
12285
12286static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
12287				 struct intel_shared_dpll *pll)
12288{
12289	struct drm_device *dev = dev_priv->dev;
12290	struct intel_crtc *crtc;
12291
12292	/* Make sure no transcoder isn't still depending on us. */
12293	for_each_intel_crtc(dev, crtc) {
12294		if (intel_crtc_to_shared_dpll(crtc) == pll)
12295			assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
12296	}
12297
12298	I915_WRITE(PCH_DPLL(pll->id), 0);
12299	POSTING_READ(PCH_DPLL(pll->id));
12300	udelay(200);
12301}
12302
12303static char *ibx_pch_dpll_names[] = {
12304	"PCH DPLL A",
12305	"PCH DPLL B",
12306};
12307
12308static void ibx_pch_dpll_init(struct drm_device *dev)
12309{
12310	struct drm_i915_private *dev_priv = dev->dev_private;
12311	int i;
12312
12313	dev_priv->num_shared_dpll = 2;
12314
12315	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12316		dev_priv->shared_dplls[i].id = i;
12317		dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
12318		dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
12319		dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
12320		dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
12321		dev_priv->shared_dplls[i].get_hw_state =
12322			ibx_pch_dpll_get_hw_state;
12323	}
12324}
12325
12326static void intel_shared_dpll_init(struct drm_device *dev)
12327{
12328	struct drm_i915_private *dev_priv = dev->dev_private;
12329
12330	if (HAS_DDI(dev))
12331		intel_ddi_pll_init(dev);
12332	else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
12333		ibx_pch_dpll_init(dev);
12334	else
12335		dev_priv->num_shared_dpll = 0;
12336
12337	BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
12338}
12339
12340/**
12341 * intel_wm_need_update - Check whether watermarks need updating
12342 * @plane: drm plane
12343 * @state: new plane state
12344 *
12345 * Check current plane state versus the new one to determine whether
12346 * watermarks need to be recalculated.
12347 *
12348 * Returns true or false.
12349 */
12350bool intel_wm_need_update(struct drm_plane *plane,
12351			  struct drm_plane_state *state)
12352{
12353	/* Update watermarks on tiling changes. */
12354	if (!plane->state->fb || !state->fb ||
12355	    plane->state->fb->modifier[0] != state->fb->modifier[0] ||
12356	    plane->state->rotation != state->rotation)
12357		return true;
12358
12359	return false;
12360}
12361
12362/**
12363 * intel_prepare_plane_fb - Prepare fb for usage on plane
12364 * @plane: drm plane to prepare for
12365 * @fb: framebuffer to prepare for presentation
12366 *
12367 * Prepares a framebuffer for usage on a display plane.  Generally this
12368 * involves pinning the underlying object and updating the frontbuffer tracking
12369 * bits.  Some older platforms need special physical address handling for
12370 * cursor planes.
12371 *
12372 * Returns 0 on success, negative error code on failure.
12373 */
12374int
12375intel_prepare_plane_fb(struct drm_plane *plane,
12376		       struct drm_framebuffer *fb,
12377		       const struct drm_plane_state *new_state)
12378{
12379	struct drm_device *dev = plane->dev;
12380	struct intel_plane *intel_plane = to_intel_plane(plane);
12381	enum pipe pipe = intel_plane->pipe;
12382	struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12383	struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
12384	unsigned frontbuffer_bits = 0;
12385	int ret = 0;
12386
12387	if (!obj)
12388		return 0;
12389
12390	switch (plane->type) {
12391	case DRM_PLANE_TYPE_PRIMARY:
12392		frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(pipe);
12393		break;
12394	case DRM_PLANE_TYPE_CURSOR:
12395		frontbuffer_bits = INTEL_FRONTBUFFER_CURSOR(pipe);
12396		break;
12397	case DRM_PLANE_TYPE_OVERLAY:
12398		frontbuffer_bits = INTEL_FRONTBUFFER_SPRITE(pipe);
12399		break;
12400	}
12401
12402	mutex_lock(&dev->struct_mutex);
12403
12404	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12405	    INTEL_INFO(dev)->cursor_needs_physical) {
12406		int align = IS_I830(dev) ? 16 * 1024 : 256;
12407		ret = i915_gem_object_attach_phys(obj, align);
12408		if (ret)
12409			DRM_DEBUG_KMS("failed to attach phys object\n");
12410	} else {
12411		ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL);
12412	}
12413
12414	if (ret == 0)
12415		i915_gem_track_fb(old_obj, obj, frontbuffer_bits);
12416
12417	mutex_unlock(&dev->struct_mutex);
12418
12419	return ret;
12420}
12421
12422/**
12423 * intel_cleanup_plane_fb - Cleans up an fb after plane use
12424 * @plane: drm plane to clean up for
12425 * @fb: old framebuffer that was on plane
12426 *
12427 * Cleans up a framebuffer that has just been removed from a plane.
12428 */
12429void
12430intel_cleanup_plane_fb(struct drm_plane *plane,
12431		       struct drm_framebuffer *fb,
12432		       const struct drm_plane_state *old_state)
12433{
12434	struct drm_device *dev = plane->dev;
12435	struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12436
12437	if (WARN_ON(!obj))
12438		return;
12439
12440	if (plane->type != DRM_PLANE_TYPE_CURSOR ||
12441	    !INTEL_INFO(dev)->cursor_needs_physical) {
12442		mutex_lock(&dev->struct_mutex);
12443		intel_unpin_fb_obj(fb, old_state);
12444		mutex_unlock(&dev->struct_mutex);
12445	}
12446}
12447
12448static int
12449intel_check_primary_plane(struct drm_plane *plane,
12450			  struct intel_plane_state *state)
12451{
12452	struct drm_device *dev = plane->dev;
12453	struct drm_i915_private *dev_priv = dev->dev_private;
12454	struct drm_crtc *crtc = state->base.crtc;
12455	struct intel_crtc *intel_crtc;
12456	struct drm_framebuffer *fb = state->base.fb;
12457	struct drm_rect *dest = &state->dst;
12458	struct drm_rect *src = &state->src;
12459	const struct drm_rect *clip = &state->clip;
12460	int ret;
12461
12462	crtc = crtc ? crtc : plane->crtc;
12463	intel_crtc = to_intel_crtc(crtc);
12464
12465	ret = drm_plane_helper_check_update(plane, crtc, fb,
12466					    src, dest, clip,
12467					    DRM_PLANE_HELPER_NO_SCALING,
12468					    DRM_PLANE_HELPER_NO_SCALING,
12469					    false, true, &state->visible);
12470	if (ret)
12471		return ret;
12472
12473	if (intel_crtc->active) {
12474		intel_crtc->atomic.wait_for_flips = true;
12475
12476		/*
12477		 * FBC does not work on some platforms for rotated
12478		 * planes, so disable it when rotation is not 0 and
12479		 * update it when rotation is set back to 0.
12480		 *
12481		 * FIXME: This is redundant with the fbc update done in
12482		 * the primary plane enable function except that that
12483		 * one is done too late. We eventually need to unify
12484		 * this.
12485		 */
12486		if (intel_crtc->primary_enabled &&
12487		    INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
12488		    dev_priv->fbc.crtc == intel_crtc &&
12489		    state->base.rotation != BIT(DRM_ROTATE_0)) {
12490			intel_crtc->atomic.disable_fbc = true;
12491		}
12492
12493		if (state->visible) {
12494			/*
12495			 * BDW signals flip done immediately if the plane
12496			 * is disabled, even if the plane enable is already
12497			 * armed to occur at the next vblank :(
12498			 */
12499			if (IS_BROADWELL(dev) && !intel_crtc->primary_enabled)
12500				intel_crtc->atomic.wait_vblank = true;
12501		}
12502
12503		/*
12504		 * FIXME: Actually if we will still have any other plane enabled
12505		 * on the pipe we could let IPS enabled still, but for
12506		 * now lets consider that when we make primary invisible
12507		 * by setting DSPCNTR to 0 on update_primary_plane function
12508		 * IPS needs to be disable.
12509		 */
12510		if (!state->visible || !fb)
12511			intel_crtc->atomic.disable_ips = true;
12512
12513		intel_crtc->atomic.fb_bits |=
12514			INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
12515
12516		intel_crtc->atomic.update_fbc = true;
12517
12518		if (intel_wm_need_update(plane, &state->base))
12519			intel_crtc->atomic.update_wm = true;
12520	}
12521
12522	return 0;
12523}
12524
12525static void
12526intel_commit_primary_plane(struct drm_plane *plane,
12527			   struct intel_plane_state *state)
12528{
12529	struct drm_crtc *crtc = state->base.crtc;
12530	struct drm_framebuffer *fb = state->base.fb;
12531	struct drm_device *dev = plane->dev;
12532	struct drm_i915_private *dev_priv = dev->dev_private;
12533	struct intel_crtc *intel_crtc;
12534	struct drm_rect *src = &state->src;
12535
12536	crtc = crtc ? crtc : plane->crtc;
12537	intel_crtc = to_intel_crtc(crtc);
12538
12539	plane->fb = fb;
12540	crtc->x = src->x1 >> 16;
12541	crtc->y = src->y1 >> 16;
12542
12543	if (intel_crtc->active) {
12544		if (state->visible) {
12545			/* FIXME: kill this fastboot hack */
12546			intel_update_pipe_size(intel_crtc);
12547
12548			intel_crtc->primary_enabled = true;
12549
12550			dev_priv->display.update_primary_plane(crtc, plane->fb,
12551					crtc->x, crtc->y);
12552		} else {
12553			/*
12554			 * If clipping results in a non-visible primary plane,
12555			 * we'll disable the primary plane.  Note that this is
12556			 * a bit different than what happens if userspace
12557			 * explicitly disables the plane by passing fb=0
12558			 * because plane->fb still gets set and pinned.
12559			 */
12560			intel_disable_primary_hw_plane(plane, crtc);
12561		}
12562	}
12563}
12564
12565static void intel_begin_crtc_commit(struct drm_crtc *crtc)
12566{
12567	struct drm_device *dev = crtc->dev;
12568	struct drm_i915_private *dev_priv = dev->dev_private;
12569	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12570	struct intel_plane *intel_plane;
12571	struct drm_plane *p;
12572	unsigned fb_bits = 0;
12573
12574	/* Track fb's for any planes being disabled */
12575	list_for_each_entry(p, &dev->mode_config.plane_list, head) {
12576		intel_plane = to_intel_plane(p);
12577
12578		if (intel_crtc->atomic.disabled_planes &
12579		    (1 << drm_plane_index(p))) {
12580			switch (p->type) {
12581			case DRM_PLANE_TYPE_PRIMARY:
12582				fb_bits = INTEL_FRONTBUFFER_PRIMARY(intel_plane->pipe);
12583				break;
12584			case DRM_PLANE_TYPE_CURSOR:
12585				fb_bits = INTEL_FRONTBUFFER_CURSOR(intel_plane->pipe);
12586				break;
12587			case DRM_PLANE_TYPE_OVERLAY:
12588				fb_bits = INTEL_FRONTBUFFER_SPRITE(intel_plane->pipe);
12589				break;
12590			}
12591
12592			mutex_lock(&dev->struct_mutex);
12593			i915_gem_track_fb(intel_fb_obj(p->fb), NULL, fb_bits);
12594			mutex_unlock(&dev->struct_mutex);
12595		}
12596	}
12597
12598	if (intel_crtc->atomic.wait_for_flips)
12599		intel_crtc_wait_for_pending_flips(crtc);
12600
12601	if (intel_crtc->atomic.disable_fbc)
12602		intel_fbc_disable(dev);
12603
12604	if (intel_crtc->atomic.disable_ips)
12605		hsw_disable_ips(intel_crtc);
12606
12607	if (intel_crtc->atomic.pre_disable_primary)
12608		intel_pre_disable_primary(crtc);
12609
12610	if (intel_crtc->atomic.update_wm)
12611		intel_update_watermarks(crtc);
12612
12613	intel_runtime_pm_get(dev_priv);
12614
12615	/* Perform vblank evasion around commit operation */
12616	if (intel_crtc->active)
12617		intel_crtc->atomic.evade =
12618			intel_pipe_update_start(intel_crtc,
12619						&intel_crtc->atomic.start_vbl_count);
12620}
12621
12622static void intel_finish_crtc_commit(struct drm_crtc *crtc)
12623{
12624	struct drm_device *dev = crtc->dev;
12625	struct drm_i915_private *dev_priv = dev->dev_private;
12626	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12627	struct drm_plane *p;
12628
12629	if (intel_crtc->atomic.evade)
12630		intel_pipe_update_end(intel_crtc,
12631				      intel_crtc->atomic.start_vbl_count);
12632
12633	intel_runtime_pm_put(dev_priv);
12634
12635	if (intel_crtc->atomic.wait_vblank)
12636		intel_wait_for_vblank(dev, intel_crtc->pipe);
12637
12638	intel_frontbuffer_flip(dev, intel_crtc->atomic.fb_bits);
12639
12640	if (intel_crtc->atomic.update_fbc) {
12641		mutex_lock(&dev->struct_mutex);
12642		intel_fbc_update(dev);
12643		mutex_unlock(&dev->struct_mutex);
12644	}
12645
12646	if (intel_crtc->atomic.post_enable_primary)
12647		intel_post_enable_primary(crtc);
12648
12649	drm_for_each_legacy_plane(p, &dev->mode_config.plane_list)
12650		if (intel_crtc->atomic.update_sprite_watermarks & drm_plane_index(p))
12651			intel_update_sprite_watermarks(p, crtc, 0, 0, 0,
12652						       false, false);
12653
12654	memset(&intel_crtc->atomic, 0, sizeof(intel_crtc->atomic));
12655}
12656
12657/**
12658 * intel_plane_destroy - destroy a plane
12659 * @plane: plane to destroy
12660 *
12661 * Common destruction function for all types of planes (primary, cursor,
12662 * sprite).
12663 */
12664void intel_plane_destroy(struct drm_plane *plane)
12665{
12666	struct intel_plane *intel_plane = to_intel_plane(plane);
12667	drm_plane_cleanup(plane);
12668	kfree(intel_plane);
12669}
12670
12671const struct drm_plane_funcs intel_plane_funcs = {
12672	.update_plane = drm_plane_helper_update,
12673	.disable_plane = drm_plane_helper_disable,
12674	.destroy = intel_plane_destroy,
12675	.set_property = drm_atomic_helper_plane_set_property,
12676	.atomic_get_property = intel_plane_atomic_get_property,
12677	.atomic_set_property = intel_plane_atomic_set_property,
12678	.atomic_duplicate_state = intel_plane_duplicate_state,
12679	.atomic_destroy_state = intel_plane_destroy_state,
12680
12681};
12682
12683static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
12684						    int pipe)
12685{
12686	struct intel_plane *primary;
12687	struct intel_plane_state *state;
12688	const uint32_t *intel_primary_formats;
12689	int num_formats;
12690
12691	primary = kzalloc(sizeof(*primary), GFP_KERNEL);
12692	if (primary == NULL)
12693		return NULL;
12694
12695	state = intel_create_plane_state(&primary->base);
12696	if (!state) {
12697		kfree(primary);
12698		return NULL;
12699	}
12700	primary->base.state = &state->base;
12701
12702	primary->can_scale = false;
12703	primary->max_downscale = 1;
12704	primary->pipe = pipe;
12705	primary->plane = pipe;
12706	primary->check_plane = intel_check_primary_plane;
12707	primary->commit_plane = intel_commit_primary_plane;
12708	if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
12709		primary->plane = !pipe;
12710
12711	if (INTEL_INFO(dev)->gen <= 3) {
12712		intel_primary_formats = intel_primary_formats_gen2;
12713		num_formats = ARRAY_SIZE(intel_primary_formats_gen2);
12714	} else {
12715		intel_primary_formats = intel_primary_formats_gen4;
12716		num_formats = ARRAY_SIZE(intel_primary_formats_gen4);
12717	}
12718
12719	drm_universal_plane_init(dev, &primary->base, 0,
12720				 &intel_plane_funcs,
12721				 intel_primary_formats, num_formats,
12722				 DRM_PLANE_TYPE_PRIMARY);
12723
12724	if (INTEL_INFO(dev)->gen >= 4) {
12725		if (!dev->mode_config.rotation_property)
12726			dev->mode_config.rotation_property =
12727				drm_mode_create_rotation_property(dev,
12728							BIT(DRM_ROTATE_0) |
12729							BIT(DRM_ROTATE_180));
12730		if (dev->mode_config.rotation_property)
12731			drm_object_attach_property(&primary->base.base,
12732				dev->mode_config.rotation_property,
12733				state->base.rotation);
12734	}
12735
12736	drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
12737
12738	return &primary->base;
12739}
12740
12741static int
12742intel_check_cursor_plane(struct drm_plane *plane,
12743			 struct intel_plane_state *state)
12744{
12745	struct drm_crtc *crtc = state->base.crtc;
12746	struct drm_device *dev = plane->dev;
12747	struct drm_framebuffer *fb = state->base.fb;
12748	struct drm_rect *dest = &state->dst;
12749	struct drm_rect *src = &state->src;
12750	const struct drm_rect *clip = &state->clip;
12751	struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12752	struct intel_crtc *intel_crtc;
12753	unsigned stride;
12754	int ret;
12755
12756	crtc = crtc ? crtc : plane->crtc;
12757	intel_crtc = to_intel_crtc(crtc);
12758
12759	ret = drm_plane_helper_check_update(plane, crtc, fb,
12760					    src, dest, clip,
12761					    DRM_PLANE_HELPER_NO_SCALING,
12762					    DRM_PLANE_HELPER_NO_SCALING,
12763					    true, true, &state->visible);
12764	if (ret)
12765		return ret;
12766
12767
12768	/* if we want to turn off the cursor ignore width and height */
12769	if (!obj)
12770		goto finish;
12771
12772	/* Check for which cursor types we support */
12773	if (!cursor_size_ok(dev, state->base.crtc_w, state->base.crtc_h)) {
12774		DRM_DEBUG("Cursor dimension %dx%d not supported\n",
12775			  state->base.crtc_w, state->base.crtc_h);
12776		return -EINVAL;
12777	}
12778
12779	stride = roundup_pow_of_two(state->base.crtc_w) * 4;
12780	if (obj->base.size < stride * state->base.crtc_h) {
12781		DRM_DEBUG_KMS("buffer is too small\n");
12782		return -ENOMEM;
12783	}
12784
12785	if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
12786		DRM_DEBUG_KMS("cursor cannot be tiled\n");
12787		ret = -EINVAL;
12788	}
12789
12790finish:
12791	if (intel_crtc->active) {
12792		if (plane->state->crtc_w != state->base.crtc_w)
12793			intel_crtc->atomic.update_wm = true;
12794
12795		intel_crtc->atomic.fb_bits |=
12796			INTEL_FRONTBUFFER_CURSOR(intel_crtc->pipe);
12797	}
12798
12799	return ret;
12800}
12801
12802static void
12803intel_commit_cursor_plane(struct drm_plane *plane,
12804			  struct intel_plane_state *state)
12805{
12806	struct drm_crtc *crtc = state->base.crtc;
12807	struct drm_device *dev = plane->dev;
12808	struct intel_crtc *intel_crtc;
12809	struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
12810	uint32_t addr;
12811
12812	crtc = crtc ? crtc : plane->crtc;
12813	intel_crtc = to_intel_crtc(crtc);
12814
12815	plane->fb = state->base.fb;
12816	crtc->cursor_x = state->base.crtc_x;
12817	crtc->cursor_y = state->base.crtc_y;
12818
12819	if (intel_crtc->cursor_bo == obj)
12820		goto update;
12821
12822	if (!obj)
12823		addr = 0;
12824	else if (!INTEL_INFO(dev)->cursor_needs_physical)
12825		addr = i915_gem_obj_ggtt_offset(obj);
12826	else
12827		addr = obj->phys_handle->busaddr;
12828
12829	intel_crtc->cursor_addr = addr;
12830	intel_crtc->cursor_bo = obj;
12831update:
12832
12833	if (intel_crtc->active)
12834		intel_crtc_update_cursor(crtc, state->visible);
12835}
12836
12837static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
12838						   int pipe)
12839{
12840	struct intel_plane *cursor;
12841	struct intel_plane_state *state;
12842
12843	cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
12844	if (cursor == NULL)
12845		return NULL;
12846
12847	state = intel_create_plane_state(&cursor->base);
12848	if (!state) {
12849		kfree(cursor);
12850		return NULL;
12851	}
12852	cursor->base.state = &state->base;
12853
12854	cursor->can_scale = false;
12855	cursor->max_downscale = 1;
12856	cursor->pipe = pipe;
12857	cursor->plane = pipe;
12858	cursor->check_plane = intel_check_cursor_plane;
12859	cursor->commit_plane = intel_commit_cursor_plane;
12860
12861	drm_universal_plane_init(dev, &cursor->base, 0,
12862				 &intel_plane_funcs,
12863				 intel_cursor_formats,
12864				 ARRAY_SIZE(intel_cursor_formats),
12865				 DRM_PLANE_TYPE_CURSOR);
12866
12867	if (INTEL_INFO(dev)->gen >= 4) {
12868		if (!dev->mode_config.rotation_property)
12869			dev->mode_config.rotation_property =
12870				drm_mode_create_rotation_property(dev,
12871							BIT(DRM_ROTATE_0) |
12872							BIT(DRM_ROTATE_180));
12873		if (dev->mode_config.rotation_property)
12874			drm_object_attach_property(&cursor->base.base,
12875				dev->mode_config.rotation_property,
12876				state->base.rotation);
12877	}
12878
12879	drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
12880
12881	return &cursor->base;
12882}
12883
12884static void intel_crtc_init(struct drm_device *dev, int pipe)
12885{
12886	struct drm_i915_private *dev_priv = dev->dev_private;
12887	struct intel_crtc *intel_crtc;
12888	struct intel_crtc_state *crtc_state = NULL;
12889	struct drm_plane *primary = NULL;
12890	struct drm_plane *cursor = NULL;
12891	int i, ret;
12892
12893	intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
12894	if (intel_crtc == NULL)
12895		return;
12896
12897	crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
12898	if (!crtc_state)
12899		goto fail;
12900	intel_crtc_set_state(intel_crtc, crtc_state);
12901	crtc_state->base.crtc = &intel_crtc->base;
12902
12903	primary = intel_primary_plane_create(dev, pipe);
12904	if (!primary)
12905		goto fail;
12906
12907	cursor = intel_cursor_plane_create(dev, pipe);
12908	if (!cursor)
12909		goto fail;
12910
12911	ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
12912					cursor, &intel_crtc_funcs);
12913	if (ret)
12914		goto fail;
12915
12916	drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
12917	for (i = 0; i < 256; i++) {
12918		intel_crtc->lut_r[i] = i;
12919		intel_crtc->lut_g[i] = i;
12920		intel_crtc->lut_b[i] = i;
12921	}
12922
12923	/*
12924	 * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
12925	 * is hooked to pipe B. Hence we want plane A feeding pipe B.
12926	 */
12927	intel_crtc->pipe = pipe;
12928	intel_crtc->plane = pipe;
12929	if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
12930		DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
12931		intel_crtc->plane = !pipe;
12932	}
12933
12934	intel_crtc->cursor_base = ~0;
12935	intel_crtc->cursor_cntl = ~0;
12936	intel_crtc->cursor_size = ~0;
12937
12938	BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
12939	       dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
12940	dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
12941	dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
12942
12943	INIT_WORK(&intel_crtc->mmio_flip.work, intel_mmio_flip_work_func);
12944
12945	drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
12946
12947	WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
12948	return;
12949
12950fail:
12951	if (primary)
12952		drm_plane_cleanup(primary);
12953	if (cursor)
12954		drm_plane_cleanup(cursor);
12955	kfree(crtc_state);
12956	kfree(intel_crtc);
12957}
12958
12959enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
12960{
12961	struct drm_encoder *encoder = connector->base.encoder;
12962	struct drm_device *dev = connector->base.dev;
12963
12964	WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
12965
12966	if (!encoder || WARN_ON(!encoder->crtc))
12967		return INVALID_PIPE;
12968
12969	return to_intel_crtc(encoder->crtc)->pipe;
12970}
12971
12972int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
12973				struct drm_file *file)
12974{
12975	struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
12976	struct drm_crtc *drmmode_crtc;
12977	struct intel_crtc *crtc;
12978
12979	drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
12980
12981	if (!drmmode_crtc) {
12982		DRM_ERROR("no such CRTC id\n");
12983		return -ENOENT;
12984	}
12985
12986	crtc = to_intel_crtc(drmmode_crtc);
12987	pipe_from_crtc_id->pipe = crtc->pipe;
12988
12989	return 0;
12990}
12991
12992static int intel_encoder_clones(struct intel_encoder *encoder)
12993{
12994	struct drm_device *dev = encoder->base.dev;
12995	struct intel_encoder *source_encoder;
12996	int index_mask = 0;
12997	int entry = 0;
12998
12999	for_each_intel_encoder(dev, source_encoder) {
13000		if (encoders_cloneable(encoder, source_encoder))
13001			index_mask |= (1 << entry);
13002
13003		entry++;
13004	}
13005
13006	return index_mask;
13007}
13008
13009static bool has_edp_a(struct drm_device *dev)
13010{
13011	struct drm_i915_private *dev_priv = dev->dev_private;
13012
13013	if (!IS_MOBILE(dev))
13014		return false;
13015
13016	if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13017		return false;
13018
13019	if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13020		return false;
13021
13022	return true;
13023}
13024
13025static bool intel_crt_present(struct drm_device *dev)
13026{
13027	struct drm_i915_private *dev_priv = dev->dev_private;
13028
13029	if (INTEL_INFO(dev)->gen >= 9)
13030		return false;
13031
13032	if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13033		return false;
13034
13035	if (IS_CHERRYVIEW(dev))
13036		return false;
13037
13038	if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
13039		return false;
13040
13041	return true;
13042}
13043
13044static void intel_setup_outputs(struct drm_device *dev)
13045{
13046	struct drm_i915_private *dev_priv = dev->dev_private;
13047	struct intel_encoder *encoder;
13048	bool dpd_is_edp = false;
13049
13050	intel_lvds_init(dev);
13051
13052	if (intel_crt_present(dev))
13053		intel_crt_init(dev);
13054
13055	if (HAS_DDI(dev)) {
13056		int found;
13057
13058		/*
13059		 * Haswell uses DDI functions to detect digital outputs.
13060		 * On SKL pre-D0 the strap isn't connected, so we assume
13061		 * it's there.
13062		 */
13063		found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
13064		/* WaIgnoreDDIAStrap: skl */
13065		if (found ||
13066		    (IS_SKYLAKE(dev) && INTEL_REVID(dev) < SKL_REVID_D0))
13067			intel_ddi_init(dev, PORT_A);
13068
13069		/* DDI B, C and D detection is indicated by the SFUSE_STRAP
13070		 * register */
13071		found = I915_READ(SFUSE_STRAP);
13072
13073		if (found & SFUSE_STRAP_DDIB_DETECTED)
13074			intel_ddi_init(dev, PORT_B);
13075		if (found & SFUSE_STRAP_DDIC_DETECTED)
13076			intel_ddi_init(dev, PORT_C);
13077		if (found & SFUSE_STRAP_DDID_DETECTED)
13078			intel_ddi_init(dev, PORT_D);
13079	} else if (HAS_PCH_SPLIT(dev)) {
13080		int found;
13081		dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13082
13083		if (has_edp_a(dev))
13084			intel_dp_init(dev, DP_A, PORT_A);
13085
13086		if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13087			/* PCH SDVOB multiplex with HDMIB */
13088			found = intel_sdvo_init(dev, PCH_SDVOB, true);
13089			if (!found)
13090				intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13091			if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13092				intel_dp_init(dev, PCH_DP_B, PORT_B);
13093		}
13094
13095		if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13096			intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
13097
13098		if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13099			intel_hdmi_init(dev, PCH_HDMID, PORT_D);
13100
13101		if (I915_READ(PCH_DP_C) & DP_DETECTED)
13102			intel_dp_init(dev, PCH_DP_C, PORT_C);
13103
13104		if (I915_READ(PCH_DP_D) & DP_DETECTED)
13105			intel_dp_init(dev, PCH_DP_D, PORT_D);
13106	} else if (IS_VALLEYVIEW(dev)) {
13107		/*
13108		 * The DP_DETECTED bit is the latched state of the DDC
13109		 * SDA pin at boot. However since eDP doesn't require DDC
13110		 * (no way to plug in a DP->HDMI dongle) the DDC pins for
13111		 * eDP ports may have been muxed to an alternate function.
13112		 * Thus we can't rely on the DP_DETECTED bit alone to detect
13113		 * eDP ports. Consult the VBT as well as DP_DETECTED to
13114		 * detect eDP ports.
13115		 */
13116		if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
13117		    !intel_dp_is_edp(dev, PORT_B))
13118			intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
13119					PORT_B);
13120		if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
13121		    intel_dp_is_edp(dev, PORT_B))
13122			intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
13123
13124		if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
13125		    !intel_dp_is_edp(dev, PORT_C))
13126			intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
13127					PORT_C);
13128		if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
13129		    intel_dp_is_edp(dev, PORT_C))
13130			intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
13131
13132		if (IS_CHERRYVIEW(dev)) {
13133			if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
13134				intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
13135						PORT_D);
13136			/* eDP not supported on port D, so don't check VBT */
13137			if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
13138				intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
13139		}
13140
13141		intel_dsi_init(dev);
13142	} else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
13143		bool found = false;
13144
13145		if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13146			DRM_DEBUG_KMS("probing SDVOB\n");
13147			found = intel_sdvo_init(dev, GEN3_SDVOB, true);
13148			if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
13149				DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13150				intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
13151			}
13152
13153			if (!found && SUPPORTS_INTEGRATED_DP(dev))
13154				intel_dp_init(dev, DP_B, PORT_B);
13155		}
13156
13157		/* Before G4X SDVOC doesn't have its own detect register */
13158
13159		if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13160			DRM_DEBUG_KMS("probing SDVOC\n");
13161			found = intel_sdvo_init(dev, GEN3_SDVOC, false);
13162		}
13163
13164		if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13165
13166			if (SUPPORTS_INTEGRATED_HDMI(dev)) {
13167				DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13168				intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
13169			}
13170			if (SUPPORTS_INTEGRATED_DP(dev))
13171				intel_dp_init(dev, DP_C, PORT_C);
13172		}
13173
13174		if (SUPPORTS_INTEGRATED_DP(dev) &&
13175		    (I915_READ(DP_D) & DP_DETECTED))
13176			intel_dp_init(dev, DP_D, PORT_D);
13177	} else if (IS_GEN2(dev))
13178		intel_dvo_init(dev);
13179
13180	if (SUPPORTS_TV(dev))
13181		intel_tv_init(dev);
13182
13183	intel_psr_init(dev);
13184
13185	for_each_intel_encoder(dev, encoder) {
13186		encoder->base.possible_crtcs = encoder->crtc_mask;
13187		encoder->base.possible_clones =
13188			intel_encoder_clones(encoder);
13189	}
13190
13191	intel_init_pch_refclk(dev);
13192
13193	drm_helper_move_panel_connectors_to_head(dev);
13194}
13195
13196static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13197{
13198	struct drm_device *dev = fb->dev;
13199	struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13200
13201	drm_framebuffer_cleanup(fb);
13202	mutex_lock(&dev->struct_mutex);
13203	WARN_ON(!intel_fb->obj->framebuffer_references--);
13204	drm_gem_object_unreference(&intel_fb->obj->base);
13205	mutex_unlock(&dev->struct_mutex);
13206	kfree(intel_fb);
13207}
13208
13209static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13210						struct drm_file *file,
13211						unsigned int *handle)
13212{
13213	struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13214	struct drm_i915_gem_object *obj = intel_fb->obj;
13215
13216	if (obj->userptr.mm) {
13217		DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
13218		return -EINVAL;
13219	}
13220
13221	return drm_gem_handle_create(file, &obj->base, handle);
13222}
13223
13224static const struct drm_framebuffer_funcs intel_fb_funcs = {
13225	.destroy = intel_user_framebuffer_destroy,
13226	.create_handle = intel_user_framebuffer_create_handle,
13227};
13228
13229static
13230u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
13231			 uint32_t pixel_format)
13232{
13233	u32 gen = INTEL_INFO(dev)->gen;
13234
13235	if (gen >= 9) {
13236		/* "The stride in bytes must not exceed the of the size of 8K
13237		 *  pixels and 32K bytes."
13238		 */
13239		 return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
13240	} else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
13241		return 32*1024;
13242	} else if (gen >= 4) {
13243		if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13244			return 16*1024;
13245		else
13246			return 32*1024;
13247	} else if (gen >= 3) {
13248		if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13249			return 8*1024;
13250		else
13251			return 16*1024;
13252	} else {
13253		/* XXX DSPC is limited to 4k tiled */
13254		return 8*1024;
13255	}
13256}
13257
13258static int intel_framebuffer_init(struct drm_device *dev,
13259				  struct intel_framebuffer *intel_fb,
13260				  struct drm_mode_fb_cmd2 *mode_cmd,
13261				  struct drm_i915_gem_object *obj)
13262{
13263	unsigned int aligned_height;
13264	int ret;
13265	u32 pitch_limit, stride_alignment;
13266
13267	WARN_ON(!mutex_is_locked(&dev->struct_mutex));
13268
13269	if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
13270		/* Enforce that fb modifier and tiling mode match, but only for
13271		 * X-tiled. This is needed for FBC. */
13272		if (!!(obj->tiling_mode == I915_TILING_X) !=
13273		    !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
13274			DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
13275			return -EINVAL;
13276		}
13277	} else {
13278		if (obj->tiling_mode == I915_TILING_X)
13279			mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
13280		else if (obj->tiling_mode == I915_TILING_Y) {
13281			DRM_DEBUG("No Y tiling for legacy addfb\n");
13282			return -EINVAL;
13283		}
13284	}
13285
13286	/* Passed in modifier sanity checking. */
13287	switch (mode_cmd->modifier[0]) {
13288	case I915_FORMAT_MOD_Y_TILED:
13289	case I915_FORMAT_MOD_Yf_TILED:
13290		if (INTEL_INFO(dev)->gen < 9) {
13291			DRM_DEBUG("Unsupported tiling 0x%llx!\n",
13292				  mode_cmd->modifier[0]);
13293			return -EINVAL;
13294		}
13295	case DRM_FORMAT_MOD_NONE:
13296	case I915_FORMAT_MOD_X_TILED:
13297		break;
13298	default:
13299		DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
13300			  mode_cmd->modifier[0]);
13301		return -EINVAL;
13302	}
13303
13304	stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
13305						     mode_cmd->pixel_format);
13306	if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
13307		DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
13308			  mode_cmd->pitches[0], stride_alignment);
13309		return -EINVAL;
13310	}
13311
13312	pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
13313					   mode_cmd->pixel_format);
13314	if (mode_cmd->pitches[0] > pitch_limit) {
13315		DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
13316			  mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
13317			  "tiled" : "linear",
13318			  mode_cmd->pitches[0], pitch_limit);
13319		return -EINVAL;
13320	}
13321
13322	if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
13323	    mode_cmd->pitches[0] != obj->stride) {
13324		DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
13325			  mode_cmd->pitches[0], obj->stride);
13326		return -EINVAL;
13327	}
13328
13329	/* Reject formats not supported by any plane early. */
13330	switch (mode_cmd->pixel_format) {
13331	case DRM_FORMAT_C8:
13332	case DRM_FORMAT_RGB565:
13333	case DRM_FORMAT_XRGB8888:
13334	case DRM_FORMAT_ARGB8888:
13335		break;
13336	case DRM_FORMAT_XRGB1555:
13337	case DRM_FORMAT_ARGB1555:
13338		if (INTEL_INFO(dev)->gen > 3) {
13339			DRM_DEBUG("unsupported pixel format: %s\n",
13340				  drm_get_format_name(mode_cmd->pixel_format));
13341			return -EINVAL;
13342		}
13343		break;
13344	case DRM_FORMAT_XBGR8888:
13345	case DRM_FORMAT_ABGR8888:
13346	case DRM_FORMAT_XRGB2101010:
13347	case DRM_FORMAT_ARGB2101010:
13348	case DRM_FORMAT_XBGR2101010:
13349	case DRM_FORMAT_ABGR2101010:
13350		if (INTEL_INFO(dev)->gen < 4) {
13351			DRM_DEBUG("unsupported pixel format: %s\n",
13352				  drm_get_format_name(mode_cmd->pixel_format));
13353			return -EINVAL;
13354		}
13355		break;
13356	case DRM_FORMAT_YUYV:
13357	case DRM_FORMAT_UYVY:
13358	case DRM_FORMAT_YVYU:
13359	case DRM_FORMAT_VYUY:
13360		if (INTEL_INFO(dev)->gen < 5) {
13361			DRM_DEBUG("unsupported pixel format: %s\n",
13362				  drm_get_format_name(mode_cmd->pixel_format));
13363			return -EINVAL;
13364		}
13365		break;
13366	default:
13367		DRM_DEBUG("unsupported pixel format: %s\n",
13368			  drm_get_format_name(mode_cmd->pixel_format));
13369		return -EINVAL;
13370	}
13371
13372	/* FIXME need to adjust LINOFF/TILEOFF accordingly. */
13373	if (mode_cmd->offsets[0] != 0)
13374		return -EINVAL;
13375
13376	aligned_height = intel_fb_align_height(dev, mode_cmd->height,
13377					       mode_cmd->pixel_format,
13378					       mode_cmd->modifier[0]);
13379	/* FIXME drm helper for size checks (especially planar formats)? */
13380	if (obj->base.size < aligned_height * mode_cmd->pitches[0])
13381		return -EINVAL;
13382
13383	drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
13384	intel_fb->obj = obj;
13385	intel_fb->obj->framebuffer_references++;
13386
13387	ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
13388	if (ret) {
13389		DRM_ERROR("framebuffer init failed %d\n", ret);
13390		return ret;
13391	}
13392
13393	return 0;
13394}
13395
13396static struct drm_framebuffer *
13397intel_user_framebuffer_create(struct drm_device *dev,
13398			      struct drm_file *filp,
13399			      struct drm_mode_fb_cmd2 *mode_cmd)
13400{
13401	struct drm_i915_gem_object *obj;
13402
13403	obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
13404						mode_cmd->handles[0]));
13405	if (&obj->base == NULL)
13406		return ERR_PTR(-ENOENT);
13407
13408	return intel_framebuffer_create(dev, mode_cmd, obj);
13409}
13410
13411#ifndef CONFIG_DRM_I915_FBDEV
13412static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
13413{
13414}
13415#endif
13416
13417static const struct drm_mode_config_funcs intel_mode_funcs = {
13418	.fb_create = intel_user_framebuffer_create,
13419	.output_poll_changed = intel_fbdev_output_poll_changed,
13420	.atomic_check = intel_atomic_check,
13421	.atomic_commit = intel_atomic_commit,
13422};
13423
13424/* Set up chip specific display functions */
13425static void intel_init_display(struct drm_device *dev)
13426{
13427	struct drm_i915_private *dev_priv = dev->dev_private;
13428
13429	if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
13430		dev_priv->display.find_dpll = g4x_find_best_dpll;
13431	else if (IS_CHERRYVIEW(dev))
13432		dev_priv->display.find_dpll = chv_find_best_dpll;
13433	else if (IS_VALLEYVIEW(dev))
13434		dev_priv->display.find_dpll = vlv_find_best_dpll;
13435	else if (IS_PINEVIEW(dev))
13436		dev_priv->display.find_dpll = pnv_find_best_dpll;
13437	else
13438		dev_priv->display.find_dpll = i9xx_find_best_dpll;
13439
13440	if (INTEL_INFO(dev)->gen >= 9) {
13441		dev_priv->display.get_pipe_config = haswell_get_pipe_config;
13442		dev_priv->display.get_initial_plane_config =
13443			skylake_get_initial_plane_config;
13444		dev_priv->display.crtc_compute_clock =
13445			haswell_crtc_compute_clock;
13446		dev_priv->display.crtc_enable = haswell_crtc_enable;
13447		dev_priv->display.crtc_disable = haswell_crtc_disable;
13448		dev_priv->display.off = ironlake_crtc_off;
13449		dev_priv->display.update_primary_plane =
13450			skylake_update_primary_plane;
13451	} else if (HAS_DDI(dev)) {
13452		dev_priv->display.get_pipe_config = haswell_get_pipe_config;
13453		dev_priv->display.get_initial_plane_config =
13454			ironlake_get_initial_plane_config;
13455		dev_priv->display.crtc_compute_clock =
13456			haswell_crtc_compute_clock;
13457		dev_priv->display.crtc_enable = haswell_crtc_enable;
13458		dev_priv->display.crtc_disable = haswell_crtc_disable;
13459		dev_priv->display.off = ironlake_crtc_off;
13460		dev_priv->display.update_primary_plane =
13461			ironlake_update_primary_plane;
13462	} else if (HAS_PCH_SPLIT(dev)) {
13463		dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
13464		dev_priv->display.get_initial_plane_config =
13465			ironlake_get_initial_plane_config;
13466		dev_priv->display.crtc_compute_clock =
13467			ironlake_crtc_compute_clock;
13468		dev_priv->display.crtc_enable = ironlake_crtc_enable;
13469		dev_priv->display.crtc_disable = ironlake_crtc_disable;
13470		dev_priv->display.off = ironlake_crtc_off;
13471		dev_priv->display.update_primary_plane =
13472			ironlake_update_primary_plane;
13473	} else if (IS_VALLEYVIEW(dev)) {
13474		dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
13475		dev_priv->display.get_initial_plane_config =
13476			i9xx_get_initial_plane_config;
13477		dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
13478		dev_priv->display.crtc_enable = valleyview_crtc_enable;
13479		dev_priv->display.crtc_disable = i9xx_crtc_disable;
13480		dev_priv->display.off = i9xx_crtc_off;
13481		dev_priv->display.update_primary_plane =
13482			i9xx_update_primary_plane;
13483	} else {
13484		dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
13485		dev_priv->display.get_initial_plane_config =
13486			i9xx_get_initial_plane_config;
13487		dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
13488		dev_priv->display.crtc_enable = i9xx_crtc_enable;
13489		dev_priv->display.crtc_disable = i9xx_crtc_disable;
13490		dev_priv->display.off = i9xx_crtc_off;
13491		dev_priv->display.update_primary_plane =
13492			i9xx_update_primary_plane;
13493	}
13494
13495	/* Returns the core display clock speed */
13496	if (IS_VALLEYVIEW(dev))
13497		dev_priv->display.get_display_clock_speed =
13498			valleyview_get_display_clock_speed;
13499	else if (IS_I945G(dev) || (IS_G33(dev) && !IS_PINEVIEW_M(dev)))
13500		dev_priv->display.get_display_clock_speed =
13501			i945_get_display_clock_speed;
13502	else if (IS_I915G(dev))
13503		dev_priv->display.get_display_clock_speed =
13504			i915_get_display_clock_speed;
13505	else if (IS_I945GM(dev) || IS_845G(dev))
13506		dev_priv->display.get_display_clock_speed =
13507			i9xx_misc_get_display_clock_speed;
13508	else if (IS_PINEVIEW(dev))
13509		dev_priv->display.get_display_clock_speed =
13510			pnv_get_display_clock_speed;
13511	else if (IS_I915GM(dev))
13512		dev_priv->display.get_display_clock_speed =
13513			i915gm_get_display_clock_speed;
13514	else if (IS_I865G(dev))
13515		dev_priv->display.get_display_clock_speed =
13516			i865_get_display_clock_speed;
13517	else if (IS_I85X(dev))
13518		dev_priv->display.get_display_clock_speed =
13519			i855_get_display_clock_speed;
13520	else /* 852, 830 */
13521		dev_priv->display.get_display_clock_speed =
13522			i830_get_display_clock_speed;
13523
13524	if (IS_GEN5(dev)) {
13525		dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
13526	} else if (IS_GEN6(dev)) {
13527		dev_priv->display.fdi_link_train = gen6_fdi_link_train;
13528	} else if (IS_IVYBRIDGE(dev)) {
13529		/* FIXME: detect B0+ stepping and use auto training */
13530		dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
13531	} else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
13532		dev_priv->display.fdi_link_train = hsw_fdi_link_train;
13533	} else if (IS_VALLEYVIEW(dev)) {
13534		dev_priv->display.modeset_global_resources =
13535			valleyview_modeset_global_resources;
13536	}
13537
13538	switch (INTEL_INFO(dev)->gen) {
13539	case 2:
13540		dev_priv->display.queue_flip = intel_gen2_queue_flip;
13541		break;
13542
13543	case 3:
13544		dev_priv->display.queue_flip = intel_gen3_queue_flip;
13545		break;
13546
13547	case 4:
13548	case 5:
13549		dev_priv->display.queue_flip = intel_gen4_queue_flip;
13550		break;
13551
13552	case 6:
13553		dev_priv->display.queue_flip = intel_gen6_queue_flip;
13554		break;
13555	case 7:
13556	case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
13557		dev_priv->display.queue_flip = intel_gen7_queue_flip;
13558		break;
13559	case 9:
13560		/* Drop through - unsupported since execlist only. */
13561	default:
13562		/* Default just returns -ENODEV to indicate unsupported */
13563		dev_priv->display.queue_flip = intel_default_queue_flip;
13564	}
13565
13566	intel_panel_init_backlight_funcs(dev);
13567
13568	mutex_init(&dev_priv->pps_mutex);
13569}
13570
13571/*
13572 * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
13573 * resume, or other times.  This quirk makes sure that's the case for
13574 * affected systems.
13575 */
13576static void quirk_pipea_force(struct drm_device *dev)
13577{
13578	struct drm_i915_private *dev_priv = dev->dev_private;
13579
13580	dev_priv->quirks |= QUIRK_PIPEA_FORCE;
13581	DRM_INFO("applying pipe a force quirk\n");
13582}
13583
13584static void quirk_pipeb_force(struct drm_device *dev)
13585{
13586	struct drm_i915_private *dev_priv = dev->dev_private;
13587
13588	dev_priv->quirks |= QUIRK_PIPEB_FORCE;
13589	DRM_INFO("applying pipe b force quirk\n");
13590}
13591
13592/*
13593 * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
13594 */
13595static void quirk_ssc_force_disable(struct drm_device *dev)
13596{
13597	struct drm_i915_private *dev_priv = dev->dev_private;
13598	dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
13599	DRM_INFO("applying lvds SSC disable quirk\n");
13600}
13601
13602/*
13603 * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
13604 * brightness value
13605 */
13606static void quirk_invert_brightness(struct drm_device *dev)
13607{
13608	struct drm_i915_private *dev_priv = dev->dev_private;
13609	dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
13610	DRM_INFO("applying inverted panel brightness quirk\n");
13611}
13612
13613/* Some VBT's incorrectly indicate no backlight is present */
13614static void quirk_backlight_present(struct drm_device *dev)
13615{
13616	struct drm_i915_private *dev_priv = dev->dev_private;
13617	dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
13618	DRM_INFO("applying backlight present quirk\n");
13619}
13620
13621struct intel_quirk {
13622	int device;
13623	int subsystem_vendor;
13624	int subsystem_device;
13625	void (*hook)(struct drm_device *dev);
13626};
13627
13628/* For systems that don't have a meaningful PCI subdevice/subvendor ID */
13629struct intel_dmi_quirk {
13630	void (*hook)(struct drm_device *dev);
13631	const struct dmi_system_id (*dmi_id_list)[];
13632};
13633
13634static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
13635{
13636	DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
13637	return 1;
13638}
13639
13640static const struct intel_dmi_quirk intel_dmi_quirks[] = {
13641	{
13642		.dmi_id_list = &(const struct dmi_system_id[]) {
13643			{
13644				.callback = intel_dmi_reverse_brightness,
13645				.ident = "NCR Corporation",
13646				.matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
13647					    DMI_MATCH(DMI_PRODUCT_NAME, ""),
13648				},
13649			},
13650			{ }  /* terminating entry */
13651		},
13652		.hook = quirk_invert_brightness,
13653	},
13654};
13655
13656static struct intel_quirk intel_quirks[] = {
13657	/* Toshiba Protege R-205, S-209 needs pipe A force quirk */
13658	{ 0x2592, 0x1179, 0x0001, quirk_pipea_force },
13659
13660	/* ThinkPad T60 needs pipe A force quirk (bug #16494) */
13661	{ 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
13662
13663	/* 830 needs to leave pipe A & dpll A up */
13664	{ 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
13665
13666	/* 830 needs to leave pipe B & dpll B up */
13667	{ 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
13668
13669	/* Lenovo U160 cannot use SSC on LVDS */
13670	{ 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
13671
13672	/* Sony Vaio Y cannot use SSC on LVDS */
13673	{ 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
13674
13675	/* Acer Aspire 5734Z must invert backlight brightness */
13676	{ 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
13677
13678	/* Acer/eMachines G725 */
13679	{ 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
13680
13681	/* Acer/eMachines e725 */
13682	{ 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
13683
13684	/* Acer/Packard Bell NCL20 */
13685	{ 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
13686
13687	/* Acer Aspire 4736Z */
13688	{ 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
13689
13690	/* Acer Aspire 5336 */
13691	{ 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
13692
13693	/* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
13694	{ 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
13695
13696	/* Acer C720 Chromebook (Core i3 4005U) */
13697	{ 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
13698
13699	/* Apple Macbook 2,1 (Core 2 T7400) */
13700	{ 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
13701
13702	/* Toshiba CB35 Chromebook (Celeron 2955U) */
13703	{ 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
13704
13705	/* HP Chromebook 14 (Celeron 2955U) */
13706	{ 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
13707
13708	/* Dell Chromebook 11 */
13709	{ 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
13710};
13711
13712static void intel_init_quirks(struct drm_device *dev)
13713{
13714	struct pci_dev *d = dev->pdev;
13715	int i;
13716
13717	for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
13718		struct intel_quirk *q = &intel_quirks[i];
13719
13720		if (d->device == q->device &&
13721		    (d->subsystem_vendor == q->subsystem_vendor ||
13722		     q->subsystem_vendor == PCI_ANY_ID) &&
13723		    (d->subsystem_device == q->subsystem_device ||
13724		     q->subsystem_device == PCI_ANY_ID))
13725			q->hook(dev);
13726	}
13727	for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
13728		if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
13729			intel_dmi_quirks[i].hook(dev);
13730	}
13731}
13732
13733/* Disable the VGA plane that we never use */
13734static void i915_disable_vga(struct drm_device *dev)
13735{
13736	struct drm_i915_private *dev_priv = dev->dev_private;
13737	u8 sr1;
13738	u32 vga_reg = i915_vgacntrl_reg(dev);
13739
13740	/* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
13741	vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
13742	outb(SR01, VGA_SR_INDEX);
13743	sr1 = inb(VGA_SR_DATA);
13744	outb(sr1 | 1<<5, VGA_SR_DATA);
13745	vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
13746	udelay(300);
13747
13748	I915_WRITE(vga_reg, VGA_DISP_DISABLE);
13749	POSTING_READ(vga_reg);
13750}
13751
13752void intel_modeset_init_hw(struct drm_device *dev)
13753{
13754	intel_prepare_ddi(dev);
13755
13756	if (IS_VALLEYVIEW(dev))
13757		vlv_update_cdclk(dev);
13758
13759	intel_init_clock_gating(dev);
13760
13761	intel_enable_gt_powersave(dev);
13762}
13763
13764void intel_modeset_init(struct drm_device *dev)
13765{
13766	struct drm_i915_private *dev_priv = dev->dev_private;
13767	int sprite, ret;
13768	enum pipe pipe;
13769	struct intel_crtc *crtc;
13770
13771	drm_mode_config_init(dev);
13772
13773	dev->mode_config.min_width = 0;
13774	dev->mode_config.min_height = 0;
13775
13776	dev->mode_config.preferred_depth = 24;
13777	dev->mode_config.prefer_shadow = 1;
13778
13779	dev->mode_config.allow_fb_modifiers = true;
13780
13781	dev->mode_config.funcs = &intel_mode_funcs;
13782
13783	intel_init_quirks(dev);
13784
13785	intel_init_pm(dev);
13786
13787	if (INTEL_INFO(dev)->num_pipes == 0)
13788		return;
13789
13790	/*
13791	 * There may be no VBT; and if the BIOS enabled SSC we can
13792	 * just keep using it to avoid unnecessary flicker.  Whereas if the
13793	 * BIOS isn't using it, don't assume it will work even if the VBT
13794	 * indicates as much.
13795	 */
13796	if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
13797		bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
13798					    DREF_SSC1_ENABLE);
13799
13800		if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
13801			DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
13802				     bios_lvds_use_ssc ? "en" : "dis",
13803				     dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
13804			dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
13805		}
13806	}
13807
13808	intel_init_display(dev);
13809	intel_init_audio(dev);
13810
13811	if (IS_GEN2(dev)) {
13812		dev->mode_config.max_width = 2048;
13813		dev->mode_config.max_height = 2048;
13814	} else if (IS_GEN3(dev)) {
13815		dev->mode_config.max_width = 4096;
13816		dev->mode_config.max_height = 4096;
13817	} else {
13818		dev->mode_config.max_width = 8192;
13819		dev->mode_config.max_height = 8192;
13820	}
13821
13822	if (IS_845G(dev) || IS_I865G(dev)) {
13823		dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
13824		dev->mode_config.cursor_height = 1023;
13825	} else if (IS_GEN2(dev)) {
13826		dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
13827		dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
13828	} else {
13829		dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
13830		dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
13831	}
13832
13833	dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
13834
13835	DRM_DEBUG_KMS("%d display pipe%s available.\n",
13836		      INTEL_INFO(dev)->num_pipes,
13837		      INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
13838
13839	for_each_pipe(dev_priv, pipe) {
13840		intel_crtc_init(dev, pipe);
13841		for_each_sprite(dev_priv, pipe, sprite) {
13842			ret = intel_plane_init(dev, pipe, sprite);
13843			if (ret)
13844				DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
13845					      pipe_name(pipe), sprite_name(pipe, sprite), ret);
13846		}
13847	}
13848
13849	intel_init_dpio(dev);
13850
13851	intel_shared_dpll_init(dev);
13852
13853	/* Just disable it once at startup */
13854	i915_disable_vga(dev);
13855	intel_setup_outputs(dev);
13856
13857	/* Just in case the BIOS is doing something questionable. */
13858	intel_fbc_disable(dev);
13859
13860	drm_modeset_lock_all(dev);
13861	intel_modeset_setup_hw_state(dev, false);
13862	drm_modeset_unlock_all(dev);
13863
13864	for_each_intel_crtc(dev, crtc) {
13865		if (!crtc->active)
13866			continue;
13867
13868		/*
13869		 * Note that reserving the BIOS fb up front prevents us
13870		 * from stuffing other stolen allocations like the ring
13871		 * on top.  This prevents some ugliness at boot time, and
13872		 * can even allow for smooth boot transitions if the BIOS
13873		 * fb is large enough for the active pipe configuration.
13874		 */
13875		if (dev_priv->display.get_initial_plane_config) {
13876			dev_priv->display.get_initial_plane_config(crtc,
13877							   &crtc->plane_config);
13878			/*
13879			 * If the fb is shared between multiple heads, we'll
13880			 * just get the first one.
13881			 */
13882			intel_find_initial_plane_obj(crtc, &crtc->plane_config);
13883		}
13884	}
13885}
13886
13887static void intel_enable_pipe_a(struct drm_device *dev)
13888{
13889	struct intel_connector *connector;
13890	struct drm_connector *crt = NULL;
13891	struct intel_load_detect_pipe load_detect_temp;
13892	struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
13893
13894	/* We can't just switch on the pipe A, we need to set things up with a
13895	 * proper mode and output configuration. As a gross hack, enable pipe A
13896	 * by enabling the load detect pipe once. */
13897	for_each_intel_connector(dev, connector) {
13898		if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
13899			crt = &connector->base;
13900			break;
13901		}
13902	}
13903
13904	if (!crt)
13905		return;
13906
13907	if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
13908		intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
13909}
13910
13911static bool
13912intel_check_plane_mapping(struct intel_crtc *crtc)
13913{
13914	struct drm_device *dev = crtc->base.dev;
13915	struct drm_i915_private *dev_priv = dev->dev_private;
13916	u32 reg, val;
13917
13918	if (INTEL_INFO(dev)->num_pipes == 1)
13919		return true;
13920
13921	reg = DSPCNTR(!crtc->plane);
13922	val = I915_READ(reg);
13923
13924	if ((val & DISPLAY_PLANE_ENABLE) &&
13925	    (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
13926		return false;
13927
13928	return true;
13929}
13930
13931static void intel_sanitize_crtc(struct intel_crtc *crtc)
13932{
13933	struct drm_device *dev = crtc->base.dev;
13934	struct drm_i915_private *dev_priv = dev->dev_private;
13935	u32 reg;
13936
13937	/* Clear any frame start delays used for debugging left by the BIOS */
13938	reg = PIPECONF(crtc->config->cpu_transcoder);
13939	I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
13940
13941	/* restore vblank interrupts to correct state */
13942	drm_crtc_vblank_reset(&crtc->base);
13943	if (crtc->active) {
13944		update_scanline_offset(crtc);
13945		drm_crtc_vblank_on(&crtc->base);
13946	}
13947
13948	/* We need to sanitize the plane -> pipe mapping first because this will
13949	 * disable the crtc (and hence change the state) if it is wrong. Note
13950	 * that gen4+ has a fixed plane -> pipe mapping.  */
13951	if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
13952		struct intel_connector *connector;
13953		bool plane;
13954
13955		DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
13956			      crtc->base.base.id);
13957
13958		/* Pipe has the wrong plane attached and the plane is active.
13959		 * Temporarily change the plane mapping and disable everything
13960		 * ...  */
13961		plane = crtc->plane;
13962		crtc->plane = !plane;
13963		crtc->primary_enabled = true;
13964		dev_priv->display.crtc_disable(&crtc->base);
13965		crtc->plane = plane;
13966
13967		/* ... and break all links. */
13968		for_each_intel_connector(dev, connector) {
13969			if (connector->encoder->base.crtc != &crtc->base)
13970				continue;
13971
13972			connector->base.dpms = DRM_MODE_DPMS_OFF;
13973			connector->base.encoder = NULL;
13974		}
13975		/* multiple connectors may have the same encoder:
13976		 *  handle them and break crtc link separately */
13977		for_each_intel_connector(dev, connector)
13978			if (connector->encoder->base.crtc == &crtc->base) {
13979				connector->encoder->base.crtc = NULL;
13980				connector->encoder->connectors_active = false;
13981			}
13982
13983		WARN_ON(crtc->active);
13984		crtc->base.state->enable = false;
13985		crtc->base.enabled = false;
13986	}
13987
13988	if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
13989	    crtc->pipe == PIPE_A && !crtc->active) {
13990		/* BIOS forgot to enable pipe A, this mostly happens after
13991		 * resume. Force-enable the pipe to fix this, the update_dpms
13992		 * call below we restore the pipe to the right state, but leave
13993		 * the required bits on. */
13994		intel_enable_pipe_a(dev);
13995	}
13996
13997	/* Adjust the state of the output pipe according to whether we
13998	 * have active connectors/encoders. */
13999	intel_crtc_update_dpms(&crtc->base);
14000
14001	if (crtc->active != crtc->base.state->enable) {
14002		struct intel_encoder *encoder;
14003
14004		/* This can happen either due to bugs in the get_hw_state
14005		 * functions or because the pipe is force-enabled due to the
14006		 * pipe A quirk. */
14007		DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
14008			      crtc->base.base.id,
14009			      crtc->base.state->enable ? "enabled" : "disabled",
14010			      crtc->active ? "enabled" : "disabled");
14011
14012		crtc->base.state->enable = crtc->active;
14013		crtc->base.enabled = crtc->active;
14014
14015		/* Because we only establish the connector -> encoder ->
14016		 * crtc links if something is active, this means the
14017		 * crtc is now deactivated. Break the links. connector
14018		 * -> encoder links are only establish when things are
14019		 *  actually up, hence no need to break them. */
14020		WARN_ON(crtc->active);
14021
14022		for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
14023			WARN_ON(encoder->connectors_active);
14024			encoder->base.crtc = NULL;
14025		}
14026	}
14027
14028	if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
14029		/*
14030		 * We start out with underrun reporting disabled to avoid races.
14031		 * For correct bookkeeping mark this on active crtcs.
14032		 *
14033		 * Also on gmch platforms we dont have any hardware bits to
14034		 * disable the underrun reporting. Which means we need to start
14035		 * out with underrun reporting disabled also on inactive pipes,
14036		 * since otherwise we'll complain about the garbage we read when
14037		 * e.g. coming up after runtime pm.
14038		 *
14039		 * No protection against concurrent access is required - at
14040		 * worst a fifo underrun happens which also sets this to false.
14041		 */
14042		crtc->cpu_fifo_underrun_disabled = true;
14043		crtc->pch_fifo_underrun_disabled = true;
14044	}
14045}
14046
14047static void intel_sanitize_encoder(struct intel_encoder *encoder)
14048{
14049	struct intel_connector *connector;
14050	struct drm_device *dev = encoder->base.dev;
14051
14052	/* We need to check both for a crtc link (meaning that the
14053	 * encoder is active and trying to read from a pipe) and the
14054	 * pipe itself being active. */
14055	bool has_active_crtc = encoder->base.crtc &&
14056		to_intel_crtc(encoder->base.crtc)->active;
14057
14058	if (encoder->connectors_active && !has_active_crtc) {
14059		DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14060			      encoder->base.base.id,
14061			      encoder->base.name);
14062
14063		/* Connector is active, but has no active pipe. This is
14064		 * fallout from our resume register restoring. Disable
14065		 * the encoder manually again. */
14066		if (encoder->base.crtc) {
14067			DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14068				      encoder->base.base.id,
14069				      encoder->base.name);
14070			encoder->disable(encoder);
14071			if (encoder->post_disable)
14072				encoder->post_disable(encoder);
14073		}
14074		encoder->base.crtc = NULL;
14075		encoder->connectors_active = false;
14076
14077		/* Inconsistent output/port/pipe state happens presumably due to
14078		 * a bug in one of the get_hw_state functions. Or someplace else
14079		 * in our code, like the register restore mess on resume. Clamp
14080		 * things to off as a safer default. */
14081		for_each_intel_connector(dev, connector) {
14082			if (connector->encoder != encoder)
14083				continue;
14084			connector->base.dpms = DRM_MODE_DPMS_OFF;
14085			connector->base.encoder = NULL;
14086		}
14087	}
14088	/* Enabled encoders without active connectors will be fixed in
14089	 * the crtc fixup. */
14090}
14091
14092void i915_redisable_vga_power_on(struct drm_device *dev)
14093{
14094	struct drm_i915_private *dev_priv = dev->dev_private;
14095	u32 vga_reg = i915_vgacntrl_reg(dev);
14096
14097	if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
14098		DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
14099		i915_disable_vga(dev);
14100	}
14101}
14102
14103void i915_redisable_vga(struct drm_device *dev)
14104{
14105	struct drm_i915_private *dev_priv = dev->dev_private;
14106
14107	/* This function can be called both from intel_modeset_setup_hw_state or
14108	 * at a very early point in our resume sequence, where the power well
14109	 * structures are not yet restored. Since this function is at a very
14110	 * paranoid "someone might have enabled VGA while we were not looking"
14111	 * level, just check if the power well is enabled instead of trying to
14112	 * follow the "don't touch the power well if we don't need it" policy
14113	 * the rest of the driver uses. */
14114	if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
14115		return;
14116
14117	i915_redisable_vga_power_on(dev);
14118}
14119
14120static bool primary_get_hw_state(struct intel_crtc *crtc)
14121{
14122	struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
14123
14124	if (!crtc->active)
14125		return false;
14126
14127	return I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE;
14128}
14129
14130static void intel_modeset_readout_hw_state(struct drm_device *dev)
14131{
14132	struct drm_i915_private *dev_priv = dev->dev_private;
14133	enum pipe pipe;
14134	struct intel_crtc *crtc;
14135	struct intel_encoder *encoder;
14136	struct intel_connector *connector;
14137	int i;
14138
14139	for_each_intel_crtc(dev, crtc) {
14140		memset(crtc->config, 0, sizeof(*crtc->config));
14141
14142		crtc->config->quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
14143
14144		crtc->active = dev_priv->display.get_pipe_config(crtc,
14145								 crtc->config);
14146
14147		crtc->base.state->enable = crtc->active;
14148		crtc->base.enabled = crtc->active;
14149		crtc->primary_enabled = primary_get_hw_state(crtc);
14150
14151		DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
14152			      crtc->base.base.id,
14153			      crtc->active ? "enabled" : "disabled");
14154	}
14155
14156	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
14157		struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
14158
14159		pll->on = pll->get_hw_state(dev_priv, pll,
14160					    &pll->config.hw_state);
14161		pll->active = 0;
14162		pll->config.crtc_mask = 0;
14163		for_each_intel_crtc(dev, crtc) {
14164			if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
14165				pll->active++;
14166				pll->config.crtc_mask |= 1 << crtc->pipe;
14167			}
14168		}
14169
14170		DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
14171			      pll->name, pll->config.crtc_mask, pll->on);
14172
14173		if (pll->config.crtc_mask)
14174			intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
14175	}
14176
14177	for_each_intel_encoder(dev, encoder) {
14178		pipe = 0;
14179
14180		if (encoder->get_hw_state(encoder, &pipe)) {
14181			crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
14182			encoder->base.crtc = &crtc->base;
14183			encoder->get_config(encoder, crtc->config);
14184		} else {
14185			encoder->base.crtc = NULL;
14186		}
14187
14188		encoder->connectors_active = false;
14189		DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
14190			      encoder->base.base.id,
14191			      encoder->base.name,
14192			      encoder->base.crtc ? "enabled" : "disabled",
14193			      pipe_name(pipe));
14194	}
14195
14196	for_each_intel_connector(dev, connector) {
14197		if (connector->get_hw_state(connector)) {
14198			connector->base.dpms = DRM_MODE_DPMS_ON;
14199			connector->encoder->connectors_active = true;
14200			connector->base.encoder = &connector->encoder->base;
14201		} else {
14202			connector->base.dpms = DRM_MODE_DPMS_OFF;
14203			connector->base.encoder = NULL;
14204		}
14205		DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
14206			      connector->base.base.id,
14207			      connector->base.name,
14208			      connector->base.encoder ? "enabled" : "disabled");
14209	}
14210}
14211
14212/* Scan out the current hw modeset state, sanitizes it and maps it into the drm
14213 * and i915 state tracking structures. */
14214void intel_modeset_setup_hw_state(struct drm_device *dev,
14215				  bool force_restore)
14216{
14217	struct drm_i915_private *dev_priv = dev->dev_private;
14218	enum pipe pipe;
14219	struct intel_crtc *crtc;
14220	struct intel_encoder *encoder;
14221	int i;
14222
14223	intel_modeset_readout_hw_state(dev);
14224
14225	/*
14226	 * Now that we have the config, copy it to each CRTC struct
14227	 * Note that this could go away if we move to using crtc_config
14228	 * checking everywhere.
14229	 */
14230	for_each_intel_crtc(dev, crtc) {
14231		if (crtc->active && i915.fastboot) {
14232			intel_mode_from_pipe_config(&crtc->base.mode,
14233						    crtc->config);
14234			DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
14235				      crtc->base.base.id);
14236			drm_mode_debug_printmodeline(&crtc->base.mode);
14237		}
14238	}
14239
14240	/* HW state is read out, now we need to sanitize this mess. */
14241	for_each_intel_encoder(dev, encoder) {
14242		intel_sanitize_encoder(encoder);
14243	}
14244
14245	for_each_pipe(dev_priv, pipe) {
14246		crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
14247		intel_sanitize_crtc(crtc);
14248		intel_dump_pipe_config(crtc, crtc->config,
14249				       "[setup_hw_state]");
14250	}
14251
14252	intel_modeset_update_connector_atomic_state(dev);
14253
14254	for (i = 0; i < dev_priv->num_shared_dpll; i++) {
14255		struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
14256
14257		if (!pll->on || pll->active)
14258			continue;
14259
14260		DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
14261
14262		pll->disable(dev_priv, pll);
14263		pll->on = false;
14264	}
14265
14266	if (IS_GEN9(dev))
14267		skl_wm_get_hw_state(dev);
14268	else if (HAS_PCH_SPLIT(dev))
14269		ilk_wm_get_hw_state(dev);
14270
14271	if (force_restore) {
14272		i915_redisable_vga(dev);
14273
14274		/*
14275		 * We need to use raw interfaces for restoring state to avoid
14276		 * checking (bogus) intermediate states.
14277		 */
14278		for_each_pipe(dev_priv, pipe) {
14279			struct drm_crtc *crtc =
14280				dev_priv->pipe_to_crtc_mapping[pipe];
14281
14282			intel_crtc_restore_mode(crtc);
14283		}
14284	} else {
14285		intel_modeset_update_staged_output_state(dev);
14286	}
14287
14288	intel_modeset_check_state(dev);
14289}
14290
14291void intel_modeset_gem_init(struct drm_device *dev)
14292{
14293	struct drm_crtc *c;
14294	struct drm_i915_gem_object *obj;
14295	int ret;
14296
14297	mutex_lock(&dev->struct_mutex);
14298	intel_init_gt_powersave(dev);
14299	mutex_unlock(&dev->struct_mutex);
14300
14301	intel_modeset_init_hw(dev);
14302
14303	intel_setup_overlay(dev);
14304
14305	/*
14306	 * Make sure any fbs we allocated at startup are properly
14307	 * pinned & fenced.  When we do the allocation it's too early
14308	 * for this.
14309	 */
14310	for_each_crtc(dev, c) {
14311		obj = intel_fb_obj(c->primary->fb);
14312		if (obj == NULL)
14313			continue;
14314
14315		mutex_lock(&dev->struct_mutex);
14316		ret = intel_pin_and_fence_fb_obj(c->primary,
14317						 c->primary->fb,
14318						 c->primary->state,
14319						 NULL);
14320		mutex_unlock(&dev->struct_mutex);
14321		if (ret) {
14322			DRM_ERROR("failed to pin boot fb on pipe %d\n",
14323				  to_intel_crtc(c)->pipe);
14324			drm_framebuffer_unreference(c->primary->fb);
14325			c->primary->fb = NULL;
14326			update_state_fb(c->primary);
14327		}
14328	}
14329
14330	intel_backlight_register(dev);
14331}
14332
14333void intel_connector_unregister(struct intel_connector *intel_connector)
14334{
14335	struct drm_connector *connector = &intel_connector->base;
14336
14337	intel_panel_destroy_backlight(connector);
14338	drm_connector_unregister(connector);
14339}
14340
14341void intel_modeset_cleanup(struct drm_device *dev)
14342{
14343	struct drm_i915_private *dev_priv = dev->dev_private;
14344	struct drm_connector *connector;
14345
14346	intel_disable_gt_powersave(dev);
14347
14348	intel_backlight_unregister(dev);
14349
14350	/*
14351	 * Interrupts and polling as the first thing to avoid creating havoc.
14352	 * Too much stuff here (turning of connectors, ...) would
14353	 * experience fancy races otherwise.
14354	 */
14355	intel_irq_uninstall(dev_priv);
14356
14357	/*
14358	 * Due to the hpd irq storm handling the hotplug work can re-arm the
14359	 * poll handlers. Hence disable polling after hpd handling is shut down.
14360	 */
14361	drm_kms_helper_poll_fini(dev);
14362
14363	mutex_lock(&dev->struct_mutex);
14364
14365	intel_unregister_dsm_handler();
14366
14367	intel_fbc_disable(dev);
14368
14369	mutex_unlock(&dev->struct_mutex);
14370
14371	/* flush any delayed tasks or pending work */
14372	flush_scheduled_work();
14373
14374	/* destroy the backlight and sysfs files before encoders/connectors */
14375	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
14376		struct intel_connector *intel_connector;
14377
14378		intel_connector = to_intel_connector(connector);
14379		intel_connector->unregister(intel_connector);
14380	}
14381
14382	drm_mode_config_cleanup(dev);
14383
14384	intel_cleanup_overlay(dev);
14385
14386	mutex_lock(&dev->struct_mutex);
14387	intel_cleanup_gt_powersave(dev);
14388	mutex_unlock(&dev->struct_mutex);
14389}
14390
14391/*
14392 * Return which encoder is currently attached for connector.
14393 */
14394struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
14395{
14396	return &intel_attached_encoder(connector)->base;
14397}
14398
14399void intel_connector_attach_encoder(struct intel_connector *connector,
14400				    struct intel_encoder *encoder)
14401{
14402	connector->encoder = encoder;
14403	drm_mode_connector_attach_encoder(&connector->base,
14404					  &encoder->base);
14405}
14406
14407/*
14408 * set vga decode state - true == enable VGA decode
14409 */
14410int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
14411{
14412	struct drm_i915_private *dev_priv = dev->dev_private;
14413	unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
14414	u16 gmch_ctrl;
14415
14416	if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
14417		DRM_ERROR("failed to read control word\n");
14418		return -EIO;
14419	}
14420
14421	if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
14422		return 0;
14423
14424	if (state)
14425		gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
14426	else
14427		gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
14428
14429	if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
14430		DRM_ERROR("failed to write control word\n");
14431		return -EIO;
14432	}
14433
14434	return 0;
14435}
14436
14437struct intel_display_error_state {
14438
14439	u32 power_well_driver;
14440
14441	int num_transcoders;
14442
14443	struct intel_cursor_error_state {
14444		u32 control;
14445		u32 position;
14446		u32 base;
14447		u32 size;
14448	} cursor[I915_MAX_PIPES];
14449
14450	struct intel_pipe_error_state {
14451		bool power_domain_on;
14452		u32 source;
14453		u32 stat;
14454	} pipe[I915_MAX_PIPES];
14455
14456	struct intel_plane_error_state {
14457		u32 control;
14458		u32 stride;
14459		u32 size;
14460		u32 pos;
14461		u32 addr;
14462		u32 surface;
14463		u32 tile_offset;
14464	} plane[I915_MAX_PIPES];
14465
14466	struct intel_transcoder_error_state {
14467		bool power_domain_on;
14468		enum transcoder cpu_transcoder;
14469
14470		u32 conf;
14471
14472		u32 htotal;
14473		u32 hblank;
14474		u32 hsync;
14475		u32 vtotal;
14476		u32 vblank;
14477		u32 vsync;
14478	} transcoder[4];
14479};
14480
14481struct intel_display_error_state *
14482intel_display_capture_error_state(struct drm_device *dev)
14483{
14484	struct drm_i915_private *dev_priv = dev->dev_private;
14485	struct intel_display_error_state *error;
14486	int transcoders[] = {
14487		TRANSCODER_A,
14488		TRANSCODER_B,
14489		TRANSCODER_C,
14490		TRANSCODER_EDP,
14491	};
14492	int i;
14493
14494	if (INTEL_INFO(dev)->num_pipes == 0)
14495		return NULL;
14496
14497	error = kzalloc(sizeof(*error), GFP_ATOMIC);
14498	if (error == NULL)
14499		return NULL;
14500
14501	if (IS_HASWELL(dev) || IS_BROADWELL(dev))
14502		error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
14503
14504	for_each_pipe(dev_priv, i) {
14505		error->pipe[i].power_domain_on =
14506			__intel_display_power_is_enabled(dev_priv,
14507							 POWER_DOMAIN_PIPE(i));
14508		if (!error->pipe[i].power_domain_on)
14509			continue;
14510
14511		error->cursor[i].control = I915_READ(CURCNTR(i));
14512		error->cursor[i].position = I915_READ(CURPOS(i));
14513		error->cursor[i].base = I915_READ(CURBASE(i));
14514
14515		error->plane[i].control = I915_READ(DSPCNTR(i));
14516		error->plane[i].stride = I915_READ(DSPSTRIDE(i));
14517		if (INTEL_INFO(dev)->gen <= 3) {
14518			error->plane[i].size = I915_READ(DSPSIZE(i));
14519			error->plane[i].pos = I915_READ(DSPPOS(i));
14520		}
14521		if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
14522			error->plane[i].addr = I915_READ(DSPADDR(i));
14523		if (INTEL_INFO(dev)->gen >= 4) {
14524			error->plane[i].surface = I915_READ(DSPSURF(i));
14525			error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
14526		}
14527
14528		error->pipe[i].source = I915_READ(PIPESRC(i));
14529
14530		if (HAS_GMCH_DISPLAY(dev))
14531			error->pipe[i].stat = I915_READ(PIPESTAT(i));
14532	}
14533
14534	error->num_transcoders = INTEL_INFO(dev)->num_pipes;
14535	if (HAS_DDI(dev_priv->dev))
14536		error->num_transcoders++; /* Account for eDP. */
14537
14538	for (i = 0; i < error->num_transcoders; i++) {
14539		enum transcoder cpu_transcoder = transcoders[i];
14540
14541		error->transcoder[i].power_domain_on =
14542			__intel_display_power_is_enabled(dev_priv,
14543				POWER_DOMAIN_TRANSCODER(cpu_transcoder));
14544		if (!error->transcoder[i].power_domain_on)
14545			continue;
14546
14547		error->transcoder[i].cpu_transcoder = cpu_transcoder;
14548
14549		error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
14550		error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
14551		error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
14552		error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
14553		error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
14554		error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
14555		error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
14556	}
14557
14558	return error;
14559}
14560
14561#define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
14562
14563void
14564intel_display_print_error_state(struct drm_i915_error_state_buf *m,
14565				struct drm_device *dev,
14566				struct intel_display_error_state *error)
14567{
14568	struct drm_i915_private *dev_priv = dev->dev_private;
14569	int i;
14570
14571	if (!error)
14572		return;
14573
14574	err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
14575	if (IS_HASWELL(dev) || IS_BROADWELL(dev))
14576		err_printf(m, "PWR_WELL_CTL2: %08x\n",
14577			   error->power_well_driver);
14578	for_each_pipe(dev_priv, i) {
14579		err_printf(m, "Pipe [%d]:\n", i);
14580		err_printf(m, "  Power: %s\n",
14581			   error->pipe[i].power_domain_on ? "on" : "off");
14582		err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
14583		err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
14584
14585		err_printf(m, "Plane [%d]:\n", i);
14586		err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
14587		err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
14588		if (INTEL_INFO(dev)->gen <= 3) {
14589			err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
14590			err_printf(m, "  POS: %08x\n", error->plane[i].pos);
14591		}
14592		if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
14593			err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
14594		if (INTEL_INFO(dev)->gen >= 4) {
14595			err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
14596			err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
14597		}
14598
14599		err_printf(m, "Cursor [%d]:\n", i);
14600		err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
14601		err_printf(m, "  POS: %08x\n", error->cursor[i].position);
14602		err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
14603	}
14604
14605	for (i = 0; i < error->num_transcoders; i++) {
14606		err_printf(m, "CPU transcoder: %c\n",
14607			   transcoder_name(error->transcoder[i].cpu_transcoder));
14608		err_printf(m, "  Power: %s\n",
14609			   error->transcoder[i].power_domain_on ? "on" : "off");
14610		err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
14611		err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
14612		err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
14613		err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
14614		err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
14615		err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
14616		err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
14617	}
14618}
14619
14620void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
14621{
14622	struct intel_crtc *crtc;
14623
14624	for_each_intel_crtc(dev, crtc) {
14625		struct intel_unpin_work *work;
14626
14627		spin_lock_irq(&dev->event_lock);
14628
14629		work = crtc->unpin_work;
14630
14631		if (work && work->event &&
14632		    work->event->base.file_priv == file) {
14633			kfree(work->event);
14634			work->event = NULL;
14635		}
14636
14637		spin_unlock_irq(&dev->event_lock);
14638	}
14639}
14640