1 /*
2  * Copyright © 2010 Daniel Vetter
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  */
24 
25 #include <drm/drmP.h>
26 #include <drm/i915_drm.h>
27 #include "i915_drv.h"
28 #include "i915_trace.h"
29 #include "intel_drv.h"
30 
31 #define GEN6_PPGTT_PD_ENTRIES 512
32 #define I915_PPGTT_PT_ENTRIES (PAGE_SIZE / sizeof(gen6_gtt_pte_t))
33 typedef uint64_t gen8_gtt_pte_t;
34 typedef gen8_gtt_pte_t gen8_ppgtt_pde_t;
35 
36 /* PPGTT stuff */
37 #define GEN6_GTT_ADDR_ENCODE(addr)	((addr) | (((addr) >> 28) & 0xff0))
38 #define HSW_GTT_ADDR_ENCODE(addr)	((addr) | (((addr) >> 28) & 0x7f0))
39 
40 #define GEN6_PDE_VALID			(1 << 0)
41 /* gen6+ has bit 11-4 for physical addr bit 39-32 */
42 #define GEN6_PDE_ADDR_ENCODE(addr)	GEN6_GTT_ADDR_ENCODE(addr)
43 
44 #define GEN6_PTE_VALID			(1 << 0)
45 #define GEN6_PTE_UNCACHED		(1 << 1)
46 #define HSW_PTE_UNCACHED		(0)
47 #define GEN6_PTE_CACHE_LLC		(2 << 1)
48 #define GEN7_PTE_CACHE_L3_LLC		(3 << 1)
49 #define GEN6_PTE_ADDR_ENCODE(addr)	GEN6_GTT_ADDR_ENCODE(addr)
50 #define HSW_PTE_ADDR_ENCODE(addr)	HSW_GTT_ADDR_ENCODE(addr)
51 
52 /* Cacheability Control is a 4-bit value. The low three bits are stored in *
53  * bits 3:1 of the PTE, while the fourth bit is stored in bit 11 of the PTE.
54  */
55 #define HSW_CACHEABILITY_CONTROL(bits)	((((bits) & 0x7) << 1) | \
56 					 (((bits) & 0x8) << (11 - 3)))
57 #define HSW_WB_LLC_AGE3			HSW_CACHEABILITY_CONTROL(0x2)
58 #define HSW_WB_LLC_AGE0			HSW_CACHEABILITY_CONTROL(0x3)
59 #define HSW_WB_ELLC_LLC_AGE0		HSW_CACHEABILITY_CONTROL(0xb)
60 #define HSW_WB_ELLC_LLC_AGE3		HSW_CACHEABILITY_CONTROL(0x8)
61 #define HSW_WT_ELLC_LLC_AGE0		HSW_CACHEABILITY_CONTROL(0x6)
62 #define HSW_WT_ELLC_LLC_AGE3		HSW_CACHEABILITY_CONTROL(0x7)
63 
64 #define GEN8_PTES_PER_PAGE		(PAGE_SIZE / sizeof(gen8_gtt_pte_t))
65 #define GEN8_PDES_PER_PAGE		(PAGE_SIZE / sizeof(gen8_ppgtt_pde_t))
66 #define GEN8_LEGACY_PDPS		4
67 
68 #define PPAT_UNCACHED_INDEX		(_PAGE_PWT | _PAGE_PCD)
69 #define PPAT_CACHED_PDE_INDEX		0 /* WB LLC */
70 #define PPAT_CACHED_INDEX		_PAGE_PAT /* WB LLCeLLC */
71 #define PPAT_DISPLAY_ELLC_INDEX		_PAGE_PCD /* WT eLLC */
72 
73 static inline gen8_gtt_pte_t gen8_pte_encode(dma_addr_t addr,
74 					     enum i915_cache_level level,
75 					     bool valid)
76 {
77 	gen8_gtt_pte_t pte = valid ? _PAGE_PRESENT | _PAGE_RW : 0;
78 	pte |= addr;
79 	if (level != I915_CACHE_NONE)
80 		pte |= PPAT_CACHED_INDEX;
81 	else
82 		pte |= PPAT_UNCACHED_INDEX;
83 	return pte;
84 }
85 
86 static inline gen8_ppgtt_pde_t gen8_pde_encode(struct drm_device *dev,
87 					     dma_addr_t addr,
88 					     enum i915_cache_level level)
89 {
90 	gen8_ppgtt_pde_t pde = _PAGE_PRESENT | _PAGE_RW;
91 	pde |= addr;
92 	if (level != I915_CACHE_NONE)
93 		pde |= PPAT_CACHED_PDE_INDEX;
94 	else
95 		pde |= PPAT_UNCACHED_INDEX;
96 	return pde;
97 }
98 
99 static gen6_gtt_pte_t snb_pte_encode(dma_addr_t addr,
100 				     enum i915_cache_level level,
101 				     bool valid)
102 {
103 	gen6_gtt_pte_t pte = valid ? GEN6_PTE_VALID : 0;
104 	pte |= GEN6_PTE_ADDR_ENCODE(addr);
105 
106 	switch (level) {
107 	case I915_CACHE_L3_LLC:
108 	case I915_CACHE_LLC:
109 		pte |= GEN6_PTE_CACHE_LLC;
110 		break;
111 	case I915_CACHE_NONE:
112 		pte |= GEN6_PTE_UNCACHED;
113 		break;
114 	default:
115 		WARN_ON(1);
116 	}
117 
118 	return pte;
119 }
120 
121 static gen6_gtt_pte_t ivb_pte_encode(dma_addr_t addr,
122 				     enum i915_cache_level level,
123 				     bool valid)
124 {
125 	gen6_gtt_pte_t pte = valid ? GEN6_PTE_VALID : 0;
126 	pte |= GEN6_PTE_ADDR_ENCODE(addr);
127 
128 	switch (level) {
129 	case I915_CACHE_L3_LLC:
130 		pte |= GEN7_PTE_CACHE_L3_LLC;
131 		break;
132 	case I915_CACHE_LLC:
133 		pte |= GEN6_PTE_CACHE_LLC;
134 		break;
135 	case I915_CACHE_NONE:
136 		pte |= GEN6_PTE_UNCACHED;
137 		break;
138 	default:
139 		WARN_ON(1);
140 	}
141 
142 	return pte;
143 }
144 
145 #define BYT_PTE_WRITEABLE		(1 << 1)
146 #define BYT_PTE_SNOOPED_BY_CPU_CACHES	(1 << 2)
147 
148 static gen6_gtt_pte_t byt_pte_encode(dma_addr_t addr,
149 				     enum i915_cache_level level,
150 				     bool valid)
151 {
152 	gen6_gtt_pte_t pte = valid ? GEN6_PTE_VALID : 0;
153 	pte |= GEN6_PTE_ADDR_ENCODE(addr);
154 
155 	/* Mark the page as writeable.  Other platforms don't have a
156 	 * setting for read-only/writable, so this matches that behavior.
157 	 */
158 	pte |= BYT_PTE_WRITEABLE;
159 
160 	if (level != I915_CACHE_NONE)
161 		pte |= BYT_PTE_SNOOPED_BY_CPU_CACHES;
162 
163 	return pte;
164 }
165 
166 static gen6_gtt_pte_t hsw_pte_encode(dma_addr_t addr,
167 				     enum i915_cache_level level,
168 				     bool valid)
169 {
170 	gen6_gtt_pte_t pte = valid ? GEN6_PTE_VALID : 0;
171 	pte |= HSW_PTE_ADDR_ENCODE(addr);
172 
173 	if (level != I915_CACHE_NONE)
174 		pte |= HSW_WB_LLC_AGE3;
175 
176 	return pte;
177 }
178 
179 static gen6_gtt_pte_t iris_pte_encode(dma_addr_t addr,
180 				      enum i915_cache_level level,
181 				      bool valid)
182 {
183 	gen6_gtt_pte_t pte = valid ? GEN6_PTE_VALID : 0;
184 	pte |= HSW_PTE_ADDR_ENCODE(addr);
185 
186 	switch (level) {
187 	case I915_CACHE_NONE:
188 		break;
189 	case I915_CACHE_WT:
190 		pte |= HSW_WT_ELLC_LLC_AGE3;
191 		break;
192 	default:
193 		pte |= HSW_WB_ELLC_LLC_AGE3;
194 		break;
195 	}
196 
197 	return pte;
198 }
199 
200 /* Broadwell Page Directory Pointer Descriptors */
201 static int gen8_write_pdp(struct intel_ring_buffer *ring, unsigned entry,
202 			   uint64_t val)
203 {
204 	int ret;
205 
206 	BUG_ON(entry >= 4);
207 
208 	ret = intel_ring_begin(ring, 6);
209 	if (ret)
210 		return ret;
211 
212 	intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
213 	intel_ring_emit(ring, GEN8_RING_PDP_UDW(ring, entry));
214 	intel_ring_emit(ring, (u32)(val >> 32));
215 	intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
216 	intel_ring_emit(ring, GEN8_RING_PDP_LDW(ring, entry));
217 	intel_ring_emit(ring, (u32)(val));
218 	intel_ring_advance(ring);
219 
220 	return 0;
221 }
222 
223 static int gen8_ppgtt_enable(struct drm_device *dev)
224 {
225 	struct drm_i915_private *dev_priv = dev->dev_private;
226 	struct intel_ring_buffer *ring;
227 	struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
228 	int i, j, ret;
229 
230 	/* bit of a hack to find the actual last used pd */
231 	int used_pd = ppgtt->num_pd_entries / GEN8_PDES_PER_PAGE;
232 
233 	for_each_ring(ring, dev_priv, j) {
234 		I915_WRITE(RING_MODE_GEN7(ring),
235 			   _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
236 	}
237 
238 	for (i = used_pd - 1; i >= 0; i--) {
239 		dma_addr_t addr = ppgtt->pd_dma_addr[i];
240 		for_each_ring(ring, dev_priv, j) {
241 			ret = gen8_write_pdp(ring, i, addr);
242 			if (ret)
243 				return ret;
244 		}
245 	}
246 	return 0;
247 }
248 
249 static void gen8_ppgtt_clear_range(struct i915_address_space *vm,
250 				   unsigned first_entry,
251 				   unsigned num_entries,
252 				   bool use_scratch)
253 {
254 	struct i915_hw_ppgtt *ppgtt =
255 		container_of(vm, struct i915_hw_ppgtt, base);
256 	gen8_gtt_pte_t *pt_vaddr, scratch_pte;
257 	unsigned act_pt = first_entry / GEN8_PTES_PER_PAGE;
258 	unsigned first_pte = first_entry % GEN8_PTES_PER_PAGE;
259 	unsigned last_pte, i;
260 
261 	scratch_pte = gen8_pte_encode(ppgtt->base.scratch.addr,
262 				      I915_CACHE_LLC, use_scratch);
263 
264 	while (num_entries) {
265 		struct page *page_table = &ppgtt->gen8_pt_pages[act_pt];
266 
267 		last_pte = first_pte + num_entries;
268 		if (last_pte > GEN8_PTES_PER_PAGE)
269 			last_pte = GEN8_PTES_PER_PAGE;
270 
271 		pt_vaddr = kmap_atomic(page_table);
272 
273 		for (i = first_pte; i < last_pte; i++)
274 			pt_vaddr[i] = scratch_pte;
275 
276 		kunmap_atomic(pt_vaddr);
277 
278 		num_entries -= last_pte - first_pte;
279 		first_pte = 0;
280 		act_pt++;
281 	}
282 }
283 
284 static void gen8_ppgtt_insert_entries(struct i915_address_space *vm,
285 				      struct sg_table *pages,
286 				      unsigned first_entry,
287 				      enum i915_cache_level cache_level)
288 {
289 	struct i915_hw_ppgtt *ppgtt =
290 		container_of(vm, struct i915_hw_ppgtt, base);
291 	gen8_gtt_pte_t *pt_vaddr;
292 	unsigned act_pt = first_entry / GEN8_PTES_PER_PAGE;
293 	unsigned act_pte = first_entry % GEN8_PTES_PER_PAGE;
294 	struct sg_page_iter sg_iter;
295 
296 	pt_vaddr = kmap_atomic(&ppgtt->gen8_pt_pages[act_pt]);
297 	for_each_sg_page(pages->sgl, &sg_iter, pages->nents, 0) {
298 		dma_addr_t page_addr;
299 
300 		page_addr = sg_dma_address(sg_iter.sg) +
301 				(sg_iter.sg_pgoffset << PAGE_SHIFT);
302 		pt_vaddr[act_pte] = gen8_pte_encode(page_addr, cache_level,
303 						    true);
304 		if (++act_pte == GEN8_PTES_PER_PAGE) {
305 			kunmap_atomic(pt_vaddr);
306 			act_pt++;
307 			pt_vaddr = kmap_atomic(&ppgtt->gen8_pt_pages[act_pt]);
308 			act_pte = 0;
309 
310 		}
311 	}
312 	kunmap_atomic(pt_vaddr);
313 }
314 
315 static void gen8_ppgtt_cleanup(struct i915_address_space *vm)
316 {
317 	struct i915_hw_ppgtt *ppgtt =
318 		container_of(vm, struct i915_hw_ppgtt, base);
319 	int i, j;
320 
321 	for (i = 0; i < ppgtt->num_pd_pages ; i++) {
322 		if (ppgtt->pd_dma_addr[i]) {
323 			pci_unmap_page(ppgtt->base.dev->pdev,
324 				       ppgtt->pd_dma_addr[i],
325 				       PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
326 
327 			for (j = 0; j < GEN8_PDES_PER_PAGE; j++) {
328 				dma_addr_t addr = ppgtt->gen8_pt_dma_addr[i][j];
329 				if (addr)
330 					pci_unmap_page(ppgtt->base.dev->pdev,
331 						       addr,
332 						       PAGE_SIZE,
333 						       PCI_DMA_BIDIRECTIONAL);
334 
335 			}
336 		}
337 		kfree(ppgtt->gen8_pt_dma_addr[i]);
338 	}
339 
340 	__free_pages(ppgtt->gen8_pt_pages, get_order(ppgtt->num_pt_pages << PAGE_SHIFT));
341 	__free_pages(ppgtt->pd_pages, get_order(ppgtt->num_pd_pages << PAGE_SHIFT));
342 }
343 
344 /**
345  * GEN8 legacy ppgtt programming is accomplished through 4 PDP registers with a
346  * net effect resembling a 2-level page table in normal x86 terms. Each PDP
347  * represents 1GB of memory
348  * 4 * 512 * 512 * 4096 = 4GB legacy 32b address space.
349  *
350  * TODO: Do something with the size parameter
351  **/
352 static int gen8_ppgtt_init(struct i915_hw_ppgtt *ppgtt, uint64_t size)
353 {
354 	struct page *pt_pages;
355 	int i, j, ret = -ENOMEM;
356 	const int max_pdp = DIV_ROUND_UP(size, 1 << 30);
357 	const int num_pt_pages = GEN8_PDES_PER_PAGE * max_pdp;
358 
359 	if (size % (1<<30))
360 		DRM_INFO("Pages will be wasted unless GTT size (%llu) is divisible by 1GB\n", size);
361 
362 	/* FIXME: split allocation into smaller pieces. For now we only ever do
363 	 * this once, but with full PPGTT, the multiple contiguous allocations
364 	 * will be bad.
365 	 */
366 	ppgtt->pd_pages = alloc_pages(GFP_KERNEL, get_order(max_pdp << PAGE_SHIFT));
367 	if (!ppgtt->pd_pages)
368 		return -ENOMEM;
369 
370 	pt_pages = alloc_pages(GFP_KERNEL, get_order(num_pt_pages << PAGE_SHIFT));
371 	if (!pt_pages) {
372 		__free_pages(ppgtt->pd_pages, get_order(max_pdp << PAGE_SHIFT));
373 		return -ENOMEM;
374 	}
375 
376 	ppgtt->gen8_pt_pages = pt_pages;
377 	ppgtt->num_pd_pages = 1 << get_order(max_pdp << PAGE_SHIFT);
378 	ppgtt->num_pt_pages = 1 << get_order(num_pt_pages << PAGE_SHIFT);
379 	ppgtt->num_pd_entries = max_pdp * GEN8_PDES_PER_PAGE;
380 	ppgtt->enable = gen8_ppgtt_enable;
381 	ppgtt->base.clear_range = gen8_ppgtt_clear_range;
382 	ppgtt->base.insert_entries = gen8_ppgtt_insert_entries;
383 	ppgtt->base.cleanup = gen8_ppgtt_cleanup;
384 
385 	BUG_ON(ppgtt->num_pd_pages > GEN8_LEGACY_PDPS);
386 
387 	/*
388 	 * - Create a mapping for the page directories.
389 	 * - For each page directory:
390 	 *      allocate space for page table mappings.
391 	 *      map each page table
392 	 */
393 	for (i = 0; i < max_pdp; i++) {
394 		dma_addr_t temp;
395 		temp = pci_map_page(ppgtt->base.dev->pdev,
396 				    &ppgtt->pd_pages[i], 0,
397 				    PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
398 		if (pci_dma_mapping_error(ppgtt->base.dev->pdev, temp))
399 			goto err_out;
400 
401 		ppgtt->pd_dma_addr[i] = temp;
402 
403 		ppgtt->gen8_pt_dma_addr[i] = kmalloc(sizeof(dma_addr_t) * GEN8_PDES_PER_PAGE, GFP_KERNEL);
404 		if (!ppgtt->gen8_pt_dma_addr[i])
405 			goto err_out;
406 
407 		for (j = 0; j < GEN8_PDES_PER_PAGE; j++) {
408 			struct page *p = &pt_pages[i * GEN8_PDES_PER_PAGE + j];
409 			temp = pci_map_page(ppgtt->base.dev->pdev,
410 					    p, 0, PAGE_SIZE,
411 					    PCI_DMA_BIDIRECTIONAL);
412 
413 			if (pci_dma_mapping_error(ppgtt->base.dev->pdev, temp))
414 				goto err_out;
415 
416 			ppgtt->gen8_pt_dma_addr[i][j] = temp;
417 		}
418 	}
419 
420 	/* For now, the PPGTT helper functions all require that the PDEs are
421 	 * plugged in correctly. So we do that now/here. For aliasing PPGTT, we
422 	 * will never need to touch the PDEs again */
423 	for (i = 0; i < max_pdp; i++) {
424 		gen8_ppgtt_pde_t *pd_vaddr;
425 		pd_vaddr = kmap_atomic(&ppgtt->pd_pages[i]);
426 		for (j = 0; j < GEN8_PDES_PER_PAGE; j++) {
427 			dma_addr_t addr = ppgtt->gen8_pt_dma_addr[i][j];
428 			pd_vaddr[j] = gen8_pde_encode(ppgtt->base.dev, addr,
429 						      I915_CACHE_LLC);
430 		}
431 		kunmap_atomic(pd_vaddr);
432 	}
433 
434 	ppgtt->base.clear_range(&ppgtt->base, 0,
435 				ppgtt->num_pd_entries * GEN8_PTES_PER_PAGE,
436 				true);
437 
438 	DRM_DEBUG_DRIVER("Allocated %d pages for page directories (%d wasted)\n",
439 			 ppgtt->num_pd_pages, ppgtt->num_pd_pages - max_pdp);
440 	DRM_DEBUG_DRIVER("Allocated %d pages for page tables (%lld wasted)\n",
441 			 ppgtt->num_pt_pages,
442 			 (ppgtt->num_pt_pages - num_pt_pages) +
443 			 size % (1<<30));
444 	return 0;
445 
446 err_out:
447 	ppgtt->base.cleanup(&ppgtt->base);
448 	return ret;
449 }
450 
451 static void gen6_write_pdes(struct i915_hw_ppgtt *ppgtt)
452 {
453 	struct drm_i915_private *dev_priv = ppgtt->base.dev->dev_private;
454 	gen6_gtt_pte_t __iomem *pd_addr;
455 	uint32_t pd_entry;
456 	int i;
457 
458 	WARN_ON(ppgtt->pd_offset & 0x3f);
459 	pd_addr = (gen6_gtt_pte_t __iomem*)dev_priv->gtt.gsm +
460 		ppgtt->pd_offset / sizeof(gen6_gtt_pte_t);
461 	for (i = 0; i < ppgtt->num_pd_entries; i++) {
462 		dma_addr_t pt_addr;
463 
464 		pt_addr = ppgtt->pt_dma_addr[i];
465 		pd_entry = GEN6_PDE_ADDR_ENCODE(pt_addr);
466 		pd_entry |= GEN6_PDE_VALID;
467 
468 		writel(pd_entry, pd_addr + i);
469 	}
470 	readl(pd_addr);
471 }
472 
473 static int gen6_ppgtt_enable(struct drm_device *dev)
474 {
475 	drm_i915_private_t *dev_priv = dev->dev_private;
476 	uint32_t pd_offset;
477 	struct intel_ring_buffer *ring;
478 	struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
479 	int i;
480 
481 	BUG_ON(ppgtt->pd_offset & 0x3f);
482 
483 	gen6_write_pdes(ppgtt);
484 
485 	pd_offset = ppgtt->pd_offset;
486 	pd_offset /= 64; /* in cachelines, */
487 	pd_offset <<= 16;
488 
489 	if (INTEL_INFO(dev)->gen == 6) {
490 		uint32_t ecochk, gab_ctl, ecobits;
491 
492 		ecobits = I915_READ(GAC_ECO_BITS);
493 		I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_SNB_BIT |
494 					 ECOBITS_PPGTT_CACHE64B);
495 
496 		gab_ctl = I915_READ(GAB_CTL);
497 		I915_WRITE(GAB_CTL, gab_ctl | GAB_CTL_CONT_AFTER_PAGEFAULT);
498 
499 		ecochk = I915_READ(GAM_ECOCHK);
500 		I915_WRITE(GAM_ECOCHK, ecochk | ECOCHK_SNB_BIT |
501 				       ECOCHK_PPGTT_CACHE64B);
502 		I915_WRITE(GFX_MODE, _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
503 	} else if (INTEL_INFO(dev)->gen >= 7) {
504 		uint32_t ecochk, ecobits;
505 
506 		ecobits = I915_READ(GAC_ECO_BITS);
507 		I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_PPGTT_CACHE64B);
508 
509 		ecochk = I915_READ(GAM_ECOCHK);
510 		if (IS_HASWELL(dev)) {
511 			ecochk |= ECOCHK_PPGTT_WB_HSW;
512 		} else {
513 			ecochk |= ECOCHK_PPGTT_LLC_IVB;
514 			ecochk &= ~ECOCHK_PPGTT_GFDT_IVB;
515 		}
516 		I915_WRITE(GAM_ECOCHK, ecochk);
517 		/* GFX_MODE is per-ring on gen7+ */
518 	}
519 
520 	for_each_ring(ring, dev_priv, i) {
521 		if (INTEL_INFO(dev)->gen >= 7)
522 			I915_WRITE(RING_MODE_GEN7(ring),
523 				   _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
524 
525 		I915_WRITE(RING_PP_DIR_DCLV(ring), PP_DIR_DCLV_2G);
526 		I915_WRITE(RING_PP_DIR_BASE(ring), pd_offset);
527 	}
528 	return 0;
529 }
530 
531 /* PPGTT support for Sandybdrige/Gen6 and later */
532 static void gen6_ppgtt_clear_range(struct i915_address_space *vm,
533 				   unsigned first_entry,
534 				   unsigned num_entries,
535 				   bool use_scratch)
536 {
537 	struct i915_hw_ppgtt *ppgtt =
538 		container_of(vm, struct i915_hw_ppgtt, base);
539 	gen6_gtt_pte_t *pt_vaddr, scratch_pte;
540 	unsigned act_pt = first_entry / I915_PPGTT_PT_ENTRIES;
541 	unsigned first_pte = first_entry % I915_PPGTT_PT_ENTRIES;
542 	unsigned last_pte, i;
543 
544 	scratch_pte = vm->pte_encode(vm->scratch.addr, I915_CACHE_LLC, true);
545 
546 	while (num_entries) {
547 		last_pte = first_pte + num_entries;
548 		if (last_pte > I915_PPGTT_PT_ENTRIES)
549 			last_pte = I915_PPGTT_PT_ENTRIES;
550 
551 		pt_vaddr = kmap_atomic(ppgtt->pt_pages[act_pt]);
552 
553 		for (i = first_pte; i < last_pte; i++)
554 			pt_vaddr[i] = scratch_pte;
555 
556 		kunmap_atomic(pt_vaddr);
557 
558 		num_entries -= last_pte - first_pte;
559 		first_pte = 0;
560 		act_pt++;
561 	}
562 }
563 
564 static void gen6_ppgtt_insert_entries(struct i915_address_space *vm,
565 				      struct sg_table *pages,
566 				      unsigned first_entry,
567 				      enum i915_cache_level cache_level)
568 {
569 	struct i915_hw_ppgtt *ppgtt =
570 		container_of(vm, struct i915_hw_ppgtt, base);
571 	gen6_gtt_pte_t *pt_vaddr;
572 	unsigned act_pt = first_entry / I915_PPGTT_PT_ENTRIES;
573 	unsigned act_pte = first_entry % I915_PPGTT_PT_ENTRIES;
574 	struct sg_page_iter sg_iter;
575 
576 	pt_vaddr = kmap_atomic(ppgtt->pt_pages[act_pt]);
577 	for_each_sg_page(pages->sgl, &sg_iter, pages->nents, 0) {
578 		dma_addr_t page_addr;
579 
580 		page_addr = sg_page_iter_dma_address(&sg_iter);
581 		pt_vaddr[act_pte] = vm->pte_encode(page_addr, cache_level, true);
582 		if (++act_pte == I915_PPGTT_PT_ENTRIES) {
583 			kunmap_atomic(pt_vaddr);
584 			act_pt++;
585 			pt_vaddr = kmap_atomic(ppgtt->pt_pages[act_pt]);
586 			act_pte = 0;
587 
588 		}
589 	}
590 	kunmap_atomic(pt_vaddr);
591 }
592 
593 static void gen6_ppgtt_cleanup(struct i915_address_space *vm)
594 {
595 	struct i915_hw_ppgtt *ppgtt =
596 		container_of(vm, struct i915_hw_ppgtt, base);
597 	int i;
598 
599 	drm_mm_takedown(&ppgtt->base.mm);
600 
601 	if (ppgtt->pt_dma_addr) {
602 		for (i = 0; i < ppgtt->num_pd_entries; i++)
603 			pci_unmap_page(ppgtt->base.dev->pdev,
604 				       ppgtt->pt_dma_addr[i],
605 				       4096, PCI_DMA_BIDIRECTIONAL);
606 	}
607 
608 	kfree(ppgtt->pt_dma_addr);
609 	for (i = 0; i < ppgtt->num_pd_entries; i++)
610 		__free_page(ppgtt->pt_pages[i]);
611 	kfree(ppgtt->pt_pages);
612 	kfree(ppgtt);
613 }
614 
615 static int gen6_ppgtt_init(struct i915_hw_ppgtt *ppgtt)
616 {
617 	struct drm_device *dev = ppgtt->base.dev;
618 	struct drm_i915_private *dev_priv = dev->dev_private;
619 	unsigned first_pd_entry_in_global_pt;
620 	int i;
621 	int ret = -ENOMEM;
622 
623 	/* ppgtt PDEs reside in the global gtt pagetable, which has 512*1024
624 	 * entries. For aliasing ppgtt support we just steal them at the end for
625 	 * now. */
626 	first_pd_entry_in_global_pt = gtt_total_entries(dev_priv->gtt);
627 
628 	ppgtt->base.pte_encode = dev_priv->gtt.base.pte_encode;
629 	ppgtt->num_pd_entries = GEN6_PPGTT_PD_ENTRIES;
630 	ppgtt->enable = gen6_ppgtt_enable;
631 	ppgtt->base.clear_range = gen6_ppgtt_clear_range;
632 	ppgtt->base.insert_entries = gen6_ppgtt_insert_entries;
633 	ppgtt->base.cleanup = gen6_ppgtt_cleanup;
634 	ppgtt->base.scratch = dev_priv->gtt.base.scratch;
635 	ppgtt->pt_pages = kcalloc(ppgtt->num_pd_entries, sizeof(struct page *),
636 				  GFP_KERNEL);
637 	if (!ppgtt->pt_pages)
638 		return -ENOMEM;
639 
640 	for (i = 0; i < ppgtt->num_pd_entries; i++) {
641 		ppgtt->pt_pages[i] = alloc_page(GFP_KERNEL);
642 		if (!ppgtt->pt_pages[i])
643 			goto err_pt_alloc;
644 	}
645 
646 	ppgtt->pt_dma_addr = kcalloc(ppgtt->num_pd_entries, sizeof(dma_addr_t),
647 				     GFP_KERNEL);
648 	if (!ppgtt->pt_dma_addr)
649 		goto err_pt_alloc;
650 
651 	for (i = 0; i < ppgtt->num_pd_entries; i++) {
652 		dma_addr_t pt_addr;
653 
654 		pt_addr = pci_map_page(dev->pdev, ppgtt->pt_pages[i], 0, 4096,
655 				       PCI_DMA_BIDIRECTIONAL);
656 
657 		if (pci_dma_mapping_error(dev->pdev, pt_addr)) {
658 			ret = -EIO;
659 			goto err_pd_pin;
660 
661 		}
662 		ppgtt->pt_dma_addr[i] = pt_addr;
663 	}
664 
665 	ppgtt->base.clear_range(&ppgtt->base, 0,
666 				ppgtt->num_pd_entries * I915_PPGTT_PT_ENTRIES, true);
667 
668 	ppgtt->pd_offset = first_pd_entry_in_global_pt * sizeof(gen6_gtt_pte_t);
669 
670 	return 0;
671 
672 err_pd_pin:
673 	if (ppgtt->pt_dma_addr) {
674 		for (i--; i >= 0; i--)
675 			pci_unmap_page(dev->pdev, ppgtt->pt_dma_addr[i],
676 				       4096, PCI_DMA_BIDIRECTIONAL);
677 	}
678 err_pt_alloc:
679 	kfree(ppgtt->pt_dma_addr);
680 	for (i = 0; i < ppgtt->num_pd_entries; i++) {
681 		if (ppgtt->pt_pages[i])
682 			__free_page(ppgtt->pt_pages[i]);
683 	}
684 	kfree(ppgtt->pt_pages);
685 
686 	return ret;
687 }
688 
689 static int i915_gem_init_aliasing_ppgtt(struct drm_device *dev)
690 {
691 	struct drm_i915_private *dev_priv = dev->dev_private;
692 	struct i915_hw_ppgtt *ppgtt;
693 	int ret;
694 
695 	ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
696 	if (!ppgtt)
697 		return -ENOMEM;
698 
699 	ppgtt->base.dev = dev;
700 
701 	if (INTEL_INFO(dev)->gen < 8)
702 		ret = gen6_ppgtt_init(ppgtt);
703 	else if (IS_GEN8(dev))
704 		ret = gen8_ppgtt_init(ppgtt, dev_priv->gtt.base.total);
705 	else
706 		BUG();
707 
708 	if (ret)
709 		kfree(ppgtt);
710 	else {
711 		dev_priv->mm.aliasing_ppgtt = ppgtt;
712 		drm_mm_init(&ppgtt->base.mm, ppgtt->base.start,
713 			    ppgtt->base.total);
714 	}
715 
716 	return ret;
717 }
718 
719 void i915_gem_cleanup_aliasing_ppgtt(struct drm_device *dev)
720 {
721 	struct drm_i915_private *dev_priv = dev->dev_private;
722 	struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
723 
724 	if (!ppgtt)
725 		return;
726 
727 	ppgtt->base.cleanup(&ppgtt->base);
728 	dev_priv->mm.aliasing_ppgtt = NULL;
729 }
730 
731 void i915_ppgtt_bind_object(struct i915_hw_ppgtt *ppgtt,
732 			    struct drm_i915_gem_object *obj,
733 			    enum i915_cache_level cache_level)
734 {
735 	ppgtt->base.insert_entries(&ppgtt->base, obj->pages,
736 				   i915_gem_obj_ggtt_offset(obj) >> PAGE_SHIFT,
737 				   cache_level);
738 }
739 
740 void i915_ppgtt_unbind_object(struct i915_hw_ppgtt *ppgtt,
741 			      struct drm_i915_gem_object *obj)
742 {
743 	ppgtt->base.clear_range(&ppgtt->base,
744 				i915_gem_obj_ggtt_offset(obj) >> PAGE_SHIFT,
745 				obj->base.size >> PAGE_SHIFT,
746 				true);
747 }
748 
749 extern int intel_iommu_gfx_mapped;
750 /* Certain Gen5 chipsets require require idling the GPU before
751  * unmapping anything from the GTT when VT-d is enabled.
752  */
753 static inline bool needs_idle_maps(struct drm_device *dev)
754 {
755 #ifdef CONFIG_INTEL_IOMMU
756 	/* Query intel_iommu to see if we need the workaround. Presumably that
757 	 * was loaded first.
758 	 */
759 	if (IS_GEN5(dev) && IS_MOBILE(dev) && intel_iommu_gfx_mapped)
760 		return true;
761 #endif
762 	return false;
763 }
764 
765 static bool do_idling(struct drm_i915_private *dev_priv)
766 {
767 	bool ret = dev_priv->mm.interruptible;
768 
769 	if (unlikely(dev_priv->gtt.do_idle_maps)) {
770 		dev_priv->mm.interruptible = false;
771 		if (i915_gpu_idle(dev_priv->dev)) {
772 			DRM_ERROR("Couldn't idle GPU\n");
773 			/* Wait a bit, in hopes it avoids the hang */
774 			udelay(10);
775 		}
776 	}
777 
778 	return ret;
779 }
780 
781 static void undo_idling(struct drm_i915_private *dev_priv, bool interruptible)
782 {
783 	if (unlikely(dev_priv->gtt.do_idle_maps))
784 		dev_priv->mm.interruptible = interruptible;
785 }
786 
787 void i915_check_and_clear_faults(struct drm_device *dev)
788 {
789 	struct drm_i915_private *dev_priv = dev->dev_private;
790 	struct intel_ring_buffer *ring;
791 	int i;
792 
793 	if (INTEL_INFO(dev)->gen < 6)
794 		return;
795 
796 	for_each_ring(ring, dev_priv, i) {
797 		u32 fault_reg;
798 		fault_reg = I915_READ(RING_FAULT_REG(ring));
799 		if (fault_reg & RING_FAULT_VALID) {
800 			DRM_DEBUG_DRIVER("Unexpected fault\n"
801 					 "\tAddr: 0x%08lx\\n"
802 					 "\tAddress space: %s\n"
803 					 "\tSource ID: %d\n"
804 					 "\tType: %d\n",
805 					 fault_reg & PAGE_MASK,
806 					 fault_reg & RING_FAULT_GTTSEL_MASK ? "GGTT" : "PPGTT",
807 					 RING_FAULT_SRCID(fault_reg),
808 					 RING_FAULT_FAULT_TYPE(fault_reg));
809 			I915_WRITE(RING_FAULT_REG(ring),
810 				   fault_reg & ~RING_FAULT_VALID);
811 		}
812 	}
813 	POSTING_READ(RING_FAULT_REG(&dev_priv->ring[RCS]));
814 }
815 
816 void i915_gem_suspend_gtt_mappings(struct drm_device *dev)
817 {
818 	struct drm_i915_private *dev_priv = dev->dev_private;
819 
820 	/* Don't bother messing with faults pre GEN6 as we have little
821 	 * documentation supporting that it's a good idea.
822 	 */
823 	if (INTEL_INFO(dev)->gen < 6)
824 		return;
825 
826 	i915_check_and_clear_faults(dev);
827 
828 	dev_priv->gtt.base.clear_range(&dev_priv->gtt.base,
829 				       dev_priv->gtt.base.start / PAGE_SIZE,
830 				       dev_priv->gtt.base.total / PAGE_SIZE,
831 				       false);
832 }
833 
834 void i915_gem_restore_gtt_mappings(struct drm_device *dev)
835 {
836 	struct drm_i915_private *dev_priv = dev->dev_private;
837 	struct drm_i915_gem_object *obj;
838 
839 	i915_check_and_clear_faults(dev);
840 
841 	/* First fill our portion of the GTT with scratch pages */
842 	dev_priv->gtt.base.clear_range(&dev_priv->gtt.base,
843 				       dev_priv->gtt.base.start / PAGE_SIZE,
844 				       dev_priv->gtt.base.total / PAGE_SIZE,
845 				       true);
846 
847 	list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
848 		i915_gem_clflush_object(obj, obj->pin_display);
849 		i915_gem_gtt_bind_object(obj, obj->cache_level);
850 	}
851 
852 	i915_gem_chipset_flush(dev);
853 }
854 
855 int i915_gem_gtt_prepare_object(struct drm_i915_gem_object *obj)
856 {
857 	if (obj->has_dma_mapping)
858 		return 0;
859 
860 	if (!dma_map_sg(&obj->base.dev->pdev->dev,
861 			obj->pages->sgl, obj->pages->nents,
862 			PCI_DMA_BIDIRECTIONAL))
863 		return -ENOSPC;
864 
865 	return 0;
866 }
867 
868 static inline void gen8_set_pte(void __iomem *addr, gen8_gtt_pte_t pte)
869 {
870 #ifdef writeq
871 	writeq(pte, addr);
872 #else
873 	iowrite32((u32)pte, addr);
874 	iowrite32(pte >> 32, addr + 4);
875 #endif
876 }
877 
878 static void gen8_ggtt_insert_entries(struct i915_address_space *vm,
879 				     struct sg_table *st,
880 				     unsigned int first_entry,
881 				     enum i915_cache_level level)
882 {
883 	struct drm_i915_private *dev_priv = vm->dev->dev_private;
884 	gen8_gtt_pte_t __iomem *gtt_entries =
885 		(gen8_gtt_pte_t __iomem *)dev_priv->gtt.gsm + first_entry;
886 	int i = 0;
887 	struct sg_page_iter sg_iter;
888 	dma_addr_t addr;
889 
890 	for_each_sg_page(st->sgl, &sg_iter, st->nents, 0) {
891 		addr = sg_dma_address(sg_iter.sg) +
892 			(sg_iter.sg_pgoffset << PAGE_SHIFT);
893 		gen8_set_pte(&gtt_entries[i],
894 			     gen8_pte_encode(addr, level, true));
895 		i++;
896 	}
897 
898 	/*
899 	 * XXX: This serves as a posting read to make sure that the PTE has
900 	 * actually been updated. There is some concern that even though
901 	 * registers and PTEs are within the same BAR that they are potentially
902 	 * of NUMA access patterns. Therefore, even with the way we assume
903 	 * hardware should work, we must keep this posting read for paranoia.
904 	 */
905 	if (i != 0)
906 		WARN_ON(readq(&gtt_entries[i-1])
907 			!= gen8_pte_encode(addr, level, true));
908 
909 	/* This next bit makes the above posting read even more important. We
910 	 * want to flush the TLBs only after we're certain all the PTE updates
911 	 * have finished.
912 	 */
913 	I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
914 	POSTING_READ(GFX_FLSH_CNTL_GEN6);
915 }
916 
917 /*
918  * Binds an object into the global gtt with the specified cache level. The object
919  * will be accessible to the GPU via commands whose operands reference offsets
920  * within the global GTT as well as accessible by the GPU through the GMADR
921  * mapped BAR (dev_priv->mm.gtt->gtt).
922  */
923 static void gen6_ggtt_insert_entries(struct i915_address_space *vm,
924 				     struct sg_table *st,
925 				     unsigned int first_entry,
926 				     enum i915_cache_level level)
927 {
928 	struct drm_i915_private *dev_priv = vm->dev->dev_private;
929 	gen6_gtt_pte_t __iomem *gtt_entries =
930 		(gen6_gtt_pte_t __iomem *)dev_priv->gtt.gsm + first_entry;
931 	int i = 0;
932 	struct sg_page_iter sg_iter;
933 	dma_addr_t addr;
934 
935 	for_each_sg_page(st->sgl, &sg_iter, st->nents, 0) {
936 		addr = sg_page_iter_dma_address(&sg_iter);
937 		iowrite32(vm->pte_encode(addr, level, true), &gtt_entries[i]);
938 		i++;
939 	}
940 
941 	/* XXX: This serves as a posting read to make sure that the PTE has
942 	 * actually been updated. There is some concern that even though
943 	 * registers and PTEs are within the same BAR that they are potentially
944 	 * of NUMA access patterns. Therefore, even with the way we assume
945 	 * hardware should work, we must keep this posting read for paranoia.
946 	 */
947 	if (i != 0)
948 		WARN_ON(readl(&gtt_entries[i-1]) !=
949 			vm->pte_encode(addr, level, true));
950 
951 	/* This next bit makes the above posting read even more important. We
952 	 * want to flush the TLBs only after we're certain all the PTE updates
953 	 * have finished.
954 	 */
955 	I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
956 	POSTING_READ(GFX_FLSH_CNTL_GEN6);
957 }
958 
959 static void gen8_ggtt_clear_range(struct i915_address_space *vm,
960 				  unsigned int first_entry,
961 				  unsigned int num_entries,
962 				  bool use_scratch)
963 {
964 	struct drm_i915_private *dev_priv = vm->dev->dev_private;
965 	gen8_gtt_pte_t scratch_pte, __iomem *gtt_base =
966 		(gen8_gtt_pte_t __iomem *) dev_priv->gtt.gsm + first_entry;
967 	const int max_entries = gtt_total_entries(dev_priv->gtt) - first_entry;
968 	int i;
969 
970 	if (WARN(num_entries > max_entries,
971 		 "First entry = %d; Num entries = %d (max=%d)\n",
972 		 first_entry, num_entries, max_entries))
973 		num_entries = max_entries;
974 
975 	scratch_pte = gen8_pte_encode(vm->scratch.addr,
976 				      I915_CACHE_LLC,
977 				      use_scratch);
978 	for (i = 0; i < num_entries; i++)
979 		gen8_set_pte(&gtt_base[i], scratch_pte);
980 	readl(gtt_base);
981 }
982 
983 static void gen6_ggtt_clear_range(struct i915_address_space *vm,
984 				  unsigned int first_entry,
985 				  unsigned int num_entries,
986 				  bool use_scratch)
987 {
988 	struct drm_i915_private *dev_priv = vm->dev->dev_private;
989 	gen6_gtt_pte_t scratch_pte, __iomem *gtt_base =
990 		(gen6_gtt_pte_t __iomem *) dev_priv->gtt.gsm + first_entry;
991 	const int max_entries = gtt_total_entries(dev_priv->gtt) - first_entry;
992 	int i;
993 
994 	if (WARN(num_entries > max_entries,
995 		 "First entry = %d; Num entries = %d (max=%d)\n",
996 		 first_entry, num_entries, max_entries))
997 		num_entries = max_entries;
998 
999 	scratch_pte = vm->pte_encode(vm->scratch.addr, I915_CACHE_LLC, use_scratch);
1000 
1001 	for (i = 0; i < num_entries; i++)
1002 		iowrite32(scratch_pte, &gtt_base[i]);
1003 	readl(gtt_base);
1004 }
1005 
1006 static void i915_ggtt_insert_entries(struct i915_address_space *vm,
1007 				     struct sg_table *st,
1008 				     unsigned int pg_start,
1009 				     enum i915_cache_level cache_level)
1010 {
1011 	unsigned int flags = (cache_level == I915_CACHE_NONE) ?
1012 		AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
1013 
1014 	intel_gtt_insert_sg_entries(st, pg_start, flags);
1015 
1016 }
1017 
1018 static void i915_ggtt_clear_range(struct i915_address_space *vm,
1019 				  unsigned int first_entry,
1020 				  unsigned int num_entries,
1021 				  bool unused)
1022 {
1023 	intel_gtt_clear_range(first_entry, num_entries);
1024 }
1025 
1026 
1027 void i915_gem_gtt_bind_object(struct drm_i915_gem_object *obj,
1028 			      enum i915_cache_level cache_level)
1029 {
1030 	struct drm_device *dev = obj->base.dev;
1031 	struct drm_i915_private *dev_priv = dev->dev_private;
1032 	const unsigned long entry = i915_gem_obj_ggtt_offset(obj) >> PAGE_SHIFT;
1033 
1034 	dev_priv->gtt.base.insert_entries(&dev_priv->gtt.base, obj->pages,
1035 					  entry,
1036 					  cache_level);
1037 
1038 	obj->has_global_gtt_mapping = 1;
1039 }
1040 
1041 void i915_gem_gtt_unbind_object(struct drm_i915_gem_object *obj)
1042 {
1043 	struct drm_device *dev = obj->base.dev;
1044 	struct drm_i915_private *dev_priv = dev->dev_private;
1045 	const unsigned long entry = i915_gem_obj_ggtt_offset(obj) >> PAGE_SHIFT;
1046 
1047 	dev_priv->gtt.base.clear_range(&dev_priv->gtt.base,
1048 				       entry,
1049 				       obj->base.size >> PAGE_SHIFT,
1050 				       true);
1051 
1052 	obj->has_global_gtt_mapping = 0;
1053 }
1054 
1055 void i915_gem_gtt_finish_object(struct drm_i915_gem_object *obj)
1056 {
1057 	struct drm_device *dev = obj->base.dev;
1058 	struct drm_i915_private *dev_priv = dev->dev_private;
1059 	bool interruptible;
1060 
1061 	interruptible = do_idling(dev_priv);
1062 
1063 	if (!obj->has_dma_mapping)
1064 		dma_unmap_sg(&dev->pdev->dev,
1065 			     obj->pages->sgl, obj->pages->nents,
1066 			     PCI_DMA_BIDIRECTIONAL);
1067 
1068 	undo_idling(dev_priv, interruptible);
1069 }
1070 
1071 static void i915_gtt_color_adjust(struct drm_mm_node *node,
1072 				  unsigned long color,
1073 				  unsigned long *start,
1074 				  unsigned long *end)
1075 {
1076 	if (node->color != color)
1077 		*start += 4096;
1078 
1079 	if (!list_empty(&node->node_list)) {
1080 		node = list_entry(node->node_list.next,
1081 				  struct drm_mm_node,
1082 				  node_list);
1083 		if (node->allocated && node->color != color)
1084 			*end -= 4096;
1085 	}
1086 }
1087 
1088 void i915_gem_setup_global_gtt(struct drm_device *dev,
1089 			       unsigned long start,
1090 			       unsigned long mappable_end,
1091 			       unsigned long end)
1092 {
1093 	/* Let GEM Manage all of the aperture.
1094 	 *
1095 	 * However, leave one page at the end still bound to the scratch page.
1096 	 * There are a number of places where the hardware apparently prefetches
1097 	 * past the end of the object, and we've seen multiple hangs with the
1098 	 * GPU head pointer stuck in a batchbuffer bound at the last page of the
1099 	 * aperture.  One page should be enough to keep any prefetching inside
1100 	 * of the aperture.
1101 	 */
1102 	struct drm_i915_private *dev_priv = dev->dev_private;
1103 	struct i915_address_space *ggtt_vm = &dev_priv->gtt.base;
1104 	struct drm_mm_node *entry;
1105 	struct drm_i915_gem_object *obj;
1106 	unsigned long hole_start, hole_end;
1107 
1108 	BUG_ON(mappable_end > end);
1109 
1110 	/* Subtract the guard page ... */
1111 	drm_mm_init(&ggtt_vm->mm, start, end - start - PAGE_SIZE);
1112 	if (!HAS_LLC(dev))
1113 		dev_priv->gtt.base.mm.color_adjust = i915_gtt_color_adjust;
1114 
1115 	/* Mark any preallocated objects as occupied */
1116 	list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
1117 		struct i915_vma *vma = i915_gem_obj_to_vma(obj, ggtt_vm);
1118 		int ret;
1119 		DRM_DEBUG_KMS("reserving preallocated space: %lx + %zx\n",
1120 			      i915_gem_obj_ggtt_offset(obj), obj->base.size);
1121 
1122 		WARN_ON(i915_gem_obj_ggtt_bound(obj));
1123 		ret = drm_mm_reserve_node(&ggtt_vm->mm, &vma->node);
1124 		if (ret)
1125 			DRM_DEBUG_KMS("Reservation failed\n");
1126 		obj->has_global_gtt_mapping = 1;
1127 		list_add(&vma->vma_link, &obj->vma_list);
1128 	}
1129 
1130 	dev_priv->gtt.base.start = start;
1131 	dev_priv->gtt.base.total = end - start;
1132 
1133 	/* Clear any non-preallocated blocks */
1134 	drm_mm_for_each_hole(entry, &ggtt_vm->mm, hole_start, hole_end) {
1135 		const unsigned long count = (hole_end - hole_start) / PAGE_SIZE;
1136 		DRM_DEBUG_KMS("clearing unused GTT space: [%lx, %lx]\n",
1137 			      hole_start, hole_end);
1138 		ggtt_vm->clear_range(ggtt_vm, hole_start / PAGE_SIZE, count, true);
1139 	}
1140 
1141 	/* And finally clear the reserved guard page */
1142 	ggtt_vm->clear_range(ggtt_vm, end / PAGE_SIZE - 1, 1, true);
1143 }
1144 
1145 static bool
1146 intel_enable_ppgtt(struct drm_device *dev)
1147 {
1148 	if (i915_enable_ppgtt >= 0)
1149 		return i915_enable_ppgtt;
1150 
1151 #ifdef CONFIG_INTEL_IOMMU
1152 	/* Disable ppgtt on SNB if VT-d is on. */
1153 	if (INTEL_INFO(dev)->gen == 6 && intel_iommu_gfx_mapped)
1154 		return false;
1155 #endif
1156 
1157 	return true;
1158 }
1159 
1160 void i915_gem_init_global_gtt(struct drm_device *dev)
1161 {
1162 	struct drm_i915_private *dev_priv = dev->dev_private;
1163 	unsigned long gtt_size, mappable_size;
1164 
1165 	gtt_size = dev_priv->gtt.base.total;
1166 	mappable_size = dev_priv->gtt.mappable_end;
1167 
1168 	if (intel_enable_ppgtt(dev) && HAS_ALIASING_PPGTT(dev)) {
1169 		int ret;
1170 
1171 		if (INTEL_INFO(dev)->gen <= 7) {
1172 			/* PPGTT pdes are stolen from global gtt ptes, so shrink the
1173 			 * aperture accordingly when using aliasing ppgtt. */
1174 			gtt_size -= GEN6_PPGTT_PD_ENTRIES * PAGE_SIZE;
1175 		}
1176 
1177 		i915_gem_setup_global_gtt(dev, 0, mappable_size, gtt_size);
1178 
1179 		ret = i915_gem_init_aliasing_ppgtt(dev);
1180 		if (!ret)
1181 			return;
1182 
1183 		DRM_ERROR("Aliased PPGTT setup failed %d\n", ret);
1184 		drm_mm_takedown(&dev_priv->gtt.base.mm);
1185 		if (INTEL_INFO(dev)->gen < 8)
1186 			gtt_size += GEN6_PPGTT_PD_ENTRIES*PAGE_SIZE;
1187 	}
1188 	i915_gem_setup_global_gtt(dev, 0, mappable_size, gtt_size);
1189 }
1190 
1191 static int setup_scratch_page(struct drm_device *dev)
1192 {
1193 	struct drm_i915_private *dev_priv = dev->dev_private;
1194 	struct page *page;
1195 	dma_addr_t dma_addr;
1196 
1197 	page = alloc_page(GFP_KERNEL | GFP_DMA32 | __GFP_ZERO);
1198 	if (page == NULL)
1199 		return -ENOMEM;
1200 	get_page(page);
1201 	set_pages_uc(page, 1);
1202 
1203 #ifdef CONFIG_INTEL_IOMMU
1204 	dma_addr = pci_map_page(dev->pdev, page, 0, PAGE_SIZE,
1205 				PCI_DMA_BIDIRECTIONAL);
1206 	if (pci_dma_mapping_error(dev->pdev, dma_addr))
1207 		return -EINVAL;
1208 #else
1209 	dma_addr = page_to_phys(page);
1210 #endif
1211 	dev_priv->gtt.base.scratch.page = page;
1212 	dev_priv->gtt.base.scratch.addr = dma_addr;
1213 
1214 	return 0;
1215 }
1216 
1217 static void teardown_scratch_page(struct drm_device *dev)
1218 {
1219 	struct drm_i915_private *dev_priv = dev->dev_private;
1220 	struct page *page = dev_priv->gtt.base.scratch.page;
1221 
1222 	set_pages_wb(page, 1);
1223 	pci_unmap_page(dev->pdev, dev_priv->gtt.base.scratch.addr,
1224 		       PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
1225 	put_page(page);
1226 	__free_page(page);
1227 }
1228 
1229 static inline unsigned int gen6_get_total_gtt_size(u16 snb_gmch_ctl)
1230 {
1231 	snb_gmch_ctl >>= SNB_GMCH_GGMS_SHIFT;
1232 	snb_gmch_ctl &= SNB_GMCH_GGMS_MASK;
1233 	return snb_gmch_ctl << 20;
1234 }
1235 
1236 static inline unsigned int gen8_get_total_gtt_size(u16 bdw_gmch_ctl)
1237 {
1238 	bdw_gmch_ctl >>= BDW_GMCH_GGMS_SHIFT;
1239 	bdw_gmch_ctl &= BDW_GMCH_GGMS_MASK;
1240 	if (bdw_gmch_ctl)
1241 		bdw_gmch_ctl = 1 << bdw_gmch_ctl;
1242 	if (bdw_gmch_ctl > 4) {
1243 		WARN_ON(!i915_preliminary_hw_support);
1244 		return 4<<20;
1245 	}
1246 
1247 	return bdw_gmch_ctl << 20;
1248 }
1249 
1250 static inline size_t gen6_get_stolen_size(u16 snb_gmch_ctl)
1251 {
1252 	snb_gmch_ctl >>= SNB_GMCH_GMS_SHIFT;
1253 	snb_gmch_ctl &= SNB_GMCH_GMS_MASK;
1254 	return snb_gmch_ctl << 25; /* 32 MB units */
1255 }
1256 
1257 static inline size_t gen8_get_stolen_size(u16 bdw_gmch_ctl)
1258 {
1259 	bdw_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
1260 	bdw_gmch_ctl &= BDW_GMCH_GMS_MASK;
1261 	return bdw_gmch_ctl << 25; /* 32 MB units */
1262 }
1263 
1264 static int ggtt_probe_common(struct drm_device *dev,
1265 			     size_t gtt_size)
1266 {
1267 	struct drm_i915_private *dev_priv = dev->dev_private;
1268 	phys_addr_t gtt_bus_addr;
1269 	int ret;
1270 
1271 	/* For Modern GENs the PTEs and register space are split in the BAR */
1272 	gtt_bus_addr = pci_resource_start(dev->pdev, 0) +
1273 		(pci_resource_len(dev->pdev, 0) / 2);
1274 
1275 	dev_priv->gtt.gsm = ioremap_wc(gtt_bus_addr, gtt_size);
1276 	if (!dev_priv->gtt.gsm) {
1277 		DRM_ERROR("Failed to map the gtt page table\n");
1278 		return -ENOMEM;
1279 	}
1280 
1281 	ret = setup_scratch_page(dev);
1282 	if (ret) {
1283 		DRM_ERROR("Scratch setup failed\n");
1284 		/* iounmap will also get called at remove, but meh */
1285 		iounmap(dev_priv->gtt.gsm);
1286 	}
1287 
1288 	return ret;
1289 }
1290 
1291 /* The GGTT and PPGTT need a private PPAT setup in order to handle cacheability
1292  * bits. When using advanced contexts each context stores its own PAT, but
1293  * writing this data shouldn't be harmful even in those cases. */
1294 static void gen8_setup_private_ppat(struct drm_i915_private *dev_priv)
1295 {
1296 #define GEN8_PPAT_UC		(0<<0)
1297 #define GEN8_PPAT_WC		(1<<0)
1298 #define GEN8_PPAT_WT		(2<<0)
1299 #define GEN8_PPAT_WB		(3<<0)
1300 #define GEN8_PPAT_ELLC_OVERRIDE	(0<<2)
1301 /* FIXME(BDW): Bspec is completely confused about cache control bits. */
1302 #define GEN8_PPAT_LLC		(1<<2)
1303 #define GEN8_PPAT_LLCELLC	(2<<2)
1304 #define GEN8_PPAT_LLCeLLC	(3<<2)
1305 #define GEN8_PPAT_AGE(x)	(x<<4)
1306 #define GEN8_PPAT(i, x) ((uint64_t) (x) << ((i) * 8))
1307 	uint64_t pat;
1308 
1309 	pat = GEN8_PPAT(0, GEN8_PPAT_WB | GEN8_PPAT_LLC)     | /* for normal objects, no eLLC */
1310 	      GEN8_PPAT(1, GEN8_PPAT_WC | GEN8_PPAT_LLCELLC) | /* for something pointing to ptes? */
1311 	      GEN8_PPAT(2, GEN8_PPAT_WT | GEN8_PPAT_LLCELLC) | /* for scanout with eLLC */
1312 	      GEN8_PPAT(3, GEN8_PPAT_UC)                     | /* Uncached objects, mostly for scanout */
1313 	      GEN8_PPAT(4, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(0)) |
1314 	      GEN8_PPAT(5, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(1)) |
1315 	      GEN8_PPAT(6, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(2)) |
1316 	      GEN8_PPAT(7, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(3));
1317 
1318 	/* XXX: spec defines this as 2 distinct registers. It's unclear if a 64b
1319 	 * write would work. */
1320 	I915_WRITE(GEN8_PRIVATE_PAT, pat);
1321 	I915_WRITE(GEN8_PRIVATE_PAT + 4, pat >> 32);
1322 }
1323 
1324 static int gen8_gmch_probe(struct drm_device *dev,
1325 			   size_t *gtt_total,
1326 			   size_t *stolen,
1327 			   phys_addr_t *mappable_base,
1328 			   unsigned long *mappable_end)
1329 {
1330 	struct drm_i915_private *dev_priv = dev->dev_private;
1331 	unsigned int gtt_size;
1332 	u16 snb_gmch_ctl;
1333 	int ret;
1334 
1335 	/* TODO: We're not aware of mappable constraints on gen8 yet */
1336 	*mappable_base = pci_resource_start(dev->pdev, 2);
1337 	*mappable_end = pci_resource_len(dev->pdev, 2);
1338 
1339 	if (!pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(39)))
1340 		pci_set_consistent_dma_mask(dev->pdev, DMA_BIT_MASK(39));
1341 
1342 	pci_read_config_word(dev->pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
1343 
1344 	*stolen = gen8_get_stolen_size(snb_gmch_ctl);
1345 
1346 	gtt_size = gen8_get_total_gtt_size(snb_gmch_ctl);
1347 	*gtt_total = (gtt_size / sizeof(gen8_gtt_pte_t)) << PAGE_SHIFT;
1348 
1349 	gen8_setup_private_ppat(dev_priv);
1350 
1351 	ret = ggtt_probe_common(dev, gtt_size);
1352 
1353 	dev_priv->gtt.base.clear_range = gen8_ggtt_clear_range;
1354 	dev_priv->gtt.base.insert_entries = gen8_ggtt_insert_entries;
1355 
1356 	return ret;
1357 }
1358 
1359 static int gen6_gmch_probe(struct drm_device *dev,
1360 			   size_t *gtt_total,
1361 			   size_t *stolen,
1362 			   phys_addr_t *mappable_base,
1363 			   unsigned long *mappable_end)
1364 {
1365 	struct drm_i915_private *dev_priv = dev->dev_private;
1366 	unsigned int gtt_size;
1367 	u16 snb_gmch_ctl;
1368 	int ret;
1369 
1370 	*mappable_base = pci_resource_start(dev->pdev, 2);
1371 	*mappable_end = pci_resource_len(dev->pdev, 2);
1372 
1373 	/* 64/512MB is the current min/max we actually know of, but this is just
1374 	 * a coarse sanity check.
1375 	 */
1376 	if ((*mappable_end < (64<<20) || (*mappable_end > (512<<20)))) {
1377 		DRM_ERROR("Unknown GMADR size (%lx)\n",
1378 			  dev_priv->gtt.mappable_end);
1379 		return -ENXIO;
1380 	}
1381 
1382 	if (!pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(40)))
1383 		pci_set_consistent_dma_mask(dev->pdev, DMA_BIT_MASK(40));
1384 	pci_read_config_word(dev->pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
1385 
1386 	*stolen = gen6_get_stolen_size(snb_gmch_ctl);
1387 
1388 	gtt_size = gen6_get_total_gtt_size(snb_gmch_ctl);
1389 	*gtt_total = (gtt_size / sizeof(gen6_gtt_pte_t)) << PAGE_SHIFT;
1390 
1391 	ret = ggtt_probe_common(dev, gtt_size);
1392 
1393 	dev_priv->gtt.base.clear_range = gen6_ggtt_clear_range;
1394 	dev_priv->gtt.base.insert_entries = gen6_ggtt_insert_entries;
1395 
1396 	return ret;
1397 }
1398 
1399 static void gen6_gmch_remove(struct i915_address_space *vm)
1400 {
1401 
1402 	struct i915_gtt *gtt = container_of(vm, struct i915_gtt, base);
1403 	iounmap(gtt->gsm);
1404 	teardown_scratch_page(vm->dev);
1405 }
1406 
1407 static int i915_gmch_probe(struct drm_device *dev,
1408 			   size_t *gtt_total,
1409 			   size_t *stolen,
1410 			   phys_addr_t *mappable_base,
1411 			   unsigned long *mappable_end)
1412 {
1413 	struct drm_i915_private *dev_priv = dev->dev_private;
1414 	int ret;
1415 
1416 	ret = intel_gmch_probe(dev_priv->bridge_dev, dev_priv->dev->pdev, NULL);
1417 	if (!ret) {
1418 		DRM_ERROR("failed to set up gmch\n");
1419 		return -EIO;
1420 	}
1421 
1422 	intel_gtt_get(gtt_total, stolen, mappable_base, mappable_end);
1423 
1424 	dev_priv->gtt.do_idle_maps = needs_idle_maps(dev_priv->dev);
1425 	dev_priv->gtt.base.clear_range = i915_ggtt_clear_range;
1426 	dev_priv->gtt.base.insert_entries = i915_ggtt_insert_entries;
1427 
1428 	return 0;
1429 }
1430 
1431 static void i915_gmch_remove(struct i915_address_space *vm)
1432 {
1433 	intel_gmch_remove();
1434 }
1435 
1436 int i915_gem_gtt_init(struct drm_device *dev)
1437 {
1438 	struct drm_i915_private *dev_priv = dev->dev_private;
1439 	struct i915_gtt *gtt = &dev_priv->gtt;
1440 	int ret;
1441 
1442 	if (INTEL_INFO(dev)->gen <= 5) {
1443 		gtt->gtt_probe = i915_gmch_probe;
1444 		gtt->base.cleanup = i915_gmch_remove;
1445 	} else if (INTEL_INFO(dev)->gen < 8) {
1446 		gtt->gtt_probe = gen6_gmch_probe;
1447 		gtt->base.cleanup = gen6_gmch_remove;
1448 		if (IS_HASWELL(dev) && dev_priv->ellc_size)
1449 			gtt->base.pte_encode = iris_pte_encode;
1450 		else if (IS_HASWELL(dev))
1451 			gtt->base.pte_encode = hsw_pte_encode;
1452 		else if (IS_VALLEYVIEW(dev))
1453 			gtt->base.pte_encode = byt_pte_encode;
1454 		else if (INTEL_INFO(dev)->gen >= 7)
1455 			gtt->base.pte_encode = ivb_pte_encode;
1456 		else
1457 			gtt->base.pte_encode = snb_pte_encode;
1458 	} else {
1459 		dev_priv->gtt.gtt_probe = gen8_gmch_probe;
1460 		dev_priv->gtt.base.cleanup = gen6_gmch_remove;
1461 	}
1462 
1463 	ret = gtt->gtt_probe(dev, &gtt->base.total, &gtt->stolen_size,
1464 			     &gtt->mappable_base, &gtt->mappable_end);
1465 	if (ret)
1466 		return ret;
1467 
1468 	gtt->base.dev = dev;
1469 
1470 	/* GMADR is the PCI mmio aperture into the global GTT. */
1471 	DRM_INFO("Memory usable by graphics device = %zdM\n",
1472 		 gtt->base.total >> 20);
1473 	DRM_DEBUG_DRIVER("GMADR size = %ldM\n", gtt->mappable_end >> 20);
1474 	DRM_DEBUG_DRIVER("GTT stolen size = %zdM\n", gtt->stolen_size >> 20);
1475 
1476 	return 0;
1477 }
1478