xref: /dragonfly/sys/dev/drm/i915/intel_pm.c (revision 23b3ef78)
1 /*
2  * Copyright © 2012 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 DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eugeni Dodonov <eugeni.dodonov@intel.com>
25  *
26  */
27 
28 #include "i915_drv.h"
29 #include "intel_drv.h"
30 #include <linux/module.h>
31 #include <machine/clock.h>
32 
33 /**
34  * RC6 is a special power stage which allows the GPU to enter an very
35  * low-voltage mode when idle, using down to 0V while at this stage.  This
36  * stage is entered automatically when the GPU is idle when RC6 support is
37  * enabled, and as soon as new workload arises GPU wakes up automatically as well.
38  *
39  * There are different RC6 modes available in Intel GPU, which differentiate
40  * among each other with the latency required to enter and leave RC6 and
41  * voltage consumed by the GPU in different states.
42  *
43  * The combination of the following flags define which states GPU is allowed
44  * to enter, while RC6 is the normal RC6 state, RC6p is the deep RC6, and
45  * RC6pp is deepest RC6. Their support by hardware varies according to the
46  * GPU, BIOS, chipset and platform. RC6 is usually the safest one and the one
47  * which brings the most power savings; deeper states save more power, but
48  * require higher latency to switch to and wake up.
49  */
50 #define INTEL_RC6_ENABLE			(1<<0)
51 #define INTEL_RC6p_ENABLE			(1<<1)
52 #define INTEL_RC6pp_ENABLE			(1<<2)
53 
54 static void gen9_init_clock_gating(struct drm_device *dev)
55 {
56 	struct drm_i915_private *dev_priv = dev->dev_private;
57 
58 	/* WaEnableLbsSlaRetryTimerDecrement:skl */
59 	I915_WRITE(BDW_SCRATCH1, I915_READ(BDW_SCRATCH1) |
60 		   GEN9_LBS_SLA_RETRY_TIMER_DECREMENT_ENABLE);
61 }
62 
63 static void skl_init_clock_gating(struct drm_device *dev)
64 {
65 	struct drm_i915_private *dev_priv = dev->dev_private;
66 
67 	gen9_init_clock_gating(dev);
68 
69 	if (INTEL_REVID(dev) == SKL_REVID_A0) {
70 		/*
71 		 * WaDisableSDEUnitClockGating:skl
72 		 * WaSetGAPSunitClckGateDisable:skl
73 		 */
74 		I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
75 			   GEN8_GAPSUNIT_CLOCK_GATE_DISABLE |
76 			   GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
77 	}
78 
79 	if (INTEL_REVID(dev) <= SKL_REVID_D0) {
80 		/* WaDisableHDCInvalidation:skl */
81 		I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) |
82 			   BDW_DISABLE_HDC_INVALIDATION);
83 
84 		/* WaDisableChickenBitTSGBarrierAckForFFSliceCS:skl */
85 		I915_WRITE(FF_SLICE_CS_CHICKEN2,
86 			   I915_READ(FF_SLICE_CS_CHICKEN2) |
87 			   GEN9_TSG_BARRIER_ACK_DISABLE);
88 	}
89 
90 	if (INTEL_REVID(dev) <= SKL_REVID_E0)
91 		/* WaDisableLSQCROPERFforOCL:skl */
92 		I915_WRITE(GEN8_L3SQCREG4, I915_READ(GEN8_L3SQCREG4) |
93 			   GEN8_LQSC_RO_PERF_DIS);
94 }
95 
96 static void i915_pineview_get_mem_freq(struct drm_device *dev)
97 {
98 	struct drm_i915_private *dev_priv = dev->dev_private;
99 	u32 tmp;
100 
101 	tmp = I915_READ(CLKCFG);
102 
103 	switch (tmp & CLKCFG_FSB_MASK) {
104 	case CLKCFG_FSB_533:
105 		dev_priv->fsb_freq = 533; /* 133*4 */
106 		break;
107 	case CLKCFG_FSB_800:
108 		dev_priv->fsb_freq = 800; /* 200*4 */
109 		break;
110 	case CLKCFG_FSB_667:
111 		dev_priv->fsb_freq =  667; /* 167*4 */
112 		break;
113 	case CLKCFG_FSB_400:
114 		dev_priv->fsb_freq = 400; /* 100*4 */
115 		break;
116 	}
117 
118 	switch (tmp & CLKCFG_MEM_MASK) {
119 	case CLKCFG_MEM_533:
120 		dev_priv->mem_freq = 533;
121 		break;
122 	case CLKCFG_MEM_667:
123 		dev_priv->mem_freq = 667;
124 		break;
125 	case CLKCFG_MEM_800:
126 		dev_priv->mem_freq = 800;
127 		break;
128 	}
129 
130 	/* detect pineview DDR3 setting */
131 	tmp = I915_READ(CSHRDDR3CTL);
132 	dev_priv->is_ddr3 = (tmp & CSHRDDR3CTL_DDR3) ? 1 : 0;
133 }
134 
135 static void i915_ironlake_get_mem_freq(struct drm_device *dev)
136 {
137 	struct drm_i915_private *dev_priv = dev->dev_private;
138 	u16 ddrpll, csipll;
139 
140 	ddrpll = I915_READ16(DDRMPLL1);
141 	csipll = I915_READ16(CSIPLL0);
142 
143 	switch (ddrpll & 0xff) {
144 	case 0xc:
145 		dev_priv->mem_freq = 800;
146 		break;
147 	case 0x10:
148 		dev_priv->mem_freq = 1066;
149 		break;
150 	case 0x14:
151 		dev_priv->mem_freq = 1333;
152 		break;
153 	case 0x18:
154 		dev_priv->mem_freq = 1600;
155 		break;
156 	default:
157 		DRM_DEBUG_DRIVER("unknown memory frequency 0x%02x\n",
158 				 ddrpll & 0xff);
159 		dev_priv->mem_freq = 0;
160 		break;
161 	}
162 
163 	dev_priv->ips.r_t = dev_priv->mem_freq;
164 
165 	switch (csipll & 0x3ff) {
166 	case 0x00c:
167 		dev_priv->fsb_freq = 3200;
168 		break;
169 	case 0x00e:
170 		dev_priv->fsb_freq = 3733;
171 		break;
172 	case 0x010:
173 		dev_priv->fsb_freq = 4266;
174 		break;
175 	case 0x012:
176 		dev_priv->fsb_freq = 4800;
177 		break;
178 	case 0x014:
179 		dev_priv->fsb_freq = 5333;
180 		break;
181 	case 0x016:
182 		dev_priv->fsb_freq = 5866;
183 		break;
184 	case 0x018:
185 		dev_priv->fsb_freq = 6400;
186 		break;
187 	default:
188 		DRM_DEBUG_DRIVER("unknown fsb frequency 0x%04x\n",
189 				 csipll & 0x3ff);
190 		dev_priv->fsb_freq = 0;
191 		break;
192 	}
193 
194 	if (dev_priv->fsb_freq == 3200) {
195 		dev_priv->ips.c_m = 0;
196 	} else if (dev_priv->fsb_freq > 3200 && dev_priv->fsb_freq <= 4800) {
197 		dev_priv->ips.c_m = 1;
198 	} else {
199 		dev_priv->ips.c_m = 2;
200 	}
201 }
202 
203 static const struct cxsr_latency cxsr_latency_table[] = {
204 	{1, 0, 800, 400, 3382, 33382, 3983, 33983},    /* DDR2-400 SC */
205 	{1, 0, 800, 667, 3354, 33354, 3807, 33807},    /* DDR2-667 SC */
206 	{1, 0, 800, 800, 3347, 33347, 3763, 33763},    /* DDR2-800 SC */
207 	{1, 1, 800, 667, 6420, 36420, 6873, 36873},    /* DDR3-667 SC */
208 	{1, 1, 800, 800, 5902, 35902, 6318, 36318},    /* DDR3-800 SC */
209 
210 	{1, 0, 667, 400, 3400, 33400, 4021, 34021},    /* DDR2-400 SC */
211 	{1, 0, 667, 667, 3372, 33372, 3845, 33845},    /* DDR2-667 SC */
212 	{1, 0, 667, 800, 3386, 33386, 3822, 33822},    /* DDR2-800 SC */
213 	{1, 1, 667, 667, 6438, 36438, 6911, 36911},    /* DDR3-667 SC */
214 	{1, 1, 667, 800, 5941, 35941, 6377, 36377},    /* DDR3-800 SC */
215 
216 	{1, 0, 400, 400, 3472, 33472, 4173, 34173},    /* DDR2-400 SC */
217 	{1, 0, 400, 667, 3443, 33443, 3996, 33996},    /* DDR2-667 SC */
218 	{1, 0, 400, 800, 3430, 33430, 3946, 33946},    /* DDR2-800 SC */
219 	{1, 1, 400, 667, 6509, 36509, 7062, 37062},    /* DDR3-667 SC */
220 	{1, 1, 400, 800, 5985, 35985, 6501, 36501},    /* DDR3-800 SC */
221 
222 	{0, 0, 800, 400, 3438, 33438, 4065, 34065},    /* DDR2-400 SC */
223 	{0, 0, 800, 667, 3410, 33410, 3889, 33889},    /* DDR2-667 SC */
224 	{0, 0, 800, 800, 3403, 33403, 3845, 33845},    /* DDR2-800 SC */
225 	{0, 1, 800, 667, 6476, 36476, 6955, 36955},    /* DDR3-667 SC */
226 	{0, 1, 800, 800, 5958, 35958, 6400, 36400},    /* DDR3-800 SC */
227 
228 	{0, 0, 667, 400, 3456, 33456, 4103, 34106},    /* DDR2-400 SC */
229 	{0, 0, 667, 667, 3428, 33428, 3927, 33927},    /* DDR2-667 SC */
230 	{0, 0, 667, 800, 3443, 33443, 3905, 33905},    /* DDR2-800 SC */
231 	{0, 1, 667, 667, 6494, 36494, 6993, 36993},    /* DDR3-667 SC */
232 	{0, 1, 667, 800, 5998, 35998, 6460, 36460},    /* DDR3-800 SC */
233 
234 	{0, 0, 400, 400, 3528, 33528, 4255, 34255},    /* DDR2-400 SC */
235 	{0, 0, 400, 667, 3500, 33500, 4079, 34079},    /* DDR2-667 SC */
236 	{0, 0, 400, 800, 3487, 33487, 4029, 34029},    /* DDR2-800 SC */
237 	{0, 1, 400, 667, 6566, 36566, 7145, 37145},    /* DDR3-667 SC */
238 	{0, 1, 400, 800, 6042, 36042, 6584, 36584},    /* DDR3-800 SC */
239 };
240 
241 static const struct cxsr_latency *intel_get_cxsr_latency(int is_desktop,
242 							 int is_ddr3,
243 							 int fsb,
244 							 int mem)
245 {
246 	const struct cxsr_latency *latency;
247 	int i;
248 
249 	if (fsb == 0 || mem == 0)
250 		return NULL;
251 
252 	for (i = 0; i < ARRAY_SIZE(cxsr_latency_table); i++) {
253 		latency = &cxsr_latency_table[i];
254 		if (is_desktop == latency->is_desktop &&
255 		    is_ddr3 == latency->is_ddr3 &&
256 		    fsb == latency->fsb_freq && mem == latency->mem_freq)
257 			return latency;
258 	}
259 
260 	DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
261 
262 	return NULL;
263 }
264 
265 static void chv_set_memory_dvfs(struct drm_i915_private *dev_priv, bool enable)
266 {
267 	u32 val;
268 
269 	mutex_lock(&dev_priv->rps.hw_lock);
270 
271 	val = vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2);
272 	if (enable)
273 		val &= ~FORCE_DDR_HIGH_FREQ;
274 	else
275 		val |= FORCE_DDR_HIGH_FREQ;
276 	val &= ~FORCE_DDR_LOW_FREQ;
277 	val |= FORCE_DDR_FREQ_REQ_ACK;
278 	vlv_punit_write(dev_priv, PUNIT_REG_DDR_SETUP2, val);
279 
280 	if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2) &
281 		      FORCE_DDR_FREQ_REQ_ACK) == 0, 3))
282 		DRM_ERROR("timed out waiting for Punit DDR DVFS request\n");
283 
284 	mutex_unlock(&dev_priv->rps.hw_lock);
285 }
286 
287 static void chv_set_memory_pm5(struct drm_i915_private *dev_priv, bool enable)
288 {
289 	u32 val;
290 
291 	mutex_lock(&dev_priv->rps.hw_lock);
292 
293 	val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
294 	if (enable)
295 		val |= DSP_MAXFIFO_PM5_ENABLE;
296 	else
297 		val &= ~DSP_MAXFIFO_PM5_ENABLE;
298 	vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
299 
300 	mutex_unlock(&dev_priv->rps.hw_lock);
301 }
302 
303 #define FW_WM(value, plane) \
304 	(((value) << DSPFW_ ## plane ## _SHIFT) & DSPFW_ ## plane ## _MASK)
305 
306 void intel_set_memory_cxsr(struct drm_i915_private *dev_priv, bool enable)
307 {
308 	struct drm_device *dev = dev_priv->dev;
309 	u32 val;
310 
311 	if (IS_VALLEYVIEW(dev)) {
312 		I915_WRITE(FW_BLC_SELF_VLV, enable ? FW_CSPWRDWNEN : 0);
313 		if (IS_CHERRYVIEW(dev))
314 			chv_set_memory_pm5(dev_priv, enable);
315 	} else if (IS_G4X(dev) || IS_CRESTLINE(dev)) {
316 		I915_WRITE(FW_BLC_SELF, enable ? FW_BLC_SELF_EN : 0);
317 	} else if (IS_PINEVIEW(dev)) {
318 		val = I915_READ(DSPFW3) & ~PINEVIEW_SELF_REFRESH_EN;
319 		val |= enable ? PINEVIEW_SELF_REFRESH_EN : 0;
320 		I915_WRITE(DSPFW3, val);
321 	} else if (IS_I945G(dev) || IS_I945GM(dev)) {
322 		val = enable ? _MASKED_BIT_ENABLE(FW_BLC_SELF_EN) :
323 			       _MASKED_BIT_DISABLE(FW_BLC_SELF_EN);
324 		I915_WRITE(FW_BLC_SELF, val);
325 	} else if (IS_I915GM(dev)) {
326 		val = enable ? _MASKED_BIT_ENABLE(INSTPM_SELF_EN) :
327 			       _MASKED_BIT_DISABLE(INSTPM_SELF_EN);
328 		I915_WRITE(INSTPM, val);
329 	} else {
330 		return;
331 	}
332 
333 	DRM_DEBUG_KMS("memory self-refresh is %s\n",
334 		      enable ? "enabled" : "disabled");
335 }
336 
337 
338 /*
339  * Latency for FIFO fetches is dependent on several factors:
340  *   - memory configuration (speed, channels)
341  *   - chipset
342  *   - current MCH state
343  * It can be fairly high in some situations, so here we assume a fairly
344  * pessimal value.  It's a tradeoff between extra memory fetches (if we
345  * set this value too high, the FIFO will fetch frequently to stay full)
346  * and power consumption (set it too low to save power and we might see
347  * FIFO underruns and display "flicker").
348  *
349  * A value of 5us seems to be a good balance; safe for very low end
350  * platforms but not overly aggressive on lower latency configs.
351  */
352 static const int pessimal_latency_ns = 5000;
353 
354 #define VLV_FIFO_START(dsparb, dsparb2, lo_shift, hi_shift) \
355 	((((dsparb) >> (lo_shift)) & 0xff) | ((((dsparb2) >> (hi_shift)) & 0x1) << 8))
356 
357 static int vlv_get_fifo_size(struct drm_device *dev,
358 			      enum i915_pipe pipe, int plane)
359 {
360 	struct drm_i915_private *dev_priv = dev->dev_private;
361 	int sprite0_start, sprite1_start, size;
362 
363 	switch (pipe) {
364 		uint32_t dsparb, dsparb2, dsparb3;
365 	case PIPE_A:
366 		dsparb = I915_READ(DSPARB);
367 		dsparb2 = I915_READ(DSPARB2);
368 		sprite0_start = VLV_FIFO_START(dsparb, dsparb2, 0, 0);
369 		sprite1_start = VLV_FIFO_START(dsparb, dsparb2, 8, 4);
370 		break;
371 	case PIPE_B:
372 		dsparb = I915_READ(DSPARB);
373 		dsparb2 = I915_READ(DSPARB2);
374 		sprite0_start = VLV_FIFO_START(dsparb, dsparb2, 16, 8);
375 		sprite1_start = VLV_FIFO_START(dsparb, dsparb2, 24, 12);
376 		break;
377 	case PIPE_C:
378 		dsparb2 = I915_READ(DSPARB2);
379 		dsparb3 = I915_READ(DSPARB3);
380 		sprite0_start = VLV_FIFO_START(dsparb3, dsparb2, 0, 16);
381 		sprite1_start = VLV_FIFO_START(dsparb3, dsparb2, 8, 20);
382 		break;
383 	default:
384 		return 0;
385 	}
386 
387 	switch (plane) {
388 	case 0:
389 		size = sprite0_start;
390 		break;
391 	case 1:
392 		size = sprite1_start - sprite0_start;
393 		break;
394 	case 2:
395 		size = 512 - 1 - sprite1_start;
396 		break;
397 	default:
398 		return 0;
399 	}
400 
401 	DRM_DEBUG_KMS("Pipe %c %s %c FIFO size: %d\n",
402 		      pipe_name(pipe), plane == 0 ? "primary" : "sprite",
403 		      plane == 0 ? plane_name(pipe) : sprite_name(pipe, plane - 1),
404 		      size);
405 
406 	return size;
407 }
408 
409 static int i9xx_get_fifo_size(struct drm_device *dev, int plane)
410 {
411 	struct drm_i915_private *dev_priv = dev->dev_private;
412 	uint32_t dsparb = I915_READ(DSPARB);
413 	int size;
414 
415 	size = dsparb & 0x7f;
416 	if (plane)
417 		size = ((dsparb >> DSPARB_CSTART_SHIFT) & 0x7f) - size;
418 
419 	DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
420 		      plane ? "B" : "A", size);
421 
422 	return size;
423 }
424 
425 static int i830_get_fifo_size(struct drm_device *dev, int plane)
426 {
427 	struct drm_i915_private *dev_priv = dev->dev_private;
428 	uint32_t dsparb = I915_READ(DSPARB);
429 	int size;
430 
431 	size = dsparb & 0x1ff;
432 	if (plane)
433 		size = ((dsparb >> DSPARB_BEND_SHIFT) & 0x1ff) - size;
434 	size >>= 1; /* Convert to cachelines */
435 
436 	DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
437 		      plane ? "B" : "A", size);
438 
439 	return size;
440 }
441 
442 static int i845_get_fifo_size(struct drm_device *dev, int plane)
443 {
444 	struct drm_i915_private *dev_priv = dev->dev_private;
445 	uint32_t dsparb = I915_READ(DSPARB);
446 	int size;
447 
448 	size = dsparb & 0x7f;
449 	size >>= 2; /* Convert to cachelines */
450 
451 	DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
452 		      plane ? "B" : "A",
453 		      size);
454 
455 	return size;
456 }
457 
458 /* Pineview has different values for various configs */
459 static const struct intel_watermark_params pineview_display_wm = {
460 	.fifo_size = PINEVIEW_DISPLAY_FIFO,
461 	.max_wm = PINEVIEW_MAX_WM,
462 	.default_wm = PINEVIEW_DFT_WM,
463 	.guard_size = PINEVIEW_GUARD_WM,
464 	.cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
465 };
466 static const struct intel_watermark_params pineview_display_hplloff_wm = {
467 	.fifo_size = PINEVIEW_DISPLAY_FIFO,
468 	.max_wm = PINEVIEW_MAX_WM,
469 	.default_wm = PINEVIEW_DFT_HPLLOFF_WM,
470 	.guard_size = PINEVIEW_GUARD_WM,
471 	.cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
472 };
473 static const struct intel_watermark_params pineview_cursor_wm = {
474 	.fifo_size = PINEVIEW_CURSOR_FIFO,
475 	.max_wm = PINEVIEW_CURSOR_MAX_WM,
476 	.default_wm = PINEVIEW_CURSOR_DFT_WM,
477 	.guard_size = PINEVIEW_CURSOR_GUARD_WM,
478 	.cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
479 };
480 static const struct intel_watermark_params pineview_cursor_hplloff_wm = {
481 	.fifo_size = PINEVIEW_CURSOR_FIFO,
482 	.max_wm = PINEVIEW_CURSOR_MAX_WM,
483 	.default_wm = PINEVIEW_CURSOR_DFT_WM,
484 	.guard_size = PINEVIEW_CURSOR_GUARD_WM,
485 	.cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
486 };
487 static const struct intel_watermark_params g4x_wm_info = {
488 	.fifo_size = G4X_FIFO_SIZE,
489 	.max_wm = G4X_MAX_WM,
490 	.default_wm = G4X_MAX_WM,
491 	.guard_size = 2,
492 	.cacheline_size = G4X_FIFO_LINE_SIZE,
493 };
494 static const struct intel_watermark_params g4x_cursor_wm_info = {
495 	.fifo_size = I965_CURSOR_FIFO,
496 	.max_wm = I965_CURSOR_MAX_WM,
497 	.default_wm = I965_CURSOR_DFT_WM,
498 	.guard_size = 2,
499 	.cacheline_size = G4X_FIFO_LINE_SIZE,
500 };
501 static const struct intel_watermark_params valleyview_wm_info = {
502 	.fifo_size = VALLEYVIEW_FIFO_SIZE,
503 	.max_wm = VALLEYVIEW_MAX_WM,
504 	.default_wm = VALLEYVIEW_MAX_WM,
505 	.guard_size = 2,
506 	.cacheline_size = G4X_FIFO_LINE_SIZE,
507 };
508 static const struct intel_watermark_params valleyview_cursor_wm_info = {
509 	.fifo_size = I965_CURSOR_FIFO,
510 	.max_wm = VALLEYVIEW_CURSOR_MAX_WM,
511 	.default_wm = I965_CURSOR_DFT_WM,
512 	.guard_size = 2,
513 	.cacheline_size = G4X_FIFO_LINE_SIZE,
514 };
515 static const struct intel_watermark_params i965_cursor_wm_info = {
516 	.fifo_size = I965_CURSOR_FIFO,
517 	.max_wm = I965_CURSOR_MAX_WM,
518 	.default_wm = I965_CURSOR_DFT_WM,
519 	.guard_size = 2,
520 	.cacheline_size = I915_FIFO_LINE_SIZE,
521 };
522 static const struct intel_watermark_params i945_wm_info = {
523 	.fifo_size = I945_FIFO_SIZE,
524 	.max_wm = I915_MAX_WM,
525 	.default_wm = 1,
526 	.guard_size = 2,
527 	.cacheline_size = I915_FIFO_LINE_SIZE,
528 };
529 static const struct intel_watermark_params i915_wm_info = {
530 	.fifo_size = I915_FIFO_SIZE,
531 	.max_wm = I915_MAX_WM,
532 	.default_wm = 1,
533 	.guard_size = 2,
534 	.cacheline_size = I915_FIFO_LINE_SIZE,
535 };
536 static const struct intel_watermark_params i830_a_wm_info = {
537 	.fifo_size = I855GM_FIFO_SIZE,
538 	.max_wm = I915_MAX_WM,
539 	.default_wm = 1,
540 	.guard_size = 2,
541 	.cacheline_size = I830_FIFO_LINE_SIZE,
542 };
543 static const struct intel_watermark_params i830_bc_wm_info = {
544 	.fifo_size = I855GM_FIFO_SIZE,
545 	.max_wm = I915_MAX_WM/2,
546 	.default_wm = 1,
547 	.guard_size = 2,
548 	.cacheline_size = I830_FIFO_LINE_SIZE,
549 };
550 static const struct intel_watermark_params i845_wm_info = {
551 	.fifo_size = I830_FIFO_SIZE,
552 	.max_wm = I915_MAX_WM,
553 	.default_wm = 1,
554 	.guard_size = 2,
555 	.cacheline_size = I830_FIFO_LINE_SIZE,
556 };
557 
558 /**
559  * intel_calculate_wm - calculate watermark level
560  * @clock_in_khz: pixel clock
561  * @wm: chip FIFO params
562  * @pixel_size: display pixel size
563  * @latency_ns: memory latency for the platform
564  *
565  * Calculate the watermark level (the level at which the display plane will
566  * start fetching from memory again).  Each chip has a different display
567  * FIFO size and allocation, so the caller needs to figure that out and pass
568  * in the correct intel_watermark_params structure.
569  *
570  * As the pixel clock runs, the FIFO will be drained at a rate that depends
571  * on the pixel size.  When it reaches the watermark level, it'll start
572  * fetching FIFO line sized based chunks from memory until the FIFO fills
573  * past the watermark point.  If the FIFO drains completely, a FIFO underrun
574  * will occur, and a display engine hang could result.
575  */
576 static unsigned long intel_calculate_wm(unsigned long clock_in_khz,
577 					const struct intel_watermark_params *wm,
578 					int fifo_size,
579 					int pixel_size,
580 					unsigned long latency_ns)
581 {
582 	long entries_required, wm_size;
583 
584 	/*
585 	 * Note: we need to make sure we don't overflow for various clock &
586 	 * latency values.
587 	 * clocks go from a few thousand to several hundred thousand.
588 	 * latency is usually a few thousand
589 	 */
590 	entries_required = ((clock_in_khz / 1000) * pixel_size * latency_ns) /
591 		1000;
592 	entries_required = DIV_ROUND_UP(entries_required, wm->cacheline_size);
593 
594 	DRM_DEBUG_KMS("FIFO entries required for mode: %ld\n", entries_required);
595 
596 	wm_size = fifo_size - (entries_required + wm->guard_size);
597 
598 	DRM_DEBUG_KMS("FIFO watermark level: %ld\n", wm_size);
599 
600 	/* Don't promote wm_size to unsigned... */
601 	if (wm_size > (long)wm->max_wm)
602 		wm_size = wm->max_wm;
603 	if (wm_size <= 0)
604 		wm_size = wm->default_wm;
605 
606 	/*
607 	 * Bspec seems to indicate that the value shouldn't be lower than
608 	 * 'burst size + 1'. Certainly 830 is quite unhappy with low values.
609 	 * Lets go for 8 which is the burst size since certain platforms
610 	 * already use a hardcoded 8 (which is what the spec says should be
611 	 * done).
612 	 */
613 	if (wm_size <= 8)
614 		wm_size = 8;
615 
616 	return wm_size;
617 }
618 
619 static struct drm_crtc *single_enabled_crtc(struct drm_device *dev)
620 {
621 	struct drm_crtc *crtc, *enabled = NULL;
622 
623 	for_each_crtc(dev, crtc) {
624 		if (intel_crtc_active(crtc)) {
625 			if (enabled)
626 				return NULL;
627 			enabled = crtc;
628 		}
629 	}
630 
631 	return enabled;
632 }
633 
634 static void pineview_update_wm(struct drm_crtc *unused_crtc)
635 {
636 	struct drm_device *dev = unused_crtc->dev;
637 	struct drm_i915_private *dev_priv = dev->dev_private;
638 	struct drm_crtc *crtc;
639 	const struct cxsr_latency *latency;
640 	u32 reg;
641 	unsigned long wm;
642 
643 	latency = intel_get_cxsr_latency(IS_PINEVIEW_G(dev), dev_priv->is_ddr3,
644 					 dev_priv->fsb_freq, dev_priv->mem_freq);
645 	if (!latency) {
646 		DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
647 		intel_set_memory_cxsr(dev_priv, false);
648 		return;
649 	}
650 
651 	crtc = single_enabled_crtc(dev);
652 	if (crtc) {
653 		const struct drm_display_mode *adjusted_mode;
654 		int pixel_size = crtc->primary->state->fb->bits_per_pixel / 8;
655 		int clock;
656 
657 		adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
658 		clock = adjusted_mode->crtc_clock;
659 
660 		/* Display SR */
661 		wm = intel_calculate_wm(clock, &pineview_display_wm,
662 					pineview_display_wm.fifo_size,
663 					pixel_size, latency->display_sr);
664 		reg = I915_READ(DSPFW1);
665 		reg &= ~DSPFW_SR_MASK;
666 		reg |= FW_WM(wm, SR);
667 		I915_WRITE(DSPFW1, reg);
668 		DRM_DEBUG_KMS("DSPFW1 register is %x\n", reg);
669 
670 		/* cursor SR */
671 		wm = intel_calculate_wm(clock, &pineview_cursor_wm,
672 					pineview_display_wm.fifo_size,
673 					pixel_size, latency->cursor_sr);
674 		reg = I915_READ(DSPFW3);
675 		reg &= ~DSPFW_CURSOR_SR_MASK;
676 		reg |= FW_WM(wm, CURSOR_SR);
677 		I915_WRITE(DSPFW3, reg);
678 
679 		/* Display HPLL off SR */
680 		wm = intel_calculate_wm(clock, &pineview_display_hplloff_wm,
681 					pineview_display_hplloff_wm.fifo_size,
682 					pixel_size, latency->display_hpll_disable);
683 		reg = I915_READ(DSPFW3);
684 		reg &= ~DSPFW_HPLL_SR_MASK;
685 		reg |= FW_WM(wm, HPLL_SR);
686 		I915_WRITE(DSPFW3, reg);
687 
688 		/* cursor HPLL off SR */
689 		wm = intel_calculate_wm(clock, &pineview_cursor_hplloff_wm,
690 					pineview_display_hplloff_wm.fifo_size,
691 					pixel_size, latency->cursor_hpll_disable);
692 		reg = I915_READ(DSPFW3);
693 		reg &= ~DSPFW_HPLL_CURSOR_MASK;
694 		reg |= FW_WM(wm, HPLL_CURSOR);
695 		I915_WRITE(DSPFW3, reg);
696 		DRM_DEBUG_KMS("DSPFW3 register is %x\n", reg);
697 
698 		intel_set_memory_cxsr(dev_priv, true);
699 	} else {
700 		intel_set_memory_cxsr(dev_priv, false);
701 	}
702 }
703 
704 static bool g4x_compute_wm0(struct drm_device *dev,
705 			    int plane,
706 			    const struct intel_watermark_params *display,
707 			    int display_latency_ns,
708 			    const struct intel_watermark_params *cursor,
709 			    int cursor_latency_ns,
710 			    int *plane_wm,
711 			    int *cursor_wm)
712 {
713 	struct drm_crtc *crtc;
714 	const struct drm_display_mode *adjusted_mode;
715 	int htotal, hdisplay, clock, pixel_size;
716 	int line_time_us, line_count;
717 	int entries, tlb_miss;
718 
719 	crtc = intel_get_crtc_for_plane(dev, plane);
720 	if (!intel_crtc_active(crtc)) {
721 		*cursor_wm = cursor->guard_size;
722 		*plane_wm = display->guard_size;
723 		return false;
724 	}
725 
726 	adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
727 	clock = adjusted_mode->crtc_clock;
728 	htotal = adjusted_mode->crtc_htotal;
729 	hdisplay = to_intel_crtc(crtc)->config->pipe_src_w;
730 	pixel_size = crtc->primary->state->fb->bits_per_pixel / 8;
731 
732 	/* Use the small buffer method to calculate plane watermark */
733 	entries = ((clock * pixel_size / 1000) * display_latency_ns) / 1000;
734 	tlb_miss = display->fifo_size*display->cacheline_size - hdisplay * 8;
735 	if (tlb_miss > 0)
736 		entries += tlb_miss;
737 	entries = DIV_ROUND_UP(entries, display->cacheline_size);
738 	*plane_wm = entries + display->guard_size;
739 	if (*plane_wm > (int)display->max_wm)
740 		*plane_wm = display->max_wm;
741 
742 	/* Use the large buffer method to calculate cursor watermark */
743 	line_time_us = max(htotal * 1000 / clock, 1);
744 	line_count = (cursor_latency_ns / line_time_us + 1000) / 1000;
745 	entries = line_count * crtc->cursor->state->crtc_w * pixel_size;
746 	tlb_miss = cursor->fifo_size*cursor->cacheline_size - hdisplay * 8;
747 	if (tlb_miss > 0)
748 		entries += tlb_miss;
749 	entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
750 	*cursor_wm = entries + cursor->guard_size;
751 	if (*cursor_wm > (int)cursor->max_wm)
752 		*cursor_wm = (int)cursor->max_wm;
753 
754 	return true;
755 }
756 
757 /*
758  * Check the wm result.
759  *
760  * If any calculated watermark values is larger than the maximum value that
761  * can be programmed into the associated watermark register, that watermark
762  * must be disabled.
763  */
764 static bool g4x_check_srwm(struct drm_device *dev,
765 			   int display_wm, int cursor_wm,
766 			   const struct intel_watermark_params *display,
767 			   const struct intel_watermark_params *cursor)
768 {
769 	DRM_DEBUG_KMS("SR watermark: display plane %d, cursor %d\n",
770 		      display_wm, cursor_wm);
771 
772 	if (display_wm > display->max_wm) {
773 		DRM_DEBUG_KMS("display watermark is too large(%d/%ld), disabling\n",
774 			      display_wm, display->max_wm);
775 		return false;
776 	}
777 
778 	if (cursor_wm > cursor->max_wm) {
779 		DRM_DEBUG_KMS("cursor watermark is too large(%d/%ld), disabling\n",
780 			      cursor_wm, cursor->max_wm);
781 		return false;
782 	}
783 
784 	if (!(display_wm || cursor_wm)) {
785 		DRM_DEBUG_KMS("SR latency is 0, disabling\n");
786 		return false;
787 	}
788 
789 	return true;
790 }
791 
792 static bool g4x_compute_srwm(struct drm_device *dev,
793 			     int plane,
794 			     int latency_ns,
795 			     const struct intel_watermark_params *display,
796 			     const struct intel_watermark_params *cursor,
797 			     int *display_wm, int *cursor_wm)
798 {
799 	struct drm_crtc *crtc;
800 	const struct drm_display_mode *adjusted_mode;
801 	int hdisplay, htotal, pixel_size, clock;
802 	unsigned long line_time_us;
803 	int line_count, line_size;
804 	int small, large;
805 	int entries;
806 
807 	if (!latency_ns) {
808 		*display_wm = *cursor_wm = 0;
809 		return false;
810 	}
811 
812 	crtc = intel_get_crtc_for_plane(dev, plane);
813 	adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
814 	clock = adjusted_mode->crtc_clock;
815 	htotal = adjusted_mode->crtc_htotal;
816 	hdisplay = to_intel_crtc(crtc)->config->pipe_src_w;
817 	pixel_size = crtc->primary->state->fb->bits_per_pixel / 8;
818 
819 	line_time_us = max(htotal * 1000 / clock, 1);
820 	line_count = (latency_ns / line_time_us + 1000) / 1000;
821 	line_size = hdisplay * pixel_size;
822 
823 	/* Use the minimum of the small and large buffer method for primary */
824 	small = ((clock * pixel_size / 1000) * latency_ns) / 1000;
825 	large = line_count * line_size;
826 
827 	entries = DIV_ROUND_UP(min(small, large), display->cacheline_size);
828 	*display_wm = entries + display->guard_size;
829 
830 	/* calculate the self-refresh watermark for display cursor */
831 	entries = line_count * pixel_size * crtc->cursor->state->crtc_w;
832 	entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
833 	*cursor_wm = entries + cursor->guard_size;
834 
835 	return g4x_check_srwm(dev,
836 			      *display_wm, *cursor_wm,
837 			      display, cursor);
838 }
839 
840 #define FW_WM_VLV(value, plane) \
841 	(((value) << DSPFW_ ## plane ## _SHIFT) & DSPFW_ ## plane ## _MASK_VLV)
842 
843 static void vlv_write_wm_values(struct intel_crtc *crtc,
844 				const struct vlv_wm_values *wm)
845 {
846 	struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
847 	enum i915_pipe pipe = crtc->pipe;
848 
849 	I915_WRITE(VLV_DDL(pipe),
850 		   (wm->ddl[pipe].cursor << DDL_CURSOR_SHIFT) |
851 		   (wm->ddl[pipe].sprite[1] << DDL_SPRITE_SHIFT(1)) |
852 		   (wm->ddl[pipe].sprite[0] << DDL_SPRITE_SHIFT(0)) |
853 		   (wm->ddl[pipe].primary << DDL_PLANE_SHIFT));
854 
855 	I915_WRITE(DSPFW1,
856 		   FW_WM(wm->sr.plane, SR) |
857 		   FW_WM(wm->pipe[PIPE_B].cursor, CURSORB) |
858 		   FW_WM_VLV(wm->pipe[PIPE_B].primary, PLANEB) |
859 		   FW_WM_VLV(wm->pipe[PIPE_A].primary, PLANEA));
860 	I915_WRITE(DSPFW2,
861 		   FW_WM_VLV(wm->pipe[PIPE_A].sprite[1], SPRITEB) |
862 		   FW_WM(wm->pipe[PIPE_A].cursor, CURSORA) |
863 		   FW_WM_VLV(wm->pipe[PIPE_A].sprite[0], SPRITEA));
864 	I915_WRITE(DSPFW3,
865 		   FW_WM(wm->sr.cursor, CURSOR_SR));
866 
867 	if (IS_CHERRYVIEW(dev_priv)) {
868 		I915_WRITE(DSPFW7_CHV,
869 			   FW_WM_VLV(wm->pipe[PIPE_B].sprite[1], SPRITED) |
870 			   FW_WM_VLV(wm->pipe[PIPE_B].sprite[0], SPRITEC));
871 		I915_WRITE(DSPFW8_CHV,
872 			   FW_WM_VLV(wm->pipe[PIPE_C].sprite[1], SPRITEF) |
873 			   FW_WM_VLV(wm->pipe[PIPE_C].sprite[0], SPRITEE));
874 		I915_WRITE(DSPFW9_CHV,
875 			   FW_WM_VLV(wm->pipe[PIPE_C].primary, PLANEC) |
876 			   FW_WM(wm->pipe[PIPE_C].cursor, CURSORC));
877 		I915_WRITE(DSPHOWM,
878 			   FW_WM(wm->sr.plane >> 9, SR_HI) |
879 			   FW_WM(wm->pipe[PIPE_C].sprite[1] >> 8, SPRITEF_HI) |
880 			   FW_WM(wm->pipe[PIPE_C].sprite[0] >> 8, SPRITEE_HI) |
881 			   FW_WM(wm->pipe[PIPE_C].primary >> 8, PLANEC_HI) |
882 			   FW_WM(wm->pipe[PIPE_B].sprite[1] >> 8, SPRITED_HI) |
883 			   FW_WM(wm->pipe[PIPE_B].sprite[0] >> 8, SPRITEC_HI) |
884 			   FW_WM(wm->pipe[PIPE_B].primary >> 8, PLANEB_HI) |
885 			   FW_WM(wm->pipe[PIPE_A].sprite[1] >> 8, SPRITEB_HI) |
886 			   FW_WM(wm->pipe[PIPE_A].sprite[0] >> 8, SPRITEA_HI) |
887 			   FW_WM(wm->pipe[PIPE_A].primary >> 8, PLANEA_HI));
888 	} else {
889 		I915_WRITE(DSPFW7,
890 			   FW_WM_VLV(wm->pipe[PIPE_B].sprite[1], SPRITED) |
891 			   FW_WM_VLV(wm->pipe[PIPE_B].sprite[0], SPRITEC));
892 		I915_WRITE(DSPHOWM,
893 			   FW_WM(wm->sr.plane >> 9, SR_HI) |
894 			   FW_WM(wm->pipe[PIPE_B].sprite[1] >> 8, SPRITED_HI) |
895 			   FW_WM(wm->pipe[PIPE_B].sprite[0] >> 8, SPRITEC_HI) |
896 			   FW_WM(wm->pipe[PIPE_B].primary >> 8, PLANEB_HI) |
897 			   FW_WM(wm->pipe[PIPE_A].sprite[1] >> 8, SPRITEB_HI) |
898 			   FW_WM(wm->pipe[PIPE_A].sprite[0] >> 8, SPRITEA_HI) |
899 			   FW_WM(wm->pipe[PIPE_A].primary >> 8, PLANEA_HI));
900 	}
901 
902 	POSTING_READ(DSPFW1);
903 
904 	dev_priv->wm.vlv = *wm;
905 }
906 
907 #undef FW_WM_VLV
908 
909 static uint8_t vlv_compute_drain_latency(struct drm_crtc *crtc,
910 					 struct drm_plane *plane)
911 {
912 	struct drm_device *dev = crtc->dev;
913 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
914 	int entries, prec_mult, drain_latency, pixel_size;
915 	int clock = intel_crtc->config->base.adjusted_mode.crtc_clock;
916 	const int high_precision = IS_CHERRYVIEW(dev) ? 16 : 64;
917 
918 	/*
919 	 * FIXME the plane might have an fb
920 	 * but be invisible (eg. due to clipping)
921 	 */
922 	if (!intel_crtc->active || !plane->state->fb)
923 		return 0;
924 
925 	if (WARN(clock == 0, "Pixel clock is zero!\n"))
926 		return 0;
927 
928 	pixel_size = drm_format_plane_cpp(plane->state->fb->pixel_format, 0);
929 
930 	if (WARN(pixel_size == 0, "Pixel size is zero!\n"))
931 		return 0;
932 
933 	entries = DIV_ROUND_UP(clock, 1000) * pixel_size;
934 
935 	prec_mult = high_precision;
936 	drain_latency = 64 * prec_mult * 4 / entries;
937 
938 	if (drain_latency > DRAIN_LATENCY_MASK) {
939 		prec_mult /= 2;
940 		drain_latency = 64 * prec_mult * 4 / entries;
941 	}
942 
943 	if (drain_latency > DRAIN_LATENCY_MASK)
944 		drain_latency = DRAIN_LATENCY_MASK;
945 
946 	return drain_latency | (prec_mult == high_precision ?
947 				DDL_PRECISION_HIGH : DDL_PRECISION_LOW);
948 }
949 
950 static int vlv_compute_wm(struct intel_crtc *crtc,
951 			  struct intel_plane *plane,
952 			  int fifo_size)
953 {
954 	int clock, entries, pixel_size;
955 
956 	/*
957 	 * FIXME the plane might have an fb
958 	 * but be invisible (eg. due to clipping)
959 	 */
960 	if (!crtc->active || !plane->base.state->fb)
961 		return 0;
962 
963 	pixel_size = drm_format_plane_cpp(plane->base.state->fb->pixel_format, 0);
964 	clock = crtc->config->base.adjusted_mode.crtc_clock;
965 
966 	entries = DIV_ROUND_UP(clock, 1000) * pixel_size;
967 
968 	/*
969 	 * Set up the watermark such that we don't start issuing memory
970 	 * requests until we are within PND's max deadline value (256us).
971 	 * Idea being to be idle as long as possible while still taking
972 	 * advatange of PND's deadline scheduling. The limit of 8
973 	 * cachelines (used when the FIFO will anyway drain in less time
974 	 * than 256us) should match what we would be done if trickle
975 	 * feed were enabled.
976 	 */
977 	return fifo_size - clamp(DIV_ROUND_UP(256 * entries, 64), 0, fifo_size - 8);
978 }
979 
980 static bool vlv_compute_sr_wm(struct drm_device *dev,
981 			      struct vlv_wm_values *wm)
982 {
983 	struct drm_i915_private *dev_priv = to_i915(dev);
984 	struct drm_crtc *crtc;
985 	enum i915_pipe pipe = INVALID_PIPE;
986 	int num_planes = 0;
987 	int fifo_size = 0;
988 	struct intel_plane *plane;
989 
990 	wm->sr.cursor = wm->sr.plane = 0;
991 
992 	crtc = single_enabled_crtc(dev);
993 	/* maxfifo not supported on pipe C */
994 	if (crtc && to_intel_crtc(crtc)->pipe != PIPE_C) {
995 		pipe = to_intel_crtc(crtc)->pipe;
996 		num_planes = !!wm->pipe[pipe].primary +
997 			!!wm->pipe[pipe].sprite[0] +
998 			!!wm->pipe[pipe].sprite[1];
999 		fifo_size = INTEL_INFO(dev_priv)->num_pipes * 512 - 1;
1000 	}
1001 
1002 	if (fifo_size == 0 || num_planes > 1)
1003 		return false;
1004 
1005 	wm->sr.cursor = vlv_compute_wm(to_intel_crtc(crtc),
1006 				       to_intel_plane(crtc->cursor), 0x3f);
1007 
1008 	list_for_each_entry(plane, &dev->mode_config.plane_list, base.head) {
1009 		if (plane->base.type == DRM_PLANE_TYPE_CURSOR)
1010 			continue;
1011 
1012 		if (plane->pipe != pipe)
1013 			continue;
1014 
1015 		wm->sr.plane = vlv_compute_wm(to_intel_crtc(crtc),
1016 					      plane, fifo_size);
1017 		if (wm->sr.plane != 0)
1018 			break;
1019 	}
1020 
1021 	return true;
1022 }
1023 
1024 static void valleyview_update_wm(struct drm_crtc *crtc)
1025 {
1026 	struct drm_device *dev = crtc->dev;
1027 	struct drm_i915_private *dev_priv = dev->dev_private;
1028 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1029 	enum i915_pipe pipe = intel_crtc->pipe;
1030 	bool cxsr_enabled;
1031 	struct vlv_wm_values wm = dev_priv->wm.vlv;
1032 
1033 	wm.ddl[pipe].primary = vlv_compute_drain_latency(crtc, crtc->primary);
1034 	wm.pipe[pipe].primary = vlv_compute_wm(intel_crtc,
1035 					       to_intel_plane(crtc->primary),
1036 					       vlv_get_fifo_size(dev, pipe, 0));
1037 
1038 	wm.ddl[pipe].cursor = vlv_compute_drain_latency(crtc, crtc->cursor);
1039 	wm.pipe[pipe].cursor = vlv_compute_wm(intel_crtc,
1040 					      to_intel_plane(crtc->cursor),
1041 					      0x3f);
1042 
1043 	cxsr_enabled = vlv_compute_sr_wm(dev, &wm);
1044 
1045 	if (memcmp(&wm, &dev_priv->wm.vlv, sizeof(wm)) == 0)
1046 		return;
1047 
1048 	DRM_DEBUG_KMS("Setting FIFO watermarks - %c: plane=%d, cursor=%d, "
1049 		      "SR: plane=%d, cursor=%d\n", pipe_name(pipe),
1050 		      wm.pipe[pipe].primary, wm.pipe[pipe].cursor,
1051 		      wm.sr.plane, wm.sr.cursor);
1052 
1053 	/*
1054 	 * FIXME DDR DVFS introduces massive memory latencies which
1055 	 * are not known to system agent so any deadline specified
1056 	 * by the display may not be respected. To support DDR DVFS
1057 	 * the watermark code needs to be rewritten to essentially
1058 	 * bypass deadline mechanism and rely solely on the
1059 	 * watermarks. For now disable DDR DVFS.
1060 	 */
1061 	if (IS_CHERRYVIEW(dev_priv))
1062 		chv_set_memory_dvfs(dev_priv, false);
1063 
1064 	if (!cxsr_enabled)
1065 		intel_set_memory_cxsr(dev_priv, false);
1066 
1067 	vlv_write_wm_values(intel_crtc, &wm);
1068 
1069 	if (cxsr_enabled)
1070 		intel_set_memory_cxsr(dev_priv, true);
1071 }
1072 
1073 static void valleyview_update_sprite_wm(struct drm_plane *plane,
1074 					struct drm_crtc *crtc,
1075 					uint32_t sprite_width,
1076 					uint32_t sprite_height,
1077 					int pixel_size,
1078 					bool enabled, bool scaled)
1079 {
1080 	struct drm_device *dev = crtc->dev;
1081 	struct drm_i915_private *dev_priv = dev->dev_private;
1082 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1083 	enum i915_pipe pipe = intel_crtc->pipe;
1084 	int sprite = to_intel_plane(plane)->plane;
1085 	bool cxsr_enabled;
1086 	struct vlv_wm_values wm = dev_priv->wm.vlv;
1087 
1088 	if (enabled) {
1089 		wm.ddl[pipe].sprite[sprite] =
1090 			vlv_compute_drain_latency(crtc, plane);
1091 
1092 		wm.pipe[pipe].sprite[sprite] =
1093 			vlv_compute_wm(intel_crtc,
1094 				       to_intel_plane(plane),
1095 				       vlv_get_fifo_size(dev, pipe, sprite+1));
1096 	} else {
1097 		wm.ddl[pipe].sprite[sprite] = 0;
1098 		wm.pipe[pipe].sprite[sprite] = 0;
1099 	}
1100 
1101 	cxsr_enabled = vlv_compute_sr_wm(dev, &wm);
1102 
1103 	if (memcmp(&wm, &dev_priv->wm.vlv, sizeof(wm)) == 0)
1104 		return;
1105 
1106 	DRM_DEBUG_KMS("Setting FIFO watermarks - %c: sprite %c=%d, "
1107 		      "SR: plane=%d, cursor=%d\n", pipe_name(pipe),
1108 		      sprite_name(pipe, sprite),
1109 		      wm.pipe[pipe].sprite[sprite],
1110 		      wm.sr.plane, wm.sr.cursor);
1111 
1112 	if (!cxsr_enabled)
1113 		intel_set_memory_cxsr(dev_priv, false);
1114 
1115 	vlv_write_wm_values(intel_crtc, &wm);
1116 
1117 	if (cxsr_enabled)
1118 		intel_set_memory_cxsr(dev_priv, true);
1119 }
1120 
1121 #define single_plane_enabled(mask) is_power_of_2(mask)
1122 
1123 static void g4x_update_wm(struct drm_crtc *crtc)
1124 {
1125 	struct drm_device *dev = crtc->dev;
1126 	static const int sr_latency_ns = 12000;
1127 	struct drm_i915_private *dev_priv = dev->dev_private;
1128 	int planea_wm, planeb_wm, cursora_wm, cursorb_wm;
1129 	int plane_sr, cursor_sr;
1130 	unsigned int enabled = 0;
1131 	bool cxsr_enabled;
1132 
1133 	if (g4x_compute_wm0(dev, PIPE_A,
1134 			    &g4x_wm_info, pessimal_latency_ns,
1135 			    &g4x_cursor_wm_info, pessimal_latency_ns,
1136 			    &planea_wm, &cursora_wm))
1137 		enabled |= 1 << PIPE_A;
1138 
1139 	if (g4x_compute_wm0(dev, PIPE_B,
1140 			    &g4x_wm_info, pessimal_latency_ns,
1141 			    &g4x_cursor_wm_info, pessimal_latency_ns,
1142 			    &planeb_wm, &cursorb_wm))
1143 		enabled |= 1 << PIPE_B;
1144 
1145 	if (single_plane_enabled(enabled) &&
1146 	    g4x_compute_srwm(dev, ffs(enabled) - 1,
1147 			     sr_latency_ns,
1148 			     &g4x_wm_info,
1149 			     &g4x_cursor_wm_info,
1150 			     &plane_sr, &cursor_sr)) {
1151 		cxsr_enabled = true;
1152 	} else {
1153 		cxsr_enabled = false;
1154 		intel_set_memory_cxsr(dev_priv, false);
1155 		plane_sr = cursor_sr = 0;
1156 	}
1157 
1158 	DRM_DEBUG_KMS("Setting FIFO watermarks - A: plane=%d, cursor=%d, "
1159 		      "B: plane=%d, cursor=%d, SR: plane=%d, cursor=%d\n",
1160 		      planea_wm, cursora_wm,
1161 		      planeb_wm, cursorb_wm,
1162 		      plane_sr, cursor_sr);
1163 
1164 	I915_WRITE(DSPFW1,
1165 		   FW_WM(plane_sr, SR) |
1166 		   FW_WM(cursorb_wm, CURSORB) |
1167 		   FW_WM(planeb_wm, PLANEB) |
1168 		   FW_WM(planea_wm, PLANEA));
1169 	I915_WRITE(DSPFW2,
1170 		   (I915_READ(DSPFW2) & ~DSPFW_CURSORA_MASK) |
1171 		   FW_WM(cursora_wm, CURSORA));
1172 	/* HPLL off in SR has some issues on G4x... disable it */
1173 	I915_WRITE(DSPFW3,
1174 		   (I915_READ(DSPFW3) & ~(DSPFW_HPLL_SR_EN | DSPFW_CURSOR_SR_MASK)) |
1175 		   FW_WM(cursor_sr, CURSOR_SR));
1176 
1177 	if (cxsr_enabled)
1178 		intel_set_memory_cxsr(dev_priv, true);
1179 }
1180 
1181 static void i965_update_wm(struct drm_crtc *unused_crtc)
1182 {
1183 	struct drm_device *dev = unused_crtc->dev;
1184 	struct drm_i915_private *dev_priv = dev->dev_private;
1185 	struct drm_crtc *crtc;
1186 	int srwm = 1;
1187 	int cursor_sr = 16;
1188 	bool cxsr_enabled;
1189 
1190 	/* Calc sr entries for one plane configs */
1191 	crtc = single_enabled_crtc(dev);
1192 	if (crtc) {
1193 		/* self-refresh has much higher latency */
1194 		static const int sr_latency_ns = 12000;
1195 		const struct drm_display_mode *adjusted_mode =
1196 			&to_intel_crtc(crtc)->config->base.adjusted_mode;
1197 		int clock = adjusted_mode->crtc_clock;
1198 		int htotal = adjusted_mode->crtc_htotal;
1199 		int hdisplay = to_intel_crtc(crtc)->config->pipe_src_w;
1200 		int pixel_size = crtc->primary->state->fb->bits_per_pixel / 8;
1201 		unsigned long line_time_us;
1202 		int entries;
1203 
1204 		line_time_us = max(htotal * 1000 / clock, 1);
1205 
1206 		/* Use ns/us then divide to preserve precision */
1207 		entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1208 			pixel_size * hdisplay;
1209 		entries = DIV_ROUND_UP(entries, I915_FIFO_LINE_SIZE);
1210 		srwm = I965_FIFO_SIZE - entries;
1211 		if (srwm < 0)
1212 			srwm = 1;
1213 		srwm &= 0x1ff;
1214 		DRM_DEBUG_KMS("self-refresh entries: %d, wm: %d\n",
1215 			      entries, srwm);
1216 
1217 		entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1218 			pixel_size * crtc->cursor->state->crtc_w;
1219 		entries = DIV_ROUND_UP(entries,
1220 					  i965_cursor_wm_info.cacheline_size);
1221 		cursor_sr = i965_cursor_wm_info.fifo_size -
1222 			(entries + i965_cursor_wm_info.guard_size);
1223 
1224 		if (cursor_sr > i965_cursor_wm_info.max_wm)
1225 			cursor_sr = i965_cursor_wm_info.max_wm;
1226 
1227 		DRM_DEBUG_KMS("self-refresh watermark: display plane %d "
1228 			      "cursor %d\n", srwm, cursor_sr);
1229 
1230 		cxsr_enabled = true;
1231 	} else {
1232 		cxsr_enabled = false;
1233 		/* Turn off self refresh if both pipes are enabled */
1234 		intel_set_memory_cxsr(dev_priv, false);
1235 	}
1236 
1237 	DRM_DEBUG_KMS("Setting FIFO watermarks - A: 8, B: 8, C: 8, SR %d\n",
1238 		      srwm);
1239 
1240 	/* 965 has limitations... */
1241 	I915_WRITE(DSPFW1, FW_WM(srwm, SR) |
1242 		   FW_WM(8, CURSORB) |
1243 		   FW_WM(8, PLANEB) |
1244 		   FW_WM(8, PLANEA));
1245 	I915_WRITE(DSPFW2, FW_WM(8, CURSORA) |
1246 		   FW_WM(8, PLANEC_OLD));
1247 	/* update cursor SR watermark */
1248 	I915_WRITE(DSPFW3, FW_WM(cursor_sr, CURSOR_SR));
1249 
1250 	if (cxsr_enabled)
1251 		intel_set_memory_cxsr(dev_priv, true);
1252 }
1253 
1254 #undef FW_WM
1255 
1256 static void i9xx_update_wm(struct drm_crtc *unused_crtc)
1257 {
1258 	struct drm_device *dev = unused_crtc->dev;
1259 	struct drm_i915_private *dev_priv = dev->dev_private;
1260 	const struct intel_watermark_params *wm_info;
1261 	uint32_t fwater_lo;
1262 	uint32_t fwater_hi;
1263 	int cwm, srwm = 1;
1264 	int fifo_size;
1265 	int planea_wm, planeb_wm;
1266 	struct drm_crtc *crtc, *enabled = NULL;
1267 
1268 	if (IS_I945GM(dev))
1269 		wm_info = &i945_wm_info;
1270 	else if (!IS_GEN2(dev))
1271 		wm_info = &i915_wm_info;
1272 	else
1273 		wm_info = &i830_a_wm_info;
1274 
1275 	fifo_size = dev_priv->display.get_fifo_size(dev, 0);
1276 	crtc = intel_get_crtc_for_plane(dev, 0);
1277 	if (intel_crtc_active(crtc)) {
1278 		const struct drm_display_mode *adjusted_mode;
1279 		int cpp = crtc->primary->state->fb->bits_per_pixel / 8;
1280 		if (IS_GEN2(dev))
1281 			cpp = 4;
1282 
1283 		adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
1284 		planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1285 					       wm_info, fifo_size, cpp,
1286 					       pessimal_latency_ns);
1287 		enabled = crtc;
1288 	} else {
1289 		planea_wm = fifo_size - wm_info->guard_size;
1290 		if (planea_wm > (long)wm_info->max_wm)
1291 			planea_wm = wm_info->max_wm;
1292 	}
1293 
1294 	if (IS_GEN2(dev))
1295 		wm_info = &i830_bc_wm_info;
1296 
1297 	fifo_size = dev_priv->display.get_fifo_size(dev, 1);
1298 	crtc = intel_get_crtc_for_plane(dev, 1);
1299 	if (intel_crtc_active(crtc)) {
1300 		const struct drm_display_mode *adjusted_mode;
1301 		int cpp = crtc->primary->state->fb->bits_per_pixel / 8;
1302 		if (IS_GEN2(dev))
1303 			cpp = 4;
1304 
1305 		adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
1306 		planeb_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1307 					       wm_info, fifo_size, cpp,
1308 					       pessimal_latency_ns);
1309 		if (enabled == NULL)
1310 			enabled = crtc;
1311 		else
1312 			enabled = NULL;
1313 	} else {
1314 		planeb_wm = fifo_size - wm_info->guard_size;
1315 		if (planeb_wm > (long)wm_info->max_wm)
1316 			planeb_wm = wm_info->max_wm;
1317 	}
1318 
1319 	DRM_DEBUG_KMS("FIFO watermarks - A: %d, B: %d\n", planea_wm, planeb_wm);
1320 
1321 	if (IS_I915GM(dev) && enabled) {
1322 		struct drm_i915_gem_object *obj;
1323 
1324 		obj = intel_fb_obj(enabled->primary->state->fb);
1325 
1326 		/* self-refresh seems busted with untiled */
1327 		if (obj->tiling_mode == I915_TILING_NONE)
1328 			enabled = NULL;
1329 	}
1330 
1331 	/*
1332 	 * Overlay gets an aggressive default since video jitter is bad.
1333 	 */
1334 	cwm = 2;
1335 
1336 	/* Play safe and disable self-refresh before adjusting watermarks. */
1337 	intel_set_memory_cxsr(dev_priv, false);
1338 
1339 	/* Calc sr entries for one plane configs */
1340 	if (HAS_FW_BLC(dev) && enabled) {
1341 		/* self-refresh has much higher latency */
1342 		static const int sr_latency_ns = 6000;
1343 		const struct drm_display_mode *adjusted_mode =
1344 			&to_intel_crtc(enabled)->config->base.adjusted_mode;
1345 		int clock = adjusted_mode->crtc_clock;
1346 		int htotal = adjusted_mode->crtc_htotal;
1347 		int hdisplay = to_intel_crtc(enabled)->config->pipe_src_w;
1348 		int pixel_size = enabled->primary->state->fb->bits_per_pixel / 8;
1349 		unsigned long line_time_us;
1350 		int entries;
1351 
1352 		line_time_us = max(htotal * 1000 / clock, 1);
1353 
1354 		/* Use ns/us then divide to preserve precision */
1355 		entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1356 			pixel_size * hdisplay;
1357 		entries = DIV_ROUND_UP(entries, wm_info->cacheline_size);
1358 		DRM_DEBUG_KMS("self-refresh entries: %d\n", entries);
1359 		srwm = wm_info->fifo_size - entries;
1360 		if (srwm < 0)
1361 			srwm = 1;
1362 
1363 		if (IS_I945G(dev) || IS_I945GM(dev))
1364 			I915_WRITE(FW_BLC_SELF,
1365 				   FW_BLC_SELF_FIFO_MASK | (srwm & 0xff));
1366 		else if (IS_I915GM(dev))
1367 			I915_WRITE(FW_BLC_SELF, srwm & 0x3f);
1368 	}
1369 
1370 	DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d, B: %d, C: %d, SR %d\n",
1371 		      planea_wm, planeb_wm, cwm, srwm);
1372 
1373 	fwater_lo = ((planeb_wm & 0x3f) << 16) | (planea_wm & 0x3f);
1374 	fwater_hi = (cwm & 0x1f);
1375 
1376 	/* Set request length to 8 cachelines per fetch */
1377 	fwater_lo = fwater_lo | (1 << 24) | (1 << 8);
1378 	fwater_hi = fwater_hi | (1 << 8);
1379 
1380 	I915_WRITE(FW_BLC, fwater_lo);
1381 	I915_WRITE(FW_BLC2, fwater_hi);
1382 
1383 	if (enabled)
1384 		intel_set_memory_cxsr(dev_priv, true);
1385 }
1386 
1387 static void i845_update_wm(struct drm_crtc *unused_crtc)
1388 {
1389 	struct drm_device *dev = unused_crtc->dev;
1390 	struct drm_i915_private *dev_priv = dev->dev_private;
1391 	struct drm_crtc *crtc;
1392 	const struct drm_display_mode *adjusted_mode;
1393 	uint32_t fwater_lo;
1394 	int planea_wm;
1395 
1396 	crtc = single_enabled_crtc(dev);
1397 	if (crtc == NULL)
1398 		return;
1399 
1400 	adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
1401 	planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1402 				       &i845_wm_info,
1403 				       dev_priv->display.get_fifo_size(dev, 0),
1404 				       4, pessimal_latency_ns);
1405 	fwater_lo = I915_READ(FW_BLC) & ~0xfff;
1406 	fwater_lo |= (3<<8) | planea_wm;
1407 
1408 	DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d\n", planea_wm);
1409 
1410 	I915_WRITE(FW_BLC, fwater_lo);
1411 }
1412 
1413 static uint32_t ilk_pipe_pixel_rate(struct drm_device *dev,
1414 				    struct drm_crtc *crtc)
1415 {
1416 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1417 	uint32_t pixel_rate;
1418 
1419 	pixel_rate = intel_crtc->config->base.adjusted_mode.crtc_clock;
1420 
1421 	/* We only use IF-ID interlacing. If we ever use PF-ID we'll need to
1422 	 * adjust the pixel_rate here. */
1423 
1424 	if (intel_crtc->config->pch_pfit.enabled) {
1425 		uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
1426 		uint32_t pfit_size = intel_crtc->config->pch_pfit.size;
1427 
1428 		pipe_w = intel_crtc->config->pipe_src_w;
1429 		pipe_h = intel_crtc->config->pipe_src_h;
1430 		pfit_w = (pfit_size >> 16) & 0xFFFF;
1431 		pfit_h = pfit_size & 0xFFFF;
1432 		if (pipe_w < pfit_w)
1433 			pipe_w = pfit_w;
1434 		if (pipe_h < pfit_h)
1435 			pipe_h = pfit_h;
1436 
1437 		pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
1438 				     pfit_w * pfit_h);
1439 	}
1440 
1441 	return pixel_rate;
1442 }
1443 
1444 /* latency must be in 0.1us units. */
1445 static uint32_t ilk_wm_method1(uint32_t pixel_rate, uint8_t bytes_per_pixel,
1446 			       uint32_t latency)
1447 {
1448 	uint64_t ret;
1449 
1450 	if (WARN(latency == 0, "Latency value missing\n"))
1451 		return UINT_MAX;
1452 
1453 	ret = (uint64_t) pixel_rate * bytes_per_pixel * latency;
1454 	ret = DIV_ROUND_UP_ULL(ret, 64 * 10000) + 2;
1455 
1456 	return ret;
1457 }
1458 
1459 /* latency must be in 0.1us units. */
1460 static uint32_t ilk_wm_method2(uint32_t pixel_rate, uint32_t pipe_htotal,
1461 			       uint32_t horiz_pixels, uint8_t bytes_per_pixel,
1462 			       uint32_t latency)
1463 {
1464 	uint32_t ret;
1465 
1466 	if (WARN(latency == 0, "Latency value missing\n"))
1467 		return UINT_MAX;
1468 
1469 	ret = (latency * pixel_rate) / (pipe_htotal * 10000);
1470 	ret = (ret + 1) * horiz_pixels * bytes_per_pixel;
1471 	ret = DIV_ROUND_UP(ret, 64) + 2;
1472 	return ret;
1473 }
1474 
1475 static uint32_t ilk_wm_fbc(uint32_t pri_val, uint32_t horiz_pixels,
1476 			   uint8_t bytes_per_pixel)
1477 {
1478 	return DIV_ROUND_UP(pri_val * 64, horiz_pixels * bytes_per_pixel) + 2;
1479 }
1480 
1481 struct skl_pipe_wm_parameters {
1482 	bool active;
1483 	uint32_t pipe_htotal;
1484 	uint32_t pixel_rate; /* in KHz */
1485 	struct intel_plane_wm_parameters plane[I915_MAX_PLANES];
1486 	struct intel_plane_wm_parameters cursor;
1487 };
1488 
1489 struct ilk_pipe_wm_parameters {
1490 	bool active;
1491 	uint32_t pipe_htotal;
1492 	uint32_t pixel_rate;
1493 	struct intel_plane_wm_parameters pri;
1494 	struct intel_plane_wm_parameters spr;
1495 	struct intel_plane_wm_parameters cur;
1496 };
1497 
1498 struct ilk_wm_maximums {
1499 	uint16_t pri;
1500 	uint16_t spr;
1501 	uint16_t cur;
1502 	uint16_t fbc;
1503 };
1504 
1505 /* used in computing the new watermarks state */
1506 struct intel_wm_config {
1507 	unsigned int num_pipes_active;
1508 	bool sprites_enabled;
1509 	bool sprites_scaled;
1510 };
1511 
1512 /*
1513  * For both WM_PIPE and WM_LP.
1514  * mem_value must be in 0.1us units.
1515  */
1516 static uint32_t ilk_compute_pri_wm(const struct ilk_pipe_wm_parameters *params,
1517 				   uint32_t mem_value,
1518 				   bool is_lp)
1519 {
1520 	uint32_t method1, method2;
1521 
1522 	if (!params->active || !params->pri.enabled)
1523 		return 0;
1524 
1525 	method1 = ilk_wm_method1(params->pixel_rate,
1526 				 params->pri.bytes_per_pixel,
1527 				 mem_value);
1528 
1529 	if (!is_lp)
1530 		return method1;
1531 
1532 	method2 = ilk_wm_method2(params->pixel_rate,
1533 				 params->pipe_htotal,
1534 				 params->pri.horiz_pixels,
1535 				 params->pri.bytes_per_pixel,
1536 				 mem_value);
1537 
1538 	return min(method1, method2);
1539 }
1540 
1541 /*
1542  * For both WM_PIPE and WM_LP.
1543  * mem_value must be in 0.1us units.
1544  */
1545 static uint32_t ilk_compute_spr_wm(const struct ilk_pipe_wm_parameters *params,
1546 				   uint32_t mem_value)
1547 {
1548 	uint32_t method1, method2;
1549 
1550 	if (!params->active || !params->spr.enabled)
1551 		return 0;
1552 
1553 	method1 = ilk_wm_method1(params->pixel_rate,
1554 				 params->spr.bytes_per_pixel,
1555 				 mem_value);
1556 	method2 = ilk_wm_method2(params->pixel_rate,
1557 				 params->pipe_htotal,
1558 				 params->spr.horiz_pixels,
1559 				 params->spr.bytes_per_pixel,
1560 				 mem_value);
1561 	return min(method1, method2);
1562 }
1563 
1564 /*
1565  * For both WM_PIPE and WM_LP.
1566  * mem_value must be in 0.1us units.
1567  */
1568 static uint32_t ilk_compute_cur_wm(const struct ilk_pipe_wm_parameters *params,
1569 				   uint32_t mem_value)
1570 {
1571 	if (!params->active || !params->cur.enabled)
1572 		return 0;
1573 
1574 	return ilk_wm_method2(params->pixel_rate,
1575 			      params->pipe_htotal,
1576 			      params->cur.horiz_pixels,
1577 			      params->cur.bytes_per_pixel,
1578 			      mem_value);
1579 }
1580 
1581 /* Only for WM_LP. */
1582 static uint32_t ilk_compute_fbc_wm(const struct ilk_pipe_wm_parameters *params,
1583 				   uint32_t pri_val)
1584 {
1585 	if (!params->active || !params->pri.enabled)
1586 		return 0;
1587 
1588 	return ilk_wm_fbc(pri_val,
1589 			  params->pri.horiz_pixels,
1590 			  params->pri.bytes_per_pixel);
1591 }
1592 
1593 static unsigned int ilk_display_fifo_size(const struct drm_device *dev)
1594 {
1595 	if (INTEL_INFO(dev)->gen >= 8)
1596 		return 3072;
1597 	else if (INTEL_INFO(dev)->gen >= 7)
1598 		return 768;
1599 	else
1600 		return 512;
1601 }
1602 
1603 static unsigned int ilk_plane_wm_reg_max(const struct drm_device *dev,
1604 					 int level, bool is_sprite)
1605 {
1606 	if (INTEL_INFO(dev)->gen >= 8)
1607 		/* BDW primary/sprite plane watermarks */
1608 		return level == 0 ? 255 : 2047;
1609 	else if (INTEL_INFO(dev)->gen >= 7)
1610 		/* IVB/HSW primary/sprite plane watermarks */
1611 		return level == 0 ? 127 : 1023;
1612 	else if (!is_sprite)
1613 		/* ILK/SNB primary plane watermarks */
1614 		return level == 0 ? 127 : 511;
1615 	else
1616 		/* ILK/SNB sprite plane watermarks */
1617 		return level == 0 ? 63 : 255;
1618 }
1619 
1620 static unsigned int ilk_cursor_wm_reg_max(const struct drm_device *dev,
1621 					  int level)
1622 {
1623 	if (INTEL_INFO(dev)->gen >= 7)
1624 		return level == 0 ? 63 : 255;
1625 	else
1626 		return level == 0 ? 31 : 63;
1627 }
1628 
1629 static unsigned int ilk_fbc_wm_reg_max(const struct drm_device *dev)
1630 {
1631 	if (INTEL_INFO(dev)->gen >= 8)
1632 		return 31;
1633 	else
1634 		return 15;
1635 }
1636 
1637 /* Calculate the maximum primary/sprite plane watermark */
1638 static unsigned int ilk_plane_wm_max(const struct drm_device *dev,
1639 				     int level,
1640 				     const struct intel_wm_config *config,
1641 				     enum intel_ddb_partitioning ddb_partitioning,
1642 				     bool is_sprite)
1643 {
1644 	unsigned int fifo_size = ilk_display_fifo_size(dev);
1645 
1646 	/* if sprites aren't enabled, sprites get nothing */
1647 	if (is_sprite && !config->sprites_enabled)
1648 		return 0;
1649 
1650 	/* HSW allows LP1+ watermarks even with multiple pipes */
1651 	if (level == 0 || config->num_pipes_active > 1) {
1652 		fifo_size /= INTEL_INFO(dev)->num_pipes;
1653 
1654 		/*
1655 		 * For some reason the non self refresh
1656 		 * FIFO size is only half of the self
1657 		 * refresh FIFO size on ILK/SNB.
1658 		 */
1659 		if (INTEL_INFO(dev)->gen <= 6)
1660 			fifo_size /= 2;
1661 	}
1662 
1663 	if (config->sprites_enabled) {
1664 		/* level 0 is always calculated with 1:1 split */
1665 		if (level > 0 && ddb_partitioning == INTEL_DDB_PART_5_6) {
1666 			if (is_sprite)
1667 				fifo_size *= 5;
1668 			fifo_size /= 6;
1669 		} else {
1670 			fifo_size /= 2;
1671 		}
1672 	}
1673 
1674 	/* clamp to max that the registers can hold */
1675 	return min(fifo_size, ilk_plane_wm_reg_max(dev, level, is_sprite));
1676 }
1677 
1678 /* Calculate the maximum cursor plane watermark */
1679 static unsigned int ilk_cursor_wm_max(const struct drm_device *dev,
1680 				      int level,
1681 				      const struct intel_wm_config *config)
1682 {
1683 	/* HSW LP1+ watermarks w/ multiple pipes */
1684 	if (level > 0 && config->num_pipes_active > 1)
1685 		return 64;
1686 
1687 	/* otherwise just report max that registers can hold */
1688 	return ilk_cursor_wm_reg_max(dev, level);
1689 }
1690 
1691 static void ilk_compute_wm_maximums(const struct drm_device *dev,
1692 				    int level,
1693 				    const struct intel_wm_config *config,
1694 				    enum intel_ddb_partitioning ddb_partitioning,
1695 				    struct ilk_wm_maximums *max)
1696 {
1697 	max->pri = ilk_plane_wm_max(dev, level, config, ddb_partitioning, false);
1698 	max->spr = ilk_plane_wm_max(dev, level, config, ddb_partitioning, true);
1699 	max->cur = ilk_cursor_wm_max(dev, level, config);
1700 	max->fbc = ilk_fbc_wm_reg_max(dev);
1701 }
1702 
1703 static void ilk_compute_wm_reg_maximums(struct drm_device *dev,
1704 					int level,
1705 					struct ilk_wm_maximums *max)
1706 {
1707 	max->pri = ilk_plane_wm_reg_max(dev, level, false);
1708 	max->spr = ilk_plane_wm_reg_max(dev, level, true);
1709 	max->cur = ilk_cursor_wm_reg_max(dev, level);
1710 	max->fbc = ilk_fbc_wm_reg_max(dev);
1711 }
1712 
1713 static bool ilk_validate_wm_level(int level,
1714 				  const struct ilk_wm_maximums *max,
1715 				  struct intel_wm_level *result)
1716 {
1717 	bool ret;
1718 
1719 	/* already determined to be invalid? */
1720 	if (!result->enable)
1721 		return false;
1722 
1723 	result->enable = result->pri_val <= max->pri &&
1724 			 result->spr_val <= max->spr &&
1725 			 result->cur_val <= max->cur;
1726 
1727 	ret = result->enable;
1728 
1729 	/*
1730 	 * HACK until we can pre-compute everything,
1731 	 * and thus fail gracefully if LP0 watermarks
1732 	 * are exceeded...
1733 	 */
1734 	if (level == 0 && !result->enable) {
1735 		if (result->pri_val > max->pri)
1736 			DRM_DEBUG_KMS("Primary WM%d too large %u (max %u)\n",
1737 				      level, result->pri_val, max->pri);
1738 		if (result->spr_val > max->spr)
1739 			DRM_DEBUG_KMS("Sprite WM%d too large %u (max %u)\n",
1740 				      level, result->spr_val, max->spr);
1741 		if (result->cur_val > max->cur)
1742 			DRM_DEBUG_KMS("Cursor WM%d too large %u (max %u)\n",
1743 				      level, result->cur_val, max->cur);
1744 
1745 		result->pri_val = min_t(uint32_t, result->pri_val, max->pri);
1746 		result->spr_val = min_t(uint32_t, result->spr_val, max->spr);
1747 		result->cur_val = min_t(uint32_t, result->cur_val, max->cur);
1748 		result->enable = true;
1749 	}
1750 
1751 	return ret;
1752 }
1753 
1754 static void ilk_compute_wm_level(const struct drm_i915_private *dev_priv,
1755 				 int level,
1756 				 const struct ilk_pipe_wm_parameters *p,
1757 				 struct intel_wm_level *result)
1758 {
1759 	uint16_t pri_latency = dev_priv->wm.pri_latency[level];
1760 	uint16_t spr_latency = dev_priv->wm.spr_latency[level];
1761 	uint16_t cur_latency = dev_priv->wm.cur_latency[level];
1762 
1763 	/* WM1+ latency values stored in 0.5us units */
1764 	if (level > 0) {
1765 		pri_latency *= 5;
1766 		spr_latency *= 5;
1767 		cur_latency *= 5;
1768 	}
1769 
1770 	result->pri_val = ilk_compute_pri_wm(p, pri_latency, level);
1771 	result->spr_val = ilk_compute_spr_wm(p, spr_latency);
1772 	result->cur_val = ilk_compute_cur_wm(p, cur_latency);
1773 	result->fbc_val = ilk_compute_fbc_wm(p, result->pri_val);
1774 	result->enable = true;
1775 }
1776 
1777 static uint32_t
1778 hsw_compute_linetime_wm(struct drm_device *dev, struct drm_crtc *crtc)
1779 {
1780 	struct drm_i915_private *dev_priv = dev->dev_private;
1781 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1782 	struct drm_display_mode *mode = &intel_crtc->config->base.adjusted_mode;
1783 	u32 linetime, ips_linetime;
1784 
1785 	if (!intel_crtc->active)
1786 		return 0;
1787 
1788 	/* The WM are computed with base on how long it takes to fill a single
1789 	 * row at the given clock rate, multiplied by 8.
1790 	 * */
1791 	linetime = DIV_ROUND_CLOSEST(mode->crtc_htotal * 1000 * 8,
1792 				     mode->crtc_clock);
1793 	ips_linetime = DIV_ROUND_CLOSEST(mode->crtc_htotal * 1000 * 8,
1794 					 intel_ddi_get_cdclk_freq(dev_priv));
1795 
1796 	return PIPE_WM_LINETIME_IPS_LINETIME(ips_linetime) |
1797 	       PIPE_WM_LINETIME_TIME(linetime);
1798 }
1799 
1800 static void intel_read_wm_latency(struct drm_device *dev, uint16_t wm[8])
1801 {
1802 	struct drm_i915_private *dev_priv = dev->dev_private;
1803 
1804 	if (IS_GEN9(dev)) {
1805 		uint32_t val;
1806 		int ret, i;
1807 		int level, max_level = ilk_wm_max_level(dev);
1808 
1809 		/* read the first set of memory latencies[0:3] */
1810 		val = 0; /* data0 to be programmed to 0 for first set */
1811 		mutex_lock(&dev_priv->rps.hw_lock);
1812 		ret = sandybridge_pcode_read(dev_priv,
1813 					     GEN9_PCODE_READ_MEM_LATENCY,
1814 					     &val);
1815 		mutex_unlock(&dev_priv->rps.hw_lock);
1816 
1817 		if (ret) {
1818 			DRM_ERROR("SKL Mailbox read error = %d\n", ret);
1819 			return;
1820 		}
1821 
1822 		wm[0] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
1823 		wm[1] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
1824 				GEN9_MEM_LATENCY_LEVEL_MASK;
1825 		wm[2] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
1826 				GEN9_MEM_LATENCY_LEVEL_MASK;
1827 		wm[3] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
1828 				GEN9_MEM_LATENCY_LEVEL_MASK;
1829 
1830 		/* read the second set of memory latencies[4:7] */
1831 		val = 1; /* data0 to be programmed to 1 for second set */
1832 		mutex_lock(&dev_priv->rps.hw_lock);
1833 		ret = sandybridge_pcode_read(dev_priv,
1834 					     GEN9_PCODE_READ_MEM_LATENCY,
1835 					     &val);
1836 		mutex_unlock(&dev_priv->rps.hw_lock);
1837 		if (ret) {
1838 			DRM_ERROR("SKL Mailbox read error = %d\n", ret);
1839 			return;
1840 		}
1841 
1842 		wm[4] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
1843 		wm[5] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
1844 				GEN9_MEM_LATENCY_LEVEL_MASK;
1845 		wm[6] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
1846 				GEN9_MEM_LATENCY_LEVEL_MASK;
1847 		wm[7] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
1848 				GEN9_MEM_LATENCY_LEVEL_MASK;
1849 
1850 		/*
1851 		 * WaWmMemoryReadLatency:skl
1852 		 *
1853 		 * punit doesn't take into account the read latency so we need
1854 		 * to add 2us to the various latency levels we retrieve from
1855 		 * the punit.
1856 		 *   - W0 is a bit special in that it's the only level that
1857 		 *   can't be disabled if we want to have display working, so
1858 		 *   we always add 2us there.
1859 		 *   - For levels >=1, punit returns 0us latency when they are
1860 		 *   disabled, so we respect that and don't add 2us then
1861 		 *
1862 		 * Additionally, if a level n (n > 1) has a 0us latency, all
1863 		 * levels m (m >= n) need to be disabled. We make sure to
1864 		 * sanitize the values out of the punit to satisfy this
1865 		 * requirement.
1866 		 */
1867 		wm[0] += 2;
1868 		for (level = 1; level <= max_level; level++)
1869 			if (wm[level] != 0)
1870 				wm[level] += 2;
1871 			else {
1872 				for (i = level + 1; i <= max_level; i++)
1873 					wm[i] = 0;
1874 
1875 				break;
1876 			}
1877 	} else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
1878 		uint64_t sskpd = I915_READ64(MCH_SSKPD);
1879 
1880 		wm[0] = (sskpd >> 56) & 0xFF;
1881 		if (wm[0] == 0)
1882 			wm[0] = sskpd & 0xF;
1883 		wm[1] = (sskpd >> 4) & 0xFF;
1884 		wm[2] = (sskpd >> 12) & 0xFF;
1885 		wm[3] = (sskpd >> 20) & 0x1FF;
1886 		wm[4] = (sskpd >> 32) & 0x1FF;
1887 	} else if (INTEL_INFO(dev)->gen >= 6) {
1888 		uint32_t sskpd = I915_READ(MCH_SSKPD);
1889 
1890 		wm[0] = (sskpd >> SSKPD_WM0_SHIFT) & SSKPD_WM_MASK;
1891 		wm[1] = (sskpd >> SSKPD_WM1_SHIFT) & SSKPD_WM_MASK;
1892 		wm[2] = (sskpd >> SSKPD_WM2_SHIFT) & SSKPD_WM_MASK;
1893 		wm[3] = (sskpd >> SSKPD_WM3_SHIFT) & SSKPD_WM_MASK;
1894 	} else if (INTEL_INFO(dev)->gen >= 5) {
1895 		uint32_t mltr = I915_READ(MLTR_ILK);
1896 
1897 		/* ILK primary LP0 latency is 700 ns */
1898 		wm[0] = 7;
1899 		wm[1] = (mltr >> MLTR_WM1_SHIFT) & ILK_SRLT_MASK;
1900 		wm[2] = (mltr >> MLTR_WM2_SHIFT) & ILK_SRLT_MASK;
1901 	}
1902 }
1903 
1904 static void intel_fixup_spr_wm_latency(struct drm_device *dev, uint16_t wm[5])
1905 {
1906 	/* ILK sprite LP0 latency is 1300 ns */
1907 	if (INTEL_INFO(dev)->gen == 5)
1908 		wm[0] = 13;
1909 }
1910 
1911 static void intel_fixup_cur_wm_latency(struct drm_device *dev, uint16_t wm[5])
1912 {
1913 	/* ILK cursor LP0 latency is 1300 ns */
1914 	if (INTEL_INFO(dev)->gen == 5)
1915 		wm[0] = 13;
1916 
1917 	/* WaDoubleCursorLP3Latency:ivb */
1918 	if (IS_IVYBRIDGE(dev))
1919 		wm[3] *= 2;
1920 }
1921 
1922 int ilk_wm_max_level(const struct drm_device *dev)
1923 {
1924 	/* how many WM levels are we expecting */
1925 	if (IS_GEN9(dev))
1926 		return 7;
1927 	else if (IS_HASWELL(dev) || IS_BROADWELL(dev))
1928 		return 4;
1929 	else if (INTEL_INFO(dev)->gen >= 6)
1930 		return 3;
1931 	else
1932 		return 2;
1933 }
1934 
1935 static void intel_print_wm_latency(struct drm_device *dev,
1936 				   const char *name,
1937 				   const uint16_t wm[8])
1938 {
1939 	int level, max_level = ilk_wm_max_level(dev);
1940 
1941 	for (level = 0; level <= max_level; level++) {
1942 		unsigned int latency = wm[level];
1943 
1944 		if (latency == 0) {
1945 			DRM_ERROR("%s WM%d latency not provided\n",
1946 				  name, level);
1947 			continue;
1948 		}
1949 
1950 		/*
1951 		 * - latencies are in us on gen9.
1952 		 * - before then, WM1+ latency values are in 0.5us units
1953 		 */
1954 		if (IS_GEN9(dev))
1955 			latency *= 10;
1956 		else if (level > 0)
1957 			latency *= 5;
1958 
1959 		DRM_DEBUG_KMS("%s WM%d latency %u (%u.%u usec)\n",
1960 			      name, level, wm[level],
1961 			      latency / 10, latency % 10);
1962 	}
1963 }
1964 
1965 static bool ilk_increase_wm_latency(struct drm_i915_private *dev_priv,
1966 				    uint16_t wm[5], uint16_t min)
1967 {
1968 	int level, max_level = ilk_wm_max_level(dev_priv->dev);
1969 
1970 	if (wm[0] >= min)
1971 		return false;
1972 
1973 	wm[0] = max(wm[0], min);
1974 	for (level = 1; level <= max_level; level++)
1975 		wm[level] = max_t(uint16_t, wm[level], DIV_ROUND_UP(min, 5));
1976 
1977 	return true;
1978 }
1979 
1980 static void snb_wm_latency_quirk(struct drm_device *dev)
1981 {
1982 	struct drm_i915_private *dev_priv = dev->dev_private;
1983 	bool changed;
1984 
1985 	/*
1986 	 * The BIOS provided WM memory latency values are often
1987 	 * inadequate for high resolution displays. Adjust them.
1988 	 */
1989 	changed = ilk_increase_wm_latency(dev_priv, dev_priv->wm.pri_latency, 12) |
1990 		ilk_increase_wm_latency(dev_priv, dev_priv->wm.spr_latency, 12) |
1991 		ilk_increase_wm_latency(dev_priv, dev_priv->wm.cur_latency, 12);
1992 
1993 	if (!changed)
1994 		return;
1995 
1996 	DRM_DEBUG_KMS("WM latency values increased to avoid potential underruns\n");
1997 	intel_print_wm_latency(dev, "Primary", dev_priv->wm.pri_latency);
1998 	intel_print_wm_latency(dev, "Sprite", dev_priv->wm.spr_latency);
1999 	intel_print_wm_latency(dev, "Cursor", dev_priv->wm.cur_latency);
2000 }
2001 
2002 static void ilk_setup_wm_latency(struct drm_device *dev)
2003 {
2004 	struct drm_i915_private *dev_priv = dev->dev_private;
2005 
2006 	intel_read_wm_latency(dev, dev_priv->wm.pri_latency);
2007 
2008 	memcpy(dev_priv->wm.spr_latency, dev_priv->wm.pri_latency,
2009 	       sizeof(dev_priv->wm.pri_latency));
2010 	memcpy(dev_priv->wm.cur_latency, dev_priv->wm.pri_latency,
2011 	       sizeof(dev_priv->wm.pri_latency));
2012 
2013 	intel_fixup_spr_wm_latency(dev, dev_priv->wm.spr_latency);
2014 	intel_fixup_cur_wm_latency(dev, dev_priv->wm.cur_latency);
2015 
2016 	intel_print_wm_latency(dev, "Primary", dev_priv->wm.pri_latency);
2017 	intel_print_wm_latency(dev, "Sprite", dev_priv->wm.spr_latency);
2018 	intel_print_wm_latency(dev, "Cursor", dev_priv->wm.cur_latency);
2019 
2020 	if (IS_GEN6(dev))
2021 		snb_wm_latency_quirk(dev);
2022 }
2023 
2024 static void skl_setup_wm_latency(struct drm_device *dev)
2025 {
2026 	struct drm_i915_private *dev_priv = dev->dev_private;
2027 
2028 	intel_read_wm_latency(dev, dev_priv->wm.skl_latency);
2029 	intel_print_wm_latency(dev, "Gen9 Plane", dev_priv->wm.skl_latency);
2030 }
2031 
2032 static void ilk_compute_wm_parameters(struct drm_crtc *crtc,
2033 				      struct ilk_pipe_wm_parameters *p)
2034 {
2035 	struct drm_device *dev = crtc->dev;
2036 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2037 	enum i915_pipe pipe = intel_crtc->pipe;
2038 	struct drm_plane *plane;
2039 
2040 	if (!intel_crtc->active)
2041 		return;
2042 
2043 	p->active = true;
2044 	p->pipe_htotal = intel_crtc->config->base.adjusted_mode.crtc_htotal;
2045 	p->pixel_rate = ilk_pipe_pixel_rate(dev, crtc);
2046 
2047 	if (crtc->primary->state->fb)
2048 		p->pri.bytes_per_pixel =
2049 			crtc->primary->state->fb->bits_per_pixel / 8;
2050 	else
2051 		p->pri.bytes_per_pixel = 4;
2052 
2053 	p->cur.bytes_per_pixel = 4;
2054 	/*
2055 	 * TODO: for now, assume primary and cursor planes are always enabled.
2056 	 * Setting them to false makes the screen flicker.
2057 	 */
2058 	p->pri.enabled = true;
2059 	p->cur.enabled = true;
2060 
2061 	p->pri.horiz_pixels = intel_crtc->config->pipe_src_w;
2062 	p->cur.horiz_pixels = intel_crtc->base.cursor->state->crtc_w;
2063 
2064 	drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
2065 		struct intel_plane *intel_plane = to_intel_plane(plane);
2066 
2067 		if (intel_plane->pipe == pipe) {
2068 			p->spr = intel_plane->wm;
2069 			break;
2070 		}
2071 	}
2072 }
2073 
2074 static void ilk_compute_wm_config(struct drm_device *dev,
2075 				  struct intel_wm_config *config)
2076 {
2077 	struct intel_crtc *intel_crtc;
2078 
2079 	/* Compute the currently _active_ config */
2080 	for_each_intel_crtc(dev, intel_crtc) {
2081 		const struct intel_pipe_wm *wm = &intel_crtc->wm.active;
2082 
2083 		if (!wm->pipe_enabled)
2084 			continue;
2085 
2086 		config->sprites_enabled |= wm->sprites_enabled;
2087 		config->sprites_scaled |= wm->sprites_scaled;
2088 		config->num_pipes_active++;
2089 	}
2090 }
2091 
2092 /* Compute new watermarks for the pipe */
2093 static bool intel_compute_pipe_wm(struct drm_crtc *crtc,
2094 				  const struct ilk_pipe_wm_parameters *params,
2095 				  struct intel_pipe_wm *pipe_wm)
2096 {
2097 	struct drm_device *dev = crtc->dev;
2098 	const struct drm_i915_private *dev_priv = dev->dev_private;
2099 	int level, max_level = ilk_wm_max_level(dev);
2100 	/* LP0 watermark maximums depend on this pipe alone */
2101 	struct intel_wm_config config = {
2102 		.num_pipes_active = 1,
2103 		.sprites_enabled = params->spr.enabled,
2104 		.sprites_scaled = params->spr.scaled,
2105 	};
2106 	struct ilk_wm_maximums max;
2107 
2108 	pipe_wm->pipe_enabled = params->active;
2109 	pipe_wm->sprites_enabled = params->spr.enabled;
2110 	pipe_wm->sprites_scaled = params->spr.scaled;
2111 
2112 	/* ILK/SNB: LP2+ watermarks only w/o sprites */
2113 	if (INTEL_INFO(dev)->gen <= 6 && params->spr.enabled)
2114 		max_level = 1;
2115 
2116 	/* ILK/SNB/IVB: LP1+ watermarks only w/o scaling */
2117 	if (params->spr.scaled)
2118 		max_level = 0;
2119 
2120 	ilk_compute_wm_level(dev_priv, 0, params, &pipe_wm->wm[0]);
2121 
2122 	if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2123 		pipe_wm->linetime = hsw_compute_linetime_wm(dev, crtc);
2124 
2125 	/* LP0 watermarks always use 1/2 DDB partitioning */
2126 	ilk_compute_wm_maximums(dev, 0, &config, INTEL_DDB_PART_1_2, &max);
2127 
2128 	/* At least LP0 must be valid */
2129 	if (!ilk_validate_wm_level(0, &max, &pipe_wm->wm[0]))
2130 		return false;
2131 
2132 	ilk_compute_wm_reg_maximums(dev, 1, &max);
2133 
2134 	for (level = 1; level <= max_level; level++) {
2135 		struct intel_wm_level wm = {};
2136 
2137 		ilk_compute_wm_level(dev_priv, level, params, &wm);
2138 
2139 		/*
2140 		 * Disable any watermark level that exceeds the
2141 		 * register maximums since such watermarks are
2142 		 * always invalid.
2143 		 */
2144 		if (!ilk_validate_wm_level(level, &max, &wm))
2145 			break;
2146 
2147 		pipe_wm->wm[level] = wm;
2148 	}
2149 
2150 	return true;
2151 }
2152 
2153 /*
2154  * Merge the watermarks from all active pipes for a specific level.
2155  */
2156 static void ilk_merge_wm_level(struct drm_device *dev,
2157 			       int level,
2158 			       struct intel_wm_level *ret_wm)
2159 {
2160 	struct intel_crtc *intel_crtc;
2161 
2162 	ret_wm->enable = true;
2163 
2164 	for_each_intel_crtc(dev, intel_crtc) {
2165 		const struct intel_pipe_wm *active = &intel_crtc->wm.active;
2166 		const struct intel_wm_level *wm = &active->wm[level];
2167 
2168 		if (!active->pipe_enabled)
2169 			continue;
2170 
2171 		/*
2172 		 * The watermark values may have been used in the past,
2173 		 * so we must maintain them in the registers for some
2174 		 * time even if the level is now disabled.
2175 		 */
2176 		if (!wm->enable)
2177 			ret_wm->enable = false;
2178 
2179 		ret_wm->pri_val = max(ret_wm->pri_val, wm->pri_val);
2180 		ret_wm->spr_val = max(ret_wm->spr_val, wm->spr_val);
2181 		ret_wm->cur_val = max(ret_wm->cur_val, wm->cur_val);
2182 		ret_wm->fbc_val = max(ret_wm->fbc_val, wm->fbc_val);
2183 	}
2184 }
2185 
2186 /*
2187  * Merge all low power watermarks for all active pipes.
2188  */
2189 static void ilk_wm_merge(struct drm_device *dev,
2190 			 const struct intel_wm_config *config,
2191 			 const struct ilk_wm_maximums *max,
2192 			 struct intel_pipe_wm *merged)
2193 {
2194 	int level, max_level = ilk_wm_max_level(dev);
2195 	int last_enabled_level = max_level;
2196 
2197 	/* ILK/SNB/IVB: LP1+ watermarks only w/ single pipe */
2198 	if ((INTEL_INFO(dev)->gen <= 6 || IS_IVYBRIDGE(dev)) &&
2199 	    config->num_pipes_active > 1)
2200 		return;
2201 
2202 	/* ILK: FBC WM must be disabled always */
2203 	merged->fbc_wm_enabled = INTEL_INFO(dev)->gen >= 6;
2204 
2205 	/* merge each WM1+ level */
2206 	for (level = 1; level <= max_level; level++) {
2207 		struct intel_wm_level *wm = &merged->wm[level];
2208 
2209 		ilk_merge_wm_level(dev, level, wm);
2210 
2211 		if (level > last_enabled_level)
2212 			wm->enable = false;
2213 		else if (!ilk_validate_wm_level(level, max, wm))
2214 			/* make sure all following levels get disabled */
2215 			last_enabled_level = level - 1;
2216 
2217 		/*
2218 		 * The spec says it is preferred to disable
2219 		 * FBC WMs instead of disabling a WM level.
2220 		 */
2221 		if (wm->fbc_val > max->fbc) {
2222 			if (wm->enable)
2223 				merged->fbc_wm_enabled = false;
2224 			wm->fbc_val = 0;
2225 		}
2226 	}
2227 
2228 	/* ILK: LP2+ must be disabled when FBC WM is disabled but FBC enabled */
2229 	/*
2230 	 * FIXME this is racy. FBC might get enabled later.
2231 	 * What we should check here is whether FBC can be
2232 	 * enabled sometime later.
2233 	 */
2234 	if (IS_GEN5(dev) && !merged->fbc_wm_enabled && intel_fbc_enabled(dev)) {
2235 		for (level = 2; level <= max_level; level++) {
2236 			struct intel_wm_level *wm = &merged->wm[level];
2237 
2238 			wm->enable = false;
2239 		}
2240 	}
2241 }
2242 
2243 static int ilk_wm_lp_to_level(int wm_lp, const struct intel_pipe_wm *pipe_wm)
2244 {
2245 	/* LP1,LP2,LP3 levels are either 1,2,3 or 1,3,4 */
2246 	return wm_lp + (wm_lp >= 2 && pipe_wm->wm[4].enable);
2247 }
2248 
2249 /* The value we need to program into the WM_LPx latency field */
2250 static unsigned int ilk_wm_lp_latency(struct drm_device *dev, int level)
2251 {
2252 	struct drm_i915_private *dev_priv = dev->dev_private;
2253 
2254 	if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2255 		return 2 * level;
2256 	else
2257 		return dev_priv->wm.pri_latency[level];
2258 }
2259 
2260 static void ilk_compute_wm_results(struct drm_device *dev,
2261 				   const struct intel_pipe_wm *merged,
2262 				   enum intel_ddb_partitioning partitioning,
2263 				   struct ilk_wm_values *results)
2264 {
2265 	struct intel_crtc *intel_crtc;
2266 	int level, wm_lp;
2267 
2268 	results->enable_fbc_wm = merged->fbc_wm_enabled;
2269 	results->partitioning = partitioning;
2270 
2271 	/* LP1+ register values */
2272 	for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
2273 		const struct intel_wm_level *r;
2274 
2275 		level = ilk_wm_lp_to_level(wm_lp, merged);
2276 
2277 		r = &merged->wm[level];
2278 
2279 		/*
2280 		 * Maintain the watermark values even if the level is
2281 		 * disabled. Doing otherwise could cause underruns.
2282 		 */
2283 		results->wm_lp[wm_lp - 1] =
2284 			(ilk_wm_lp_latency(dev, level) << WM1_LP_LATENCY_SHIFT) |
2285 			(r->pri_val << WM1_LP_SR_SHIFT) |
2286 			r->cur_val;
2287 
2288 		if (r->enable)
2289 			results->wm_lp[wm_lp - 1] |= WM1_LP_SR_EN;
2290 
2291 		if (INTEL_INFO(dev)->gen >= 8)
2292 			results->wm_lp[wm_lp - 1] |=
2293 				r->fbc_val << WM1_LP_FBC_SHIFT_BDW;
2294 		else
2295 			results->wm_lp[wm_lp - 1] |=
2296 				r->fbc_val << WM1_LP_FBC_SHIFT;
2297 
2298 		/*
2299 		 * Always set WM1S_LP_EN when spr_val != 0, even if the
2300 		 * level is disabled. Doing otherwise could cause underruns.
2301 		 */
2302 		if (INTEL_INFO(dev)->gen <= 6 && r->spr_val) {
2303 			WARN_ON(wm_lp != 1);
2304 			results->wm_lp_spr[wm_lp - 1] = WM1S_LP_EN | r->spr_val;
2305 		} else
2306 			results->wm_lp_spr[wm_lp - 1] = r->spr_val;
2307 	}
2308 
2309 	/* LP0 register values */
2310 	for_each_intel_crtc(dev, intel_crtc) {
2311 		enum i915_pipe pipe = intel_crtc->pipe;
2312 		const struct intel_wm_level *r =
2313 			&intel_crtc->wm.active.wm[0];
2314 
2315 		if (WARN_ON(!r->enable))
2316 			continue;
2317 
2318 		results->wm_linetime[pipe] = intel_crtc->wm.active.linetime;
2319 
2320 		results->wm_pipe[pipe] =
2321 			(r->pri_val << WM0_PIPE_PLANE_SHIFT) |
2322 			(r->spr_val << WM0_PIPE_SPRITE_SHIFT) |
2323 			r->cur_val;
2324 	}
2325 }
2326 
2327 /* Find the result with the highest level enabled. Check for enable_fbc_wm in
2328  * case both are at the same level. Prefer r1 in case they're the same. */
2329 static struct intel_pipe_wm *ilk_find_best_result(struct drm_device *dev,
2330 						  struct intel_pipe_wm *r1,
2331 						  struct intel_pipe_wm *r2)
2332 {
2333 	int level, max_level = ilk_wm_max_level(dev);
2334 	int level1 = 0, level2 = 0;
2335 
2336 	for (level = 1; level <= max_level; level++) {
2337 		if (r1->wm[level].enable)
2338 			level1 = level;
2339 		if (r2->wm[level].enable)
2340 			level2 = level;
2341 	}
2342 
2343 	if (level1 == level2) {
2344 		if (r2->fbc_wm_enabled && !r1->fbc_wm_enabled)
2345 			return r2;
2346 		else
2347 			return r1;
2348 	} else if (level1 > level2) {
2349 		return r1;
2350 	} else {
2351 		return r2;
2352 	}
2353 }
2354 
2355 /* dirty bits used to track which watermarks need changes */
2356 #define WM_DIRTY_PIPE(pipe) (1 << (pipe))
2357 #define WM_DIRTY_LINETIME(pipe) (1 << (8 + (pipe)))
2358 #define WM_DIRTY_LP(wm_lp) (1 << (15 + (wm_lp)))
2359 #define WM_DIRTY_LP_ALL (WM_DIRTY_LP(1) | WM_DIRTY_LP(2) | WM_DIRTY_LP(3))
2360 #define WM_DIRTY_FBC (1 << 24)
2361 #define WM_DIRTY_DDB (1 << 25)
2362 
2363 static unsigned int ilk_compute_wm_dirty(struct drm_i915_private *dev_priv,
2364 					 const struct ilk_wm_values *old,
2365 					 const struct ilk_wm_values *new)
2366 {
2367 	unsigned int dirty = 0;
2368 	enum i915_pipe pipe;
2369 	int wm_lp;
2370 
2371 	for_each_pipe(dev_priv, pipe) {
2372 		if (old->wm_linetime[pipe] != new->wm_linetime[pipe]) {
2373 			dirty |= WM_DIRTY_LINETIME(pipe);
2374 			/* Must disable LP1+ watermarks too */
2375 			dirty |= WM_DIRTY_LP_ALL;
2376 		}
2377 
2378 		if (old->wm_pipe[pipe] != new->wm_pipe[pipe]) {
2379 			dirty |= WM_DIRTY_PIPE(pipe);
2380 			/* Must disable LP1+ watermarks too */
2381 			dirty |= WM_DIRTY_LP_ALL;
2382 		}
2383 	}
2384 
2385 	if (old->enable_fbc_wm != new->enable_fbc_wm) {
2386 		dirty |= WM_DIRTY_FBC;
2387 		/* Must disable LP1+ watermarks too */
2388 		dirty |= WM_DIRTY_LP_ALL;
2389 	}
2390 
2391 	if (old->partitioning != new->partitioning) {
2392 		dirty |= WM_DIRTY_DDB;
2393 		/* Must disable LP1+ watermarks too */
2394 		dirty |= WM_DIRTY_LP_ALL;
2395 	}
2396 
2397 	/* LP1+ watermarks already deemed dirty, no need to continue */
2398 	if (dirty & WM_DIRTY_LP_ALL)
2399 		return dirty;
2400 
2401 	/* Find the lowest numbered LP1+ watermark in need of an update... */
2402 	for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
2403 		if (old->wm_lp[wm_lp - 1] != new->wm_lp[wm_lp - 1] ||
2404 		    old->wm_lp_spr[wm_lp - 1] != new->wm_lp_spr[wm_lp - 1])
2405 			break;
2406 	}
2407 
2408 	/* ...and mark it and all higher numbered LP1+ watermarks as dirty */
2409 	for (; wm_lp <= 3; wm_lp++)
2410 		dirty |= WM_DIRTY_LP(wm_lp);
2411 
2412 	return dirty;
2413 }
2414 
2415 static bool _ilk_disable_lp_wm(struct drm_i915_private *dev_priv,
2416 			       unsigned int dirty)
2417 {
2418 	struct ilk_wm_values *previous = &dev_priv->wm.hw;
2419 	bool changed = false;
2420 
2421 	if (dirty & WM_DIRTY_LP(3) && previous->wm_lp[2] & WM1_LP_SR_EN) {
2422 		previous->wm_lp[2] &= ~WM1_LP_SR_EN;
2423 		I915_WRITE(WM3_LP_ILK, previous->wm_lp[2]);
2424 		changed = true;
2425 	}
2426 	if (dirty & WM_DIRTY_LP(2) && previous->wm_lp[1] & WM1_LP_SR_EN) {
2427 		previous->wm_lp[1] &= ~WM1_LP_SR_EN;
2428 		I915_WRITE(WM2_LP_ILK, previous->wm_lp[1]);
2429 		changed = true;
2430 	}
2431 	if (dirty & WM_DIRTY_LP(1) && previous->wm_lp[0] & WM1_LP_SR_EN) {
2432 		previous->wm_lp[0] &= ~WM1_LP_SR_EN;
2433 		I915_WRITE(WM1_LP_ILK, previous->wm_lp[0]);
2434 		changed = true;
2435 	}
2436 
2437 	/*
2438 	 * Don't touch WM1S_LP_EN here.
2439 	 * Doing so could cause underruns.
2440 	 */
2441 
2442 	return changed;
2443 }
2444 
2445 /*
2446  * The spec says we shouldn't write when we don't need, because every write
2447  * causes WMs to be re-evaluated, expending some power.
2448  */
2449 static void ilk_write_wm_values(struct drm_i915_private *dev_priv,
2450 				struct ilk_wm_values *results)
2451 {
2452 	struct drm_device *dev = dev_priv->dev;
2453 	struct ilk_wm_values *previous = &dev_priv->wm.hw;
2454 	unsigned int dirty;
2455 	uint32_t val;
2456 
2457 	dirty = ilk_compute_wm_dirty(dev_priv, previous, results);
2458 	if (!dirty)
2459 		return;
2460 
2461 	_ilk_disable_lp_wm(dev_priv, dirty);
2462 
2463 	if (dirty & WM_DIRTY_PIPE(PIPE_A))
2464 		I915_WRITE(WM0_PIPEA_ILK, results->wm_pipe[0]);
2465 	if (dirty & WM_DIRTY_PIPE(PIPE_B))
2466 		I915_WRITE(WM0_PIPEB_ILK, results->wm_pipe[1]);
2467 	if (dirty & WM_DIRTY_PIPE(PIPE_C))
2468 		I915_WRITE(WM0_PIPEC_IVB, results->wm_pipe[2]);
2469 
2470 	if (dirty & WM_DIRTY_LINETIME(PIPE_A))
2471 		I915_WRITE(PIPE_WM_LINETIME(PIPE_A), results->wm_linetime[0]);
2472 	if (dirty & WM_DIRTY_LINETIME(PIPE_B))
2473 		I915_WRITE(PIPE_WM_LINETIME(PIPE_B), results->wm_linetime[1]);
2474 	if (dirty & WM_DIRTY_LINETIME(PIPE_C))
2475 		I915_WRITE(PIPE_WM_LINETIME(PIPE_C), results->wm_linetime[2]);
2476 
2477 	if (dirty & WM_DIRTY_DDB) {
2478 		if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2479 			val = I915_READ(WM_MISC);
2480 			if (results->partitioning == INTEL_DDB_PART_1_2)
2481 				val &= ~WM_MISC_DATA_PARTITION_5_6;
2482 			else
2483 				val |= WM_MISC_DATA_PARTITION_5_6;
2484 			I915_WRITE(WM_MISC, val);
2485 		} else {
2486 			val = I915_READ(DISP_ARB_CTL2);
2487 			if (results->partitioning == INTEL_DDB_PART_1_2)
2488 				val &= ~DISP_DATA_PARTITION_5_6;
2489 			else
2490 				val |= DISP_DATA_PARTITION_5_6;
2491 			I915_WRITE(DISP_ARB_CTL2, val);
2492 		}
2493 	}
2494 
2495 	if (dirty & WM_DIRTY_FBC) {
2496 		val = I915_READ(DISP_ARB_CTL);
2497 		if (results->enable_fbc_wm)
2498 			val &= ~DISP_FBC_WM_DIS;
2499 		else
2500 			val |= DISP_FBC_WM_DIS;
2501 		I915_WRITE(DISP_ARB_CTL, val);
2502 	}
2503 
2504 	if (dirty & WM_DIRTY_LP(1) &&
2505 	    previous->wm_lp_spr[0] != results->wm_lp_spr[0])
2506 		I915_WRITE(WM1S_LP_ILK, results->wm_lp_spr[0]);
2507 
2508 	if (INTEL_INFO(dev)->gen >= 7) {
2509 		if (dirty & WM_DIRTY_LP(2) && previous->wm_lp_spr[1] != results->wm_lp_spr[1])
2510 			I915_WRITE(WM2S_LP_IVB, results->wm_lp_spr[1]);
2511 		if (dirty & WM_DIRTY_LP(3) && previous->wm_lp_spr[2] != results->wm_lp_spr[2])
2512 			I915_WRITE(WM3S_LP_IVB, results->wm_lp_spr[2]);
2513 	}
2514 
2515 	if (dirty & WM_DIRTY_LP(1) && previous->wm_lp[0] != results->wm_lp[0])
2516 		I915_WRITE(WM1_LP_ILK, results->wm_lp[0]);
2517 	if (dirty & WM_DIRTY_LP(2) && previous->wm_lp[1] != results->wm_lp[1])
2518 		I915_WRITE(WM2_LP_ILK, results->wm_lp[1]);
2519 	if (dirty & WM_DIRTY_LP(3) && previous->wm_lp[2] != results->wm_lp[2])
2520 		I915_WRITE(WM3_LP_ILK, results->wm_lp[2]);
2521 
2522 	dev_priv->wm.hw = *results;
2523 }
2524 
2525 static bool ilk_disable_lp_wm(struct drm_device *dev)
2526 {
2527 	struct drm_i915_private *dev_priv = dev->dev_private;
2528 
2529 	return _ilk_disable_lp_wm(dev_priv, WM_DIRTY_LP_ALL);
2530 }
2531 
2532 /*
2533  * On gen9, we need to allocate Display Data Buffer (DDB) portions to the
2534  * different active planes.
2535  */
2536 
2537 #define SKL_DDB_SIZE		896	/* in blocks */
2538 
2539 static void
2540 skl_ddb_get_pipe_allocation_limits(struct drm_device *dev,
2541 				   struct drm_crtc *for_crtc,
2542 				   const struct intel_wm_config *config,
2543 				   const struct skl_pipe_wm_parameters *params,
2544 				   struct skl_ddb_entry *alloc /* out */)
2545 {
2546 	struct drm_crtc *crtc;
2547 	unsigned int pipe_size, ddb_size;
2548 	int nth_active_pipe;
2549 
2550 	if (!params->active) {
2551 		alloc->start = 0;
2552 		alloc->end = 0;
2553 		return;
2554 	}
2555 
2556 	ddb_size = SKL_DDB_SIZE;
2557 
2558 	ddb_size -= 4; /* 4 blocks for bypass path allocation */
2559 
2560 	nth_active_pipe = 0;
2561 	for_each_crtc(dev, crtc) {
2562 		if (!to_intel_crtc(crtc)->active)
2563 			continue;
2564 
2565 		if (crtc == for_crtc)
2566 			break;
2567 
2568 		nth_active_pipe++;
2569 	}
2570 
2571 	pipe_size = ddb_size / config->num_pipes_active;
2572 	alloc->start = nth_active_pipe * ddb_size / config->num_pipes_active;
2573 	alloc->end = alloc->start + pipe_size;
2574 }
2575 
2576 static unsigned int skl_cursor_allocation(const struct intel_wm_config *config)
2577 {
2578 	if (config->num_pipes_active == 1)
2579 		return 32;
2580 
2581 	return 8;
2582 }
2583 
2584 static void skl_ddb_entry_init_from_hw(struct skl_ddb_entry *entry, u32 reg)
2585 {
2586 	entry->start = reg & 0x3ff;
2587 	entry->end = (reg >> 16) & 0x3ff;
2588 	if (entry->end)
2589 		entry->end += 1;
2590 }
2591 
2592 void skl_ddb_get_hw_state(struct drm_i915_private *dev_priv,
2593 			  struct skl_ddb_allocation *ddb /* out */)
2594 {
2595 	enum i915_pipe pipe;
2596 	int plane;
2597 	u32 val;
2598 
2599 	for_each_pipe(dev_priv, pipe) {
2600 		for_each_plane(dev_priv, pipe, plane) {
2601 			val = I915_READ(PLANE_BUF_CFG(pipe, plane));
2602 			skl_ddb_entry_init_from_hw(&ddb->plane[pipe][plane],
2603 						   val);
2604 		}
2605 
2606 		val = I915_READ(CUR_BUF_CFG(pipe));
2607 		skl_ddb_entry_init_from_hw(&ddb->cursor[pipe], val);
2608 	}
2609 }
2610 
2611 static unsigned int
2612 skl_plane_relative_data_rate(const struct intel_plane_wm_parameters *p)
2613 {
2614 	return p->horiz_pixels * p->vert_pixels * p->bytes_per_pixel;
2615 }
2616 
2617 /*
2618  * We don't overflow 32 bits. Worst case is 3 planes enabled, each fetching
2619  * a 8192x4096@32bpp framebuffer:
2620  *   3 * 4096 * 8192  * 4 < 2^32
2621  */
2622 static unsigned int
2623 skl_get_total_relative_data_rate(struct intel_crtc *intel_crtc,
2624 				 const struct skl_pipe_wm_parameters *params)
2625 {
2626 	unsigned int total_data_rate = 0;
2627 	int plane;
2628 
2629 	for (plane = 0; plane < intel_num_planes(intel_crtc); plane++) {
2630 		const struct intel_plane_wm_parameters *p;
2631 
2632 		p = &params->plane[plane];
2633 		if (!p->enabled)
2634 			continue;
2635 
2636 		total_data_rate += skl_plane_relative_data_rate(p);
2637 	}
2638 
2639 	return total_data_rate;
2640 }
2641 
2642 static void
2643 skl_allocate_pipe_ddb(struct drm_crtc *crtc,
2644 		      const struct intel_wm_config *config,
2645 		      const struct skl_pipe_wm_parameters *params,
2646 		      struct skl_ddb_allocation *ddb /* out */)
2647 {
2648 	struct drm_device *dev = crtc->dev;
2649 	struct drm_i915_private *dev_priv = dev->dev_private;
2650 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2651 	enum i915_pipe pipe = intel_crtc->pipe;
2652 	struct skl_ddb_entry *alloc = &ddb->pipe[pipe];
2653 	uint16_t alloc_size, start, cursor_blocks;
2654 	uint16_t minimum[I915_MAX_PLANES];
2655 	unsigned int total_data_rate;
2656 	int plane;
2657 
2658 	skl_ddb_get_pipe_allocation_limits(dev, crtc, config, params, alloc);
2659 	alloc_size = skl_ddb_entry_size(alloc);
2660 	if (alloc_size == 0) {
2661 		memset(ddb->plane[pipe], 0, sizeof(ddb->plane[pipe]));
2662 		memset(&ddb->cursor[pipe], 0, sizeof(ddb->cursor[pipe]));
2663 		return;
2664 	}
2665 
2666 	cursor_blocks = skl_cursor_allocation(config);
2667 	ddb->cursor[pipe].start = alloc->end - cursor_blocks;
2668 	ddb->cursor[pipe].end = alloc->end;
2669 
2670 	alloc_size -= cursor_blocks;
2671 	alloc->end -= cursor_blocks;
2672 
2673 	/* 1. Allocate the mininum required blocks for each active plane */
2674 	for_each_plane(dev_priv, pipe, plane) {
2675 		const struct intel_plane_wm_parameters *p;
2676 
2677 		p = &params->plane[plane];
2678 		if (!p->enabled)
2679 			continue;
2680 
2681 		minimum[plane] = 8;
2682 		alloc_size -= minimum[plane];
2683 	}
2684 
2685 	/*
2686 	 * 2. Distribute the remaining space in proportion to the amount of
2687 	 * data each plane needs to fetch from memory.
2688 	 *
2689 	 * FIXME: we may not allocate every single block here.
2690 	 */
2691 	total_data_rate = skl_get_total_relative_data_rate(intel_crtc, params);
2692 
2693 	start = alloc->start;
2694 	for (plane = 0; plane < intel_num_planes(intel_crtc); plane++) {
2695 		const struct intel_plane_wm_parameters *p;
2696 		unsigned int data_rate;
2697 		uint16_t plane_blocks;
2698 
2699 		p = &params->plane[plane];
2700 		if (!p->enabled)
2701 			continue;
2702 
2703 		data_rate = skl_plane_relative_data_rate(p);
2704 
2705 		/*
2706 		 * promote the expression to 64 bits to avoid overflowing, the
2707 		 * result is < available as data_rate / total_data_rate < 1
2708 		 */
2709 		plane_blocks = minimum[plane];
2710 		plane_blocks += div_u64((uint64_t)alloc_size * data_rate,
2711 					total_data_rate);
2712 
2713 		ddb->plane[pipe][plane].start = start;
2714 		ddb->plane[pipe][plane].end = start + plane_blocks;
2715 
2716 		start += plane_blocks;
2717 	}
2718 
2719 }
2720 
2721 static uint32_t skl_pipe_pixel_rate(const struct intel_crtc_state *config)
2722 {
2723 	/* TODO: Take into account the scalers once we support them */
2724 	return config->base.adjusted_mode.crtc_clock;
2725 }
2726 
2727 /*
2728  * The max latency should be 257 (max the punit can code is 255 and we add 2us
2729  * for the read latency) and bytes_per_pixel should always be <= 8, so that
2730  * should allow pixel_rate up to ~2 GHz which seems sufficient since max
2731  * 2xcdclk is 1350 MHz and the pixel rate should never exceed that.
2732 */
2733 static uint32_t skl_wm_method1(uint32_t pixel_rate, uint8_t bytes_per_pixel,
2734 			       uint32_t latency)
2735 {
2736 	uint32_t wm_intermediate_val, ret;
2737 
2738 	if (latency == 0)
2739 		return UINT_MAX;
2740 
2741 	wm_intermediate_val = latency * pixel_rate * bytes_per_pixel / 512;
2742 	ret = DIV_ROUND_UP(wm_intermediate_val, 1000);
2743 
2744 	return ret;
2745 }
2746 
2747 static uint32_t skl_wm_method2(uint32_t pixel_rate, uint32_t pipe_htotal,
2748 			       uint32_t horiz_pixels, uint8_t bytes_per_pixel,
2749 			       uint64_t tiling, uint32_t latency)
2750 {
2751 	uint32_t ret;
2752 	uint32_t plane_bytes_per_line, plane_blocks_per_line;
2753 	uint32_t wm_intermediate_val;
2754 
2755 	if (latency == 0)
2756 		return UINT_MAX;
2757 
2758 	plane_bytes_per_line = horiz_pixels * bytes_per_pixel;
2759 
2760 	if (tiling == I915_FORMAT_MOD_Y_TILED ||
2761 	    tiling == I915_FORMAT_MOD_Yf_TILED) {
2762 		plane_bytes_per_line *= 4;
2763 		plane_blocks_per_line = DIV_ROUND_UP(plane_bytes_per_line, 512);
2764 		plane_blocks_per_line /= 4;
2765 	} else {
2766 		plane_blocks_per_line = DIV_ROUND_UP(plane_bytes_per_line, 512);
2767 	}
2768 
2769 	wm_intermediate_val = latency * pixel_rate;
2770 	ret = DIV_ROUND_UP(wm_intermediate_val, pipe_htotal * 1000) *
2771 				plane_blocks_per_line;
2772 
2773 	return ret;
2774 }
2775 
2776 static bool skl_ddb_allocation_changed(const struct skl_ddb_allocation *new_ddb,
2777 				       const struct intel_crtc *intel_crtc)
2778 {
2779 	struct drm_device *dev = intel_crtc->base.dev;
2780 	struct drm_i915_private *dev_priv = dev->dev_private;
2781 	const struct skl_ddb_allocation *cur_ddb = &dev_priv->wm.skl_hw.ddb;
2782 	enum i915_pipe pipe = intel_crtc->pipe;
2783 
2784 	if (memcmp(new_ddb->plane[pipe], cur_ddb->plane[pipe],
2785 		   sizeof(new_ddb->plane[pipe])))
2786 		return true;
2787 
2788 	if (memcmp(&new_ddb->cursor[pipe], &cur_ddb->cursor[pipe],
2789 		    sizeof(new_ddb->cursor[pipe])))
2790 		return true;
2791 
2792 	return false;
2793 }
2794 
2795 static void skl_compute_wm_global_parameters(struct drm_device *dev,
2796 					     struct intel_wm_config *config)
2797 {
2798 	struct drm_crtc *crtc;
2799 	struct drm_plane *plane;
2800 
2801 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
2802 		config->num_pipes_active += to_intel_crtc(crtc)->active;
2803 
2804 	/* FIXME: I don't think we need those two global parameters on SKL */
2805 	list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
2806 		struct intel_plane *intel_plane = to_intel_plane(plane);
2807 
2808 		config->sprites_enabled |= intel_plane->wm.enabled;
2809 		config->sprites_scaled |= intel_plane->wm.scaled;
2810 	}
2811 }
2812 
2813 static void skl_compute_wm_pipe_parameters(struct drm_crtc *crtc,
2814 					   struct skl_pipe_wm_parameters *p)
2815 {
2816 	struct drm_device *dev = crtc->dev;
2817 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2818 	enum i915_pipe pipe = intel_crtc->pipe;
2819 	struct drm_plane *plane;
2820 	struct drm_framebuffer *fb;
2821 	int i = 1; /* Index for sprite planes start */
2822 
2823 	p->active = intel_crtc->active;
2824 	if (p->active) {
2825 		p->pipe_htotal = intel_crtc->config->base.adjusted_mode.crtc_htotal;
2826 		p->pixel_rate = skl_pipe_pixel_rate(intel_crtc->config);
2827 
2828 		fb = crtc->primary->state->fb;
2829 		if (fb) {
2830 			p->plane[0].enabled = true;
2831 			p->plane[0].bytes_per_pixel = fb->bits_per_pixel / 8;
2832 			p->plane[0].tiling = fb->modifier[0];
2833 		} else {
2834 			p->plane[0].enabled = false;
2835 			p->plane[0].bytes_per_pixel = 0;
2836 			p->plane[0].tiling = DRM_FORMAT_MOD_NONE;
2837 		}
2838 		p->plane[0].horiz_pixels = intel_crtc->config->pipe_src_w;
2839 		p->plane[0].vert_pixels = intel_crtc->config->pipe_src_h;
2840 		p->plane[0].rotation = crtc->primary->state->rotation;
2841 
2842 		fb = crtc->cursor->state->fb;
2843 		if (fb) {
2844 			p->cursor.enabled = true;
2845 			p->cursor.bytes_per_pixel = fb->bits_per_pixel / 8;
2846 			p->cursor.horiz_pixels = crtc->cursor->state->crtc_w;
2847 			p->cursor.vert_pixels = crtc->cursor->state->crtc_h;
2848 		} else {
2849 			p->cursor.enabled = false;
2850 			p->cursor.bytes_per_pixel = 0;
2851 			p->cursor.horiz_pixels = 64;
2852 			p->cursor.vert_pixels = 64;
2853 		}
2854 	}
2855 
2856 	list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
2857 		struct intel_plane *intel_plane = to_intel_plane(plane);
2858 
2859 		if (intel_plane->pipe == pipe &&
2860 			plane->type == DRM_PLANE_TYPE_OVERLAY)
2861 			p->plane[i++] = intel_plane->wm;
2862 	}
2863 }
2864 
2865 static bool skl_compute_plane_wm(const struct drm_i915_private *dev_priv,
2866 				 struct skl_pipe_wm_parameters *p,
2867 				 struct intel_plane_wm_parameters *p_params,
2868 				 uint16_t ddb_allocation,
2869 				 int level,
2870 				 uint16_t *out_blocks, /* out */
2871 				 uint8_t *out_lines /* out */)
2872 {
2873 	uint32_t latency = dev_priv->wm.skl_latency[level];
2874 	uint32_t method1, method2;
2875 	uint32_t plane_bytes_per_line, plane_blocks_per_line;
2876 	uint32_t res_blocks, res_lines;
2877 	uint32_t selected_result;
2878 
2879 	if (latency == 0 || !p->active || !p_params->enabled)
2880 		return false;
2881 
2882 	method1 = skl_wm_method1(p->pixel_rate,
2883 				 p_params->bytes_per_pixel,
2884 				 latency);
2885 	method2 = skl_wm_method2(p->pixel_rate,
2886 				 p->pipe_htotal,
2887 				 p_params->horiz_pixels,
2888 				 p_params->bytes_per_pixel,
2889 				 p_params->tiling,
2890 				 latency);
2891 
2892 	plane_bytes_per_line = p_params->horiz_pixels *
2893 					p_params->bytes_per_pixel;
2894 	plane_blocks_per_line = DIV_ROUND_UP(plane_bytes_per_line, 512);
2895 
2896 	if (p_params->tiling == I915_FORMAT_MOD_Y_TILED ||
2897 	    p_params->tiling == I915_FORMAT_MOD_Yf_TILED) {
2898 		uint32_t min_scanlines = 4;
2899 		uint32_t y_tile_minimum;
2900 		if (intel_rotation_90_or_270(p_params->rotation)) {
2901 			switch (p_params->bytes_per_pixel) {
2902 			case 1:
2903 				min_scanlines = 16;
2904 				break;
2905 			case 2:
2906 				min_scanlines = 8;
2907 				break;
2908 			case 8:
2909 				WARN(1, "Unsupported pixel depth for rotation");
2910 			}
2911 		}
2912 		y_tile_minimum = plane_blocks_per_line * min_scanlines;
2913 		selected_result = max(method2, y_tile_minimum);
2914 	} else {
2915 		if ((ddb_allocation / plane_blocks_per_line) >= 1)
2916 			selected_result = min(method1, method2);
2917 		else
2918 			selected_result = method1;
2919 	}
2920 
2921 	res_blocks = selected_result + 1;
2922 	res_lines = DIV_ROUND_UP(selected_result, plane_blocks_per_line);
2923 
2924 	if (level >= 1 && level <= 7) {
2925 		if (p_params->tiling == I915_FORMAT_MOD_Y_TILED ||
2926 		    p_params->tiling == I915_FORMAT_MOD_Yf_TILED)
2927 			res_lines += 4;
2928 		else
2929 			res_blocks++;
2930 	}
2931 
2932 	if (res_blocks >= ddb_allocation || res_lines > 31)
2933 		return false;
2934 
2935 	*out_blocks = res_blocks;
2936 	*out_lines = res_lines;
2937 
2938 	return true;
2939 }
2940 
2941 static void skl_compute_wm_level(const struct drm_i915_private *dev_priv,
2942 				 struct skl_ddb_allocation *ddb,
2943 				 struct skl_pipe_wm_parameters *p,
2944 				 enum i915_pipe pipe,
2945 				 int level,
2946 				 int num_planes,
2947 				 struct skl_wm_level *result)
2948 {
2949 	uint16_t ddb_blocks;
2950 	int i;
2951 
2952 	for (i = 0; i < num_planes; i++) {
2953 		ddb_blocks = skl_ddb_entry_size(&ddb->plane[pipe][i]);
2954 
2955 		result->plane_en[i] = skl_compute_plane_wm(dev_priv,
2956 						p, &p->plane[i],
2957 						ddb_blocks,
2958 						level,
2959 						&result->plane_res_b[i],
2960 						&result->plane_res_l[i]);
2961 	}
2962 
2963 	ddb_blocks = skl_ddb_entry_size(&ddb->cursor[pipe]);
2964 	result->cursor_en = skl_compute_plane_wm(dev_priv, p, &p->cursor,
2965 						 ddb_blocks, level,
2966 						 &result->cursor_res_b,
2967 						 &result->cursor_res_l);
2968 }
2969 
2970 static uint32_t
2971 skl_compute_linetime_wm(struct drm_crtc *crtc, struct skl_pipe_wm_parameters *p)
2972 {
2973 	if (!to_intel_crtc(crtc)->active)
2974 		return 0;
2975 
2976 	return DIV_ROUND_UP(8 * p->pipe_htotal * 1000, p->pixel_rate);
2977 
2978 }
2979 
2980 static void skl_compute_transition_wm(struct drm_crtc *crtc,
2981 				      struct skl_pipe_wm_parameters *params,
2982 				      struct skl_wm_level *trans_wm /* out */)
2983 {
2984 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2985 	int i;
2986 
2987 	if (!params->active)
2988 		return;
2989 
2990 	/* Until we know more, just disable transition WMs */
2991 	for (i = 0; i < intel_num_planes(intel_crtc); i++)
2992 		trans_wm->plane_en[i] = false;
2993 	trans_wm->cursor_en = false;
2994 }
2995 
2996 static void skl_compute_pipe_wm(struct drm_crtc *crtc,
2997 				struct skl_ddb_allocation *ddb,
2998 				struct skl_pipe_wm_parameters *params,
2999 				struct skl_pipe_wm *pipe_wm)
3000 {
3001 	struct drm_device *dev = crtc->dev;
3002 	const struct drm_i915_private *dev_priv = dev->dev_private;
3003 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3004 	int level, max_level = ilk_wm_max_level(dev);
3005 
3006 	for (level = 0; level <= max_level; level++) {
3007 		skl_compute_wm_level(dev_priv, ddb, params, intel_crtc->pipe,
3008 				     level, intel_num_planes(intel_crtc),
3009 				     &pipe_wm->wm[level]);
3010 	}
3011 	pipe_wm->linetime = skl_compute_linetime_wm(crtc, params);
3012 
3013 	skl_compute_transition_wm(crtc, params, &pipe_wm->trans_wm);
3014 }
3015 
3016 static void skl_compute_wm_results(struct drm_device *dev,
3017 				   struct skl_pipe_wm_parameters *p,
3018 				   struct skl_pipe_wm *p_wm,
3019 				   struct skl_wm_values *r,
3020 				   struct intel_crtc *intel_crtc)
3021 {
3022 	int level, max_level = ilk_wm_max_level(dev);
3023 	enum i915_pipe pipe = intel_crtc->pipe;
3024 	uint32_t temp;
3025 	int i;
3026 
3027 	for (level = 0; level <= max_level; level++) {
3028 		for (i = 0; i < intel_num_planes(intel_crtc); i++) {
3029 			temp = 0;
3030 
3031 			temp |= p_wm->wm[level].plane_res_l[i] <<
3032 					PLANE_WM_LINES_SHIFT;
3033 			temp |= p_wm->wm[level].plane_res_b[i];
3034 			if (p_wm->wm[level].plane_en[i])
3035 				temp |= PLANE_WM_EN;
3036 
3037 			r->plane[pipe][i][level] = temp;
3038 		}
3039 
3040 		temp = 0;
3041 
3042 		temp |= p_wm->wm[level].cursor_res_l << PLANE_WM_LINES_SHIFT;
3043 		temp |= p_wm->wm[level].cursor_res_b;
3044 
3045 		if (p_wm->wm[level].cursor_en)
3046 			temp |= PLANE_WM_EN;
3047 
3048 		r->cursor[pipe][level] = temp;
3049 
3050 	}
3051 
3052 	/* transition WMs */
3053 	for (i = 0; i < intel_num_planes(intel_crtc); i++) {
3054 		temp = 0;
3055 		temp |= p_wm->trans_wm.plane_res_l[i] << PLANE_WM_LINES_SHIFT;
3056 		temp |= p_wm->trans_wm.plane_res_b[i];
3057 		if (p_wm->trans_wm.plane_en[i])
3058 			temp |= PLANE_WM_EN;
3059 
3060 		r->plane_trans[pipe][i] = temp;
3061 	}
3062 
3063 	temp = 0;
3064 	temp |= p_wm->trans_wm.cursor_res_l << PLANE_WM_LINES_SHIFT;
3065 	temp |= p_wm->trans_wm.cursor_res_b;
3066 	if (p_wm->trans_wm.cursor_en)
3067 		temp |= PLANE_WM_EN;
3068 
3069 	r->cursor_trans[pipe] = temp;
3070 
3071 	r->wm_linetime[pipe] = p_wm->linetime;
3072 }
3073 
3074 static void skl_ddb_entry_write(struct drm_i915_private *dev_priv, uint32_t reg,
3075 				const struct skl_ddb_entry *entry)
3076 {
3077 	if (entry->end)
3078 		I915_WRITE(reg, (entry->end - 1) << 16 | entry->start);
3079 	else
3080 		I915_WRITE(reg, 0);
3081 }
3082 
3083 static void skl_write_wm_values(struct drm_i915_private *dev_priv,
3084 				const struct skl_wm_values *new)
3085 {
3086 	struct drm_device *dev = dev_priv->dev;
3087 	struct intel_crtc *crtc;
3088 
3089 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, base.head) {
3090 		int i, level, max_level = ilk_wm_max_level(dev);
3091 		enum i915_pipe pipe = crtc->pipe;
3092 
3093 		if (!new->dirty[pipe])
3094 			continue;
3095 
3096 		I915_WRITE(PIPE_WM_LINETIME(pipe), new->wm_linetime[pipe]);
3097 
3098 		for (level = 0; level <= max_level; level++) {
3099 			for (i = 0; i < intel_num_planes(crtc); i++)
3100 				I915_WRITE(PLANE_WM(pipe, i, level),
3101 					   new->plane[pipe][i][level]);
3102 			I915_WRITE(CUR_WM(pipe, level),
3103 				   new->cursor[pipe][level]);
3104 		}
3105 		for (i = 0; i < intel_num_planes(crtc); i++)
3106 			I915_WRITE(PLANE_WM_TRANS(pipe, i),
3107 				   new->plane_trans[pipe][i]);
3108 		I915_WRITE(CUR_WM_TRANS(pipe), new->cursor_trans[pipe]);
3109 
3110 		for (i = 0; i < intel_num_planes(crtc); i++)
3111 			skl_ddb_entry_write(dev_priv,
3112 					    PLANE_BUF_CFG(pipe, i),
3113 					    &new->ddb.plane[pipe][i]);
3114 
3115 		skl_ddb_entry_write(dev_priv, CUR_BUF_CFG(pipe),
3116 				    &new->ddb.cursor[pipe]);
3117 	}
3118 }
3119 
3120 /*
3121  * When setting up a new DDB allocation arrangement, we need to correctly
3122  * sequence the times at which the new allocations for the pipes are taken into
3123  * account or we'll have pipes fetching from space previously allocated to
3124  * another pipe.
3125  *
3126  * Roughly the sequence looks like:
3127  *  1. re-allocate the pipe(s) with the allocation being reduced and not
3128  *     overlapping with a previous light-up pipe (another way to put it is:
3129  *     pipes with their new allocation strickly included into their old ones).
3130  *  2. re-allocate the other pipes that get their allocation reduced
3131  *  3. allocate the pipes having their allocation increased
3132  *
3133  * Steps 1. and 2. are here to take care of the following case:
3134  * - Initially DDB looks like this:
3135  *     |   B    |   C    |
3136  * - enable pipe A.
3137  * - pipe B has a reduced DDB allocation that overlaps with the old pipe C
3138  *   allocation
3139  *     |  A  |  B  |  C  |
3140  *
3141  * We need to sequence the re-allocation: C, B, A (and not B, C, A).
3142  */
3143 
3144 static void
3145 skl_wm_flush_pipe(struct drm_i915_private *dev_priv, enum i915_pipe pipe, int pass)
3146 {
3147 	int plane;
3148 
3149 	DRM_DEBUG_KMS("flush pipe %c (pass %d)\n", pipe_name(pipe), pass);
3150 
3151 	for_each_plane(dev_priv, pipe, plane) {
3152 		I915_WRITE(PLANE_SURF(pipe, plane),
3153 			   I915_READ(PLANE_SURF(pipe, plane)));
3154 	}
3155 	I915_WRITE(CURBASE(pipe), I915_READ(CURBASE(pipe)));
3156 }
3157 
3158 static bool
3159 skl_ddb_allocation_included(const struct skl_ddb_allocation *old,
3160 			    const struct skl_ddb_allocation *new,
3161 			    enum i915_pipe pipe)
3162 {
3163 	uint16_t old_size, new_size;
3164 
3165 	old_size = skl_ddb_entry_size(&old->pipe[pipe]);
3166 	new_size = skl_ddb_entry_size(&new->pipe[pipe]);
3167 
3168 	return old_size != new_size &&
3169 	       new->pipe[pipe].start >= old->pipe[pipe].start &&
3170 	       new->pipe[pipe].end <= old->pipe[pipe].end;
3171 }
3172 
3173 static void skl_flush_wm_values(struct drm_i915_private *dev_priv,
3174 				struct skl_wm_values *new_values)
3175 {
3176 	struct drm_device *dev = dev_priv->dev;
3177 	struct skl_ddb_allocation *cur_ddb, *new_ddb;
3178 	bool reallocated[I915_MAX_PIPES] = {false, false, false};
3179 	struct intel_crtc *crtc;
3180 	enum i915_pipe pipe;
3181 
3182 	new_ddb = &new_values->ddb;
3183 	cur_ddb = &dev_priv->wm.skl_hw.ddb;
3184 
3185 	/*
3186 	 * First pass: flush the pipes with the new allocation contained into
3187 	 * the old space.
3188 	 *
3189 	 * We'll wait for the vblank on those pipes to ensure we can safely
3190 	 * re-allocate the freed space without this pipe fetching from it.
3191 	 */
3192 	for_each_intel_crtc(dev, crtc) {
3193 		if (!crtc->active)
3194 			continue;
3195 
3196 		pipe = crtc->pipe;
3197 
3198 		if (!skl_ddb_allocation_included(cur_ddb, new_ddb, pipe))
3199 			continue;
3200 
3201 		skl_wm_flush_pipe(dev_priv, pipe, 1);
3202 		intel_wait_for_vblank(dev, pipe);
3203 
3204 		reallocated[pipe] = true;
3205 	}
3206 
3207 
3208 	/*
3209 	 * Second pass: flush the pipes that are having their allocation
3210 	 * reduced, but overlapping with a previous allocation.
3211 	 *
3212 	 * Here as well we need to wait for the vblank to make sure the freed
3213 	 * space is not used anymore.
3214 	 */
3215 	for_each_intel_crtc(dev, crtc) {
3216 		if (!crtc->active)
3217 			continue;
3218 
3219 		pipe = crtc->pipe;
3220 
3221 		if (reallocated[pipe])
3222 			continue;
3223 
3224 		if (skl_ddb_entry_size(&new_ddb->pipe[pipe]) <
3225 		    skl_ddb_entry_size(&cur_ddb->pipe[pipe])) {
3226 			skl_wm_flush_pipe(dev_priv, pipe, 2);
3227 			intel_wait_for_vblank(dev, pipe);
3228 			reallocated[pipe] = true;
3229 		}
3230 	}
3231 
3232 	/*
3233 	 * Third pass: flush the pipes that got more space allocated.
3234 	 *
3235 	 * We don't need to actively wait for the update here, next vblank
3236 	 * will just get more DDB space with the correct WM values.
3237 	 */
3238 	for_each_intel_crtc(dev, crtc) {
3239 		if (!crtc->active)
3240 			continue;
3241 
3242 		pipe = crtc->pipe;
3243 
3244 		/*
3245 		 * At this point, only the pipes more space than before are
3246 		 * left to re-allocate.
3247 		 */
3248 		if (reallocated[pipe])
3249 			continue;
3250 
3251 		skl_wm_flush_pipe(dev_priv, pipe, 3);
3252 	}
3253 }
3254 
3255 static bool skl_update_pipe_wm(struct drm_crtc *crtc,
3256 			       struct skl_pipe_wm_parameters *params,
3257 			       struct intel_wm_config *config,
3258 			       struct skl_ddb_allocation *ddb, /* out */
3259 			       struct skl_pipe_wm *pipe_wm /* out */)
3260 {
3261 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3262 
3263 	skl_compute_wm_pipe_parameters(crtc, params);
3264 	skl_allocate_pipe_ddb(crtc, config, params, ddb);
3265 	skl_compute_pipe_wm(crtc, ddb, params, pipe_wm);
3266 
3267 	if (!memcmp(&intel_crtc->wm.skl_active, pipe_wm, sizeof(*pipe_wm)))
3268 		return false;
3269 
3270 	intel_crtc->wm.skl_active = *pipe_wm;
3271 	return true;
3272 }
3273 
3274 static void skl_update_other_pipe_wm(struct drm_device *dev,
3275 				     struct drm_crtc *crtc,
3276 				     struct intel_wm_config *config,
3277 				     struct skl_wm_values *r)
3278 {
3279 	struct intel_crtc *intel_crtc;
3280 	struct intel_crtc *this_crtc = to_intel_crtc(crtc);
3281 
3282 	/*
3283 	 * If the WM update hasn't changed the allocation for this_crtc (the
3284 	 * crtc we are currently computing the new WM values for), other
3285 	 * enabled crtcs will keep the same allocation and we don't need to
3286 	 * recompute anything for them.
3287 	 */
3288 	if (!skl_ddb_allocation_changed(&r->ddb, this_crtc))
3289 		return;
3290 
3291 	/*
3292 	 * Otherwise, because of this_crtc being freshly enabled/disabled, the
3293 	 * other active pipes need new DDB allocation and WM values.
3294 	 */
3295 	list_for_each_entry(intel_crtc, &dev->mode_config.crtc_list,
3296 				base.head) {
3297 		struct skl_pipe_wm_parameters params = {};
3298 		struct skl_pipe_wm pipe_wm = {};
3299 		bool wm_changed;
3300 
3301 		if (this_crtc->pipe == intel_crtc->pipe)
3302 			continue;
3303 
3304 		if (!intel_crtc->active)
3305 			continue;
3306 
3307 		wm_changed = skl_update_pipe_wm(&intel_crtc->base,
3308 						&params, config,
3309 						&r->ddb, &pipe_wm);
3310 
3311 		/*
3312 		 * If we end up re-computing the other pipe WM values, it's
3313 		 * because it was really needed, so we expect the WM values to
3314 		 * be different.
3315 		 */
3316 		WARN_ON(!wm_changed);
3317 
3318 		skl_compute_wm_results(dev, &params, &pipe_wm, r, intel_crtc);
3319 		r->dirty[intel_crtc->pipe] = true;
3320 	}
3321 }
3322 
3323 static void skl_update_wm(struct drm_crtc *crtc)
3324 {
3325 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3326 	struct drm_device *dev = crtc->dev;
3327 	struct drm_i915_private *dev_priv = dev->dev_private;
3328 	struct skl_pipe_wm_parameters params = {};
3329 	struct skl_wm_values *results = &dev_priv->wm.skl_results;
3330 	struct skl_pipe_wm pipe_wm = {};
3331 	struct intel_wm_config config = {};
3332 
3333 	memset(results, 0, sizeof(*results));
3334 
3335 	skl_compute_wm_global_parameters(dev, &config);
3336 
3337 	if (!skl_update_pipe_wm(crtc, &params, &config,
3338 				&results->ddb, &pipe_wm))
3339 		return;
3340 
3341 	skl_compute_wm_results(dev, &params, &pipe_wm, results, intel_crtc);
3342 	results->dirty[intel_crtc->pipe] = true;
3343 
3344 	skl_update_other_pipe_wm(dev, crtc, &config, results);
3345 	skl_write_wm_values(dev_priv, results);
3346 	skl_flush_wm_values(dev_priv, results);
3347 
3348 	/* store the new configuration */
3349 	dev_priv->wm.skl_hw = *results;
3350 }
3351 
3352 static void
3353 skl_update_sprite_wm(struct drm_plane *plane, struct drm_crtc *crtc,
3354 		     uint32_t sprite_width, uint32_t sprite_height,
3355 		     int pixel_size, bool enabled, bool scaled)
3356 {
3357 	struct intel_plane *intel_plane = to_intel_plane(plane);
3358 	struct drm_framebuffer *fb = plane->state->fb;
3359 
3360 	intel_plane->wm.enabled = enabled;
3361 	intel_plane->wm.scaled = scaled;
3362 	intel_plane->wm.horiz_pixels = sprite_width;
3363 	intel_plane->wm.vert_pixels = sprite_height;
3364 	intel_plane->wm.bytes_per_pixel = pixel_size;
3365 	intel_plane->wm.tiling = DRM_FORMAT_MOD_NONE;
3366 	/*
3367 	 * Framebuffer can be NULL on plane disable, but it does not
3368 	 * matter for watermarks if we assume no tiling in that case.
3369 	 */
3370 	if (fb)
3371 		intel_plane->wm.tiling = fb->modifier[0];
3372 	intel_plane->wm.rotation = plane->state->rotation;
3373 
3374 	skl_update_wm(crtc);
3375 }
3376 
3377 static void ilk_update_wm(struct drm_crtc *crtc)
3378 {
3379 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3380 	struct drm_device *dev = crtc->dev;
3381 	struct drm_i915_private *dev_priv = dev->dev_private;
3382 	struct ilk_wm_maximums max;
3383 	struct ilk_pipe_wm_parameters params = {};
3384 	struct ilk_wm_values results = {};
3385 	enum intel_ddb_partitioning partitioning;
3386 	struct intel_pipe_wm pipe_wm = {};
3387 	struct intel_pipe_wm lp_wm_1_2 = {}, lp_wm_5_6 = {}, *best_lp_wm;
3388 	struct intel_wm_config config = {};
3389 
3390 	ilk_compute_wm_parameters(crtc, &params);
3391 
3392 	intel_compute_pipe_wm(crtc, &params, &pipe_wm);
3393 
3394 	if (!memcmp(&intel_crtc->wm.active, &pipe_wm, sizeof(pipe_wm)))
3395 		return;
3396 
3397 	intel_crtc->wm.active = pipe_wm;
3398 
3399 	ilk_compute_wm_config(dev, &config);
3400 
3401 	ilk_compute_wm_maximums(dev, 1, &config, INTEL_DDB_PART_1_2, &max);
3402 	ilk_wm_merge(dev, &config, &max, &lp_wm_1_2);
3403 
3404 	/* 5/6 split only in single pipe config on IVB+ */
3405 	if (INTEL_INFO(dev)->gen >= 7 &&
3406 	    config.num_pipes_active == 1 && config.sprites_enabled) {
3407 		ilk_compute_wm_maximums(dev, 1, &config, INTEL_DDB_PART_5_6, &max);
3408 		ilk_wm_merge(dev, &config, &max, &lp_wm_5_6);
3409 
3410 		best_lp_wm = ilk_find_best_result(dev, &lp_wm_1_2, &lp_wm_5_6);
3411 	} else {
3412 		best_lp_wm = &lp_wm_1_2;
3413 	}
3414 
3415 	partitioning = (best_lp_wm == &lp_wm_1_2) ?
3416 		       INTEL_DDB_PART_1_2 : INTEL_DDB_PART_5_6;
3417 
3418 	ilk_compute_wm_results(dev, best_lp_wm, partitioning, &results);
3419 
3420 	ilk_write_wm_values(dev_priv, &results);
3421 }
3422 
3423 static void
3424 ilk_update_sprite_wm(struct drm_plane *plane,
3425 		     struct drm_crtc *crtc,
3426 		     uint32_t sprite_width, uint32_t sprite_height,
3427 		     int pixel_size, bool enabled, bool scaled)
3428 {
3429 	struct drm_device *dev = plane->dev;
3430 	struct intel_plane *intel_plane = to_intel_plane(plane);
3431 
3432 	intel_plane->wm.enabled = enabled;
3433 	intel_plane->wm.scaled = scaled;
3434 	intel_plane->wm.horiz_pixels = sprite_width;
3435 	intel_plane->wm.vert_pixels = sprite_width;
3436 	intel_plane->wm.bytes_per_pixel = pixel_size;
3437 
3438 	/*
3439 	 * IVB workaround: must disable low power watermarks for at least
3440 	 * one frame before enabling scaling.  LP watermarks can be re-enabled
3441 	 * when scaling is disabled.
3442 	 *
3443 	 * WaCxSRDisabledForSpriteScaling:ivb
3444 	 */
3445 	if (IS_IVYBRIDGE(dev) && scaled && ilk_disable_lp_wm(dev))
3446 		intel_wait_for_vblank(dev, intel_plane->pipe);
3447 
3448 	ilk_update_wm(crtc);
3449 }
3450 
3451 static void skl_pipe_wm_active_state(uint32_t val,
3452 				     struct skl_pipe_wm *active,
3453 				     bool is_transwm,
3454 				     bool is_cursor,
3455 				     int i,
3456 				     int level)
3457 {
3458 	bool is_enabled = (val & PLANE_WM_EN) != 0;
3459 
3460 	if (!is_transwm) {
3461 		if (!is_cursor) {
3462 			active->wm[level].plane_en[i] = is_enabled;
3463 			active->wm[level].plane_res_b[i] =
3464 					val & PLANE_WM_BLOCKS_MASK;
3465 			active->wm[level].plane_res_l[i] =
3466 					(val >> PLANE_WM_LINES_SHIFT) &
3467 						PLANE_WM_LINES_MASK;
3468 		} else {
3469 			active->wm[level].cursor_en = is_enabled;
3470 			active->wm[level].cursor_res_b =
3471 					val & PLANE_WM_BLOCKS_MASK;
3472 			active->wm[level].cursor_res_l =
3473 					(val >> PLANE_WM_LINES_SHIFT) &
3474 						PLANE_WM_LINES_MASK;
3475 		}
3476 	} else {
3477 		if (!is_cursor) {
3478 			active->trans_wm.plane_en[i] = is_enabled;
3479 			active->trans_wm.plane_res_b[i] =
3480 					val & PLANE_WM_BLOCKS_MASK;
3481 			active->trans_wm.plane_res_l[i] =
3482 					(val >> PLANE_WM_LINES_SHIFT) &
3483 						PLANE_WM_LINES_MASK;
3484 		} else {
3485 			active->trans_wm.cursor_en = is_enabled;
3486 			active->trans_wm.cursor_res_b =
3487 					val & PLANE_WM_BLOCKS_MASK;
3488 			active->trans_wm.cursor_res_l =
3489 					(val >> PLANE_WM_LINES_SHIFT) &
3490 						PLANE_WM_LINES_MASK;
3491 		}
3492 	}
3493 }
3494 
3495 static void skl_pipe_wm_get_hw_state(struct drm_crtc *crtc)
3496 {
3497 	struct drm_device *dev = crtc->dev;
3498 	struct drm_i915_private *dev_priv = dev->dev_private;
3499 	struct skl_wm_values *hw = &dev_priv->wm.skl_hw;
3500 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3501 	struct skl_pipe_wm *active = &intel_crtc->wm.skl_active;
3502 	enum i915_pipe pipe = intel_crtc->pipe;
3503 	int level, i, max_level;
3504 	uint32_t temp;
3505 
3506 	max_level = ilk_wm_max_level(dev);
3507 
3508 	hw->wm_linetime[pipe] = I915_READ(PIPE_WM_LINETIME(pipe));
3509 
3510 	for (level = 0; level <= max_level; level++) {
3511 		for (i = 0; i < intel_num_planes(intel_crtc); i++)
3512 			hw->plane[pipe][i][level] =
3513 					I915_READ(PLANE_WM(pipe, i, level));
3514 		hw->cursor[pipe][level] = I915_READ(CUR_WM(pipe, level));
3515 	}
3516 
3517 	for (i = 0; i < intel_num_planes(intel_crtc); i++)
3518 		hw->plane_trans[pipe][i] = I915_READ(PLANE_WM_TRANS(pipe, i));
3519 	hw->cursor_trans[pipe] = I915_READ(CUR_WM_TRANS(pipe));
3520 
3521 	if (!intel_crtc->active)
3522 		return;
3523 
3524 	hw->dirty[pipe] = true;
3525 
3526 	active->linetime = hw->wm_linetime[pipe];
3527 
3528 	for (level = 0; level <= max_level; level++) {
3529 		for (i = 0; i < intel_num_planes(intel_crtc); i++) {
3530 			temp = hw->plane[pipe][i][level];
3531 			skl_pipe_wm_active_state(temp, active, false,
3532 						false, i, level);
3533 		}
3534 		temp = hw->cursor[pipe][level];
3535 		skl_pipe_wm_active_state(temp, active, false, true, i, level);
3536 	}
3537 
3538 	for (i = 0; i < intel_num_planes(intel_crtc); i++) {
3539 		temp = hw->plane_trans[pipe][i];
3540 		skl_pipe_wm_active_state(temp, active, true, false, i, 0);
3541 	}
3542 
3543 	temp = hw->cursor_trans[pipe];
3544 	skl_pipe_wm_active_state(temp, active, true, true, i, 0);
3545 }
3546 
3547 void skl_wm_get_hw_state(struct drm_device *dev)
3548 {
3549 	struct drm_i915_private *dev_priv = dev->dev_private;
3550 	struct skl_ddb_allocation *ddb = &dev_priv->wm.skl_hw.ddb;
3551 	struct drm_crtc *crtc;
3552 
3553 	skl_ddb_get_hw_state(dev_priv, ddb);
3554 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
3555 		skl_pipe_wm_get_hw_state(crtc);
3556 }
3557 
3558 static void ilk_pipe_wm_get_hw_state(struct drm_crtc *crtc)
3559 {
3560 	struct drm_device *dev = crtc->dev;
3561 	struct drm_i915_private *dev_priv = dev->dev_private;
3562 	struct ilk_wm_values *hw = &dev_priv->wm.hw;
3563 	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3564 	struct intel_pipe_wm *active = &intel_crtc->wm.active;
3565 	enum i915_pipe pipe = intel_crtc->pipe;
3566 	static const unsigned int wm0_pipe_reg[] = {
3567 		[PIPE_A] = WM0_PIPEA_ILK,
3568 		[PIPE_B] = WM0_PIPEB_ILK,
3569 		[PIPE_C] = WM0_PIPEC_IVB,
3570 	};
3571 
3572 	hw->wm_pipe[pipe] = I915_READ(wm0_pipe_reg[pipe]);
3573 	if (IS_HASWELL(dev) || IS_BROADWELL(dev))
3574 		hw->wm_linetime[pipe] = I915_READ(PIPE_WM_LINETIME(pipe));
3575 
3576 	active->pipe_enabled = intel_crtc->active;
3577 
3578 	if (active->pipe_enabled) {
3579 		u32 tmp = hw->wm_pipe[pipe];
3580 
3581 		/*
3582 		 * For active pipes LP0 watermark is marked as
3583 		 * enabled, and LP1+ watermaks as disabled since
3584 		 * we can't really reverse compute them in case
3585 		 * multiple pipes are active.
3586 		 */
3587 		active->wm[0].enable = true;
3588 		active->wm[0].pri_val = (tmp & WM0_PIPE_PLANE_MASK) >> WM0_PIPE_PLANE_SHIFT;
3589 		active->wm[0].spr_val = (tmp & WM0_PIPE_SPRITE_MASK) >> WM0_PIPE_SPRITE_SHIFT;
3590 		active->wm[0].cur_val = tmp & WM0_PIPE_CURSOR_MASK;
3591 		active->linetime = hw->wm_linetime[pipe];
3592 	} else {
3593 		int level, max_level = ilk_wm_max_level(dev);
3594 
3595 		/*
3596 		 * For inactive pipes, all watermark levels
3597 		 * should be marked as enabled but zeroed,
3598 		 * which is what we'd compute them to.
3599 		 */
3600 		for (level = 0; level <= max_level; level++)
3601 			active->wm[level].enable = true;
3602 	}
3603 }
3604 
3605 void ilk_wm_get_hw_state(struct drm_device *dev)
3606 {
3607 	struct drm_i915_private *dev_priv = dev->dev_private;
3608 	struct ilk_wm_values *hw = &dev_priv->wm.hw;
3609 	struct drm_crtc *crtc;
3610 
3611 	for_each_crtc(dev, crtc)
3612 		ilk_pipe_wm_get_hw_state(crtc);
3613 
3614 	hw->wm_lp[0] = I915_READ(WM1_LP_ILK);
3615 	hw->wm_lp[1] = I915_READ(WM2_LP_ILK);
3616 	hw->wm_lp[2] = I915_READ(WM3_LP_ILK);
3617 
3618 	hw->wm_lp_spr[0] = I915_READ(WM1S_LP_ILK);
3619 	if (INTEL_INFO(dev)->gen >= 7) {
3620 		hw->wm_lp_spr[1] = I915_READ(WM2S_LP_IVB);
3621 		hw->wm_lp_spr[2] = I915_READ(WM3S_LP_IVB);
3622 	}
3623 
3624 	if (IS_HASWELL(dev) || IS_BROADWELL(dev))
3625 		hw->partitioning = (I915_READ(WM_MISC) & WM_MISC_DATA_PARTITION_5_6) ?
3626 			INTEL_DDB_PART_5_6 : INTEL_DDB_PART_1_2;
3627 	else if (IS_IVYBRIDGE(dev))
3628 		hw->partitioning = (I915_READ(DISP_ARB_CTL2) & DISP_DATA_PARTITION_5_6) ?
3629 			INTEL_DDB_PART_5_6 : INTEL_DDB_PART_1_2;
3630 
3631 	hw->enable_fbc_wm =
3632 		!(I915_READ(DISP_ARB_CTL) & DISP_FBC_WM_DIS);
3633 }
3634 
3635 /**
3636  * intel_update_watermarks - update FIFO watermark values based on current modes
3637  *
3638  * Calculate watermark values for the various WM regs based on current mode
3639  * and plane configuration.
3640  *
3641  * There are several cases to deal with here:
3642  *   - normal (i.e. non-self-refresh)
3643  *   - self-refresh (SR) mode
3644  *   - lines are large relative to FIFO size (buffer can hold up to 2)
3645  *   - lines are small relative to FIFO size (buffer can hold more than 2
3646  *     lines), so need to account for TLB latency
3647  *
3648  *   The normal calculation is:
3649  *     watermark = dotclock * bytes per pixel * latency
3650  *   where latency is platform & configuration dependent (we assume pessimal
3651  *   values here).
3652  *
3653  *   The SR calculation is:
3654  *     watermark = (trunc(latency/line time)+1) * surface width *
3655  *       bytes per pixel
3656  *   where
3657  *     line time = htotal / dotclock
3658  *     surface width = hdisplay for normal plane and 64 for cursor
3659  *   and latency is assumed to be high, as above.
3660  *
3661  * The final value programmed to the register should always be rounded up,
3662  * and include an extra 2 entries to account for clock crossings.
3663  *
3664  * We don't use the sprite, so we can ignore that.  And on Crestline we have
3665  * to set the non-SR watermarks to 8.
3666  */
3667 void intel_update_watermarks(struct drm_crtc *crtc)
3668 {
3669 	struct drm_i915_private *dev_priv = crtc->dev->dev_private;
3670 
3671 	if (dev_priv->display.update_wm)
3672 		dev_priv->display.update_wm(crtc);
3673 }
3674 
3675 void intel_update_sprite_watermarks(struct drm_plane *plane,
3676 				    struct drm_crtc *crtc,
3677 				    uint32_t sprite_width,
3678 				    uint32_t sprite_height,
3679 				    int pixel_size,
3680 				    bool enabled, bool scaled)
3681 {
3682 	struct drm_i915_private *dev_priv = plane->dev->dev_private;
3683 
3684 	if (dev_priv->display.update_sprite_wm)
3685 		dev_priv->display.update_sprite_wm(plane, crtc,
3686 						   sprite_width, sprite_height,
3687 						   pixel_size, enabled, scaled);
3688 }
3689 
3690 /**
3691  * Lock protecting IPS related data structures
3692  */
3693 struct lock mchdev_lock;
3694 LOCK_SYSINIT(mchdev, &mchdev_lock, "mchdev", LK_CANRECURSE);
3695 
3696 /* Global for IPS driver to get at the current i915 device. Protected by
3697  * mchdev_lock. */
3698 static struct drm_i915_private *i915_mch_dev;
3699 
3700 bool ironlake_set_drps(struct drm_device *dev, u8 val)
3701 {
3702 	struct drm_i915_private *dev_priv = dev->dev_private;
3703 	u16 rgvswctl;
3704 
3705 	assert_spin_locked(&mchdev_lock);
3706 
3707 	rgvswctl = I915_READ16(MEMSWCTL);
3708 	if (rgvswctl & MEMCTL_CMD_STS) {
3709 		DRM_DEBUG("gpu busy, RCS change rejected\n");
3710 		return false; /* still busy with another command */
3711 	}
3712 
3713 	rgvswctl = (MEMCTL_CMD_CHFREQ << MEMCTL_CMD_SHIFT) |
3714 		(val << MEMCTL_FREQ_SHIFT) | MEMCTL_SFCAVM;
3715 	I915_WRITE16(MEMSWCTL, rgvswctl);
3716 	POSTING_READ16(MEMSWCTL);
3717 
3718 	rgvswctl |= MEMCTL_CMD_STS;
3719 	I915_WRITE16(MEMSWCTL, rgvswctl);
3720 
3721 	return true;
3722 }
3723 
3724 static void ironlake_enable_drps(struct drm_device *dev)
3725 {
3726 	struct drm_i915_private *dev_priv = dev->dev_private;
3727 	u32 rgvmodectl = I915_READ(MEMMODECTL);
3728 	u8 fmax, fmin, fstart, vstart;
3729 
3730 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
3731 
3732 	/* Enable temp reporting */
3733 	I915_WRITE16(PMMISC, I915_READ(PMMISC) | MCPPCE_EN);
3734 	I915_WRITE16(TSC1, I915_READ(TSC1) | TSE);
3735 
3736 	/* 100ms RC evaluation intervals */
3737 	I915_WRITE(RCUPEI, 100000);
3738 	I915_WRITE(RCDNEI, 100000);
3739 
3740 	/* Set max/min thresholds to 90ms and 80ms respectively */
3741 	I915_WRITE(RCBMAXAVG, 90000);
3742 	I915_WRITE(RCBMINAVG, 80000);
3743 
3744 	I915_WRITE(MEMIHYST, 1);
3745 
3746 	/* Set up min, max, and cur for interrupt handling */
3747 	fmax = (rgvmodectl & MEMMODE_FMAX_MASK) >> MEMMODE_FMAX_SHIFT;
3748 	fmin = (rgvmodectl & MEMMODE_FMIN_MASK);
3749 	fstart = (rgvmodectl & MEMMODE_FSTART_MASK) >>
3750 		MEMMODE_FSTART_SHIFT;
3751 
3752 	vstart = (I915_READ(PXVFREQ_BASE + (fstart * 4)) & PXVFREQ_PX_MASK) >>
3753 		PXVFREQ_PX_SHIFT;
3754 
3755 	dev_priv->ips.fmax = fmax; /* IPS callback will increase this */
3756 	dev_priv->ips.fstart = fstart;
3757 
3758 	dev_priv->ips.max_delay = fstart;
3759 	dev_priv->ips.min_delay = fmin;
3760 	dev_priv->ips.cur_delay = fstart;
3761 
3762 	DRM_DEBUG_DRIVER("fmax: %d, fmin: %d, fstart: %d\n",
3763 			 fmax, fmin, fstart);
3764 
3765 	I915_WRITE(MEMINTREN, MEMINT_CX_SUPR_EN | MEMINT_EVAL_CHG_EN);
3766 
3767 	/*
3768 	 * Interrupts will be enabled in ironlake_irq_postinstall
3769 	 */
3770 
3771 	I915_WRITE(VIDSTART, vstart);
3772 	POSTING_READ(VIDSTART);
3773 
3774 	rgvmodectl |= MEMMODE_SWMODE_EN;
3775 	I915_WRITE(MEMMODECTL, rgvmodectl);
3776 
3777 	if (wait_for_atomic((I915_READ(MEMSWCTL) & MEMCTL_CMD_STS) == 0, 10))
3778 		DRM_ERROR("stuck trying to change perf mode\n");
3779 	mdelay(1);
3780 
3781 	ironlake_set_drps(dev, fstart);
3782 
3783 	dev_priv->ips.last_count1 = I915_READ(0x112e4) + I915_READ(0x112e8) +
3784 		I915_READ(0x112e0);
3785 	dev_priv->ips.last_time1 = jiffies_to_msecs(jiffies);
3786 	dev_priv->ips.last_count2 = I915_READ(0x112f4);
3787 	dev_priv->ips.last_time2 = ktime_get_raw_ns();
3788 
3789 	lockmgr(&mchdev_lock, LK_RELEASE);
3790 }
3791 
3792 static void ironlake_disable_drps(struct drm_device *dev)
3793 {
3794 	struct drm_i915_private *dev_priv = dev->dev_private;
3795 	u16 rgvswctl;
3796 
3797 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
3798 
3799 	rgvswctl = I915_READ16(MEMSWCTL);
3800 
3801 	/* Ack interrupts, disable EFC interrupt */
3802 	I915_WRITE(MEMINTREN, I915_READ(MEMINTREN) & ~MEMINT_EVAL_CHG_EN);
3803 	I915_WRITE(MEMINTRSTS, MEMINT_EVAL_CHG);
3804 	I915_WRITE(DEIER, I915_READ(DEIER) & ~DE_PCU_EVENT);
3805 	I915_WRITE(DEIIR, DE_PCU_EVENT);
3806 	I915_WRITE(DEIMR, I915_READ(DEIMR) | DE_PCU_EVENT);
3807 
3808 	/* Go back to the starting frequency */
3809 	ironlake_set_drps(dev, dev_priv->ips.fstart);
3810 	mdelay(1);
3811 	rgvswctl |= MEMCTL_CMD_STS;
3812 	I915_WRITE(MEMSWCTL, rgvswctl);
3813 	mdelay(1);
3814 
3815 	lockmgr(&mchdev_lock, LK_RELEASE);
3816 }
3817 
3818 /* There's a funny hw issue where the hw returns all 0 when reading from
3819  * GEN6_RP_INTERRUPT_LIMITS. Hence we always need to compute the desired value
3820  * ourselves, instead of doing a rmw cycle (which might result in us clearing
3821  * all limits and the gpu stuck at whatever frequency it is at atm).
3822  */
3823 static u32 intel_rps_limits(struct drm_i915_private *dev_priv, u8 val)
3824 {
3825 	u32 limits;
3826 
3827 	/* Only set the down limit when we've reached the lowest level to avoid
3828 	 * getting more interrupts, otherwise leave this clear. This prevents a
3829 	 * race in the hw when coming out of rc6: There's a tiny window where
3830 	 * the hw runs at the minimal clock before selecting the desired
3831 	 * frequency, if the down threshold expires in that window we will not
3832 	 * receive a down interrupt. */
3833 	if (IS_GEN9(dev_priv->dev)) {
3834 		limits = (dev_priv->rps.max_freq_softlimit) << 23;
3835 		if (val <= dev_priv->rps.min_freq_softlimit)
3836 			limits |= (dev_priv->rps.min_freq_softlimit) << 14;
3837 	} else {
3838 		limits = dev_priv->rps.max_freq_softlimit << 24;
3839 		if (val <= dev_priv->rps.min_freq_softlimit)
3840 			limits |= dev_priv->rps.min_freq_softlimit << 16;
3841 	}
3842 
3843 	return limits;
3844 }
3845 
3846 static void gen6_set_rps_thresholds(struct drm_i915_private *dev_priv, u8 val)
3847 {
3848 	int new_power;
3849 	u32 threshold_up = 0, threshold_down = 0; /* in % */
3850 	u32 ei_up = 0, ei_down = 0;
3851 
3852 	new_power = dev_priv->rps.power;
3853 	switch (dev_priv->rps.power) {
3854 	case LOW_POWER:
3855 		if (val > dev_priv->rps.efficient_freq + 1 && val > dev_priv->rps.cur_freq)
3856 			new_power = BETWEEN;
3857 		break;
3858 
3859 	case BETWEEN:
3860 		if (val <= dev_priv->rps.efficient_freq && val < dev_priv->rps.cur_freq)
3861 			new_power = LOW_POWER;
3862 		else if (val >= dev_priv->rps.rp0_freq && val > dev_priv->rps.cur_freq)
3863 			new_power = HIGH_POWER;
3864 		break;
3865 
3866 	case HIGH_POWER:
3867 		if (val < (dev_priv->rps.rp1_freq + dev_priv->rps.rp0_freq) >> 1 && val < dev_priv->rps.cur_freq)
3868 			new_power = BETWEEN;
3869 		break;
3870 	}
3871 	/* Max/min bins are special */
3872 	if (val <= dev_priv->rps.min_freq_softlimit)
3873 		new_power = LOW_POWER;
3874 	if (val >= dev_priv->rps.max_freq_softlimit)
3875 		new_power = HIGH_POWER;
3876 	if (new_power == dev_priv->rps.power)
3877 		return;
3878 
3879 	/* Note the units here are not exactly 1us, but 1280ns. */
3880 	switch (new_power) {
3881 	case LOW_POWER:
3882 		/* Upclock if more than 95% busy over 16ms */
3883 		ei_up = 16000;
3884 		threshold_up = 95;
3885 
3886 		/* Downclock if less than 85% busy over 32ms */
3887 		ei_down = 32000;
3888 		threshold_down = 85;
3889 		break;
3890 
3891 	case BETWEEN:
3892 		/* Upclock if more than 90% busy over 13ms */
3893 		ei_up = 13000;
3894 		threshold_up = 90;
3895 
3896 		/* Downclock if less than 75% busy over 32ms */
3897 		ei_down = 32000;
3898 		threshold_down = 75;
3899 		break;
3900 
3901 	case HIGH_POWER:
3902 		/* Upclock if more than 85% busy over 10ms */
3903 		ei_up = 10000;
3904 		threshold_up = 85;
3905 
3906 		/* Downclock if less than 60% busy over 32ms */
3907 		ei_down = 32000;
3908 		threshold_down = 60;
3909 		break;
3910 	}
3911 
3912 	I915_WRITE(GEN6_RP_UP_EI,
3913 		GT_INTERVAL_FROM_US(dev_priv, ei_up));
3914 	I915_WRITE(GEN6_RP_UP_THRESHOLD,
3915 		GT_INTERVAL_FROM_US(dev_priv, (ei_up * threshold_up / 100)));
3916 
3917 	I915_WRITE(GEN6_RP_DOWN_EI,
3918 		GT_INTERVAL_FROM_US(dev_priv, ei_down));
3919 	I915_WRITE(GEN6_RP_DOWN_THRESHOLD,
3920 		GT_INTERVAL_FROM_US(dev_priv, (ei_down * threshold_down / 100)));
3921 
3922 	 I915_WRITE(GEN6_RP_CONTROL,
3923 		    GEN6_RP_MEDIA_TURBO |
3924 		    GEN6_RP_MEDIA_HW_NORMAL_MODE |
3925 		    GEN6_RP_MEDIA_IS_GFX |
3926 		    GEN6_RP_ENABLE |
3927 		    GEN6_RP_UP_BUSY_AVG |
3928 		    GEN6_RP_DOWN_IDLE_AVG);
3929 
3930 	dev_priv->rps.power = new_power;
3931 	dev_priv->rps.last_adj = 0;
3932 }
3933 
3934 static u32 gen6_rps_pm_mask(struct drm_i915_private *dev_priv, u8 val)
3935 {
3936 	u32 mask = 0;
3937 
3938 	if (val > dev_priv->rps.min_freq_softlimit)
3939 		mask |= GEN6_PM_RP_DOWN_EI_EXPIRED | GEN6_PM_RP_DOWN_THRESHOLD | GEN6_PM_RP_DOWN_TIMEOUT;
3940 	if (val < dev_priv->rps.max_freq_softlimit)
3941 		mask |= GEN6_PM_RP_UP_EI_EXPIRED | GEN6_PM_RP_UP_THRESHOLD;
3942 
3943 	mask &= dev_priv->pm_rps_events;
3944 
3945 	return gen6_sanitize_rps_pm_mask(dev_priv, ~mask);
3946 }
3947 
3948 /* gen6_set_rps is called to update the frequency request, but should also be
3949  * called when the range (min_delay and max_delay) is modified so that we can
3950  * update the GEN6_RP_INTERRUPT_LIMITS register accordingly. */
3951 static void gen6_set_rps(struct drm_device *dev, u8 val)
3952 {
3953 	struct drm_i915_private *dev_priv = dev->dev_private;
3954 
3955 	WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
3956 	WARN_ON(val > dev_priv->rps.max_freq);
3957 	WARN_ON(val < dev_priv->rps.min_freq);
3958 
3959 	/* min/max delay may still have been modified so be sure to
3960 	 * write the limits value.
3961 	 */
3962 	if (val != dev_priv->rps.cur_freq) {
3963 		gen6_set_rps_thresholds(dev_priv, val);
3964 
3965 		if (IS_GEN9(dev))
3966 			I915_WRITE(GEN6_RPNSWREQ,
3967 				   GEN9_FREQUENCY(val));
3968 		else if (IS_HASWELL(dev) || IS_BROADWELL(dev))
3969 			I915_WRITE(GEN6_RPNSWREQ,
3970 				   HSW_FREQUENCY(val));
3971 		else
3972 			I915_WRITE(GEN6_RPNSWREQ,
3973 				   GEN6_FREQUENCY(val) |
3974 				   GEN6_OFFSET(0) |
3975 				   GEN6_AGGRESSIVE_TURBO);
3976 	}
3977 
3978 	/* Make sure we continue to get interrupts
3979 	 * until we hit the minimum or maximum frequencies.
3980 	 */
3981 	I915_WRITE(GEN6_RP_INTERRUPT_LIMITS, intel_rps_limits(dev_priv, val));
3982 	I915_WRITE(GEN6_PMINTRMSK, gen6_rps_pm_mask(dev_priv, val));
3983 
3984 	POSTING_READ(GEN6_RPNSWREQ);
3985 
3986 	dev_priv->rps.cur_freq = val;
3987 	trace_intel_gpu_freq_change(val * 50);
3988 }
3989 
3990 static void valleyview_set_rps(struct drm_device *dev, u8 val)
3991 {
3992 	struct drm_i915_private *dev_priv = dev->dev_private;
3993 
3994 	WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
3995 	WARN_ON(val > dev_priv->rps.max_freq);
3996 	WARN_ON(val < dev_priv->rps.min_freq);
3997 
3998 	if (WARN_ONCE(IS_CHERRYVIEW(dev) && (val & 1),
3999 		      "Odd GPU freq value\n"))
4000 		val &= ~1;
4001 
4002 	if (val != dev_priv->rps.cur_freq)
4003 		vlv_punit_write(dev_priv, PUNIT_REG_GPU_FREQ_REQ, val);
4004 
4005 	I915_WRITE(GEN6_PMINTRMSK, gen6_rps_pm_mask(dev_priv, val));
4006 
4007 	dev_priv->rps.cur_freq = val;
4008 	trace_intel_gpu_freq_change(intel_gpu_freq(dev_priv, val));
4009 }
4010 
4011 /* vlv_set_rps_idle: Set the frequency to Rpn if Gfx clocks are down
4012  *
4013  * * If Gfx is Idle, then
4014  * 1. Mask Turbo interrupts
4015  * 2. Bring up Gfx clock
4016  * 3. Change the freq to Rpn and wait till P-Unit updates freq
4017  * 4. Clear the Force GFX CLK ON bit so that Gfx can down
4018  * 5. Unmask Turbo interrupts
4019 */
4020 static void vlv_set_rps_idle(struct drm_i915_private *dev_priv)
4021 {
4022 	struct drm_device *dev = dev_priv->dev;
4023 	u32 val = dev_priv->rps.idle_freq;
4024 
4025 	/* CHV and latest VLV don't need to force the gfx clock */
4026 	if (IS_CHERRYVIEW(dev) || dev->pdev->revision >= 0xd) {
4027 		valleyview_set_rps(dev_priv->dev, val);
4028 		return;
4029 	}
4030 
4031 	/*
4032 	 * When we are idle.  Drop to min voltage state.
4033 	 */
4034 
4035 	if (dev_priv->rps.cur_freq <= val)
4036 		return;
4037 
4038 	/* Mask turbo interrupt so that they will not come in between */
4039 	I915_WRITE(GEN6_PMINTRMSK,
4040 		   gen6_sanitize_rps_pm_mask(dev_priv, ~0));
4041 
4042 	vlv_force_gfx_clock(dev_priv, true);
4043 
4044 	dev_priv->rps.cur_freq = val;
4045 
4046 	vlv_punit_write(dev_priv, PUNIT_REG_GPU_FREQ_REQ, val);
4047 
4048 	if (wait_for(((vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS))
4049 				& GENFREQSTATUS) == 0, 100))
4050 		DRM_ERROR("timed out waiting for Punit\n");
4051 
4052 	vlv_force_gfx_clock(dev_priv, false);
4053 
4054 	I915_WRITE(GEN6_PMINTRMSK, gen6_rps_pm_mask(dev_priv, val));
4055 }
4056 
4057 void gen6_rps_busy(struct drm_i915_private *dev_priv)
4058 {
4059 	mutex_lock(&dev_priv->rps.hw_lock);
4060 	if (dev_priv->rps.enabled) {
4061 		if (dev_priv->pm_rps_events & (GEN6_PM_RP_DOWN_EI_EXPIRED | GEN6_PM_RP_UP_EI_EXPIRED))
4062 			gen6_rps_reset_ei(dev_priv);
4063 		I915_WRITE(GEN6_PMINTRMSK,
4064 			   gen6_rps_pm_mask(dev_priv, dev_priv->rps.cur_freq));
4065 	}
4066 	mutex_unlock(&dev_priv->rps.hw_lock);
4067 }
4068 
4069 void gen6_rps_idle(struct drm_i915_private *dev_priv)
4070 {
4071 	struct drm_device *dev = dev_priv->dev;
4072 
4073 	mutex_lock(&dev_priv->rps.hw_lock);
4074 	if (dev_priv->rps.enabled) {
4075 		if (IS_VALLEYVIEW(dev))
4076 			vlv_set_rps_idle(dev_priv);
4077 		else
4078 			gen6_set_rps(dev_priv->dev, dev_priv->rps.idle_freq);
4079 		dev_priv->rps.last_adj = 0;
4080 		I915_WRITE(GEN6_PMINTRMSK, 0xffffffff);
4081 	}
4082 	mutex_unlock(&dev_priv->rps.hw_lock);
4083 }
4084 
4085 void gen6_rps_boost(struct drm_i915_private *dev_priv)
4086 {
4087 	u32 val;
4088 
4089 	mutex_lock(&dev_priv->rps.hw_lock);
4090 	val = dev_priv->rps.max_freq_softlimit;
4091 	if (dev_priv->rps.enabled &&
4092 	    dev_priv->mm.busy &&
4093 	    dev_priv->rps.cur_freq < val) {
4094 		intel_set_rps(dev_priv->dev, val);
4095 		dev_priv->rps.last_adj = 0;
4096 	}
4097 	mutex_unlock(&dev_priv->rps.hw_lock);
4098 }
4099 
4100 void intel_set_rps(struct drm_device *dev, u8 val)
4101 {
4102 	if (IS_VALLEYVIEW(dev))
4103 		valleyview_set_rps(dev, val);
4104 	else
4105 		gen6_set_rps(dev, val);
4106 }
4107 
4108 static void gen9_disable_rps(struct drm_device *dev)
4109 {
4110 	struct drm_i915_private *dev_priv = dev->dev_private;
4111 
4112 	I915_WRITE(GEN6_RC_CONTROL, 0);
4113 	I915_WRITE(GEN9_PG_ENABLE, 0);
4114 }
4115 
4116 static void gen6_disable_rps(struct drm_device *dev)
4117 {
4118 	struct drm_i915_private *dev_priv = dev->dev_private;
4119 
4120 	I915_WRITE(GEN6_RC_CONTROL, 0);
4121 	I915_WRITE(GEN6_RPNSWREQ, 1 << 31);
4122 }
4123 
4124 static void cherryview_disable_rps(struct drm_device *dev)
4125 {
4126 	struct drm_i915_private *dev_priv = dev->dev_private;
4127 
4128 	I915_WRITE(GEN6_RC_CONTROL, 0);
4129 }
4130 
4131 static void valleyview_disable_rps(struct drm_device *dev)
4132 {
4133 	struct drm_i915_private *dev_priv = dev->dev_private;
4134 
4135 	/* we're doing forcewake before Disabling RC6,
4136 	 * This what the BIOS expects when going into suspend */
4137 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4138 
4139 	I915_WRITE(GEN6_RC_CONTROL, 0);
4140 
4141 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4142 }
4143 
4144 static void intel_print_rc6_info(struct drm_device *dev, u32 mode)
4145 {
4146 	if (IS_VALLEYVIEW(dev)) {
4147 		if (mode & (GEN7_RC_CTL_TO_MODE | GEN6_RC_CTL_EI_MODE(1)))
4148 			mode = GEN6_RC_CTL_RC6_ENABLE;
4149 		else
4150 			mode = 0;
4151 	}
4152 	if (HAS_RC6p(dev))
4153 		DRM_DEBUG_KMS("Enabling RC6 states: RC6 %s RC6p %s RC6pp %s\n",
4154 			      (mode & GEN6_RC_CTL_RC6_ENABLE) ? "on" : "off",
4155 			      (mode & GEN6_RC_CTL_RC6p_ENABLE) ? "on" : "off",
4156 			      (mode & GEN6_RC_CTL_RC6pp_ENABLE) ? "on" : "off");
4157 
4158 	else
4159 		DRM_DEBUG_KMS("Enabling RC6 states: RC6 %s\n",
4160 			      (mode & GEN6_RC_CTL_RC6_ENABLE) ? "on" : "off");
4161 }
4162 
4163 static int sanitize_rc6_option(const struct drm_device *dev, int enable_rc6)
4164 {
4165 	/* No RC6 before Ironlake */
4166 	if (INTEL_INFO(dev)->gen < 5)
4167 		return 0;
4168 
4169 	/* RC6 is only on Ironlake mobile not on desktop */
4170 	if (INTEL_INFO(dev)->gen == 5 && !IS_IRONLAKE_M(dev))
4171 		return 0;
4172 
4173 	/* Respect the kernel parameter if it is set */
4174 	if (enable_rc6 >= 0) {
4175 		int mask;
4176 
4177 		if (HAS_RC6p(dev))
4178 			mask = INTEL_RC6_ENABLE | INTEL_RC6p_ENABLE |
4179 			       INTEL_RC6pp_ENABLE;
4180 		else
4181 			mask = INTEL_RC6_ENABLE;
4182 
4183 		if ((enable_rc6 & mask) != enable_rc6)
4184 			DRM_DEBUG_KMS("Adjusting RC6 mask to %d (requested %d, valid %d)\n",
4185 				      enable_rc6 & mask, enable_rc6, mask);
4186 
4187 		return enable_rc6 & mask;
4188 	}
4189 
4190 	/* Disable RC6 on Ironlake */
4191 	if (INTEL_INFO(dev)->gen == 5)
4192 		return 0;
4193 
4194 	if (IS_IVYBRIDGE(dev))
4195 		return (INTEL_RC6_ENABLE | INTEL_RC6p_ENABLE);
4196 
4197 	return INTEL_RC6_ENABLE;
4198 }
4199 
4200 int intel_enable_rc6(const struct drm_device *dev)
4201 {
4202 	return i915.enable_rc6;
4203 }
4204 
4205 static void gen6_init_rps_frequencies(struct drm_device *dev)
4206 {
4207 	struct drm_i915_private *dev_priv = dev->dev_private;
4208 	uint32_t rp_state_cap;
4209 	u32 ddcc_status = 0;
4210 	int ret;
4211 
4212 	rp_state_cap = I915_READ(GEN6_RP_STATE_CAP);
4213 	/* All of these values are in units of 50MHz */
4214 	dev_priv->rps.cur_freq		= 0;
4215 	/* static values from HW: RP0 > RP1 > RPn (min_freq) */
4216 	dev_priv->rps.rp0_freq		= (rp_state_cap >>  0) & 0xff;
4217 	dev_priv->rps.rp1_freq		= (rp_state_cap >>  8) & 0xff;
4218 	dev_priv->rps.min_freq		= (rp_state_cap >> 16) & 0xff;
4219 	if (IS_SKYLAKE(dev)) {
4220 		/* Store the frequency values in 16.66 MHZ units, which is
4221 		   the natural hardware unit for SKL */
4222 		dev_priv->rps.rp0_freq *= GEN9_FREQ_SCALER;
4223 		dev_priv->rps.rp1_freq *= GEN9_FREQ_SCALER;
4224 		dev_priv->rps.min_freq *= GEN9_FREQ_SCALER;
4225 	}
4226 	/* hw_max = RP0 until we check for overclocking */
4227 	dev_priv->rps.max_freq		= dev_priv->rps.rp0_freq;
4228 
4229 	dev_priv->rps.efficient_freq = dev_priv->rps.rp1_freq;
4230 	if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
4231 		ret = sandybridge_pcode_read(dev_priv,
4232 					HSW_PCODE_DYNAMIC_DUTY_CYCLE_CONTROL,
4233 					&ddcc_status);
4234 		if (0 == ret)
4235 			dev_priv->rps.efficient_freq =
4236 				clamp_t(u8,
4237 					((ddcc_status >> 8) & 0xff),
4238 					dev_priv->rps.min_freq,
4239 					dev_priv->rps.max_freq);
4240 	}
4241 
4242 	dev_priv->rps.idle_freq = dev_priv->rps.min_freq;
4243 
4244 	/* Preserve min/max settings in case of re-init */
4245 	if (dev_priv->rps.max_freq_softlimit == 0)
4246 		dev_priv->rps.max_freq_softlimit = dev_priv->rps.max_freq;
4247 
4248 	if (dev_priv->rps.min_freq_softlimit == 0) {
4249 		if (IS_HASWELL(dev) || IS_BROADWELL(dev))
4250 			dev_priv->rps.min_freq_softlimit =
4251 				/* max(RPe, 450 MHz) */
4252 				max(dev_priv->rps.efficient_freq, (u8) 9);
4253 		else
4254 			dev_priv->rps.min_freq_softlimit =
4255 				dev_priv->rps.min_freq;
4256 	}
4257 }
4258 
4259 /* See the Gen9_GT_PM_Programming_Guide doc for the below */
4260 static void gen9_enable_rps(struct drm_device *dev)
4261 {
4262 	struct drm_i915_private *dev_priv = dev->dev_private;
4263 
4264 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4265 
4266 	gen6_init_rps_frequencies(dev);
4267 
4268 	/* Program defaults and thresholds for RPS*/
4269 	I915_WRITE(GEN6_RC_VIDEO_FREQ,
4270 		GEN9_FREQUENCY(dev_priv->rps.rp1_freq));
4271 
4272 	/* 1 second timeout*/
4273 	I915_WRITE(GEN6_RP_DOWN_TIMEOUT,
4274 		GT_INTERVAL_FROM_US(dev_priv, 1000000));
4275 
4276 	I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 0xa);
4277 
4278 	/* Leaning on the below call to gen6_set_rps to program/setup the
4279 	 * Up/Down EI & threshold registers, as well as the RP_CONTROL,
4280 	 * RP_INTERRUPT_LIMITS & RPNSWREQ registers */
4281 	dev_priv->rps.power = HIGH_POWER; /* force a reset */
4282 	gen6_set_rps(dev_priv->dev, dev_priv->rps.min_freq_softlimit);
4283 
4284 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4285 }
4286 
4287 static void gen9_enable_rc6(struct drm_device *dev)
4288 {
4289 	struct drm_i915_private *dev_priv = dev->dev_private;
4290 	struct intel_engine_cs *ring;
4291 	uint32_t rc6_mask = 0;
4292 	int unused;
4293 
4294 	/* 1a: Software RC state - RC0 */
4295 	I915_WRITE(GEN6_RC_STATE, 0);
4296 
4297 	/* 1b: Get forcewake during program sequence. Although the driver
4298 	 * hasn't enabled a state yet where we need forcewake, BIOS may have.*/
4299 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4300 
4301 	/* 2a: Disable RC states. */
4302 	I915_WRITE(GEN6_RC_CONTROL, 0);
4303 
4304 	/* 2b: Program RC6 thresholds.*/
4305 	I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 54 << 16);
4306 	I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000); /* 12500 * 1280ns */
4307 	I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25); /* 25 * 1280ns */
4308 	for_each_ring(ring, dev_priv, unused)
4309 		I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
4310 	I915_WRITE(GEN6_RC_SLEEP, 0);
4311 	I915_WRITE(GEN6_RC6_THRESHOLD, 37500); /* 37.5/125ms per EI */
4312 
4313 	/* 2c: Program Coarse Power Gating Policies. */
4314 	I915_WRITE(GEN9_MEDIA_PG_IDLE_HYSTERESIS, 25);
4315 	I915_WRITE(GEN9_RENDER_PG_IDLE_HYSTERESIS, 25);
4316 
4317 	/* 3a: Enable RC6 */
4318 	if (intel_enable_rc6(dev) & INTEL_RC6_ENABLE)
4319 		rc6_mask = GEN6_RC_CTL_RC6_ENABLE;
4320 	DRM_INFO("RC6 %s\n", (rc6_mask & GEN6_RC_CTL_RC6_ENABLE) ?
4321 			"on" : "off");
4322 	I915_WRITE(GEN6_RC_CONTROL, GEN6_RC_CTL_HW_ENABLE |
4323 				   GEN6_RC_CTL_EI_MODE(1) |
4324 				   rc6_mask);
4325 
4326 	/* 3b: Enable Coarse Power Gating only when RC6 is enabled */
4327 	I915_WRITE(GEN9_PG_ENABLE, (rc6_mask & GEN6_RC_CTL_RC6_ENABLE) ? 3 : 0);
4328 
4329 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4330 
4331 }
4332 
4333 static void gen8_enable_rps(struct drm_device *dev)
4334 {
4335 	struct drm_i915_private *dev_priv = dev->dev_private;
4336 	struct intel_engine_cs *ring;
4337 	uint32_t rc6_mask = 0;
4338 	int unused;
4339 
4340 	/* 1a: Software RC state - RC0 */
4341 	I915_WRITE(GEN6_RC_STATE, 0);
4342 
4343 	/* 1c & 1d: Get forcewake during program sequence. Although the driver
4344 	 * hasn't enabled a state yet where we need forcewake, BIOS may have.*/
4345 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4346 
4347 	/* 2a: Disable RC states. */
4348 	I915_WRITE(GEN6_RC_CONTROL, 0);
4349 
4350 	/* Initialize rps frequencies */
4351 	gen6_init_rps_frequencies(dev);
4352 
4353 	/* 2b: Program RC6 thresholds.*/
4354 	I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 40 << 16);
4355 	I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000); /* 12500 * 1280ns */
4356 	I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25); /* 25 * 1280ns */
4357 	for_each_ring(ring, dev_priv, unused)
4358 		I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
4359 	I915_WRITE(GEN6_RC_SLEEP, 0);
4360 	if (IS_BROADWELL(dev))
4361 		I915_WRITE(GEN6_RC6_THRESHOLD, 625); /* 800us/1.28 for TO */
4362 	else
4363 		I915_WRITE(GEN6_RC6_THRESHOLD, 50000); /* 50/125ms per EI */
4364 
4365 	/* 3: Enable RC6 */
4366 	if (intel_enable_rc6(dev) & INTEL_RC6_ENABLE)
4367 		rc6_mask = GEN6_RC_CTL_RC6_ENABLE;
4368 	intel_print_rc6_info(dev, rc6_mask);
4369 	if (IS_BROADWELL(dev))
4370 		I915_WRITE(GEN6_RC_CONTROL, GEN6_RC_CTL_HW_ENABLE |
4371 				GEN7_RC_CTL_TO_MODE |
4372 				rc6_mask);
4373 	else
4374 		I915_WRITE(GEN6_RC_CONTROL, GEN6_RC_CTL_HW_ENABLE |
4375 				GEN6_RC_CTL_EI_MODE(1) |
4376 				rc6_mask);
4377 
4378 	/* 4 Program defaults and thresholds for RPS*/
4379 	I915_WRITE(GEN6_RPNSWREQ,
4380 		   HSW_FREQUENCY(dev_priv->rps.rp1_freq));
4381 	I915_WRITE(GEN6_RC_VIDEO_FREQ,
4382 		   HSW_FREQUENCY(dev_priv->rps.rp1_freq));
4383 	/* NB: Docs say 1s, and 1000000 - which aren't equivalent */
4384 	I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 100000000 / 128); /* 1 second timeout */
4385 
4386 	/* Docs recommend 900MHz, and 300 MHz respectively */
4387 	I915_WRITE(GEN6_RP_INTERRUPT_LIMITS,
4388 		   dev_priv->rps.max_freq_softlimit << 24 |
4389 		   dev_priv->rps.min_freq_softlimit << 16);
4390 
4391 	I915_WRITE(GEN6_RP_UP_THRESHOLD, 7600000 / 128); /* 76ms busyness per EI, 90% */
4392 	I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 31300000 / 128); /* 313ms busyness per EI, 70%*/
4393 	I915_WRITE(GEN6_RP_UP_EI, 66000); /* 84.48ms, XXX: random? */
4394 	I915_WRITE(GEN6_RP_DOWN_EI, 350000); /* 448ms, XXX: random? */
4395 
4396 	I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
4397 
4398 	/* 5: Enable RPS */
4399 	I915_WRITE(GEN6_RP_CONTROL,
4400 		   GEN6_RP_MEDIA_TURBO |
4401 		   GEN6_RP_MEDIA_HW_NORMAL_MODE |
4402 		   GEN6_RP_MEDIA_IS_GFX |
4403 		   GEN6_RP_ENABLE |
4404 		   GEN6_RP_UP_BUSY_AVG |
4405 		   GEN6_RP_DOWN_IDLE_AVG);
4406 
4407 	/* 6: Ring frequency + overclocking (our driver does this later */
4408 
4409 	dev_priv->rps.power = HIGH_POWER; /* force a reset */
4410 	gen6_set_rps(dev_priv->dev, dev_priv->rps.idle_freq);
4411 
4412 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4413 }
4414 
4415 static void gen6_enable_rps(struct drm_device *dev)
4416 {
4417 	struct drm_i915_private *dev_priv = dev->dev_private;
4418 	struct intel_engine_cs *ring;
4419 	u32 rc6vids, pcu_mbox = 0, rc6_mask = 0;
4420 	u32 gtfifodbg;
4421 	int rc6_mode;
4422 	int i, ret;
4423 
4424 	WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
4425 
4426 	/* Here begins a magic sequence of register writes to enable
4427 	 * auto-downclocking.
4428 	 *
4429 	 * Perhaps there might be some value in exposing these to
4430 	 * userspace...
4431 	 */
4432 	I915_WRITE(GEN6_RC_STATE, 0);
4433 
4434 	/* Clear the DBG now so we don't confuse earlier errors */
4435 	if ((gtfifodbg = I915_READ(GTFIFODBG))) {
4436 		DRM_ERROR("GT fifo had a previous error %x\n", gtfifodbg);
4437 		I915_WRITE(GTFIFODBG, gtfifodbg);
4438 	}
4439 
4440 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4441 
4442 	/* Initialize rps frequencies */
4443 	gen6_init_rps_frequencies(dev);
4444 
4445 	/* disable the counters and set deterministic thresholds */
4446 	I915_WRITE(GEN6_RC_CONTROL, 0);
4447 
4448 	I915_WRITE(GEN6_RC1_WAKE_RATE_LIMIT, 1000 << 16);
4449 	I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 40 << 16 | 30);
4450 	I915_WRITE(GEN6_RC6pp_WAKE_RATE_LIMIT, 30);
4451 	I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000);
4452 	I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25);
4453 
4454 	for_each_ring(ring, dev_priv, i)
4455 		I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
4456 
4457 	I915_WRITE(GEN6_RC_SLEEP, 0);
4458 	I915_WRITE(GEN6_RC1e_THRESHOLD, 1000);
4459 	if (IS_IVYBRIDGE(dev))
4460 		I915_WRITE(GEN6_RC6_THRESHOLD, 125000);
4461 	else
4462 		I915_WRITE(GEN6_RC6_THRESHOLD, 50000);
4463 	I915_WRITE(GEN6_RC6p_THRESHOLD, 150000);
4464 	I915_WRITE(GEN6_RC6pp_THRESHOLD, 64000); /* unused */
4465 
4466 	/* Check if we are enabling RC6 */
4467 	rc6_mode = intel_enable_rc6(dev_priv->dev);
4468 	if (rc6_mode & INTEL_RC6_ENABLE)
4469 		rc6_mask |= GEN6_RC_CTL_RC6_ENABLE;
4470 
4471 	/* We don't use those on Haswell */
4472 	if (!IS_HASWELL(dev)) {
4473 		if (rc6_mode & INTEL_RC6p_ENABLE)
4474 			rc6_mask |= GEN6_RC_CTL_RC6p_ENABLE;
4475 
4476 		if (rc6_mode & INTEL_RC6pp_ENABLE)
4477 			rc6_mask |= GEN6_RC_CTL_RC6pp_ENABLE;
4478 	}
4479 
4480 	intel_print_rc6_info(dev, rc6_mask);
4481 
4482 	I915_WRITE(GEN6_RC_CONTROL,
4483 		   rc6_mask |
4484 		   GEN6_RC_CTL_EI_MODE(1) |
4485 		   GEN6_RC_CTL_HW_ENABLE);
4486 
4487 	/* Power down if completely idle for over 50ms */
4488 	I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 50000);
4489 	I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
4490 
4491 	ret = sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_MIN_FREQ_TABLE, 0);
4492 	if (ret)
4493 		DRM_DEBUG_DRIVER("Failed to set the min frequency\n");
4494 
4495 	ret = sandybridge_pcode_read(dev_priv, GEN6_READ_OC_PARAMS, &pcu_mbox);
4496 	if (!ret && (pcu_mbox & (1<<31))) { /* OC supported */
4497 		DRM_DEBUG_DRIVER("Overclocking supported. Max: %dMHz, Overclock max: %dMHz\n",
4498 				 (dev_priv->rps.max_freq_softlimit & 0xff) * 50,
4499 				 (pcu_mbox & 0xff) * 50);
4500 		dev_priv->rps.max_freq = pcu_mbox & 0xff;
4501 	}
4502 
4503 	dev_priv->rps.power = HIGH_POWER; /* force a reset */
4504 	gen6_set_rps(dev_priv->dev, dev_priv->rps.idle_freq);
4505 
4506 	rc6vids = 0;
4507 	ret = sandybridge_pcode_read(dev_priv, GEN6_PCODE_READ_RC6VIDS, &rc6vids);
4508 	if (IS_GEN6(dev) && ret) {
4509 		DRM_DEBUG_DRIVER("Couldn't check for BIOS workaround\n");
4510 	} else if (IS_GEN6(dev) && (GEN6_DECODE_RC6_VID(rc6vids & 0xff) < 450)) {
4511 		DRM_DEBUG_DRIVER("You should update your BIOS. Correcting minimum rc6 voltage (%dmV->%dmV)\n",
4512 			  GEN6_DECODE_RC6_VID(rc6vids & 0xff), 450);
4513 		rc6vids &= 0xffff00;
4514 		rc6vids |= GEN6_ENCODE_RC6_VID(450);
4515 		ret = sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_RC6VIDS, rc6vids);
4516 		if (ret)
4517 			DRM_ERROR("Couldn't fix incorrect rc6 voltage\n");
4518 	}
4519 
4520 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4521 }
4522 
4523 static void __gen6_update_ring_freq(struct drm_device *dev)
4524 {
4525 	struct drm_i915_private *dev_priv = dev->dev_private;
4526 	int min_freq = 15;
4527 	unsigned int gpu_freq;
4528 	unsigned int max_ia_freq, min_ring_freq;
4529 	int scaling_factor = 180;
4530 
4531 	WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
4532 
4533 #if 0
4534 	policy = cpufreq_cpu_get(0);
4535 	if (policy) {
4536 		max_ia_freq = policy->cpuinfo.max_freq;
4537 		cpufreq_cpu_put(policy);
4538 	} else {
4539 		/*
4540 		 * Default to measured freq if none found, PCU will ensure we
4541 		 * don't go over
4542 		 */
4543 		max_ia_freq = tsc_khz;
4544 	}
4545 #else
4546 	max_ia_freq = tsc_frequency / 1000;
4547 #endif
4548 
4549 	/* Convert from kHz to MHz */
4550 	max_ia_freq /= 1000;
4551 
4552 	min_ring_freq = I915_READ(DCLK) & 0xf;
4553 	/* convert DDR frequency from units of 266.6MHz to bandwidth */
4554 	min_ring_freq = mult_frac(min_ring_freq, 8, 3);
4555 
4556 	/*
4557 	 * For each potential GPU frequency, load a ring frequency we'd like
4558 	 * to use for memory access.  We do this by specifying the IA frequency
4559 	 * the PCU should use as a reference to determine the ring frequency.
4560 	 */
4561 	for (gpu_freq = dev_priv->rps.max_freq; gpu_freq >= dev_priv->rps.min_freq;
4562 	     gpu_freq--) {
4563 		int diff = dev_priv->rps.max_freq - gpu_freq;
4564 		unsigned int ia_freq = 0, ring_freq = 0;
4565 
4566 		if (INTEL_INFO(dev)->gen >= 8) {
4567 			/* max(2 * GT, DDR). NB: GT is 50MHz units */
4568 			ring_freq = max(min_ring_freq, gpu_freq);
4569 		} else if (IS_HASWELL(dev)) {
4570 			ring_freq = mult_frac(gpu_freq, 5, 4);
4571 			ring_freq = max(min_ring_freq, ring_freq);
4572 			/* leave ia_freq as the default, chosen by cpufreq */
4573 		} else {
4574 			/* On older processors, there is no separate ring
4575 			 * clock domain, so in order to boost the bandwidth
4576 			 * of the ring, we need to upclock the CPU (ia_freq).
4577 			 *
4578 			 * For GPU frequencies less than 750MHz,
4579 			 * just use the lowest ring freq.
4580 			 */
4581 			if (gpu_freq < min_freq)
4582 				ia_freq = 800;
4583 			else
4584 				ia_freq = max_ia_freq - ((diff * scaling_factor) / 2);
4585 			ia_freq = DIV_ROUND_CLOSEST(ia_freq, 100);
4586 		}
4587 
4588 		sandybridge_pcode_write(dev_priv,
4589 					GEN6_PCODE_WRITE_MIN_FREQ_TABLE,
4590 					ia_freq << GEN6_PCODE_FREQ_IA_RATIO_SHIFT |
4591 					ring_freq << GEN6_PCODE_FREQ_RING_RATIO_SHIFT |
4592 					gpu_freq);
4593 	}
4594 }
4595 
4596 void gen6_update_ring_freq(struct drm_device *dev)
4597 {
4598 	struct drm_i915_private *dev_priv = dev->dev_private;
4599 
4600 	if (INTEL_INFO(dev)->gen < 6 || IS_VALLEYVIEW(dev))
4601 		return;
4602 
4603 	mutex_lock(&dev_priv->rps.hw_lock);
4604 	__gen6_update_ring_freq(dev);
4605 	mutex_unlock(&dev_priv->rps.hw_lock);
4606 }
4607 
4608 static int cherryview_rps_max_freq(struct drm_i915_private *dev_priv)
4609 {
4610 	struct drm_device *dev = dev_priv->dev;
4611 	u32 val, rp0;
4612 
4613 	if (dev->pdev->revision >= 0x20) {
4614 		val = vlv_punit_read(dev_priv, FB_GFX_FMAX_AT_VMAX_FUSE);
4615 
4616 		switch (INTEL_INFO(dev)->eu_total) {
4617 		case 8:
4618 				/* (2 * 4) config */
4619 				rp0 = (val >> FB_GFX_FMAX_AT_VMAX_2SS4EU_FUSE_SHIFT);
4620 				break;
4621 		case 12:
4622 				/* (2 * 6) config */
4623 				rp0 = (val >> FB_GFX_FMAX_AT_VMAX_2SS6EU_FUSE_SHIFT);
4624 				break;
4625 		case 16:
4626 				/* (2 * 8) config */
4627 		default:
4628 				/* Setting (2 * 8) Min RP0 for any other combination */
4629 				rp0 = (val >> FB_GFX_FMAX_AT_VMAX_2SS8EU_FUSE_SHIFT);
4630 				break;
4631 		}
4632 		rp0 = (rp0 & FB_GFX_FREQ_FUSE_MASK);
4633 	} else {
4634 		/* For pre-production hardware */
4635 		val = vlv_punit_read(dev_priv, PUNIT_GPU_STATUS_REG);
4636 		rp0 = (val >> PUNIT_GPU_STATUS_MAX_FREQ_SHIFT) &
4637 		       PUNIT_GPU_STATUS_MAX_FREQ_MASK;
4638 	}
4639 	return rp0;
4640 }
4641 
4642 static int cherryview_rps_rpe_freq(struct drm_i915_private *dev_priv)
4643 {
4644 	u32 val, rpe;
4645 
4646 	val = vlv_punit_read(dev_priv, PUNIT_GPU_DUTYCYCLE_REG);
4647 	rpe = (val >> PUNIT_GPU_DUTYCYCLE_RPE_FREQ_SHIFT) & PUNIT_GPU_DUTYCYCLE_RPE_FREQ_MASK;
4648 
4649 	return rpe;
4650 }
4651 
4652 static int cherryview_rps_guar_freq(struct drm_i915_private *dev_priv)
4653 {
4654 	struct drm_device *dev = dev_priv->dev;
4655 	u32 val, rp1;
4656 
4657 	if (dev->pdev->revision >= 0x20) {
4658 		val = vlv_punit_read(dev_priv, FB_GFX_FMAX_AT_VMAX_FUSE);
4659 		rp1 = (val & FB_GFX_FREQ_FUSE_MASK);
4660 	} else {
4661 		/* For pre-production hardware */
4662 		val = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS);
4663 		rp1 = ((val >> PUNIT_GPU_STATUS_MAX_FREQ_SHIFT) &
4664 		       PUNIT_GPU_STATUS_MAX_FREQ_MASK);
4665 	}
4666 	return rp1;
4667 }
4668 
4669 static int cherryview_rps_min_freq(struct drm_i915_private *dev_priv)
4670 {
4671 	struct drm_device *dev = dev_priv->dev;
4672 	u32 val, rpn;
4673 
4674 	if (dev->pdev->revision >= 0x20) {
4675 		val = vlv_punit_read(dev_priv, FB_GFX_FMIN_AT_VMIN_FUSE);
4676 		rpn = ((val >> FB_GFX_FMIN_AT_VMIN_FUSE_SHIFT) &
4677 		       FB_GFX_FREQ_FUSE_MASK);
4678 	} else { /* For pre-production hardware */
4679 		val = vlv_punit_read(dev_priv, PUNIT_GPU_STATUS_REG);
4680 		rpn = ((val >> PUNIT_GPU_STATIS_GFX_MIN_FREQ_SHIFT) &
4681 		       PUNIT_GPU_STATUS_GFX_MIN_FREQ_MASK);
4682 	}
4683 
4684 	return rpn;
4685 }
4686 
4687 static int valleyview_rps_guar_freq(struct drm_i915_private *dev_priv)
4688 {
4689 	u32 val, rp1;
4690 
4691 	val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FREQ_FUSE);
4692 
4693 	rp1 = (val & FB_GFX_FGUARANTEED_FREQ_FUSE_MASK) >> FB_GFX_FGUARANTEED_FREQ_FUSE_SHIFT;
4694 
4695 	return rp1;
4696 }
4697 
4698 static int valleyview_rps_max_freq(struct drm_i915_private *dev_priv)
4699 {
4700 	u32 val, rp0;
4701 
4702 	val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FREQ_FUSE);
4703 
4704 	rp0 = (val & FB_GFX_MAX_FREQ_FUSE_MASK) >> FB_GFX_MAX_FREQ_FUSE_SHIFT;
4705 	/* Clamp to max */
4706 	rp0 = min_t(u32, rp0, 0xea);
4707 
4708 	return rp0;
4709 }
4710 
4711 static int valleyview_rps_rpe_freq(struct drm_i915_private *dev_priv)
4712 {
4713 	u32 val, rpe;
4714 
4715 	val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FMAX_FUSE_LO);
4716 	rpe = (val & FB_FMAX_VMIN_FREQ_LO_MASK) >> FB_FMAX_VMIN_FREQ_LO_SHIFT;
4717 	val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FMAX_FUSE_HI);
4718 	rpe |= (val & FB_FMAX_VMIN_FREQ_HI_MASK) << 5;
4719 
4720 	return rpe;
4721 }
4722 
4723 static int valleyview_rps_min_freq(struct drm_i915_private *dev_priv)
4724 {
4725 	return vlv_punit_read(dev_priv, PUNIT_REG_GPU_LFM) & 0xff;
4726 }
4727 
4728 /* Check that the pctx buffer wasn't move under us. */
4729 static void valleyview_check_pctx(struct drm_i915_private *dev_priv)
4730 {
4731 	unsigned long pctx_addr = I915_READ(VLV_PCBR) & ~4095;
4732 
4733 	/* DragonFly - if EDID fails vlv_pctx can wind up NULL */
4734 	if (WARN_ON(!dev_priv->vlv_pctx))
4735 		return;
4736 
4737 	WARN_ON(pctx_addr != dev_priv->mm.stolen_base +
4738 			     dev_priv->vlv_pctx->stolen->start);
4739 }
4740 
4741 
4742 /* Check that the pcbr address is not empty. */
4743 static void cherryview_check_pctx(struct drm_i915_private *dev_priv)
4744 {
4745 	unsigned long pctx_addr = I915_READ(VLV_PCBR) & ~4095;
4746 
4747 	WARN_ON((pctx_addr >> VLV_PCBR_ADDR_SHIFT) == 0);
4748 }
4749 
4750 static void cherryview_setup_pctx(struct drm_device *dev)
4751 {
4752 	struct drm_i915_private *dev_priv = dev->dev_private;
4753 	unsigned long pctx_paddr, paddr;
4754 	struct i915_gtt *gtt = &dev_priv->gtt;
4755 	u32 pcbr;
4756 	int pctx_size = 32*1024;
4757 
4758 	WARN_ON(!mutex_is_locked(&dev->struct_mutex));
4759 
4760 	pcbr = I915_READ(VLV_PCBR);
4761 	if ((pcbr >> VLV_PCBR_ADDR_SHIFT) == 0) {
4762 		DRM_DEBUG_DRIVER("BIOS didn't set up PCBR, fixing up\n");
4763 		paddr = (dev_priv->mm.stolen_base +
4764 			 (gtt->stolen_size - pctx_size));
4765 
4766 		pctx_paddr = (paddr & (~4095));
4767 		I915_WRITE(VLV_PCBR, pctx_paddr);
4768 	}
4769 
4770 	DRM_DEBUG_DRIVER("PCBR: 0x%08x\n", I915_READ(VLV_PCBR));
4771 }
4772 
4773 static void valleyview_setup_pctx(struct drm_device *dev)
4774 {
4775 	struct drm_i915_private *dev_priv = dev->dev_private;
4776 	struct drm_i915_gem_object *pctx;
4777 	unsigned long pctx_paddr;
4778 	u32 pcbr;
4779 	int pctx_size = 24*1024;
4780 
4781 	WARN_ON(!mutex_is_locked(&dev->struct_mutex));
4782 
4783 	pcbr = I915_READ(VLV_PCBR);
4784 	if (pcbr) {
4785 		/* BIOS set it up already, grab the pre-alloc'd space */
4786 		int pcbr_offset;
4787 
4788 		pcbr_offset = (pcbr & (~4095)) - dev_priv->mm.stolen_base;
4789 		pctx = i915_gem_object_create_stolen_for_preallocated(dev_priv->dev,
4790 								      pcbr_offset,
4791 								      I915_GTT_OFFSET_NONE,
4792 								      pctx_size);
4793 		goto out;
4794 	}
4795 
4796 	DRM_DEBUG_DRIVER("BIOS didn't set up PCBR, fixing up\n");
4797 
4798 	/*
4799 	 * From the Gunit register HAS:
4800 	 * The Gfx driver is expected to program this register and ensure
4801 	 * proper allocation within Gfx stolen memory.  For example, this
4802 	 * register should be programmed such than the PCBR range does not
4803 	 * overlap with other ranges, such as the frame buffer, protected
4804 	 * memory, or any other relevant ranges.
4805 	 */
4806 	pctx = i915_gem_object_create_stolen(dev, pctx_size);
4807 	if (!pctx) {
4808 		DRM_DEBUG("not enough stolen space for PCTX, disabling\n");
4809 		return;
4810 	}
4811 
4812 	pctx_paddr = dev_priv->mm.stolen_base + pctx->stolen->start;
4813 	I915_WRITE(VLV_PCBR, pctx_paddr);
4814 
4815 out:
4816 	DRM_DEBUG_DRIVER("PCBR: 0x%08x\n", I915_READ(VLV_PCBR));
4817 	dev_priv->vlv_pctx = pctx;
4818 }
4819 
4820 static void valleyview_cleanup_pctx(struct drm_device *dev)
4821 {
4822 	struct drm_i915_private *dev_priv = dev->dev_private;
4823 
4824 	if (WARN_ON(!dev_priv->vlv_pctx))
4825 		return;
4826 
4827 	drm_gem_object_unreference(&dev_priv->vlv_pctx->base);
4828 	dev_priv->vlv_pctx = NULL;
4829 }
4830 
4831 static void valleyview_init_gt_powersave(struct drm_device *dev)
4832 {
4833 	struct drm_i915_private *dev_priv = dev->dev_private;
4834 	u32 val;
4835 
4836 	valleyview_setup_pctx(dev);
4837 
4838 	mutex_lock(&dev_priv->rps.hw_lock);
4839 
4840 	val = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS);
4841 	switch ((val >> 6) & 3) {
4842 	case 0:
4843 	case 1:
4844 		dev_priv->mem_freq = 800;
4845 		break;
4846 	case 2:
4847 		dev_priv->mem_freq = 1066;
4848 		break;
4849 	case 3:
4850 		dev_priv->mem_freq = 1333;
4851 		break;
4852 	}
4853 	DRM_DEBUG_DRIVER("DDR speed: %d MHz\n", dev_priv->mem_freq);
4854 
4855 	dev_priv->rps.max_freq = valleyview_rps_max_freq(dev_priv);
4856 	dev_priv->rps.rp0_freq = dev_priv->rps.max_freq;
4857 	DRM_DEBUG_DRIVER("max GPU freq: %d MHz (%u)\n",
4858 			 intel_gpu_freq(dev_priv, dev_priv->rps.max_freq),
4859 			 dev_priv->rps.max_freq);
4860 
4861 	dev_priv->rps.efficient_freq = valleyview_rps_rpe_freq(dev_priv);
4862 	DRM_DEBUG_DRIVER("RPe GPU freq: %d MHz (%u)\n",
4863 			 intel_gpu_freq(dev_priv, dev_priv->rps.efficient_freq),
4864 			 dev_priv->rps.efficient_freq);
4865 
4866 	dev_priv->rps.rp1_freq = valleyview_rps_guar_freq(dev_priv);
4867 	DRM_DEBUG_DRIVER("RP1(Guar Freq) GPU freq: %d MHz (%u)\n",
4868 			 intel_gpu_freq(dev_priv, dev_priv->rps.rp1_freq),
4869 			 dev_priv->rps.rp1_freq);
4870 
4871 	dev_priv->rps.min_freq = valleyview_rps_min_freq(dev_priv);
4872 	DRM_DEBUG_DRIVER("min GPU freq: %d MHz (%u)\n",
4873 			 intel_gpu_freq(dev_priv, dev_priv->rps.min_freq),
4874 			 dev_priv->rps.min_freq);
4875 
4876 	dev_priv->rps.idle_freq = dev_priv->rps.min_freq;
4877 
4878 	/* Preserve min/max settings in case of re-init */
4879 	if (dev_priv->rps.max_freq_softlimit == 0)
4880 		dev_priv->rps.max_freq_softlimit = dev_priv->rps.max_freq;
4881 
4882 	if (dev_priv->rps.min_freq_softlimit == 0)
4883 		dev_priv->rps.min_freq_softlimit = dev_priv->rps.min_freq;
4884 
4885 	mutex_unlock(&dev_priv->rps.hw_lock);
4886 }
4887 
4888 static void cherryview_init_gt_powersave(struct drm_device *dev)
4889 {
4890 	struct drm_i915_private *dev_priv = dev->dev_private;
4891 	u32 val;
4892 
4893 	cherryview_setup_pctx(dev);
4894 
4895 	mutex_lock(&dev_priv->rps.hw_lock);
4896 
4897 	mutex_lock(&dev_priv->dpio_lock);
4898 	val = vlv_cck_read(dev_priv, CCK_FUSE_REG);
4899 	mutex_unlock(&dev_priv->dpio_lock);
4900 
4901 	switch ((val >> 2) & 0x7) {
4902 	case 0:
4903 	case 1:
4904 		dev_priv->rps.cz_freq = 200;
4905 		dev_priv->mem_freq = 1600;
4906 		break;
4907 	case 2:
4908 		dev_priv->rps.cz_freq = 267;
4909 		dev_priv->mem_freq = 1600;
4910 		break;
4911 	case 3:
4912 		dev_priv->rps.cz_freq = 333;
4913 		dev_priv->mem_freq = 2000;
4914 		break;
4915 	case 4:
4916 		dev_priv->rps.cz_freq = 320;
4917 		dev_priv->mem_freq = 1600;
4918 		break;
4919 	case 5:
4920 		dev_priv->rps.cz_freq = 400;
4921 		dev_priv->mem_freq = 1600;
4922 		break;
4923 	}
4924 	DRM_DEBUG_DRIVER("DDR speed: %d MHz\n", dev_priv->mem_freq);
4925 
4926 	dev_priv->rps.max_freq = cherryview_rps_max_freq(dev_priv);
4927 	dev_priv->rps.rp0_freq = dev_priv->rps.max_freq;
4928 	DRM_DEBUG_DRIVER("max GPU freq: %d MHz (%u)\n",
4929 			 intel_gpu_freq(dev_priv, dev_priv->rps.max_freq),
4930 			 dev_priv->rps.max_freq);
4931 
4932 	dev_priv->rps.efficient_freq = cherryview_rps_rpe_freq(dev_priv);
4933 	DRM_DEBUG_DRIVER("RPe GPU freq: %d MHz (%u)\n",
4934 			 intel_gpu_freq(dev_priv, dev_priv->rps.efficient_freq),
4935 			 dev_priv->rps.efficient_freq);
4936 
4937 	dev_priv->rps.rp1_freq = cherryview_rps_guar_freq(dev_priv);
4938 	DRM_DEBUG_DRIVER("RP1(Guar) GPU freq: %d MHz (%u)\n",
4939 			 intel_gpu_freq(dev_priv, dev_priv->rps.rp1_freq),
4940 			 dev_priv->rps.rp1_freq);
4941 
4942 	dev_priv->rps.min_freq = cherryview_rps_min_freq(dev_priv);
4943 	DRM_DEBUG_DRIVER("min GPU freq: %d MHz (%u)\n",
4944 			 intel_gpu_freq(dev_priv, dev_priv->rps.min_freq),
4945 			 dev_priv->rps.min_freq);
4946 
4947 	WARN_ONCE((dev_priv->rps.max_freq |
4948 		   dev_priv->rps.efficient_freq |
4949 		   dev_priv->rps.rp1_freq |
4950 		   dev_priv->rps.min_freq) & 1,
4951 		  "Odd GPU freq values\n");
4952 
4953 	dev_priv->rps.idle_freq = dev_priv->rps.min_freq;
4954 
4955 	/* Preserve min/max settings in case of re-init */
4956 	if (dev_priv->rps.max_freq_softlimit == 0)
4957 		dev_priv->rps.max_freq_softlimit = dev_priv->rps.max_freq;
4958 
4959 	if (dev_priv->rps.min_freq_softlimit == 0)
4960 		dev_priv->rps.min_freq_softlimit = dev_priv->rps.min_freq;
4961 
4962 	mutex_unlock(&dev_priv->rps.hw_lock);
4963 }
4964 
4965 static void valleyview_cleanup_gt_powersave(struct drm_device *dev)
4966 {
4967 	valleyview_cleanup_pctx(dev);
4968 }
4969 
4970 static void cherryview_enable_rps(struct drm_device *dev)
4971 {
4972 	struct drm_i915_private *dev_priv = dev->dev_private;
4973 	struct intel_engine_cs *ring;
4974 	u32 gtfifodbg, val, rc6_mode = 0, pcbr;
4975 	int i;
4976 
4977 	WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
4978 
4979 	gtfifodbg = I915_READ(GTFIFODBG);
4980 	if (gtfifodbg) {
4981 		DRM_DEBUG_DRIVER("GT fifo had a previous error %x\n",
4982 				 gtfifodbg);
4983 		I915_WRITE(GTFIFODBG, gtfifodbg);
4984 	}
4985 
4986 	cherryview_check_pctx(dev_priv);
4987 
4988 	/* 1a & 1b: Get forcewake during program sequence. Although the driver
4989 	 * hasn't enabled a state yet where we need forcewake, BIOS may have.*/
4990 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4991 
4992 	/*  Disable RC states. */
4993 	I915_WRITE(GEN6_RC_CONTROL, 0);
4994 
4995 	/* 2a: Program RC6 thresholds.*/
4996 	I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 40 << 16);
4997 	I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000); /* 12500 * 1280ns */
4998 	I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25); /* 25 * 1280ns */
4999 
5000 	for_each_ring(ring, dev_priv, i)
5001 		I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
5002 	I915_WRITE(GEN6_RC_SLEEP, 0);
5003 
5004 	/* TO threshold set to 1750 us ( 0x557 * 1.28 us) */
5005 	I915_WRITE(GEN6_RC6_THRESHOLD, 0x557);
5006 
5007 	/* allows RC6 residency counter to work */
5008 	I915_WRITE(VLV_COUNTER_CONTROL,
5009 		   _MASKED_BIT_ENABLE(VLV_COUNT_RANGE_HIGH |
5010 				      VLV_MEDIA_RC6_COUNT_EN |
5011 				      VLV_RENDER_RC6_COUNT_EN));
5012 
5013 	/* For now we assume BIOS is allocating and populating the PCBR  */
5014 	pcbr = I915_READ(VLV_PCBR);
5015 
5016 	/* 3: Enable RC6 */
5017 	if ((intel_enable_rc6(dev) & INTEL_RC6_ENABLE) &&
5018 						(pcbr >> VLV_PCBR_ADDR_SHIFT))
5019 		rc6_mode = GEN7_RC_CTL_TO_MODE;
5020 
5021 	I915_WRITE(GEN6_RC_CONTROL, rc6_mode);
5022 
5023 	/* 4 Program defaults and thresholds for RPS*/
5024 	I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 1000000);
5025 	I915_WRITE(GEN6_RP_UP_THRESHOLD, 59400);
5026 	I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 245000);
5027 	I915_WRITE(GEN6_RP_UP_EI, 66000);
5028 	I915_WRITE(GEN6_RP_DOWN_EI, 350000);
5029 
5030 	I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
5031 
5032 	/* 5: Enable RPS */
5033 	I915_WRITE(GEN6_RP_CONTROL,
5034 		   GEN6_RP_MEDIA_HW_NORMAL_MODE |
5035 		   GEN6_RP_MEDIA_IS_GFX |
5036 		   GEN6_RP_ENABLE |
5037 		   GEN6_RP_UP_BUSY_AVG |
5038 		   GEN6_RP_DOWN_IDLE_AVG);
5039 
5040 	val = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS);
5041 
5042 	/* RPS code assumes GPLL is used */
5043 	WARN_ONCE((val & GPLLENABLE) == 0, "GPLL not enabled\n");
5044 
5045 	DRM_DEBUG_DRIVER("GPLL enabled? %s\n", val & GPLLENABLE ? "yes" : "no");
5046 	DRM_DEBUG_DRIVER("GPU status: 0x%08x\n", val);
5047 
5048 	dev_priv->rps.cur_freq = (val >> 8) & 0xff;
5049 	DRM_DEBUG_DRIVER("current GPU freq: %d MHz (%u)\n",
5050 			 intel_gpu_freq(dev_priv, dev_priv->rps.cur_freq),
5051 			 dev_priv->rps.cur_freq);
5052 
5053 	DRM_DEBUG_DRIVER("setting GPU freq to %d MHz (%u)\n",
5054 			 intel_gpu_freq(dev_priv, dev_priv->rps.efficient_freq),
5055 			 dev_priv->rps.efficient_freq);
5056 
5057 	valleyview_set_rps(dev_priv->dev, dev_priv->rps.efficient_freq);
5058 
5059 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5060 }
5061 
5062 static void valleyview_enable_rps(struct drm_device *dev)
5063 {
5064 	struct drm_i915_private *dev_priv = dev->dev_private;
5065 	struct intel_engine_cs *ring;
5066 	u32 gtfifodbg, val, rc6_mode = 0;
5067 	int i;
5068 
5069 	WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
5070 
5071 	valleyview_check_pctx(dev_priv);
5072 
5073 	if ((gtfifodbg = I915_READ(GTFIFODBG))) {
5074 		DRM_DEBUG_DRIVER("GT fifo had a previous error %x\n",
5075 				 gtfifodbg);
5076 		I915_WRITE(GTFIFODBG, gtfifodbg);
5077 	}
5078 
5079 	/* If VLV, Forcewake all wells, else re-direct to regular path */
5080 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
5081 
5082 	/*  Disable RC states. */
5083 	I915_WRITE(GEN6_RC_CONTROL, 0);
5084 
5085 	I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 1000000);
5086 	I915_WRITE(GEN6_RP_UP_THRESHOLD, 59400);
5087 	I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 245000);
5088 	I915_WRITE(GEN6_RP_UP_EI, 66000);
5089 	I915_WRITE(GEN6_RP_DOWN_EI, 350000);
5090 
5091 	I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
5092 
5093 	I915_WRITE(GEN6_RP_CONTROL,
5094 		   GEN6_RP_MEDIA_TURBO |
5095 		   GEN6_RP_MEDIA_HW_NORMAL_MODE |
5096 		   GEN6_RP_MEDIA_IS_GFX |
5097 		   GEN6_RP_ENABLE |
5098 		   GEN6_RP_UP_BUSY_AVG |
5099 		   GEN6_RP_DOWN_IDLE_CONT);
5100 
5101 	I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 0x00280000);
5102 	I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000);
5103 	I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25);
5104 
5105 	for_each_ring(ring, dev_priv, i)
5106 		I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
5107 
5108 	I915_WRITE(GEN6_RC6_THRESHOLD, 0x557);
5109 
5110 	/* allows RC6 residency counter to work */
5111 	I915_WRITE(VLV_COUNTER_CONTROL,
5112 		   _MASKED_BIT_ENABLE(VLV_MEDIA_RC0_COUNT_EN |
5113 				      VLV_RENDER_RC0_COUNT_EN |
5114 				      VLV_MEDIA_RC6_COUNT_EN |
5115 				      VLV_RENDER_RC6_COUNT_EN));
5116 
5117 	if (intel_enable_rc6(dev) & INTEL_RC6_ENABLE)
5118 		rc6_mode = GEN7_RC_CTL_TO_MODE | VLV_RC_CTL_CTX_RST_PARALLEL;
5119 
5120 	intel_print_rc6_info(dev, rc6_mode);
5121 
5122 	I915_WRITE(GEN6_RC_CONTROL, rc6_mode);
5123 
5124 	val = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS);
5125 
5126 	/* RPS code assumes GPLL is used */
5127 	WARN_ONCE((val & GPLLENABLE) == 0, "GPLL not enabled\n");
5128 
5129 	DRM_DEBUG_DRIVER("GPLL enabled? %s\n", val & GPLLENABLE ? "yes" : "no");
5130 	DRM_DEBUG_DRIVER("GPU status: 0x%08x\n", val);
5131 
5132 	dev_priv->rps.cur_freq = (val >> 8) & 0xff;
5133 	DRM_DEBUG_DRIVER("current GPU freq: %d MHz (%u)\n",
5134 			 intel_gpu_freq(dev_priv, dev_priv->rps.cur_freq),
5135 			 dev_priv->rps.cur_freq);
5136 
5137 	DRM_DEBUG_DRIVER("setting GPU freq to %d MHz (%u)\n",
5138 			 intel_gpu_freq(dev_priv, dev_priv->rps.efficient_freq),
5139 			 dev_priv->rps.efficient_freq);
5140 
5141 	valleyview_set_rps(dev_priv->dev, dev_priv->rps.efficient_freq);
5142 
5143 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5144 }
5145 
5146 static unsigned long intel_pxfreq(u32 vidfreq)
5147 {
5148 	unsigned long freq;
5149 	int div = (vidfreq & 0x3f0000) >> 16;
5150 	int post = (vidfreq & 0x3000) >> 12;
5151 	int pre = (vidfreq & 0x7);
5152 
5153 	if (!pre)
5154 		return 0;
5155 
5156 	freq = ((div * 133333) / ((1<<post) * pre));
5157 
5158 	return freq;
5159 }
5160 
5161 static const struct cparams {
5162 	u16 i;
5163 	u16 t;
5164 	u16 m;
5165 	u16 c;
5166 } cparams[] = {
5167 	{ 1, 1333, 301, 28664 },
5168 	{ 1, 1066, 294, 24460 },
5169 	{ 1, 800, 294, 25192 },
5170 	{ 0, 1333, 276, 27605 },
5171 	{ 0, 1066, 276, 27605 },
5172 	{ 0, 800, 231, 23784 },
5173 };
5174 
5175 static unsigned long __i915_chipset_val(struct drm_i915_private *dev_priv)
5176 {
5177 	u64 total_count, diff, ret;
5178 	u32 count1, count2, count3, m = 0, c = 0;
5179 	unsigned long now = jiffies_to_msecs(jiffies), diff1;
5180 	int i;
5181 
5182 	assert_spin_locked(&mchdev_lock);
5183 
5184 	diff1 = now - dev_priv->ips.last_time1;
5185 
5186 	/* Prevent division-by-zero if we are asking too fast.
5187 	 * Also, we don't get interesting results if we are polling
5188 	 * faster than once in 10ms, so just return the saved value
5189 	 * in such cases.
5190 	 */
5191 	if (diff1 <= 10)
5192 		return dev_priv->ips.chipset_power;
5193 
5194 	count1 = I915_READ(DMIEC);
5195 	count2 = I915_READ(DDREC);
5196 	count3 = I915_READ(CSIEC);
5197 
5198 	total_count = count1 + count2 + count3;
5199 
5200 	/* FIXME: handle per-counter overflow */
5201 	if (total_count < dev_priv->ips.last_count1) {
5202 		diff = ~0UL - dev_priv->ips.last_count1;
5203 		diff += total_count;
5204 	} else {
5205 		diff = total_count - dev_priv->ips.last_count1;
5206 	}
5207 
5208 	for (i = 0; i < ARRAY_SIZE(cparams); i++) {
5209 		if (cparams[i].i == dev_priv->ips.c_m &&
5210 		    cparams[i].t == dev_priv->ips.r_t) {
5211 			m = cparams[i].m;
5212 			c = cparams[i].c;
5213 			break;
5214 		}
5215 	}
5216 
5217 	diff = div_u64(diff, diff1);
5218 	ret = ((m * diff) + c);
5219 	ret = div_u64(ret, 10);
5220 
5221 	dev_priv->ips.last_count1 = total_count;
5222 	dev_priv->ips.last_time1 = now;
5223 
5224 	dev_priv->ips.chipset_power = ret;
5225 
5226 	return ret;
5227 }
5228 
5229 unsigned long i915_chipset_val(struct drm_i915_private *dev_priv)
5230 {
5231 	struct drm_device *dev = dev_priv->dev;
5232 	unsigned long val;
5233 
5234 	if (INTEL_INFO(dev)->gen != 5)
5235 		return 0;
5236 
5237 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5238 
5239 	val = __i915_chipset_val(dev_priv);
5240 
5241 	lockmgr(&mchdev_lock, LK_RELEASE);
5242 
5243 	return val;
5244 }
5245 
5246 unsigned long i915_mch_val(struct drm_i915_private *dev_priv)
5247 {
5248 	unsigned long m, x, b;
5249 	u32 tsfs;
5250 
5251 	tsfs = I915_READ(TSFS);
5252 
5253 	m = ((tsfs & TSFS_SLOPE_MASK) >> TSFS_SLOPE_SHIFT);
5254 	x = I915_READ8(TR1);
5255 
5256 	b = tsfs & TSFS_INTR_MASK;
5257 
5258 	return ((m * x) / 127) - b;
5259 }
5260 
5261 static int _pxvid_to_vd(u8 pxvid)
5262 {
5263 	if (pxvid == 0)
5264 		return 0;
5265 
5266 	if (pxvid >= 8 && pxvid < 31)
5267 		pxvid = 31;
5268 
5269 	return (pxvid + 2) * 125;
5270 }
5271 
5272 static u32 pvid_to_extvid(struct drm_i915_private *dev_priv, u8 pxvid)
5273 {
5274 	struct drm_device *dev = dev_priv->dev;
5275 	const int vd = _pxvid_to_vd(pxvid);
5276 	const int vm = vd - 1125;
5277 
5278 	if (INTEL_INFO(dev)->is_mobile)
5279 		return vm > 0 ? vm : 0;
5280 
5281 	return vd;
5282 }
5283 
5284 static void __i915_update_gfx_val(struct drm_i915_private *dev_priv)
5285 {
5286 	u64 now, diff, diffms;
5287 	u32 count;
5288 
5289 	assert_spin_locked(&mchdev_lock);
5290 
5291 	now = ktime_get_raw_ns();
5292 	diffms = now - dev_priv->ips.last_time2;
5293 	do_div(diffms, NSEC_PER_MSEC);
5294 
5295 	/* Don't divide by 0 */
5296 	if (!diffms)
5297 		return;
5298 
5299 	count = I915_READ(GFXEC);
5300 
5301 	if (count < dev_priv->ips.last_count2) {
5302 		diff = ~0UL - dev_priv->ips.last_count2;
5303 		diff += count;
5304 	} else {
5305 		diff = count - dev_priv->ips.last_count2;
5306 	}
5307 
5308 	dev_priv->ips.last_count2 = count;
5309 	dev_priv->ips.last_time2 = now;
5310 
5311 	/* More magic constants... */
5312 	diff = diff * 1181;
5313 	diff = div_u64(diff, diffms * 10);
5314 	dev_priv->ips.gfx_power = diff;
5315 }
5316 
5317 void i915_update_gfx_val(struct drm_i915_private *dev_priv)
5318 {
5319 	struct drm_device *dev = dev_priv->dev;
5320 
5321 	if (INTEL_INFO(dev)->gen != 5)
5322 		return;
5323 
5324 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5325 
5326 	__i915_update_gfx_val(dev_priv);
5327 
5328 	lockmgr(&mchdev_lock, LK_RELEASE);
5329 }
5330 
5331 static unsigned long __i915_gfx_val(struct drm_i915_private *dev_priv)
5332 {
5333 	unsigned long t, corr, state1, corr2, state2;
5334 	u32 pxvid, ext_v;
5335 
5336 	assert_spin_locked(&mchdev_lock);
5337 
5338 	pxvid = I915_READ(PXVFREQ_BASE + (dev_priv->rps.cur_freq * 4));
5339 	pxvid = (pxvid >> 24) & 0x7f;
5340 	ext_v = pvid_to_extvid(dev_priv, pxvid);
5341 
5342 	state1 = ext_v;
5343 
5344 	t = i915_mch_val(dev_priv);
5345 
5346 	/* Revel in the empirically derived constants */
5347 
5348 	/* Correction factor in 1/100000 units */
5349 	if (t > 80)
5350 		corr = ((t * 2349) + 135940);
5351 	else if (t >= 50)
5352 		corr = ((t * 964) + 29317);
5353 	else /* < 50 */
5354 		corr = ((t * 301) + 1004);
5355 
5356 	corr = corr * ((150142 * state1) / 10000 - 78642);
5357 	corr /= 100000;
5358 	corr2 = (corr * dev_priv->ips.corr);
5359 
5360 	state2 = (corr2 * state1) / 10000;
5361 	state2 /= 100; /* convert to mW */
5362 
5363 	__i915_update_gfx_val(dev_priv);
5364 
5365 	return dev_priv->ips.gfx_power + state2;
5366 }
5367 
5368 unsigned long i915_gfx_val(struct drm_i915_private *dev_priv)
5369 {
5370 	struct drm_device *dev = dev_priv->dev;
5371 	unsigned long val;
5372 
5373 	if (INTEL_INFO(dev)->gen != 5)
5374 		return 0;
5375 
5376 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5377 
5378 	val = __i915_gfx_val(dev_priv);
5379 
5380 	lockmgr(&mchdev_lock, LK_RELEASE);
5381 
5382 	return val;
5383 }
5384 
5385 /**
5386  * i915_read_mch_val - return value for IPS use
5387  *
5388  * Calculate and return a value for the IPS driver to use when deciding whether
5389  * we have thermal and power headroom to increase CPU or GPU power budget.
5390  */
5391 unsigned long i915_read_mch_val(void)
5392 {
5393 	struct drm_i915_private *dev_priv;
5394 	unsigned long chipset_val, graphics_val, ret = 0;
5395 
5396 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5397 	if (!i915_mch_dev)
5398 		goto out_unlock;
5399 	dev_priv = i915_mch_dev;
5400 
5401 	chipset_val = __i915_chipset_val(dev_priv);
5402 	graphics_val = __i915_gfx_val(dev_priv);
5403 
5404 	ret = chipset_val + graphics_val;
5405 
5406 out_unlock:
5407 	lockmgr(&mchdev_lock, LK_RELEASE);
5408 
5409 	return ret;
5410 }
5411 
5412 /**
5413  * i915_gpu_raise - raise GPU frequency limit
5414  *
5415  * Raise the limit; IPS indicates we have thermal headroom.
5416  */
5417 bool i915_gpu_raise(void)
5418 {
5419 	struct drm_i915_private *dev_priv;
5420 	bool ret = true;
5421 
5422 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5423 	if (!i915_mch_dev) {
5424 		ret = false;
5425 		goto out_unlock;
5426 	}
5427 	dev_priv = i915_mch_dev;
5428 
5429 	if (dev_priv->ips.max_delay > dev_priv->ips.fmax)
5430 		dev_priv->ips.max_delay--;
5431 
5432 out_unlock:
5433 	lockmgr(&mchdev_lock, LK_RELEASE);
5434 
5435 	return ret;
5436 }
5437 
5438 /**
5439  * i915_gpu_lower - lower GPU frequency limit
5440  *
5441  * IPS indicates we're close to a thermal limit, so throttle back the GPU
5442  * frequency maximum.
5443  */
5444 bool i915_gpu_lower(void)
5445 {
5446 	struct drm_i915_private *dev_priv;
5447 	bool ret = true;
5448 
5449 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5450 	if (!i915_mch_dev) {
5451 		ret = false;
5452 		goto out_unlock;
5453 	}
5454 	dev_priv = i915_mch_dev;
5455 
5456 	if (dev_priv->ips.max_delay < dev_priv->ips.min_delay)
5457 		dev_priv->ips.max_delay++;
5458 
5459 out_unlock:
5460 	lockmgr(&mchdev_lock, LK_RELEASE);
5461 
5462 	return ret;
5463 }
5464 
5465 /**
5466  * i915_gpu_busy - indicate GPU business to IPS
5467  *
5468  * Tell the IPS driver whether or not the GPU is busy.
5469  */
5470 bool i915_gpu_busy(void)
5471 {
5472 	struct drm_i915_private *dev_priv;
5473 	struct intel_engine_cs *ring;
5474 	bool ret = false;
5475 	int i;
5476 
5477 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5478 	if (!i915_mch_dev)
5479 		goto out_unlock;
5480 	dev_priv = i915_mch_dev;
5481 
5482 	for_each_ring(ring, dev_priv, i)
5483 		ret |= !list_empty(&ring->request_list);
5484 
5485 out_unlock:
5486 	lockmgr(&mchdev_lock, LK_RELEASE);
5487 
5488 	return ret;
5489 }
5490 
5491 /**
5492  * i915_gpu_turbo_disable - disable graphics turbo
5493  *
5494  * Disable graphics turbo by resetting the max frequency and setting the
5495  * current frequency to the default.
5496  */
5497 bool i915_gpu_turbo_disable(void)
5498 {
5499 	struct drm_i915_private *dev_priv;
5500 	bool ret = true;
5501 
5502 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5503 	if (!i915_mch_dev) {
5504 		ret = false;
5505 		goto out_unlock;
5506 	}
5507 	dev_priv = i915_mch_dev;
5508 
5509 	dev_priv->ips.max_delay = dev_priv->ips.fstart;
5510 
5511 	if (!ironlake_set_drps(dev_priv->dev, dev_priv->ips.fstart))
5512 		ret = false;
5513 
5514 out_unlock:
5515 	lockmgr(&mchdev_lock, LK_RELEASE);
5516 
5517 	return ret;
5518 }
5519 
5520 #if 0
5521 /**
5522  * Tells the intel_ips driver that the i915 driver is now loaded, if
5523  * IPS got loaded first.
5524  *
5525  * This awkward dance is so that neither module has to depend on the
5526  * other in order for IPS to do the appropriate communication of
5527  * GPU turbo limits to i915.
5528  */
5529 static void
5530 ips_ping_for_i915_load(void)
5531 {
5532 	void (*link)(void);
5533 
5534 	link = symbol_get(ips_link_to_i915_driver);
5535 	if (link) {
5536 		link();
5537 		symbol_put(ips_link_to_i915_driver);
5538 	}
5539 }
5540 #endif
5541 
5542 void intel_gpu_ips_init(struct drm_i915_private *dev_priv)
5543 {
5544 	/* We only register the i915 ips part with intel-ips once everything is
5545 	 * set up, to avoid intel-ips sneaking in and reading bogus values. */
5546 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5547 	i915_mch_dev = dev_priv;
5548 	lockmgr(&mchdev_lock, LK_RELEASE);
5549 }
5550 
5551 void intel_gpu_ips_teardown(void)
5552 {
5553 	lockmgr(&mchdev_lock, LK_EXCLUSIVE);
5554 	i915_mch_dev = NULL;
5555 	lockmgr(&mchdev_lock, LK_RELEASE);
5556 }
5557 
5558 static void intel_init_emon(struct drm_device *dev)
5559 {
5560 	struct drm_i915_private *dev_priv = dev->dev_private;
5561 	u32 lcfuse;
5562 	u8 pxw[16];
5563 	int i;
5564 
5565 	/* Disable to program */
5566 	I915_WRITE(ECR, 0);
5567 	POSTING_READ(ECR);
5568 
5569 	/* Program energy weights for various events */
5570 	I915_WRITE(SDEW, 0x15040d00);
5571 	I915_WRITE(CSIEW0, 0x007f0000);
5572 	I915_WRITE(CSIEW1, 0x1e220004);
5573 	I915_WRITE(CSIEW2, 0x04000004);
5574 
5575 	for (i = 0; i < 5; i++)
5576 		I915_WRITE(PEW + (i * 4), 0);
5577 	for (i = 0; i < 3; i++)
5578 		I915_WRITE(DEW + (i * 4), 0);
5579 
5580 	/* Program P-state weights to account for frequency power adjustment */
5581 	for (i = 0; i < 16; i++) {
5582 		u32 pxvidfreq = I915_READ(PXVFREQ_BASE + (i * 4));
5583 		unsigned long freq = intel_pxfreq(pxvidfreq);
5584 		unsigned long vid = (pxvidfreq & PXVFREQ_PX_MASK) >>
5585 			PXVFREQ_PX_SHIFT;
5586 		unsigned long val;
5587 
5588 		val = vid * vid;
5589 		val *= (freq / 1000);
5590 		val *= 255;
5591 		val /= (127*127*900);
5592 		if (val > 0xff)
5593 			DRM_ERROR("bad pxval: %ld\n", val);
5594 		pxw[i] = val;
5595 	}
5596 	/* Render standby states get 0 weight */
5597 	pxw[14] = 0;
5598 	pxw[15] = 0;
5599 
5600 	for (i = 0; i < 4; i++) {
5601 		u32 val = (pxw[i*4] << 24) | (pxw[(i*4)+1] << 16) |
5602 			(pxw[(i*4)+2] << 8) | (pxw[(i*4)+3]);
5603 		I915_WRITE(PXW + (i * 4), val);
5604 	}
5605 
5606 	/* Adjust magic regs to magic values (more experimental results) */
5607 	I915_WRITE(OGW0, 0);
5608 	I915_WRITE(OGW1, 0);
5609 	I915_WRITE(EG0, 0x00007f00);
5610 	I915_WRITE(EG1, 0x0000000e);
5611 	I915_WRITE(EG2, 0x000e0000);
5612 	I915_WRITE(EG3, 0x68000300);
5613 	I915_WRITE(EG4, 0x42000000);
5614 	I915_WRITE(EG5, 0x00140031);
5615 	I915_WRITE(EG6, 0);
5616 	I915_WRITE(EG7, 0);
5617 
5618 	for (i = 0; i < 8; i++)
5619 		I915_WRITE(PXWL + (i * 4), 0);
5620 
5621 	/* Enable PMON + select events */
5622 	I915_WRITE(ECR, 0x80000019);
5623 
5624 	lcfuse = I915_READ(LCFUSE02);
5625 
5626 	dev_priv->ips.corr = (lcfuse & LCFUSE_HIV_MASK);
5627 }
5628 
5629 void intel_init_gt_powersave(struct drm_device *dev)
5630 {
5631 	i915.enable_rc6 = sanitize_rc6_option(dev, i915.enable_rc6);
5632 
5633 	if (IS_CHERRYVIEW(dev))
5634 		cherryview_init_gt_powersave(dev);
5635 	else if (IS_VALLEYVIEW(dev))
5636 		valleyview_init_gt_powersave(dev);
5637 }
5638 
5639 void intel_cleanup_gt_powersave(struct drm_device *dev)
5640 {
5641 	if (IS_CHERRYVIEW(dev))
5642 		return;
5643 	else if (IS_VALLEYVIEW(dev))
5644 		valleyview_cleanup_gt_powersave(dev);
5645 }
5646 
5647 static void gen6_suspend_rps(struct drm_device *dev)
5648 {
5649 #if 0
5650 	struct drm_i915_private *dev_priv = dev->dev_private;
5651 
5652 	flush_delayed_work(&dev_priv->rps.delayed_resume_work);
5653 #endif
5654 
5655 	gen6_disable_rps_interrupts(dev);
5656 }
5657 
5658 /**
5659  * intel_suspend_gt_powersave - suspend PM work and helper threads
5660  * @dev: drm device
5661  *
5662  * We don't want to disable RC6 or other features here, we just want
5663  * to make sure any work we've queued has finished and won't bother
5664  * us while we're suspended.
5665  */
5666 void intel_suspend_gt_powersave(struct drm_device *dev)
5667 {
5668 	struct drm_i915_private *dev_priv = dev->dev_private;
5669 
5670 	if (INTEL_INFO(dev)->gen < 6)
5671 		return;
5672 
5673 	gen6_suspend_rps(dev);
5674 
5675 	/* Force GPU to min freq during suspend */
5676 	gen6_rps_idle(dev_priv);
5677 }
5678 
5679 void intel_disable_gt_powersave(struct drm_device *dev)
5680 {
5681 	struct drm_i915_private *dev_priv = dev->dev_private;
5682 
5683 	if (IS_IRONLAKE_M(dev)) {
5684 		ironlake_disable_drps(dev);
5685 	} else if (INTEL_INFO(dev)->gen >= 6) {
5686 		intel_suspend_gt_powersave(dev);
5687 
5688 		mutex_lock(&dev_priv->rps.hw_lock);
5689 		if (INTEL_INFO(dev)->gen >= 9)
5690 			gen9_disable_rps(dev);
5691 		else if (IS_CHERRYVIEW(dev))
5692 			cherryview_disable_rps(dev);
5693 		else if (IS_VALLEYVIEW(dev))
5694 			valleyview_disable_rps(dev);
5695 		else
5696 			gen6_disable_rps(dev);
5697 
5698 		dev_priv->rps.enabled = false;
5699 		mutex_unlock(&dev_priv->rps.hw_lock);
5700 	}
5701 }
5702 
5703 static void intel_gen6_powersave_work(struct work_struct *work)
5704 {
5705 	struct drm_i915_private *dev_priv =
5706 		container_of(work, struct drm_i915_private,
5707 			     rps.delayed_resume_work.work);
5708 	struct drm_device *dev = dev_priv->dev;
5709 
5710 	mutex_lock(&dev_priv->rps.hw_lock);
5711 
5712 	gen6_reset_rps_interrupts(dev);
5713 
5714 	if (IS_CHERRYVIEW(dev)) {
5715 		cherryview_enable_rps(dev);
5716 	} else if (IS_VALLEYVIEW(dev)) {
5717 		valleyview_enable_rps(dev);
5718 	} else if (INTEL_INFO(dev)->gen >= 9) {
5719 		gen9_enable_rc6(dev);
5720 		gen9_enable_rps(dev);
5721 		__gen6_update_ring_freq(dev);
5722 	} else if (IS_BROADWELL(dev)) {
5723 		gen8_enable_rps(dev);
5724 		__gen6_update_ring_freq(dev);
5725 	} else {
5726 		gen6_enable_rps(dev);
5727 		__gen6_update_ring_freq(dev);
5728 	}
5729 
5730 	WARN_ON(dev_priv->rps.max_freq < dev_priv->rps.min_freq);
5731 	WARN_ON(dev_priv->rps.idle_freq > dev_priv->rps.max_freq);
5732 
5733 	WARN_ON(dev_priv->rps.efficient_freq < dev_priv->rps.min_freq);
5734 	WARN_ON(dev_priv->rps.efficient_freq > dev_priv->rps.max_freq);
5735 
5736 	dev_priv->rps.enabled = true;
5737 
5738 	gen6_enable_rps_interrupts(dev);
5739 
5740 	mutex_unlock(&dev_priv->rps.hw_lock);
5741 
5742 	intel_runtime_pm_put(dev_priv);
5743 }
5744 
5745 void intel_enable_gt_powersave(struct drm_device *dev)
5746 {
5747 	struct drm_i915_private *dev_priv = dev->dev_private;
5748 
5749 	/* Powersaving is controlled by the host when inside a VM */
5750 	if (intel_vgpu_active(dev))
5751 		return;
5752 
5753 	if (IS_IRONLAKE_M(dev)) {
5754 		mutex_lock(&dev->struct_mutex);
5755 		ironlake_enable_drps(dev);
5756 		intel_init_emon(dev);
5757 		mutex_unlock(&dev->struct_mutex);
5758 	} else if (INTEL_INFO(dev)->gen >= 6) {
5759 		/*
5760 		 * PCU communication is slow and this doesn't need to be
5761 		 * done at any specific time, so do this out of our fast path
5762 		 * to make resume and init faster.
5763 		 *
5764 		 * We depend on the HW RC6 power context save/restore
5765 		 * mechanism when entering D3 through runtime PM suspend. So
5766 		 * disable RPM until RPS/RC6 is properly setup. We can only
5767 		 * get here via the driver load/system resume/runtime resume
5768 		 * paths, so the _noresume version is enough (and in case of
5769 		 * runtime resume it's necessary).
5770 		 */
5771 		if (schedule_delayed_work(&dev_priv->rps.delayed_resume_work,
5772 					   round_jiffies_up_relative(HZ)))
5773 			intel_runtime_pm_get_noresume(dev_priv);
5774 	}
5775 }
5776 
5777 void intel_reset_gt_powersave(struct drm_device *dev)
5778 {
5779 	struct drm_i915_private *dev_priv = dev->dev_private;
5780 
5781 	if (INTEL_INFO(dev)->gen < 6)
5782 		return;
5783 
5784 	gen6_suspend_rps(dev);
5785 	dev_priv->rps.enabled = false;
5786 }
5787 
5788 static void ibx_init_clock_gating(struct drm_device *dev)
5789 {
5790 	struct drm_i915_private *dev_priv = dev->dev_private;
5791 
5792 	/*
5793 	 * On Ibex Peak and Cougar Point, we need to disable clock
5794 	 * gating for the panel power sequencer or it will fail to
5795 	 * start up when no ports are active.
5796 	 */
5797 	I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE);
5798 }
5799 
5800 static void g4x_disable_trickle_feed(struct drm_device *dev)
5801 {
5802 	struct drm_i915_private *dev_priv = dev->dev_private;
5803 	int pipe;
5804 
5805 	for_each_pipe(dev_priv, pipe) {
5806 		I915_WRITE(DSPCNTR(pipe),
5807 			   I915_READ(DSPCNTR(pipe)) |
5808 			   DISPPLANE_TRICKLE_FEED_DISABLE);
5809 		intel_flush_primary_plane(dev_priv, pipe);
5810 	}
5811 }
5812 
5813 static void ilk_init_lp_watermarks(struct drm_device *dev)
5814 {
5815 	struct drm_i915_private *dev_priv = dev->dev_private;
5816 
5817 	I915_WRITE(WM3_LP_ILK, I915_READ(WM3_LP_ILK) & ~WM1_LP_SR_EN);
5818 	I915_WRITE(WM2_LP_ILK, I915_READ(WM2_LP_ILK) & ~WM1_LP_SR_EN);
5819 	I915_WRITE(WM1_LP_ILK, I915_READ(WM1_LP_ILK) & ~WM1_LP_SR_EN);
5820 
5821 	/*
5822 	 * Don't touch WM1S_LP_EN here.
5823 	 * Doing so could cause underruns.
5824 	 */
5825 }
5826 
5827 static void ironlake_init_clock_gating(struct drm_device *dev)
5828 {
5829 	struct drm_i915_private *dev_priv = dev->dev_private;
5830 	uint32_t dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
5831 
5832 	/*
5833 	 * Required for FBC
5834 	 * WaFbcDisableDpfcClockGating:ilk
5835 	 */
5836 	dspclk_gate |= ILK_DPFCRUNIT_CLOCK_GATE_DISABLE |
5837 		   ILK_DPFCUNIT_CLOCK_GATE_DISABLE |
5838 		   ILK_DPFDUNIT_CLOCK_GATE_ENABLE;
5839 
5840 	I915_WRITE(PCH_3DCGDIS0,
5841 		   MARIUNIT_CLOCK_GATE_DISABLE |
5842 		   SVSMUNIT_CLOCK_GATE_DISABLE);
5843 	I915_WRITE(PCH_3DCGDIS1,
5844 		   VFMUNIT_CLOCK_GATE_DISABLE);
5845 
5846 	/*
5847 	 * According to the spec the following bits should be set in
5848 	 * order to enable memory self-refresh
5849 	 * The bit 22/21 of 0x42004
5850 	 * The bit 5 of 0x42020
5851 	 * The bit 15 of 0x45000
5852 	 */
5853 	I915_WRITE(ILK_DISPLAY_CHICKEN2,
5854 		   (I915_READ(ILK_DISPLAY_CHICKEN2) |
5855 		    ILK_DPARB_GATE | ILK_VSDPFD_FULL));
5856 	dspclk_gate |= ILK_DPARBUNIT_CLOCK_GATE_ENABLE;
5857 	I915_WRITE(DISP_ARB_CTL,
5858 		   (I915_READ(DISP_ARB_CTL) |
5859 		    DISP_FBC_WM_DIS));
5860 
5861 	ilk_init_lp_watermarks(dev);
5862 
5863 	/*
5864 	 * Based on the document from hardware guys the following bits
5865 	 * should be set unconditionally in order to enable FBC.
5866 	 * The bit 22 of 0x42000
5867 	 * The bit 22 of 0x42004
5868 	 * The bit 7,8,9 of 0x42020.
5869 	 */
5870 	if (IS_IRONLAKE_M(dev)) {
5871 		/* WaFbcAsynchFlipDisableFbcQueue:ilk */
5872 		I915_WRITE(ILK_DISPLAY_CHICKEN1,
5873 			   I915_READ(ILK_DISPLAY_CHICKEN1) |
5874 			   ILK_FBCQ_DIS);
5875 		I915_WRITE(ILK_DISPLAY_CHICKEN2,
5876 			   I915_READ(ILK_DISPLAY_CHICKEN2) |
5877 			   ILK_DPARB_GATE);
5878 	}
5879 
5880 	I915_WRITE(ILK_DSPCLK_GATE_D, dspclk_gate);
5881 
5882 	I915_WRITE(ILK_DISPLAY_CHICKEN2,
5883 		   I915_READ(ILK_DISPLAY_CHICKEN2) |
5884 		   ILK_ELPIN_409_SELECT);
5885 	I915_WRITE(_3D_CHICKEN2,
5886 		   _3D_CHICKEN2_WM_READ_PIPELINED << 16 |
5887 		   _3D_CHICKEN2_WM_READ_PIPELINED);
5888 
5889 	/* WaDisableRenderCachePipelinedFlush:ilk */
5890 	I915_WRITE(CACHE_MODE_0,
5891 		   _MASKED_BIT_ENABLE(CM0_PIPELINED_RENDER_FLUSH_DISABLE));
5892 
5893 	/* WaDisable_RenderCache_OperationalFlush:ilk */
5894 	I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
5895 
5896 	g4x_disable_trickle_feed(dev);
5897 
5898 	ibx_init_clock_gating(dev);
5899 }
5900 
5901 static void cpt_init_clock_gating(struct drm_device *dev)
5902 {
5903 	struct drm_i915_private *dev_priv = dev->dev_private;
5904 	int pipe;
5905 	uint32_t val;
5906 
5907 	/*
5908 	 * On Ibex Peak and Cougar Point, we need to disable clock
5909 	 * gating for the panel power sequencer or it will fail to
5910 	 * start up when no ports are active.
5911 	 */
5912 	I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE |
5913 		   PCH_DPLUNIT_CLOCK_GATE_DISABLE |
5914 		   PCH_CPUNIT_CLOCK_GATE_DISABLE);
5915 	I915_WRITE(SOUTH_CHICKEN2, I915_READ(SOUTH_CHICKEN2) |
5916 		   DPLS_EDP_PPS_FIX_DIS);
5917 	/* The below fixes the weird display corruption, a few pixels shifted
5918 	 * downward, on (only) LVDS of some HP laptops with IVY.
5919 	 */
5920 	for_each_pipe(dev_priv, pipe) {
5921 		val = I915_READ(TRANS_CHICKEN2(pipe));
5922 		val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
5923 		val &= ~TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
5924 		if (dev_priv->vbt.fdi_rx_polarity_inverted)
5925 			val |= TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
5926 		val &= ~TRANS_CHICKEN2_FRAME_START_DELAY_MASK;
5927 		val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_COUNTER;
5928 		val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_MODESWITCH;
5929 		I915_WRITE(TRANS_CHICKEN2(pipe), val);
5930 	}
5931 	/* WADP0ClockGatingDisable */
5932 	for_each_pipe(dev_priv, pipe) {
5933 		I915_WRITE(TRANS_CHICKEN1(pipe),
5934 			   TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
5935 	}
5936 }
5937 
5938 static void gen6_check_mch_setup(struct drm_device *dev)
5939 {
5940 	struct drm_i915_private *dev_priv = dev->dev_private;
5941 	uint32_t tmp;
5942 
5943 	tmp = I915_READ(MCH_SSKPD);
5944 	if ((tmp & MCH_SSKPD_WM0_MASK) != MCH_SSKPD_WM0_VAL)
5945 		DRM_DEBUG_KMS("Wrong MCH_SSKPD value: 0x%08x This can cause underruns.\n",
5946 			      tmp);
5947 }
5948 
5949 static void gen6_init_clock_gating(struct drm_device *dev)
5950 {
5951 	struct drm_i915_private *dev_priv = dev->dev_private;
5952 	uint32_t dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
5953 
5954 	I915_WRITE(ILK_DSPCLK_GATE_D, dspclk_gate);
5955 
5956 	I915_WRITE(ILK_DISPLAY_CHICKEN2,
5957 		   I915_READ(ILK_DISPLAY_CHICKEN2) |
5958 		   ILK_ELPIN_409_SELECT);
5959 
5960 	/* WaDisableHiZPlanesWhenMSAAEnabled:snb */
5961 	I915_WRITE(_3D_CHICKEN,
5962 		   _MASKED_BIT_ENABLE(_3D_CHICKEN_HIZ_PLANE_DISABLE_MSAA_4X_SNB));
5963 
5964 	/* WaDisable_RenderCache_OperationalFlush:snb */
5965 	I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
5966 
5967 	/*
5968 	 * BSpec recoomends 8x4 when MSAA is used,
5969 	 * however in practice 16x4 seems fastest.
5970 	 *
5971 	 * Note that PS/WM thread counts depend on the WIZ hashing
5972 	 * disable bit, which we don't touch here, but it's good
5973 	 * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
5974 	 */
5975 	I915_WRITE(GEN6_GT_MODE,
5976 		   _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
5977 
5978 	ilk_init_lp_watermarks(dev);
5979 
5980 	I915_WRITE(CACHE_MODE_0,
5981 		   _MASKED_BIT_DISABLE(CM0_STC_EVICT_DISABLE_LRA_SNB));
5982 
5983 	I915_WRITE(GEN6_UCGCTL1,
5984 		   I915_READ(GEN6_UCGCTL1) |
5985 		   GEN6_BLBUNIT_CLOCK_GATE_DISABLE |
5986 		   GEN6_CSUNIT_CLOCK_GATE_DISABLE);
5987 
5988 	/* According to the BSpec vol1g, bit 12 (RCPBUNIT) clock
5989 	 * gating disable must be set.  Failure to set it results in
5990 	 * flickering pixels due to Z write ordering failures after
5991 	 * some amount of runtime in the Mesa "fire" demo, and Unigine
5992 	 * Sanctuary and Tropics, and apparently anything else with
5993 	 * alpha test or pixel discard.
5994 	 *
5995 	 * According to the spec, bit 11 (RCCUNIT) must also be set,
5996 	 * but we didn't debug actual testcases to find it out.
5997 	 *
5998 	 * WaDisableRCCUnitClockGating:snb
5999 	 * WaDisableRCPBUnitClockGating:snb
6000 	 */
6001 	I915_WRITE(GEN6_UCGCTL2,
6002 		   GEN6_RCPBUNIT_CLOCK_GATE_DISABLE |
6003 		   GEN6_RCCUNIT_CLOCK_GATE_DISABLE);
6004 
6005 	/* WaStripsFansDisableFastClipPerformanceFix:snb */
6006 	I915_WRITE(_3D_CHICKEN3,
6007 		   _MASKED_BIT_ENABLE(_3D_CHICKEN3_SF_DISABLE_FASTCLIP_CULL));
6008 
6009 	/*
6010 	 * Bspec says:
6011 	 * "This bit must be set if 3DSTATE_CLIP clip mode is set to normal and
6012 	 * 3DSTATE_SF number of SF output attributes is more than 16."
6013 	 */
6014 	I915_WRITE(_3D_CHICKEN3,
6015 		   _MASKED_BIT_ENABLE(_3D_CHICKEN3_SF_DISABLE_PIPELINED_ATTR_FETCH));
6016 
6017 	/*
6018 	 * According to the spec the following bits should be
6019 	 * set in order to enable memory self-refresh and fbc:
6020 	 * The bit21 and bit22 of 0x42000
6021 	 * The bit21 and bit22 of 0x42004
6022 	 * The bit5 and bit7 of 0x42020
6023 	 * The bit14 of 0x70180
6024 	 * The bit14 of 0x71180
6025 	 *
6026 	 * WaFbcAsynchFlipDisableFbcQueue:snb
6027 	 */
6028 	I915_WRITE(ILK_DISPLAY_CHICKEN1,
6029 		   I915_READ(ILK_DISPLAY_CHICKEN1) |
6030 		   ILK_FBCQ_DIS | ILK_PABSTRETCH_DIS);
6031 	I915_WRITE(ILK_DISPLAY_CHICKEN2,
6032 		   I915_READ(ILK_DISPLAY_CHICKEN2) |
6033 		   ILK_DPARB_GATE | ILK_VSDPFD_FULL);
6034 	I915_WRITE(ILK_DSPCLK_GATE_D,
6035 		   I915_READ(ILK_DSPCLK_GATE_D) |
6036 		   ILK_DPARBUNIT_CLOCK_GATE_ENABLE  |
6037 		   ILK_DPFDUNIT_CLOCK_GATE_ENABLE);
6038 
6039 	g4x_disable_trickle_feed(dev);
6040 
6041 	cpt_init_clock_gating(dev);
6042 
6043 	gen6_check_mch_setup(dev);
6044 }
6045 
6046 static void gen7_setup_fixed_func_scheduler(struct drm_i915_private *dev_priv)
6047 {
6048 	uint32_t reg = I915_READ(GEN7_FF_THREAD_MODE);
6049 
6050 	/*
6051 	 * WaVSThreadDispatchOverride:ivb,vlv
6052 	 *
6053 	 * This actually overrides the dispatch
6054 	 * mode for all thread types.
6055 	 */
6056 	reg &= ~GEN7_FF_SCHED_MASK;
6057 	reg |= GEN7_FF_TS_SCHED_HW;
6058 	reg |= GEN7_FF_VS_SCHED_HW;
6059 	reg |= GEN7_FF_DS_SCHED_HW;
6060 
6061 	I915_WRITE(GEN7_FF_THREAD_MODE, reg);
6062 }
6063 
6064 static void lpt_init_clock_gating(struct drm_device *dev)
6065 {
6066 	struct drm_i915_private *dev_priv = dev->dev_private;
6067 
6068 	/*
6069 	 * TODO: this bit should only be enabled when really needed, then
6070 	 * disabled when not needed anymore in order to save power.
6071 	 */
6072 	if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE)
6073 		I915_WRITE(SOUTH_DSPCLK_GATE_D,
6074 			   I915_READ(SOUTH_DSPCLK_GATE_D) |
6075 			   PCH_LP_PARTITION_LEVEL_DISABLE);
6076 
6077 	/* WADPOClockGatingDisable:hsw */
6078 	I915_WRITE(_TRANSA_CHICKEN1,
6079 		   I915_READ(_TRANSA_CHICKEN1) |
6080 		   TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
6081 }
6082 
6083 static void lpt_suspend_hw(struct drm_device *dev)
6084 {
6085 	struct drm_i915_private *dev_priv = dev->dev_private;
6086 
6087 	if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
6088 		uint32_t val = I915_READ(SOUTH_DSPCLK_GATE_D);
6089 
6090 		val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
6091 		I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
6092 	}
6093 }
6094 
6095 static void broadwell_init_clock_gating(struct drm_device *dev)
6096 {
6097 	struct drm_i915_private *dev_priv = dev->dev_private;
6098 	enum i915_pipe pipe;
6099 
6100 	I915_WRITE(WM3_LP_ILK, 0);
6101 	I915_WRITE(WM2_LP_ILK, 0);
6102 	I915_WRITE(WM1_LP_ILK, 0);
6103 
6104 	/* WaSwitchSolVfFArbitrationPriority:bdw */
6105 	I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) | HSW_ECOCHK_ARB_PRIO_SOL);
6106 
6107 	/* WaPsrDPAMaskVBlankInSRD:bdw */
6108 	I915_WRITE(CHICKEN_PAR1_1,
6109 		   I915_READ(CHICKEN_PAR1_1) | DPA_MASK_VBLANK_SRD);
6110 
6111 	/* WaPsrDPRSUnmaskVBlankInSRD:bdw */
6112 	for_each_pipe(dev_priv, pipe) {
6113 		I915_WRITE(CHICKEN_PIPESL_1(pipe),
6114 			   I915_READ(CHICKEN_PIPESL_1(pipe)) |
6115 			   BDW_DPRS_MASK_VBLANK_SRD);
6116 	}
6117 
6118 	/* WaVSRefCountFullforceMissDisable:bdw */
6119 	/* WaDSRefCountFullforceMissDisable:bdw */
6120 	I915_WRITE(GEN7_FF_THREAD_MODE,
6121 		   I915_READ(GEN7_FF_THREAD_MODE) &
6122 		   ~(GEN8_FF_DS_REF_CNT_FFME | GEN7_FF_VS_REF_CNT_FFME));
6123 
6124 	I915_WRITE(GEN6_RC_SLEEP_PSMI_CONTROL,
6125 		   _MASKED_BIT_ENABLE(GEN8_RC_SEMA_IDLE_MSG_DISABLE));
6126 
6127 	/* WaDisableSDEUnitClockGating:bdw */
6128 	I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
6129 		   GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
6130 
6131 	lpt_init_clock_gating(dev);
6132 }
6133 
6134 static void haswell_init_clock_gating(struct drm_device *dev)
6135 {
6136 	struct drm_i915_private *dev_priv = dev->dev_private;
6137 
6138 	ilk_init_lp_watermarks(dev);
6139 
6140 	/* L3 caching of data atomics doesn't work -- disable it. */
6141 	I915_WRITE(HSW_SCRATCH1, HSW_SCRATCH1_L3_DATA_ATOMICS_DISABLE);
6142 	I915_WRITE(HSW_ROW_CHICKEN3,
6143 		   _MASKED_BIT_ENABLE(HSW_ROW_CHICKEN3_L3_GLOBAL_ATOMICS_DISABLE));
6144 
6145 	/* This is required by WaCatErrorRejectionIssue:hsw */
6146 	I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6147 			I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6148 			GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6149 
6150 	/* WaVSRefCountFullforceMissDisable:hsw */
6151 	I915_WRITE(GEN7_FF_THREAD_MODE,
6152 		   I915_READ(GEN7_FF_THREAD_MODE) & ~GEN7_FF_VS_REF_CNT_FFME);
6153 
6154 	/* WaDisable_RenderCache_OperationalFlush:hsw */
6155 	I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6156 
6157 	/* enable HiZ Raw Stall Optimization */
6158 	I915_WRITE(CACHE_MODE_0_GEN7,
6159 		   _MASKED_BIT_DISABLE(HIZ_RAW_STALL_OPT_DISABLE));
6160 
6161 	/* WaDisable4x2SubspanOptimization:hsw */
6162 	I915_WRITE(CACHE_MODE_1,
6163 		   _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6164 
6165 	/*
6166 	 * BSpec recommends 8x4 when MSAA is used,
6167 	 * however in practice 16x4 seems fastest.
6168 	 *
6169 	 * Note that PS/WM thread counts depend on the WIZ hashing
6170 	 * disable bit, which we don't touch here, but it's good
6171 	 * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6172 	 */
6173 	I915_WRITE(GEN7_GT_MODE,
6174 		   _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6175 
6176 	/* WaSampleCChickenBitEnable:hsw */
6177 	I915_WRITE(HALF_SLICE_CHICKEN3,
6178 		   _MASKED_BIT_ENABLE(HSW_SAMPLE_C_PERFORMANCE));
6179 
6180 	/* WaSwitchSolVfFArbitrationPriority:hsw */
6181 	I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) | HSW_ECOCHK_ARB_PRIO_SOL);
6182 
6183 	/* WaRsPkgCStateDisplayPMReq:hsw */
6184 	I915_WRITE(CHICKEN_PAR1_1,
6185 		   I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
6186 
6187 	lpt_init_clock_gating(dev);
6188 }
6189 
6190 static void ivybridge_init_clock_gating(struct drm_device *dev)
6191 {
6192 	struct drm_i915_private *dev_priv = dev->dev_private;
6193 	uint32_t snpcr;
6194 
6195 	ilk_init_lp_watermarks(dev);
6196 
6197 	I915_WRITE(ILK_DSPCLK_GATE_D, ILK_VRHUNIT_CLOCK_GATE_DISABLE);
6198 
6199 	/* WaDisableEarlyCull:ivb */
6200 	I915_WRITE(_3D_CHICKEN3,
6201 		   _MASKED_BIT_ENABLE(_3D_CHICKEN_SF_DISABLE_OBJEND_CULL));
6202 
6203 	/* WaDisableBackToBackFlipFix:ivb */
6204 	I915_WRITE(IVB_CHICKEN3,
6205 		   CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
6206 		   CHICKEN3_DGMG_DONE_FIX_DISABLE);
6207 
6208 	/* WaDisablePSDDualDispatchEnable:ivb */
6209 	if (IS_IVB_GT1(dev))
6210 		I915_WRITE(GEN7_HALF_SLICE_CHICKEN1,
6211 			   _MASKED_BIT_ENABLE(GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
6212 
6213 	/* WaDisable_RenderCache_OperationalFlush:ivb */
6214 	I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6215 
6216 	/* Apply the WaDisableRHWOOptimizationForRenderHang:ivb workaround. */
6217 	I915_WRITE(GEN7_COMMON_SLICE_CHICKEN1,
6218 		   GEN7_CSC1_RHWO_OPT_DISABLE_IN_RCC);
6219 
6220 	/* WaApplyL3ControlAndL3ChickenMode:ivb */
6221 	I915_WRITE(GEN7_L3CNTLREG1,
6222 			GEN7_WA_FOR_GEN7_L3_CONTROL);
6223 	I915_WRITE(GEN7_L3_CHICKEN_MODE_REGISTER,
6224 		   GEN7_WA_L3_CHICKEN_MODE);
6225 	if (IS_IVB_GT1(dev))
6226 		I915_WRITE(GEN7_ROW_CHICKEN2,
6227 			   _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6228 	else {
6229 		/* must write both registers */
6230 		I915_WRITE(GEN7_ROW_CHICKEN2,
6231 			   _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6232 		I915_WRITE(GEN7_ROW_CHICKEN2_GT2,
6233 			   _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6234 	}
6235 
6236 	/* WaForceL3Serialization:ivb */
6237 	I915_WRITE(GEN7_L3SQCREG4, I915_READ(GEN7_L3SQCREG4) &
6238 		   ~L3SQ_URB_READ_CAM_MATCH_DISABLE);
6239 
6240 	/*
6241 	 * According to the spec, bit 13 (RCZUNIT) must be set on IVB.
6242 	 * This implements the WaDisableRCZUnitClockGating:ivb workaround.
6243 	 */
6244 	I915_WRITE(GEN6_UCGCTL2,
6245 		   GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
6246 
6247 	/* This is required by WaCatErrorRejectionIssue:ivb */
6248 	I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6249 			I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6250 			GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6251 
6252 	g4x_disable_trickle_feed(dev);
6253 
6254 	gen7_setup_fixed_func_scheduler(dev_priv);
6255 
6256 	if (0) { /* causes HiZ corruption on ivb:gt1 */
6257 		/* enable HiZ Raw Stall Optimization */
6258 		I915_WRITE(CACHE_MODE_0_GEN7,
6259 			   _MASKED_BIT_DISABLE(HIZ_RAW_STALL_OPT_DISABLE));
6260 	}
6261 
6262 	/* WaDisable4x2SubspanOptimization:ivb */
6263 	I915_WRITE(CACHE_MODE_1,
6264 		   _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6265 
6266 	/*
6267 	 * BSpec recommends 8x4 when MSAA is used,
6268 	 * however in practice 16x4 seems fastest.
6269 	 *
6270 	 * Note that PS/WM thread counts depend on the WIZ hashing
6271 	 * disable bit, which we don't touch here, but it's good
6272 	 * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6273 	 */
6274 	I915_WRITE(GEN7_GT_MODE,
6275 		   _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6276 
6277 	snpcr = I915_READ(GEN6_MBCUNIT_SNPCR);
6278 	snpcr &= ~GEN6_MBC_SNPCR_MASK;
6279 	snpcr |= GEN6_MBC_SNPCR_MED;
6280 	I915_WRITE(GEN6_MBCUNIT_SNPCR, snpcr);
6281 
6282 	if (!HAS_PCH_NOP(dev))
6283 		cpt_init_clock_gating(dev);
6284 
6285 	gen6_check_mch_setup(dev);
6286 }
6287 
6288 static void vlv_init_display_clock_gating(struct drm_i915_private *dev_priv)
6289 {
6290 	I915_WRITE(DSPCLK_GATE_D, VRHUNIT_CLOCK_GATE_DISABLE);
6291 
6292 	/*
6293 	 * Disable trickle feed and enable pnd deadline calculation
6294 	 */
6295 	I915_WRITE(MI_ARB_VLV, MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE);
6296 	I915_WRITE(CBR1_VLV, 0);
6297 }
6298 
6299 static void valleyview_init_clock_gating(struct drm_device *dev)
6300 {
6301 	struct drm_i915_private *dev_priv = dev->dev_private;
6302 
6303 	vlv_init_display_clock_gating(dev_priv);
6304 
6305 	/* WaDisableEarlyCull:vlv */
6306 	I915_WRITE(_3D_CHICKEN3,
6307 		   _MASKED_BIT_ENABLE(_3D_CHICKEN_SF_DISABLE_OBJEND_CULL));
6308 
6309 	/* WaDisableBackToBackFlipFix:vlv */
6310 	I915_WRITE(IVB_CHICKEN3,
6311 		   CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
6312 		   CHICKEN3_DGMG_DONE_FIX_DISABLE);
6313 
6314 	/* WaPsdDispatchEnable:vlv */
6315 	/* WaDisablePSDDualDispatchEnable:vlv */
6316 	I915_WRITE(GEN7_HALF_SLICE_CHICKEN1,
6317 		   _MASKED_BIT_ENABLE(GEN7_MAX_PS_THREAD_DEP |
6318 				      GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
6319 
6320 	/* WaDisable_RenderCache_OperationalFlush:vlv */
6321 	I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6322 
6323 	/* WaForceL3Serialization:vlv */
6324 	I915_WRITE(GEN7_L3SQCREG4, I915_READ(GEN7_L3SQCREG4) &
6325 		   ~L3SQ_URB_READ_CAM_MATCH_DISABLE);
6326 
6327 	/* WaDisableDopClockGating:vlv */
6328 	I915_WRITE(GEN7_ROW_CHICKEN2,
6329 		   _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6330 
6331 	/* This is required by WaCatErrorRejectionIssue:vlv */
6332 	I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6333 		   I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6334 		   GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6335 
6336 	gen7_setup_fixed_func_scheduler(dev_priv);
6337 
6338 	/*
6339 	 * According to the spec, bit 13 (RCZUNIT) must be set on IVB.
6340 	 * This implements the WaDisableRCZUnitClockGating:vlv workaround.
6341 	 */
6342 	I915_WRITE(GEN6_UCGCTL2,
6343 		   GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
6344 
6345 	/* WaDisableL3Bank2xClockGate:vlv
6346 	 * Disabling L3 clock gating- MMIO 940c[25] = 1
6347 	 * Set bit 25, to disable L3_BANK_2x_CLK_GATING */
6348 	I915_WRITE(GEN7_UCGCTL4,
6349 		   I915_READ(GEN7_UCGCTL4) | GEN7_L3BANK2X_CLOCK_GATE_DISABLE);
6350 
6351 	/*
6352 	 * BSpec says this must be set, even though
6353 	 * WaDisable4x2SubspanOptimization isn't listed for VLV.
6354 	 */
6355 	I915_WRITE(CACHE_MODE_1,
6356 		   _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6357 
6358 	/*
6359 	 * BSpec recommends 8x4 when MSAA is used,
6360 	 * however in practice 16x4 seems fastest.
6361 	 *
6362 	 * Note that PS/WM thread counts depend on the WIZ hashing
6363 	 * disable bit, which we don't touch here, but it's good
6364 	 * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6365 	 */
6366 	I915_WRITE(GEN7_GT_MODE,
6367 		   _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6368 
6369 	/*
6370 	 * WaIncreaseL3CreditsForVLVB0:vlv
6371 	 * This is the hardware default actually.
6372 	 */
6373 	I915_WRITE(GEN7_L3SQCREG1, VLV_B0_WA_L3SQCREG1_VALUE);
6374 
6375 	/*
6376 	 * WaDisableVLVClockGating_VBIIssue:vlv
6377 	 * Disable clock gating on th GCFG unit to prevent a delay
6378 	 * in the reporting of vblank events.
6379 	 */
6380 	I915_WRITE(VLV_GUNIT_CLOCK_GATE, GCFG_DIS);
6381 }
6382 
6383 static void cherryview_init_clock_gating(struct drm_device *dev)
6384 {
6385 	struct drm_i915_private *dev_priv = dev->dev_private;
6386 
6387 	vlv_init_display_clock_gating(dev_priv);
6388 
6389 	/* WaVSRefCountFullforceMissDisable:chv */
6390 	/* WaDSRefCountFullforceMissDisable:chv */
6391 	I915_WRITE(GEN7_FF_THREAD_MODE,
6392 		   I915_READ(GEN7_FF_THREAD_MODE) &
6393 		   ~(GEN8_FF_DS_REF_CNT_FFME | GEN7_FF_VS_REF_CNT_FFME));
6394 
6395 	/* WaDisableSemaphoreAndSyncFlipWait:chv */
6396 	I915_WRITE(GEN6_RC_SLEEP_PSMI_CONTROL,
6397 		   _MASKED_BIT_ENABLE(GEN8_RC_SEMA_IDLE_MSG_DISABLE));
6398 
6399 	/* WaDisableCSUnitClockGating:chv */
6400 	I915_WRITE(GEN6_UCGCTL1, I915_READ(GEN6_UCGCTL1) |
6401 		   GEN6_CSUNIT_CLOCK_GATE_DISABLE);
6402 
6403 	/* WaDisableSDEUnitClockGating:chv */
6404 	I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
6405 		   GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
6406 }
6407 
6408 static void g4x_init_clock_gating(struct drm_device *dev)
6409 {
6410 	struct drm_i915_private *dev_priv = dev->dev_private;
6411 	uint32_t dspclk_gate;
6412 
6413 	I915_WRITE(RENCLK_GATE_D1, 0);
6414 	I915_WRITE(RENCLK_GATE_D2, VF_UNIT_CLOCK_GATE_DISABLE |
6415 		   GS_UNIT_CLOCK_GATE_DISABLE |
6416 		   CL_UNIT_CLOCK_GATE_DISABLE);
6417 	I915_WRITE(RAMCLK_GATE_D, 0);
6418 	dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE |
6419 		OVRUNIT_CLOCK_GATE_DISABLE |
6420 		OVCUNIT_CLOCK_GATE_DISABLE;
6421 	if (IS_GM45(dev))
6422 		dspclk_gate |= DSSUNIT_CLOCK_GATE_DISABLE;
6423 	I915_WRITE(DSPCLK_GATE_D, dspclk_gate);
6424 
6425 	/* WaDisableRenderCachePipelinedFlush */
6426 	I915_WRITE(CACHE_MODE_0,
6427 		   _MASKED_BIT_ENABLE(CM0_PIPELINED_RENDER_FLUSH_DISABLE));
6428 
6429 	/* WaDisable_RenderCache_OperationalFlush:g4x */
6430 	I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6431 
6432 	g4x_disable_trickle_feed(dev);
6433 }
6434 
6435 static void crestline_init_clock_gating(struct drm_device *dev)
6436 {
6437 	struct drm_i915_private *dev_priv = dev->dev_private;
6438 
6439 	I915_WRITE(RENCLK_GATE_D1, I965_RCC_CLOCK_GATE_DISABLE);
6440 	I915_WRITE(RENCLK_GATE_D2, 0);
6441 	I915_WRITE(DSPCLK_GATE_D, 0);
6442 	I915_WRITE(RAMCLK_GATE_D, 0);
6443 	I915_WRITE16(DEUC, 0);
6444 	I915_WRITE(MI_ARB_STATE,
6445 		   _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
6446 
6447 	/* WaDisable_RenderCache_OperationalFlush:gen4 */
6448 	I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6449 }
6450 
6451 static void broadwater_init_clock_gating(struct drm_device *dev)
6452 {
6453 	struct drm_i915_private *dev_priv = dev->dev_private;
6454 
6455 	I915_WRITE(RENCLK_GATE_D1, I965_RCZ_CLOCK_GATE_DISABLE |
6456 		   I965_RCC_CLOCK_GATE_DISABLE |
6457 		   I965_RCPB_CLOCK_GATE_DISABLE |
6458 		   I965_ISC_CLOCK_GATE_DISABLE |
6459 		   I965_FBC_CLOCK_GATE_DISABLE);
6460 	I915_WRITE(RENCLK_GATE_D2, 0);
6461 	I915_WRITE(MI_ARB_STATE,
6462 		   _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
6463 
6464 	/* WaDisable_RenderCache_OperationalFlush:gen4 */
6465 	I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6466 }
6467 
6468 static void gen3_init_clock_gating(struct drm_device *dev)
6469 {
6470 	struct drm_i915_private *dev_priv = dev->dev_private;
6471 	u32 dstate = I915_READ(D_STATE);
6472 
6473 	dstate |= DSTATE_PLL_D3_OFF | DSTATE_GFX_CLOCK_GATING |
6474 		DSTATE_DOT_CLOCK_GATING;
6475 	I915_WRITE(D_STATE, dstate);
6476 
6477 	if (IS_PINEVIEW(dev))
6478 		I915_WRITE(ECOSKPD, _MASKED_BIT_ENABLE(ECO_GATING_CX_ONLY));
6479 
6480 	/* IIR "flip pending" means done if this bit is set */
6481 	I915_WRITE(ECOSKPD, _MASKED_BIT_DISABLE(ECO_FLIP_DONE));
6482 
6483 	/* interrupts should cause a wake up from C3 */
6484 	I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_AGPBUSY_INT_EN));
6485 
6486 	/* On GEN3 we really need to make sure the ARB C3 LP bit is set */
6487 	I915_WRITE(MI_ARB_STATE, _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
6488 
6489 	I915_WRITE(MI_ARB_STATE,
6490 		   _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
6491 }
6492 
6493 static void i85x_init_clock_gating(struct drm_device *dev)
6494 {
6495 	struct drm_i915_private *dev_priv = dev->dev_private;
6496 
6497 	I915_WRITE(RENCLK_GATE_D1, SV_CLOCK_GATE_DISABLE);
6498 
6499 	/* interrupts should cause a wake up from C3 */
6500 	I915_WRITE(MI_STATE, _MASKED_BIT_ENABLE(MI_AGPBUSY_INT_EN) |
6501 		   _MASKED_BIT_DISABLE(MI_AGPBUSY_830_MODE));
6502 
6503 	I915_WRITE(MEM_MODE,
6504 		   _MASKED_BIT_ENABLE(MEM_DISPLAY_TRICKLE_FEED_DISABLE));
6505 }
6506 
6507 static void i830_init_clock_gating(struct drm_device *dev)
6508 {
6509 	struct drm_i915_private *dev_priv = dev->dev_private;
6510 
6511 	I915_WRITE(DSPCLK_GATE_D, OVRUNIT_CLOCK_GATE_DISABLE);
6512 
6513 	I915_WRITE(MEM_MODE,
6514 		   _MASKED_BIT_ENABLE(MEM_DISPLAY_A_TRICKLE_FEED_DISABLE) |
6515 		   _MASKED_BIT_ENABLE(MEM_DISPLAY_B_TRICKLE_FEED_DISABLE));
6516 }
6517 
6518 void intel_init_clock_gating(struct drm_device *dev)
6519 {
6520 	struct drm_i915_private *dev_priv = dev->dev_private;
6521 
6522 	if (dev_priv->display.init_clock_gating)
6523 		dev_priv->display.init_clock_gating(dev);
6524 }
6525 
6526 void intel_suspend_hw(struct drm_device *dev)
6527 {
6528 	if (HAS_PCH_LPT(dev))
6529 		lpt_suspend_hw(dev);
6530 }
6531 
6532 /* Set up chip specific power management-related functions */
6533 void intel_init_pm(struct drm_device *dev)
6534 {
6535 	struct drm_i915_private *dev_priv = dev->dev_private;
6536 
6537 	intel_fbc_init(dev_priv);
6538 
6539 	/* For cxsr */
6540 	if (IS_PINEVIEW(dev))
6541 		i915_pineview_get_mem_freq(dev);
6542 	else if (IS_GEN5(dev))
6543 		i915_ironlake_get_mem_freq(dev);
6544 
6545 	/* For FIFO watermark updates */
6546 	if (INTEL_INFO(dev)->gen >= 9) {
6547 		skl_setup_wm_latency(dev);
6548 
6549 		dev_priv->display.init_clock_gating = skl_init_clock_gating;
6550 		dev_priv->display.update_wm = skl_update_wm;
6551 		dev_priv->display.update_sprite_wm = skl_update_sprite_wm;
6552 	} else if (HAS_PCH_SPLIT(dev)) {
6553 		ilk_setup_wm_latency(dev);
6554 
6555 		if ((IS_GEN5(dev) && dev_priv->wm.pri_latency[1] &&
6556 		     dev_priv->wm.spr_latency[1] && dev_priv->wm.cur_latency[1]) ||
6557 		    (!IS_GEN5(dev) && dev_priv->wm.pri_latency[0] &&
6558 		     dev_priv->wm.spr_latency[0] && dev_priv->wm.cur_latency[0])) {
6559 			dev_priv->display.update_wm = ilk_update_wm;
6560 			dev_priv->display.update_sprite_wm = ilk_update_sprite_wm;
6561 		} else {
6562 			DRM_DEBUG_KMS("Failed to read display plane latency. "
6563 				      "Disable CxSR\n");
6564 		}
6565 
6566 		if (IS_GEN5(dev))
6567 			dev_priv->display.init_clock_gating = ironlake_init_clock_gating;
6568 		else if (IS_GEN6(dev))
6569 			dev_priv->display.init_clock_gating = gen6_init_clock_gating;
6570 		else if (IS_IVYBRIDGE(dev))
6571 			dev_priv->display.init_clock_gating = ivybridge_init_clock_gating;
6572 		else if (IS_HASWELL(dev))
6573 			dev_priv->display.init_clock_gating = haswell_init_clock_gating;
6574 		else if (INTEL_INFO(dev)->gen == 8)
6575 			dev_priv->display.init_clock_gating = broadwell_init_clock_gating;
6576 	} else if (IS_CHERRYVIEW(dev)) {
6577 		dev_priv->display.update_wm = valleyview_update_wm;
6578 		dev_priv->display.update_sprite_wm = valleyview_update_sprite_wm;
6579 		dev_priv->display.init_clock_gating =
6580 			cherryview_init_clock_gating;
6581 	} else if (IS_VALLEYVIEW(dev)) {
6582 		dev_priv->display.update_wm = valleyview_update_wm;
6583 		dev_priv->display.update_sprite_wm = valleyview_update_sprite_wm;
6584 		dev_priv->display.init_clock_gating =
6585 			valleyview_init_clock_gating;
6586 	} else if (IS_PINEVIEW(dev)) {
6587 		if (!intel_get_cxsr_latency(IS_PINEVIEW_G(dev),
6588 					    dev_priv->is_ddr3,
6589 					    dev_priv->fsb_freq,
6590 					    dev_priv->mem_freq)) {
6591 			DRM_INFO("failed to find known CxSR latency "
6592 				 "(found ddr%s fsb freq %d, mem freq %d), "
6593 				 "disabling CxSR\n",
6594 				 (dev_priv->is_ddr3 == 1) ? "3" : "2",
6595 				 dev_priv->fsb_freq, dev_priv->mem_freq);
6596 			/* Disable CxSR and never update its watermark again */
6597 			intel_set_memory_cxsr(dev_priv, false);
6598 			dev_priv->display.update_wm = NULL;
6599 		} else
6600 			dev_priv->display.update_wm = pineview_update_wm;
6601 		dev_priv->display.init_clock_gating = gen3_init_clock_gating;
6602 	} else if (IS_G4X(dev)) {
6603 		dev_priv->display.update_wm = g4x_update_wm;
6604 		dev_priv->display.init_clock_gating = g4x_init_clock_gating;
6605 	} else if (IS_GEN4(dev)) {
6606 		dev_priv->display.update_wm = i965_update_wm;
6607 		if (IS_CRESTLINE(dev))
6608 			dev_priv->display.init_clock_gating = crestline_init_clock_gating;
6609 		else if (IS_BROADWATER(dev))
6610 			dev_priv->display.init_clock_gating = broadwater_init_clock_gating;
6611 	} else if (IS_GEN3(dev)) {
6612 		dev_priv->display.update_wm = i9xx_update_wm;
6613 		dev_priv->display.get_fifo_size = i9xx_get_fifo_size;
6614 		dev_priv->display.init_clock_gating = gen3_init_clock_gating;
6615 	} else if (IS_GEN2(dev)) {
6616 		if (INTEL_INFO(dev)->num_pipes == 1) {
6617 			dev_priv->display.update_wm = i845_update_wm;
6618 			dev_priv->display.get_fifo_size = i845_get_fifo_size;
6619 		} else {
6620 			dev_priv->display.update_wm = i9xx_update_wm;
6621 			dev_priv->display.get_fifo_size = i830_get_fifo_size;
6622 		}
6623 
6624 		if (IS_I85X(dev) || IS_I865G(dev))
6625 			dev_priv->display.init_clock_gating = i85x_init_clock_gating;
6626 		else
6627 			dev_priv->display.init_clock_gating = i830_init_clock_gating;
6628 	} else {
6629 		DRM_ERROR("unexpected fall-through in intel_init_pm\n");
6630 	}
6631 }
6632 
6633 int sandybridge_pcode_read(struct drm_i915_private *dev_priv, u32 mbox, u32 *val)
6634 {
6635 	WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
6636 
6637 	if (I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) {
6638 		DRM_DEBUG_DRIVER("warning: pcode (read) mailbox access failed\n");
6639 		return -EAGAIN;
6640 	}
6641 
6642 	I915_WRITE(GEN6_PCODE_DATA, *val);
6643 	I915_WRITE(GEN6_PCODE_DATA1, 0);
6644 	I915_WRITE(GEN6_PCODE_MAILBOX, GEN6_PCODE_READY | mbox);
6645 
6646 	if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
6647 		     500)) {
6648 		DRM_ERROR("timeout waiting for pcode read (%d) to finish\n", mbox);
6649 		return -ETIMEDOUT;
6650 	}
6651 
6652 	*val = I915_READ(GEN6_PCODE_DATA);
6653 	I915_WRITE(GEN6_PCODE_DATA, 0);
6654 
6655 	return 0;
6656 }
6657 
6658 int sandybridge_pcode_write(struct drm_i915_private *dev_priv, u32 mbox, u32 val)
6659 {
6660 	WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
6661 
6662 	if (I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) {
6663 		DRM_DEBUG_DRIVER("warning: pcode (write) mailbox access failed\n");
6664 		return -EAGAIN;
6665 	}
6666 
6667 	I915_WRITE(GEN6_PCODE_DATA, val);
6668 	I915_WRITE(GEN6_PCODE_MAILBOX, GEN6_PCODE_READY | mbox);
6669 
6670 	if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
6671 		     500)) {
6672 		DRM_ERROR("timeout waiting for pcode write (%d) to finish\n", mbox);
6673 		return -ETIMEDOUT;
6674 	}
6675 
6676 	I915_WRITE(GEN6_PCODE_DATA, 0);
6677 
6678 	return 0;
6679 }
6680 
6681 static int vlv_gpu_freq_div(unsigned int czclk_freq)
6682 {
6683 	switch (czclk_freq) {
6684 	case 200:
6685 		return 10;
6686 	case 267:
6687 		return 12;
6688 	case 320:
6689 	case 333:
6690 		return 16;
6691 	case 400:
6692 		return 20;
6693 	default:
6694 		return -1;
6695 	}
6696 }
6697 
6698 static int byt_gpu_freq(struct drm_i915_private *dev_priv, int val)
6699 {
6700 	int div, czclk_freq = DIV_ROUND_CLOSEST(dev_priv->mem_freq, 4);
6701 
6702 	div = vlv_gpu_freq_div(czclk_freq);
6703 	if (div < 0)
6704 		return div;
6705 
6706 	return DIV_ROUND_CLOSEST(czclk_freq * (val + 6 - 0xbd), div);
6707 }
6708 
6709 static int byt_freq_opcode(struct drm_i915_private *dev_priv, int val)
6710 {
6711 	int mul, czclk_freq = DIV_ROUND_CLOSEST(dev_priv->mem_freq, 4);
6712 
6713 	mul = vlv_gpu_freq_div(czclk_freq);
6714 	if (mul < 0)
6715 		return mul;
6716 
6717 	return DIV_ROUND_CLOSEST(mul * val, czclk_freq) + 0xbd - 6;
6718 }
6719 
6720 static int chv_gpu_freq(struct drm_i915_private *dev_priv, int val)
6721 {
6722 	int div, czclk_freq = dev_priv->rps.cz_freq;
6723 
6724 	div = vlv_gpu_freq_div(czclk_freq) / 2;
6725 	if (div < 0)
6726 		return div;
6727 
6728 	return DIV_ROUND_CLOSEST(czclk_freq * val, 2 * div) / 2;
6729 }
6730 
6731 static int chv_freq_opcode(struct drm_i915_private *dev_priv, int val)
6732 {
6733 	int mul, czclk_freq = dev_priv->rps.cz_freq;
6734 
6735 	mul = vlv_gpu_freq_div(czclk_freq) / 2;
6736 	if (mul < 0)
6737 		return mul;
6738 
6739 	/* CHV needs even values */
6740 	return DIV_ROUND_CLOSEST(val * 2 * mul, czclk_freq) * 2;
6741 }
6742 
6743 int intel_gpu_freq(struct drm_i915_private *dev_priv, int val)
6744 {
6745 	if (IS_GEN9(dev_priv->dev))
6746 		return (val * GT_FREQUENCY_MULTIPLIER) / GEN9_FREQ_SCALER;
6747 	else if (IS_CHERRYVIEW(dev_priv->dev))
6748 		return chv_gpu_freq(dev_priv, val);
6749 	else if (IS_VALLEYVIEW(dev_priv->dev))
6750 		return byt_gpu_freq(dev_priv, val);
6751 	else
6752 		return val * GT_FREQUENCY_MULTIPLIER;
6753 }
6754 
6755 int intel_freq_opcode(struct drm_i915_private *dev_priv, int val)
6756 {
6757 	if (IS_GEN9(dev_priv->dev))
6758 		return (val * GEN9_FREQ_SCALER) / GT_FREQUENCY_MULTIPLIER;
6759 	else if (IS_CHERRYVIEW(dev_priv->dev))
6760 		return chv_freq_opcode(dev_priv, val);
6761 	else if (IS_VALLEYVIEW(dev_priv->dev))
6762 		return byt_freq_opcode(dev_priv, val);
6763 	else
6764 		return val / GT_FREQUENCY_MULTIPLIER;
6765 }
6766 
6767 void intel_pm_setup(struct drm_device *dev)
6768 {
6769 	struct drm_i915_private *dev_priv = dev->dev_private;
6770 
6771 	lockinit(&dev_priv->rps.hw_lock, "i915 rps.hw_lock", 0, LK_CANRECURSE);
6772 
6773 	INIT_DELAYED_WORK(&dev_priv->rps.delayed_resume_work,
6774 			  intel_gen6_powersave_work);
6775 
6776 	dev_priv->pm.suspended = false;
6777 }
6778