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