]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/i915_gem_gtt.c
drm/i915: Add dynamic page trace events
[karo-tx-linux.git] / drivers / gpu / drm / i915 / i915_gem_gtt.c
1 /*
2  * Copyright © 2010 Daniel Vetter
3  * Copyright © 2011-2014 Intel Corporation
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  *
24  */
25
26 #include <linux/seq_file.h>
27 #include <drm/drmP.h>
28 #include <drm/i915_drm.h>
29 #include "i915_drv.h"
30 #include "i915_vgpu.h"
31 #include "i915_trace.h"
32 #include "intel_drv.h"
33
34 /**
35  * DOC: Global GTT views
36  *
37  * Background and previous state
38  *
39  * Historically objects could exists (be bound) in global GTT space only as
40  * singular instances with a view representing all of the object's backing pages
41  * in a linear fashion. This view will be called a normal view.
42  *
43  * To support multiple views of the same object, where the number of mapped
44  * pages is not equal to the backing store, or where the layout of the pages
45  * is not linear, concept of a GGTT view was added.
46  *
47  * One example of an alternative view is a stereo display driven by a single
48  * image. In this case we would have a framebuffer looking like this
49  * (2x2 pages):
50  *
51  *    12
52  *    34
53  *
54  * Above would represent a normal GGTT view as normally mapped for GPU or CPU
55  * rendering. In contrast, fed to the display engine would be an alternative
56  * view which could look something like this:
57  *
58  *   1212
59  *   3434
60  *
61  * In this example both the size and layout of pages in the alternative view is
62  * different from the normal view.
63  *
64  * Implementation and usage
65  *
66  * GGTT views are implemented using VMAs and are distinguished via enum
67  * i915_ggtt_view_type and struct i915_ggtt_view.
68  *
69  * A new flavour of core GEM functions which work with GGTT bound objects were
70  * added with the _ggtt_ infix, and sometimes with _view postfix to avoid
71  * renaming  in large amounts of code. They take the struct i915_ggtt_view
72  * parameter encapsulating all metadata required to implement a view.
73  *
74  * As a helper for callers which are only interested in the normal view,
75  * globally const i915_ggtt_view_normal singleton instance exists. All old core
76  * GEM API functions, the ones not taking the view parameter, are operating on,
77  * or with the normal GGTT view.
78  *
79  * Code wanting to add or use a new GGTT view needs to:
80  *
81  * 1. Add a new enum with a suitable name.
82  * 2. Extend the metadata in the i915_ggtt_view structure if required.
83  * 3. Add support to i915_get_vma_pages().
84  *
85  * New views are required to build a scatter-gather table from within the
86  * i915_get_vma_pages function. This table is stored in the vma.ggtt_view and
87  * exists for the lifetime of an VMA.
88  *
89  * Core API is designed to have copy semantics which means that passed in
90  * struct i915_ggtt_view does not need to be persistent (left around after
91  * calling the core API functions).
92  *
93  */
94
95 const struct i915_ggtt_view i915_ggtt_view_normal;
96
97 static void bdw_setup_private_ppat(struct drm_i915_private *dev_priv);
98 static void chv_setup_private_ppat(struct drm_i915_private *dev_priv);
99
100 static int sanitize_enable_ppgtt(struct drm_device *dev, int enable_ppgtt)
101 {
102         bool has_aliasing_ppgtt;
103         bool has_full_ppgtt;
104
105         has_aliasing_ppgtt = INTEL_INFO(dev)->gen >= 6;
106         has_full_ppgtt = INTEL_INFO(dev)->gen >= 7;
107
108         if (intel_vgpu_active(dev))
109                 has_full_ppgtt = false; /* emulation is too hard */
110
111         /*
112          * We don't allow disabling PPGTT for gen9+ as it's a requirement for
113          * execlists, the sole mechanism available to submit work.
114          */
115         if (INTEL_INFO(dev)->gen < 9 &&
116             (enable_ppgtt == 0 || !has_aliasing_ppgtt))
117                 return 0;
118
119         if (enable_ppgtt == 1)
120                 return 1;
121
122         if (enable_ppgtt == 2 && has_full_ppgtt)
123                 return 2;
124
125 #ifdef CONFIG_INTEL_IOMMU
126         /* Disable ppgtt on SNB if VT-d is on. */
127         if (INTEL_INFO(dev)->gen == 6 && intel_iommu_gfx_mapped) {
128                 DRM_INFO("Disabling PPGTT because VT-d is on\n");
129                 return 0;
130         }
131 #endif
132
133         /* Early VLV doesn't have this */
134         if (IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
135             dev->pdev->revision < 0xb) {
136                 DRM_DEBUG_DRIVER("disabling PPGTT on pre-B3 step VLV\n");
137                 return 0;
138         }
139
140         if (INTEL_INFO(dev)->gen >= 8 && i915.enable_execlists)
141                 return 2;
142         else
143                 return has_aliasing_ppgtt ? 1 : 0;
144 }
145
146 static void ppgtt_bind_vma(struct i915_vma *vma,
147                            enum i915_cache_level cache_level,
148                            u32 flags);
149 static void ppgtt_unbind_vma(struct i915_vma *vma);
150
151 static inline gen8_pte_t gen8_pte_encode(dma_addr_t addr,
152                                          enum i915_cache_level level,
153                                          bool valid)
154 {
155         gen8_pte_t pte = valid ? _PAGE_PRESENT | _PAGE_RW : 0;
156         pte |= addr;
157
158         switch (level) {
159         case I915_CACHE_NONE:
160                 pte |= PPAT_UNCACHED_INDEX;
161                 break;
162         case I915_CACHE_WT:
163                 pte |= PPAT_DISPLAY_ELLC_INDEX;
164                 break;
165         default:
166                 pte |= PPAT_CACHED_INDEX;
167                 break;
168         }
169
170         return pte;
171 }
172
173 static inline gen8_pde_t gen8_pde_encode(struct drm_device *dev,
174                                           dma_addr_t addr,
175                                           enum i915_cache_level level)
176 {
177         gen8_pde_t pde = _PAGE_PRESENT | _PAGE_RW;
178         pde |= addr;
179         if (level != I915_CACHE_NONE)
180                 pde |= PPAT_CACHED_PDE_INDEX;
181         else
182                 pde |= PPAT_UNCACHED_INDEX;
183         return pde;
184 }
185
186 static gen6_pte_t snb_pte_encode(dma_addr_t addr,
187                                  enum i915_cache_level level,
188                                  bool valid, u32 unused)
189 {
190         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
191         pte |= GEN6_PTE_ADDR_ENCODE(addr);
192
193         switch (level) {
194         case I915_CACHE_L3_LLC:
195         case I915_CACHE_LLC:
196                 pte |= GEN6_PTE_CACHE_LLC;
197                 break;
198         case I915_CACHE_NONE:
199                 pte |= GEN6_PTE_UNCACHED;
200                 break;
201         default:
202                 MISSING_CASE(level);
203         }
204
205         return pte;
206 }
207
208 static gen6_pte_t ivb_pte_encode(dma_addr_t addr,
209                                  enum i915_cache_level level,
210                                  bool valid, u32 unused)
211 {
212         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
213         pte |= GEN6_PTE_ADDR_ENCODE(addr);
214
215         switch (level) {
216         case I915_CACHE_L3_LLC:
217                 pte |= GEN7_PTE_CACHE_L3_LLC;
218                 break;
219         case I915_CACHE_LLC:
220                 pte |= GEN6_PTE_CACHE_LLC;
221                 break;
222         case I915_CACHE_NONE:
223                 pte |= GEN6_PTE_UNCACHED;
224                 break;
225         default:
226                 MISSING_CASE(level);
227         }
228
229         return pte;
230 }
231
232 static gen6_pte_t byt_pte_encode(dma_addr_t addr,
233                                  enum i915_cache_level level,
234                                  bool valid, u32 flags)
235 {
236         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
237         pte |= GEN6_PTE_ADDR_ENCODE(addr);
238
239         if (!(flags & PTE_READ_ONLY))
240                 pte |= BYT_PTE_WRITEABLE;
241
242         if (level != I915_CACHE_NONE)
243                 pte |= BYT_PTE_SNOOPED_BY_CPU_CACHES;
244
245         return pte;
246 }
247
248 static gen6_pte_t hsw_pte_encode(dma_addr_t addr,
249                                  enum i915_cache_level level,
250                                  bool valid, u32 unused)
251 {
252         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
253         pte |= HSW_PTE_ADDR_ENCODE(addr);
254
255         if (level != I915_CACHE_NONE)
256                 pte |= HSW_WB_LLC_AGE3;
257
258         return pte;
259 }
260
261 static gen6_pte_t iris_pte_encode(dma_addr_t addr,
262                                   enum i915_cache_level level,
263                                   bool valid, u32 unused)
264 {
265         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
266         pte |= HSW_PTE_ADDR_ENCODE(addr);
267
268         switch (level) {
269         case I915_CACHE_NONE:
270                 break;
271         case I915_CACHE_WT:
272                 pte |= HSW_WT_ELLC_LLC_AGE3;
273                 break;
274         default:
275                 pte |= HSW_WB_ELLC_LLC_AGE3;
276                 break;
277         }
278
279         return pte;
280 }
281
282 #define i915_dma_unmap_single(px, dev) \
283         __i915_dma_unmap_single((px)->daddr, dev)
284
285 static inline void __i915_dma_unmap_single(dma_addr_t daddr,
286                                         struct drm_device *dev)
287 {
288         struct device *device = &dev->pdev->dev;
289
290         dma_unmap_page(device, daddr, 4096, PCI_DMA_BIDIRECTIONAL);
291 }
292
293 /**
294  * i915_dma_map_single() - Create a dma mapping for a page table/dir/etc.
295  * @px: Page table/dir/etc to get a DMA map for
296  * @dev:        drm device
297  *
298  * Page table allocations are unified across all gens. They always require a
299  * single 4k allocation, as well as a DMA mapping. If we keep the structs
300  * symmetric here, the simple macro covers us for every page table type.
301  *
302  * Return: 0 if success.
303  */
304 #define i915_dma_map_single(px, dev) \
305         i915_dma_map_page_single((px)->page, (dev), &(px)->daddr)
306
307 static inline int i915_dma_map_page_single(struct page *page,
308                                            struct drm_device *dev,
309                                            dma_addr_t *daddr)
310 {
311         struct device *device = &dev->pdev->dev;
312
313         *daddr = dma_map_page(device, page, 0, 4096, PCI_DMA_BIDIRECTIONAL);
314         if (dma_mapping_error(device, *daddr))
315                 return -ENOMEM;
316
317         return 0;
318 }
319
320 static void unmap_and_free_pt(struct i915_page_table_entry *pt,
321                                struct drm_device *dev)
322 {
323         if (WARN_ON(!pt->page))
324                 return;
325
326         i915_dma_unmap_single(pt, dev);
327         __free_page(pt->page);
328         kfree(pt->used_ptes);
329         kfree(pt);
330 }
331
332 static struct i915_page_table_entry *alloc_pt_single(struct drm_device *dev)
333 {
334         struct i915_page_table_entry *pt;
335         const size_t count = INTEL_INFO(dev)->gen >= 8 ?
336                 GEN8_PTES : GEN6_PTES;
337         int ret = -ENOMEM;
338
339         pt = kzalloc(sizeof(*pt), GFP_KERNEL);
340         if (!pt)
341                 return ERR_PTR(-ENOMEM);
342
343         pt->used_ptes = kcalloc(BITS_TO_LONGS(count), sizeof(*pt->used_ptes),
344                                 GFP_KERNEL);
345
346         if (!pt->used_ptes)
347                 goto fail_bitmap;
348
349         pt->page = alloc_page(GFP_KERNEL);
350         if (!pt->page)
351                 goto fail_page;
352
353         ret = i915_dma_map_single(pt, dev);
354         if (ret)
355                 goto fail_dma;
356
357         return pt;
358
359 fail_dma:
360         __free_page(pt->page);
361 fail_page:
362         kfree(pt->used_ptes);
363 fail_bitmap:
364         kfree(pt);
365
366         return ERR_PTR(ret);
367 }
368
369 /**
370  * alloc_pt_range() - Allocate a multiple page tables
371  * @pd:         The page directory which will have at least @count entries
372  *              available to point to the allocated page tables.
373  * @pde:        First page directory entry for which we are allocating.
374  * @count:      Number of pages to allocate.
375  * @dev:        DRM device.
376  *
377  * Allocates multiple page table pages and sets the appropriate entries in the
378  * page table structure within the page directory. Function cleans up after
379  * itself on any failures.
380  *
381  * Return: 0 if allocation succeeded.
382  */
383 static int alloc_pt_range(struct i915_page_directory_entry *pd, uint16_t pde, size_t count,
384                           struct drm_device *dev)
385 {
386         int i, ret;
387
388         /* 512 is the max page tables per page_directory on any platform. */
389         if (WARN_ON(pde + count > I915_PDES))
390                 return -EINVAL;
391
392         for (i = pde; i < pde + count; i++) {
393                 struct i915_page_table_entry *pt = alloc_pt_single(dev);
394
395                 if (IS_ERR(pt)) {
396                         ret = PTR_ERR(pt);
397                         goto err_out;
398                 }
399                 WARN(pd->page_table[i],
400                      "Leaking page directory entry %d (%p)\n",
401                      i, pd->page_table[i]);
402                 pd->page_table[i] = pt;
403         }
404
405         return 0;
406
407 err_out:
408         while (i-- > pde)
409                 unmap_and_free_pt(pd->page_table[i], dev);
410         return ret;
411 }
412
413 static void unmap_and_free_pd(struct i915_page_directory_entry *pd)
414 {
415         if (pd->page) {
416                 __free_page(pd->page);
417                 kfree(pd);
418         }
419 }
420
421 static struct i915_page_directory_entry *alloc_pd_single(void)
422 {
423         struct i915_page_directory_entry *pd;
424
425         pd = kzalloc(sizeof(*pd), GFP_KERNEL);
426         if (!pd)
427                 return ERR_PTR(-ENOMEM);
428
429         pd->page = alloc_page(GFP_KERNEL | __GFP_ZERO);
430         if (!pd->page) {
431                 kfree(pd);
432                 return ERR_PTR(-ENOMEM);
433         }
434
435         return pd;
436 }
437
438 /* Broadwell Page Directory Pointer Descriptors */
439 static int gen8_write_pdp(struct intel_engine_cs *ring, unsigned entry,
440                            uint64_t val)
441 {
442         int ret;
443
444         BUG_ON(entry >= 4);
445
446         ret = intel_ring_begin(ring, 6);
447         if (ret)
448                 return ret;
449
450         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
451         intel_ring_emit(ring, GEN8_RING_PDP_UDW(ring, entry));
452         intel_ring_emit(ring, (u32)(val >> 32));
453         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
454         intel_ring_emit(ring, GEN8_RING_PDP_LDW(ring, entry));
455         intel_ring_emit(ring, (u32)(val));
456         intel_ring_advance(ring);
457
458         return 0;
459 }
460
461 static int gen8_mm_switch(struct i915_hw_ppgtt *ppgtt,
462                           struct intel_engine_cs *ring)
463 {
464         int i, ret;
465
466         /* bit of a hack to find the actual last used pd */
467         int used_pd = ppgtt->num_pd_entries / I915_PDES;
468
469         for (i = used_pd - 1; i >= 0; i--) {
470                 dma_addr_t addr = ppgtt->pdp.page_directory[i]->daddr;
471                 ret = gen8_write_pdp(ring, i, addr);
472                 if (ret)
473                         return ret;
474         }
475
476         return 0;
477 }
478
479 static void gen8_ppgtt_clear_range(struct i915_address_space *vm,
480                                    uint64_t start,
481                                    uint64_t length,
482                                    bool use_scratch)
483 {
484         struct i915_hw_ppgtt *ppgtt =
485                 container_of(vm, struct i915_hw_ppgtt, base);
486         gen8_pte_t *pt_vaddr, scratch_pte;
487         unsigned pdpe = start >> GEN8_PDPE_SHIFT & GEN8_PDPE_MASK;
488         unsigned pde = start >> GEN8_PDE_SHIFT & GEN8_PDE_MASK;
489         unsigned pte = start >> GEN8_PTE_SHIFT & GEN8_PTE_MASK;
490         unsigned num_entries = length >> PAGE_SHIFT;
491         unsigned last_pte, i;
492
493         scratch_pte = gen8_pte_encode(ppgtt->base.scratch.addr,
494                                       I915_CACHE_LLC, use_scratch);
495
496         while (num_entries) {
497                 struct i915_page_directory_entry *pd;
498                 struct i915_page_table_entry *pt;
499                 struct page *page_table;
500
501                 if (WARN_ON(!ppgtt->pdp.page_directory[pdpe]))
502                         continue;
503
504                 pd = ppgtt->pdp.page_directory[pdpe];
505
506                 if (WARN_ON(!pd->page_table[pde]))
507                         continue;
508
509                 pt = pd->page_table[pde];
510
511                 if (WARN_ON(!pt->page))
512                         continue;
513
514                 page_table = pt->page;
515
516                 last_pte = pte + num_entries;
517                 if (last_pte > GEN8_PTES)
518                         last_pte = GEN8_PTES;
519
520                 pt_vaddr = kmap_atomic(page_table);
521
522                 for (i = pte; i < last_pte; i++) {
523                         pt_vaddr[i] = scratch_pte;
524                         num_entries--;
525                 }
526
527                 if (!HAS_LLC(ppgtt->base.dev))
528                         drm_clflush_virt_range(pt_vaddr, PAGE_SIZE);
529                 kunmap_atomic(pt_vaddr);
530
531                 pte = 0;
532                 if (++pde == I915_PDES) {
533                         pdpe++;
534                         pde = 0;
535                 }
536         }
537 }
538
539 static void gen8_ppgtt_insert_entries(struct i915_address_space *vm,
540                                       struct sg_table *pages,
541                                       uint64_t start,
542                                       enum i915_cache_level cache_level, u32 unused)
543 {
544         struct i915_hw_ppgtt *ppgtt =
545                 container_of(vm, struct i915_hw_ppgtt, base);
546         gen8_pte_t *pt_vaddr;
547         unsigned pdpe = start >> GEN8_PDPE_SHIFT & GEN8_PDPE_MASK;
548         unsigned pde = start >> GEN8_PDE_SHIFT & GEN8_PDE_MASK;
549         unsigned pte = start >> GEN8_PTE_SHIFT & GEN8_PTE_MASK;
550         struct sg_page_iter sg_iter;
551
552         pt_vaddr = NULL;
553
554         for_each_sg_page(pages->sgl, &sg_iter, pages->nents, 0) {
555                 if (WARN_ON(pdpe >= GEN8_LEGACY_PDPES))
556                         break;
557
558                 if (pt_vaddr == NULL) {
559                         struct i915_page_directory_entry *pd = ppgtt->pdp.page_directory[pdpe];
560                         struct i915_page_table_entry *pt = pd->page_table[pde];
561                         struct page *page_table = pt->page;
562
563                         pt_vaddr = kmap_atomic(page_table);
564                 }
565
566                 pt_vaddr[pte] =
567                         gen8_pte_encode(sg_page_iter_dma_address(&sg_iter),
568                                         cache_level, true);
569                 if (++pte == GEN8_PTES) {
570                         if (!HAS_LLC(ppgtt->base.dev))
571                                 drm_clflush_virt_range(pt_vaddr, PAGE_SIZE);
572                         kunmap_atomic(pt_vaddr);
573                         pt_vaddr = NULL;
574                         if (++pde == I915_PDES) {
575                                 pdpe++;
576                                 pde = 0;
577                         }
578                         pte = 0;
579                 }
580         }
581         if (pt_vaddr) {
582                 if (!HAS_LLC(ppgtt->base.dev))
583                         drm_clflush_virt_range(pt_vaddr, PAGE_SIZE);
584                 kunmap_atomic(pt_vaddr);
585         }
586 }
587
588 static void gen8_free_page_tables(struct i915_page_directory_entry *pd, struct drm_device *dev)
589 {
590         int i;
591
592         if (!pd->page)
593                 return;
594
595         for (i = 0; i < I915_PDES; i++) {
596                 if (WARN_ON(!pd->page_table[i]))
597                         continue;
598
599                 unmap_and_free_pt(pd->page_table[i], dev);
600                 pd->page_table[i] = NULL;
601         }
602 }
603
604 static void gen8_ppgtt_free(struct i915_hw_ppgtt *ppgtt)
605 {
606         int i;
607
608         for (i = 0; i < ppgtt->num_pd_pages; i++) {
609                 if (WARN_ON(!ppgtt->pdp.page_directory[i]))
610                         continue;
611
612                 gen8_free_page_tables(ppgtt->pdp.page_directory[i], ppgtt->base.dev);
613                 unmap_and_free_pd(ppgtt->pdp.page_directory[i]);
614         }
615 }
616
617 static void gen8_ppgtt_unmap_pages(struct i915_hw_ppgtt *ppgtt)
618 {
619         struct pci_dev *hwdev = ppgtt->base.dev->pdev;
620         int i, j;
621
622         for (i = 0; i < ppgtt->num_pd_pages; i++) {
623                 /* TODO: In the future we'll support sparse mappings, so this
624                  * will have to change. */
625                 if (!ppgtt->pdp.page_directory[i]->daddr)
626                         continue;
627
628                 pci_unmap_page(hwdev, ppgtt->pdp.page_directory[i]->daddr, PAGE_SIZE,
629                                PCI_DMA_BIDIRECTIONAL);
630
631                 for (j = 0; j < I915_PDES; j++) {
632                         struct i915_page_directory_entry *pd = ppgtt->pdp.page_directory[i];
633                         struct i915_page_table_entry *pt;
634                         dma_addr_t addr;
635
636                         if (WARN_ON(!pd->page_table[j]))
637                                 continue;
638
639                         pt = pd->page_table[j];
640                         addr = pt->daddr;
641
642                         if (addr)
643                                 pci_unmap_page(hwdev, addr, PAGE_SIZE,
644                                                PCI_DMA_BIDIRECTIONAL);
645                 }
646         }
647 }
648
649 static void gen8_ppgtt_cleanup(struct i915_address_space *vm)
650 {
651         struct i915_hw_ppgtt *ppgtt =
652                 container_of(vm, struct i915_hw_ppgtt, base);
653
654         gen8_ppgtt_unmap_pages(ppgtt);
655         gen8_ppgtt_free(ppgtt);
656 }
657
658 static int gen8_ppgtt_allocate_page_tables(struct i915_hw_ppgtt *ppgtt)
659 {
660         int i, ret;
661
662         for (i = 0; i < ppgtt->num_pd_pages; i++) {
663                 ret = alloc_pt_range(ppgtt->pdp.page_directory[i],
664                                      0, I915_PDES, ppgtt->base.dev);
665                 if (ret)
666                         goto unwind_out;
667         }
668
669         return 0;
670
671 unwind_out:
672         while (i--)
673                 gen8_free_page_tables(ppgtt->pdp.page_directory[i], ppgtt->base.dev);
674
675         return -ENOMEM;
676 }
677
678 static int gen8_ppgtt_allocate_page_directories(struct i915_hw_ppgtt *ppgtt,
679                                                 const int max_pdp)
680 {
681         int i;
682
683         for (i = 0; i < max_pdp; i++) {
684                 ppgtt->pdp.page_directory[i] = alloc_pd_single();
685                 if (IS_ERR(ppgtt->pdp.page_directory[i]))
686                         goto unwind_out;
687         }
688
689         ppgtt->num_pd_pages = max_pdp;
690         BUG_ON(ppgtt->num_pd_pages > GEN8_LEGACY_PDPES);
691
692         return 0;
693
694 unwind_out:
695         while (i--)
696                 unmap_and_free_pd(ppgtt->pdp.page_directory[i]);
697
698         return -ENOMEM;
699 }
700
701 static int gen8_ppgtt_alloc(struct i915_hw_ppgtt *ppgtt,
702                             const int max_pdp)
703 {
704         int ret;
705
706         ret = gen8_ppgtt_allocate_page_directories(ppgtt, max_pdp);
707         if (ret)
708                 return ret;
709
710         ret = gen8_ppgtt_allocate_page_tables(ppgtt);
711         if (ret)
712                 goto err_out;
713
714         ppgtt->num_pd_entries = max_pdp * I915_PDES;
715
716         return 0;
717
718 err_out:
719         gen8_ppgtt_free(ppgtt);
720         return ret;
721 }
722
723 static int gen8_ppgtt_setup_page_directories(struct i915_hw_ppgtt *ppgtt,
724                                              const int pd)
725 {
726         dma_addr_t pd_addr;
727         int ret;
728
729         pd_addr = pci_map_page(ppgtt->base.dev->pdev,
730                                ppgtt->pdp.page_directory[pd]->page, 0,
731                                PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
732
733         ret = pci_dma_mapping_error(ppgtt->base.dev->pdev, pd_addr);
734         if (ret)
735                 return ret;
736
737         ppgtt->pdp.page_directory[pd]->daddr = pd_addr;
738
739         return 0;
740 }
741
742 static int gen8_ppgtt_setup_page_tables(struct i915_hw_ppgtt *ppgtt,
743                                         const int pd,
744                                         const int pt)
745 {
746         dma_addr_t pt_addr;
747         struct i915_page_directory_entry *pdir = ppgtt->pdp.page_directory[pd];
748         struct i915_page_table_entry *ptab = pdir->page_table[pt];
749         struct page *p = ptab->page;
750         int ret;
751
752         pt_addr = pci_map_page(ppgtt->base.dev->pdev,
753                                p, 0, PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
754         ret = pci_dma_mapping_error(ppgtt->base.dev->pdev, pt_addr);
755         if (ret)
756                 return ret;
757
758         ptab->daddr = pt_addr;
759
760         return 0;
761 }
762
763 /*
764  * GEN8 legacy ppgtt programming is accomplished through a max 4 PDP registers
765  * with a net effect resembling a 2-level page table in normal x86 terms. Each
766  * PDP represents 1GB of memory 4 * 512 * 512 * 4096 = 4GB legacy 32b address
767  * space.
768  *
769  * FIXME: split allocation into smaller pieces. For now we only ever do this
770  * once, but with full PPGTT, the multiple contiguous allocations will be bad.
771  * TODO: Do something with the size parameter
772  */
773 static int gen8_ppgtt_init(struct i915_hw_ppgtt *ppgtt, uint64_t size)
774 {
775         const int max_pdp = DIV_ROUND_UP(size, 1 << 30);
776         const int min_pt_pages = I915_PDES * max_pdp;
777         int i, j, ret;
778
779         if (size % (1<<30))
780                 DRM_INFO("Pages will be wasted unless GTT size (%llu) is divisible by 1GB\n", size);
781
782         /* 1. Do all our allocations for page directories and page tables.
783          * We allocate more than was asked so that we can point the unused parts
784          * to valid entries that point to scratch page. Dynamic page tables
785          * will fix this eventually.
786          */
787         ret = gen8_ppgtt_alloc(ppgtt, GEN8_LEGACY_PDPES);
788         if (ret)
789                 return ret;
790
791         /*
792          * 2. Create DMA mappings for the page directories and page tables.
793          */
794         for (i = 0; i < GEN8_LEGACY_PDPES; i++) {
795                 ret = gen8_ppgtt_setup_page_directories(ppgtt, i);
796                 if (ret)
797                         goto bail;
798
799                 for (j = 0; j < I915_PDES; j++) {
800                         ret = gen8_ppgtt_setup_page_tables(ppgtt, i, j);
801                         if (ret)
802                                 goto bail;
803                 }
804         }
805
806         /*
807          * 3. Map all the page directory entires to point to the page tables
808          * we've allocated.
809          *
810          * For now, the PPGTT helper functions all require that the PDEs are
811          * plugged in correctly. So we do that now/here. For aliasing PPGTT, we
812          * will never need to touch the PDEs again.
813          */
814         for (i = 0; i < GEN8_LEGACY_PDPES; i++) {
815                 struct i915_page_directory_entry *pd = ppgtt->pdp.page_directory[i];
816                 gen8_pde_t *pd_vaddr;
817                 pd_vaddr = kmap_atomic(ppgtt->pdp.page_directory[i]->page);
818                 for (j = 0; j < I915_PDES; j++) {
819                         struct i915_page_table_entry *pt = pd->page_table[j];
820                         dma_addr_t addr = pt->daddr;
821                         pd_vaddr[j] = gen8_pde_encode(ppgtt->base.dev, addr,
822                                                       I915_CACHE_LLC);
823                 }
824                 if (!HAS_LLC(ppgtt->base.dev))
825                         drm_clflush_virt_range(pd_vaddr, PAGE_SIZE);
826                 kunmap_atomic(pd_vaddr);
827         }
828
829         ppgtt->switch_mm = gen8_mm_switch;
830         ppgtt->base.clear_range = gen8_ppgtt_clear_range;
831         ppgtt->base.insert_entries = gen8_ppgtt_insert_entries;
832         ppgtt->base.cleanup = gen8_ppgtt_cleanup;
833         ppgtt->base.start = 0;
834
835         /* This is the area that we advertise as usable for the caller */
836         ppgtt->base.total = max_pdp * I915_PDES * GEN8_PTES * PAGE_SIZE;
837
838         /* Set all ptes to a valid scratch page. Also above requested space */
839         ppgtt->base.clear_range(&ppgtt->base, 0,
840                                 ppgtt->num_pd_pages * GEN8_PTES * PAGE_SIZE,
841                                 true);
842
843         DRM_DEBUG_DRIVER("Allocated %d pages for page directories (%d wasted)\n",
844                          ppgtt->num_pd_pages, ppgtt->num_pd_pages - max_pdp);
845         DRM_DEBUG_DRIVER("Allocated %d pages for page tables (%lld wasted)\n",
846                          ppgtt->num_pd_entries,
847                          (ppgtt->num_pd_entries - min_pt_pages) + size % (1<<30));
848         return 0;
849
850 bail:
851         gen8_ppgtt_unmap_pages(ppgtt);
852         gen8_ppgtt_free(ppgtt);
853         return ret;
854 }
855
856 static void gen6_dump_ppgtt(struct i915_hw_ppgtt *ppgtt, struct seq_file *m)
857 {
858         struct drm_i915_private *dev_priv = ppgtt->base.dev->dev_private;
859         struct i915_address_space *vm = &ppgtt->base;
860         gen6_pte_t __iomem *pd_addr;
861         gen6_pte_t scratch_pte;
862         uint32_t pd_entry;
863         int pte, pde;
864
865         scratch_pte = vm->pte_encode(vm->scratch.addr, I915_CACHE_LLC, true, 0);
866
867         pd_addr = (gen6_pte_t __iomem *)dev_priv->gtt.gsm +
868                 ppgtt->pd.pd_offset / sizeof(gen6_pte_t);
869
870         seq_printf(m, "  VM %p (pd_offset %x-%x):\n", vm,
871                    ppgtt->pd.pd_offset,
872                    ppgtt->pd.pd_offset + ppgtt->num_pd_entries);
873         for (pde = 0; pde < ppgtt->num_pd_entries; pde++) {
874                 u32 expected;
875                 gen6_pte_t *pt_vaddr;
876                 dma_addr_t pt_addr = ppgtt->pd.page_table[pde]->daddr;
877                 pd_entry = readl(pd_addr + pde);
878                 expected = (GEN6_PDE_ADDR_ENCODE(pt_addr) | GEN6_PDE_VALID);
879
880                 if (pd_entry != expected)
881                         seq_printf(m, "\tPDE #%d mismatch: Actual PDE: %x Expected PDE: %x\n",
882                                    pde,
883                                    pd_entry,
884                                    expected);
885                 seq_printf(m, "\tPDE: %x\n", pd_entry);
886
887                 pt_vaddr = kmap_atomic(ppgtt->pd.page_table[pde]->page);
888                 for (pte = 0; pte < GEN6_PTES; pte+=4) {
889                         unsigned long va =
890                                 (pde * PAGE_SIZE * GEN6_PTES) +
891                                 (pte * PAGE_SIZE);
892                         int i;
893                         bool found = false;
894                         for (i = 0; i < 4; i++)
895                                 if (pt_vaddr[pte + i] != scratch_pte)
896                                         found = true;
897                         if (!found)
898                                 continue;
899
900                         seq_printf(m, "\t\t0x%lx [%03d,%04d]: =", va, pde, pte);
901                         for (i = 0; i < 4; i++) {
902                                 if (pt_vaddr[pte + i] != scratch_pte)
903                                         seq_printf(m, " %08x", pt_vaddr[pte + i]);
904                                 else
905                                         seq_puts(m, "  SCRATCH ");
906                         }
907                         seq_puts(m, "\n");
908                 }
909                 kunmap_atomic(pt_vaddr);
910         }
911 }
912
913 /* Write pde (index) from the page directory @pd to the page table @pt */
914 static void gen6_write_pde(struct i915_page_directory_entry *pd,
915                             const int pde, struct i915_page_table_entry *pt)
916 {
917         /* Caller needs to make sure the write completes if necessary */
918         struct i915_hw_ppgtt *ppgtt =
919                 container_of(pd, struct i915_hw_ppgtt, pd);
920         u32 pd_entry;
921
922         pd_entry = GEN6_PDE_ADDR_ENCODE(pt->daddr);
923         pd_entry |= GEN6_PDE_VALID;
924
925         writel(pd_entry, ppgtt->pd_addr + pde);
926 }
927
928 /* Write all the page tables found in the ppgtt structure to incrementing page
929  * directories. */
930 static void gen6_write_page_range(struct drm_i915_private *dev_priv,
931                                   struct i915_page_directory_entry *pd,
932                                   uint32_t start, uint32_t length)
933 {
934         struct i915_page_table_entry *pt;
935         uint32_t pde, temp;
936
937         gen6_for_each_pde(pt, pd, start, length, temp, pde)
938                 gen6_write_pde(pd, pde, pt);
939
940         /* Make sure write is complete before other code can use this page
941          * table. Also require for WC mapped PTEs */
942         readl(dev_priv->gtt.gsm);
943 }
944
945 static uint32_t get_pd_offset(struct i915_hw_ppgtt *ppgtt)
946 {
947         BUG_ON(ppgtt->pd.pd_offset & 0x3f);
948
949         return (ppgtt->pd.pd_offset / 64) << 16;
950 }
951
952 static int hsw_mm_switch(struct i915_hw_ppgtt *ppgtt,
953                          struct intel_engine_cs *ring)
954 {
955         int ret;
956
957         /* NB: TLBs must be flushed and invalidated before a switch */
958         ret = ring->flush(ring, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
959         if (ret)
960                 return ret;
961
962         ret = intel_ring_begin(ring, 6);
963         if (ret)
964                 return ret;
965
966         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(2));
967         intel_ring_emit(ring, RING_PP_DIR_DCLV(ring));
968         intel_ring_emit(ring, PP_DIR_DCLV_2G);
969         intel_ring_emit(ring, RING_PP_DIR_BASE(ring));
970         intel_ring_emit(ring, get_pd_offset(ppgtt));
971         intel_ring_emit(ring, MI_NOOP);
972         intel_ring_advance(ring);
973
974         return 0;
975 }
976
977 static int vgpu_mm_switch(struct i915_hw_ppgtt *ppgtt,
978                           struct intel_engine_cs *ring)
979 {
980         struct drm_i915_private *dev_priv = to_i915(ppgtt->base.dev);
981
982         I915_WRITE(RING_PP_DIR_DCLV(ring), PP_DIR_DCLV_2G);
983         I915_WRITE(RING_PP_DIR_BASE(ring), get_pd_offset(ppgtt));
984         return 0;
985 }
986
987 static int gen7_mm_switch(struct i915_hw_ppgtt *ppgtt,
988                           struct intel_engine_cs *ring)
989 {
990         int ret;
991
992         /* NB: TLBs must be flushed and invalidated before a switch */
993         ret = ring->flush(ring, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
994         if (ret)
995                 return ret;
996
997         ret = intel_ring_begin(ring, 6);
998         if (ret)
999                 return ret;
1000
1001         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(2));
1002         intel_ring_emit(ring, RING_PP_DIR_DCLV(ring));
1003         intel_ring_emit(ring, PP_DIR_DCLV_2G);
1004         intel_ring_emit(ring, RING_PP_DIR_BASE(ring));
1005         intel_ring_emit(ring, get_pd_offset(ppgtt));
1006         intel_ring_emit(ring, MI_NOOP);
1007         intel_ring_advance(ring);
1008
1009         /* XXX: RCS is the only one to auto invalidate the TLBs? */
1010         if (ring->id != RCS) {
1011                 ret = ring->flush(ring, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
1012                 if (ret)
1013                         return ret;
1014         }
1015
1016         return 0;
1017 }
1018
1019 static int gen6_mm_switch(struct i915_hw_ppgtt *ppgtt,
1020                           struct intel_engine_cs *ring)
1021 {
1022         struct drm_device *dev = ppgtt->base.dev;
1023         struct drm_i915_private *dev_priv = dev->dev_private;
1024
1025
1026         I915_WRITE(RING_PP_DIR_DCLV(ring), PP_DIR_DCLV_2G);
1027         I915_WRITE(RING_PP_DIR_BASE(ring), get_pd_offset(ppgtt));
1028
1029         POSTING_READ(RING_PP_DIR_DCLV(ring));
1030
1031         return 0;
1032 }
1033
1034 static void gen8_ppgtt_enable(struct drm_device *dev)
1035 {
1036         struct drm_i915_private *dev_priv = dev->dev_private;
1037         struct intel_engine_cs *ring;
1038         int j;
1039
1040         for_each_ring(ring, dev_priv, j) {
1041                 I915_WRITE(RING_MODE_GEN7(ring),
1042                            _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1043         }
1044 }
1045
1046 static void gen7_ppgtt_enable(struct drm_device *dev)
1047 {
1048         struct drm_i915_private *dev_priv = dev->dev_private;
1049         struct intel_engine_cs *ring;
1050         uint32_t ecochk, ecobits;
1051         int i;
1052
1053         ecobits = I915_READ(GAC_ECO_BITS);
1054         I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_PPGTT_CACHE64B);
1055
1056         ecochk = I915_READ(GAM_ECOCHK);
1057         if (IS_HASWELL(dev)) {
1058                 ecochk |= ECOCHK_PPGTT_WB_HSW;
1059         } else {
1060                 ecochk |= ECOCHK_PPGTT_LLC_IVB;
1061                 ecochk &= ~ECOCHK_PPGTT_GFDT_IVB;
1062         }
1063         I915_WRITE(GAM_ECOCHK, ecochk);
1064
1065         for_each_ring(ring, dev_priv, i) {
1066                 /* GFX_MODE is per-ring on gen7+ */
1067                 I915_WRITE(RING_MODE_GEN7(ring),
1068                            _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1069         }
1070 }
1071
1072 static void gen6_ppgtt_enable(struct drm_device *dev)
1073 {
1074         struct drm_i915_private *dev_priv = dev->dev_private;
1075         uint32_t ecochk, gab_ctl, ecobits;
1076
1077         ecobits = I915_READ(GAC_ECO_BITS);
1078         I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_SNB_BIT |
1079                    ECOBITS_PPGTT_CACHE64B);
1080
1081         gab_ctl = I915_READ(GAB_CTL);
1082         I915_WRITE(GAB_CTL, gab_ctl | GAB_CTL_CONT_AFTER_PAGEFAULT);
1083
1084         ecochk = I915_READ(GAM_ECOCHK);
1085         I915_WRITE(GAM_ECOCHK, ecochk | ECOCHK_SNB_BIT | ECOCHK_PPGTT_CACHE64B);
1086
1087         I915_WRITE(GFX_MODE, _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1088 }
1089
1090 /* PPGTT support for Sandybdrige/Gen6 and later */
1091 static void gen6_ppgtt_clear_range(struct i915_address_space *vm,
1092                                    uint64_t start,
1093                                    uint64_t length,
1094                                    bool use_scratch)
1095 {
1096         struct i915_hw_ppgtt *ppgtt =
1097                 container_of(vm, struct i915_hw_ppgtt, base);
1098         gen6_pte_t *pt_vaddr, scratch_pte;
1099         unsigned first_entry = start >> PAGE_SHIFT;
1100         unsigned num_entries = length >> PAGE_SHIFT;
1101         unsigned act_pt = first_entry / GEN6_PTES;
1102         unsigned first_pte = first_entry % GEN6_PTES;
1103         unsigned last_pte, i;
1104
1105         scratch_pte = vm->pte_encode(vm->scratch.addr, I915_CACHE_LLC, true, 0);
1106
1107         while (num_entries) {
1108                 last_pte = first_pte + num_entries;
1109                 if (last_pte > GEN6_PTES)
1110                         last_pte = GEN6_PTES;
1111
1112                 pt_vaddr = kmap_atomic(ppgtt->pd.page_table[act_pt]->page);
1113
1114                 for (i = first_pte; i < last_pte; i++)
1115                         pt_vaddr[i] = scratch_pte;
1116
1117                 kunmap_atomic(pt_vaddr);
1118
1119                 num_entries -= last_pte - first_pte;
1120                 first_pte = 0;
1121                 act_pt++;
1122         }
1123 }
1124
1125 static void gen6_ppgtt_insert_entries(struct i915_address_space *vm,
1126                                       struct sg_table *pages,
1127                                       uint64_t start,
1128                                       enum i915_cache_level cache_level, u32 flags)
1129 {
1130         struct i915_hw_ppgtt *ppgtt =
1131                 container_of(vm, struct i915_hw_ppgtt, base);
1132         gen6_pte_t *pt_vaddr;
1133         unsigned first_entry = start >> PAGE_SHIFT;
1134         unsigned act_pt = first_entry / GEN6_PTES;
1135         unsigned act_pte = first_entry % GEN6_PTES;
1136         struct sg_page_iter sg_iter;
1137
1138         pt_vaddr = NULL;
1139         for_each_sg_page(pages->sgl, &sg_iter, pages->nents, 0) {
1140                 if (pt_vaddr == NULL)
1141                         pt_vaddr = kmap_atomic(ppgtt->pd.page_table[act_pt]->page);
1142
1143                 pt_vaddr[act_pte] =
1144                         vm->pte_encode(sg_page_iter_dma_address(&sg_iter),
1145                                        cache_level, true, flags);
1146
1147                 if (++act_pte == GEN6_PTES) {
1148                         kunmap_atomic(pt_vaddr);
1149                         pt_vaddr = NULL;
1150                         act_pt++;
1151                         act_pte = 0;
1152                 }
1153         }
1154         if (pt_vaddr)
1155                 kunmap_atomic(pt_vaddr);
1156 }
1157
1158 /* PDE TLBs are a pain invalidate pre GEN8. It requires a context reload. If we
1159  * are switching between contexts with the same LRCA, we also must do a force
1160  * restore.
1161  */
1162 static inline void mark_tlbs_dirty(struct i915_hw_ppgtt *ppgtt)
1163 {
1164         /* If current vm != vm, */
1165         ppgtt->pd_dirty_rings = INTEL_INFO(ppgtt->base.dev)->ring_mask;
1166 }
1167
1168 static void gen6_initialize_pt(struct i915_address_space *vm,
1169                 struct i915_page_table_entry *pt)
1170 {
1171         gen6_pte_t *pt_vaddr, scratch_pte;
1172         int i;
1173
1174         WARN_ON(vm->scratch.addr == 0);
1175
1176         scratch_pte = vm->pte_encode(vm->scratch.addr,
1177                         I915_CACHE_LLC, true, 0);
1178
1179         pt_vaddr = kmap_atomic(pt->page);
1180
1181         for (i = 0; i < GEN6_PTES; i++)
1182                 pt_vaddr[i] = scratch_pte;
1183
1184         kunmap_atomic(pt_vaddr);
1185 }
1186
1187 static int gen6_alloc_va_range(struct i915_address_space *vm,
1188                                uint64_t start, uint64_t length)
1189 {
1190         DECLARE_BITMAP(new_page_tables, I915_PDES);
1191         struct drm_device *dev = vm->dev;
1192         struct drm_i915_private *dev_priv = dev->dev_private;
1193         struct i915_hw_ppgtt *ppgtt =
1194                                 container_of(vm, struct i915_hw_ppgtt, base);
1195         struct i915_page_table_entry *pt;
1196         const uint32_t start_save = start, length_save = length;
1197         uint32_t pde, temp;
1198         int ret;
1199
1200         WARN_ON(upper_32_bits(start));
1201
1202         bitmap_zero(new_page_tables, I915_PDES);
1203
1204         /* The allocation is done in two stages so that we can bail out with
1205          * minimal amount of pain. The first stage finds new page tables that
1206          * need allocation. The second stage marks use ptes within the page
1207          * tables.
1208          */
1209         gen6_for_each_pde(pt, &ppgtt->pd, start, length, temp, pde) {
1210                 if (pt != ppgtt->scratch_pt) {
1211                         WARN_ON(bitmap_empty(pt->used_ptes, GEN6_PTES));
1212                         continue;
1213                 }
1214
1215                 /* We've already allocated a page table */
1216                 WARN_ON(!bitmap_empty(pt->used_ptes, GEN6_PTES));
1217
1218                 pt = alloc_pt_single(dev);
1219                 if (IS_ERR(pt)) {
1220                         ret = PTR_ERR(pt);
1221                         goto unwind_out;
1222                 }
1223
1224                 gen6_initialize_pt(vm, pt);
1225
1226                 ppgtt->pd.page_table[pde] = pt;
1227                 set_bit(pde, new_page_tables);
1228                 trace_i915_page_table_entry_alloc(vm, pde, start, GEN6_PDE_SHIFT);
1229         }
1230
1231         start = start_save;
1232         length = length_save;
1233
1234         gen6_for_each_pde(pt, &ppgtt->pd, start, length, temp, pde) {
1235                 DECLARE_BITMAP(tmp_bitmap, GEN6_PTES);
1236
1237                 bitmap_zero(tmp_bitmap, GEN6_PTES);
1238                 bitmap_set(tmp_bitmap, gen6_pte_index(start),
1239                            gen6_pte_count(start, length));
1240
1241                 if (test_and_clear_bit(pde, new_page_tables))
1242                         gen6_write_pde(&ppgtt->pd, pde, pt);
1243
1244                 trace_i915_page_table_entry_map(vm, pde, pt,
1245                                          gen6_pte_index(start),
1246                                          gen6_pte_count(start, length),
1247                                          GEN6_PTES);
1248                 bitmap_or(pt->used_ptes, tmp_bitmap, pt->used_ptes,
1249                                 GEN6_PTES);
1250         }
1251
1252         WARN_ON(!bitmap_empty(new_page_tables, I915_PDES));
1253
1254         /* Make sure write is complete before other code can use this page
1255          * table. Also require for WC mapped PTEs */
1256         readl(dev_priv->gtt.gsm);
1257
1258         mark_tlbs_dirty(ppgtt);
1259         return 0;
1260
1261 unwind_out:
1262         for_each_set_bit(pde, new_page_tables, I915_PDES) {
1263                 struct i915_page_table_entry *pt = ppgtt->pd.page_table[pde];
1264
1265                 ppgtt->pd.page_table[pde] = ppgtt->scratch_pt;
1266                 unmap_and_free_pt(pt, vm->dev);
1267         }
1268
1269         mark_tlbs_dirty(ppgtt);
1270         return ret;
1271 }
1272
1273 static void gen6_ppgtt_free(struct i915_hw_ppgtt *ppgtt)
1274 {
1275         int i;
1276
1277         for (i = 0; i < ppgtt->num_pd_entries; i++) {
1278                 struct i915_page_table_entry *pt = ppgtt->pd.page_table[i];
1279
1280                 if (pt != ppgtt->scratch_pt)
1281                         unmap_and_free_pt(ppgtt->pd.page_table[i], ppgtt->base.dev);
1282         }
1283
1284         unmap_and_free_pt(ppgtt->scratch_pt, ppgtt->base.dev);
1285         unmap_and_free_pd(&ppgtt->pd);
1286 }
1287
1288 static void gen6_ppgtt_cleanup(struct i915_address_space *vm)
1289 {
1290         struct i915_hw_ppgtt *ppgtt =
1291                 container_of(vm, struct i915_hw_ppgtt, base);
1292
1293         drm_mm_remove_node(&ppgtt->node);
1294
1295         gen6_ppgtt_free(ppgtt);
1296 }
1297
1298 static int gen6_ppgtt_allocate_page_directories(struct i915_hw_ppgtt *ppgtt)
1299 {
1300         struct drm_device *dev = ppgtt->base.dev;
1301         struct drm_i915_private *dev_priv = dev->dev_private;
1302         bool retried = false;
1303         int ret;
1304
1305         /* PPGTT PDEs reside in the GGTT and consists of 512 entries. The
1306          * allocator works in address space sizes, so it's multiplied by page
1307          * size. We allocate at the top of the GTT to avoid fragmentation.
1308          */
1309         BUG_ON(!drm_mm_initialized(&dev_priv->gtt.base.mm));
1310         ppgtt->scratch_pt = alloc_pt_single(ppgtt->base.dev);
1311         if (IS_ERR(ppgtt->scratch_pt))
1312                 return PTR_ERR(ppgtt->scratch_pt);
1313
1314         gen6_initialize_pt(&ppgtt->base, ppgtt->scratch_pt);
1315
1316 alloc:
1317         ret = drm_mm_insert_node_in_range_generic(&dev_priv->gtt.base.mm,
1318                                                   &ppgtt->node, GEN6_PD_SIZE,
1319                                                   GEN6_PD_ALIGN, 0,
1320                                                   0, dev_priv->gtt.base.total,
1321                                                   DRM_MM_TOPDOWN);
1322         if (ret == -ENOSPC && !retried) {
1323                 ret = i915_gem_evict_something(dev, &dev_priv->gtt.base,
1324                                                GEN6_PD_SIZE, GEN6_PD_ALIGN,
1325                                                I915_CACHE_NONE,
1326                                                0, dev_priv->gtt.base.total,
1327                                                0);
1328                 if (ret)
1329                         goto err_out;
1330
1331                 retried = true;
1332                 goto alloc;
1333         }
1334
1335         if (ret)
1336                 goto err_out;
1337
1338
1339         if (ppgtt->node.start < dev_priv->gtt.mappable_end)
1340                 DRM_DEBUG("Forced to use aperture for PDEs\n");
1341
1342         ppgtt->num_pd_entries = I915_PDES;
1343         return 0;
1344
1345 err_out:
1346         unmap_and_free_pt(ppgtt->scratch_pt, ppgtt->base.dev);
1347         return ret;
1348 }
1349
1350 static int gen6_ppgtt_alloc(struct i915_hw_ppgtt *ppgtt)
1351 {
1352         int ret;
1353
1354         ret = gen6_ppgtt_allocate_page_directories(ppgtt);
1355         if (ret)
1356                 return ret;
1357
1358         return 0;
1359 }
1360
1361 static void gen6_scratch_va_range(struct i915_hw_ppgtt *ppgtt,
1362                                   uint64_t start, uint64_t length)
1363 {
1364         struct i915_page_table_entry *unused;
1365         uint32_t pde, temp;
1366
1367         gen6_for_each_pde(unused, &ppgtt->pd, start, length, temp, pde)
1368                 ppgtt->pd.page_table[pde] = ppgtt->scratch_pt;
1369 }
1370
1371 static int gen6_ppgtt_init(struct i915_hw_ppgtt *ppgtt, bool aliasing)
1372 {
1373         struct drm_device *dev = ppgtt->base.dev;
1374         struct drm_i915_private *dev_priv = dev->dev_private;
1375         int ret;
1376
1377         ppgtt->base.pte_encode = dev_priv->gtt.base.pte_encode;
1378         if (IS_GEN6(dev)) {
1379                 ppgtt->switch_mm = gen6_mm_switch;
1380         } else if (IS_HASWELL(dev)) {
1381                 ppgtt->switch_mm = hsw_mm_switch;
1382         } else if (IS_GEN7(dev)) {
1383                 ppgtt->switch_mm = gen7_mm_switch;
1384         } else
1385                 BUG();
1386
1387         if (intel_vgpu_active(dev))
1388                 ppgtt->switch_mm = vgpu_mm_switch;
1389
1390         ret = gen6_ppgtt_alloc(ppgtt);
1391         if (ret)
1392                 return ret;
1393
1394         if (aliasing) {
1395                 /* preallocate all pts */
1396                 ret = alloc_pt_range(&ppgtt->pd, 0, ppgtt->num_pd_entries,
1397                                 ppgtt->base.dev);
1398
1399                 if (ret) {
1400                         gen6_ppgtt_cleanup(&ppgtt->base);
1401                         return ret;
1402                 }
1403         }
1404
1405         ppgtt->base.allocate_va_range = gen6_alloc_va_range;
1406         ppgtt->base.clear_range = gen6_ppgtt_clear_range;
1407         ppgtt->base.insert_entries = gen6_ppgtt_insert_entries;
1408         ppgtt->base.cleanup = gen6_ppgtt_cleanup;
1409         ppgtt->base.start = 0;
1410         ppgtt->base.total = ppgtt->num_pd_entries * GEN6_PTES * PAGE_SIZE;
1411         ppgtt->debug_dump = gen6_dump_ppgtt;
1412
1413         ppgtt->pd.pd_offset =
1414                 ppgtt->node.start / PAGE_SIZE * sizeof(gen6_pte_t);
1415
1416         ppgtt->pd_addr = (gen6_pte_t __iomem *)dev_priv->gtt.gsm +
1417                 ppgtt->pd.pd_offset / sizeof(gen6_pte_t);
1418
1419         if (aliasing)
1420                 ppgtt->base.clear_range(&ppgtt->base, 0, ppgtt->base.total, true);
1421         else
1422                 gen6_scratch_va_range(ppgtt, 0, ppgtt->base.total);
1423
1424         gen6_write_page_range(dev_priv, &ppgtt->pd, 0, ppgtt->base.total);
1425
1426         DRM_DEBUG_DRIVER("Allocated pde space (%lldM) at GTT entry: %llx\n",
1427                          ppgtt->node.size >> 20,
1428                          ppgtt->node.start / PAGE_SIZE);
1429
1430         DRM_DEBUG("Adding PPGTT at offset %x\n",
1431                   ppgtt->pd.pd_offset << 10);
1432
1433         return 0;
1434 }
1435
1436 static int __hw_ppgtt_init(struct drm_device *dev, struct i915_hw_ppgtt *ppgtt,
1437                 bool aliasing)
1438 {
1439         struct drm_i915_private *dev_priv = dev->dev_private;
1440
1441         ppgtt->base.dev = dev;
1442         ppgtt->base.scratch = dev_priv->gtt.base.scratch;
1443
1444         if (INTEL_INFO(dev)->gen < 8)
1445                 return gen6_ppgtt_init(ppgtt, aliasing);
1446         else
1447                 return gen8_ppgtt_init(ppgtt, dev_priv->gtt.base.total);
1448 }
1449 int i915_ppgtt_init(struct drm_device *dev, struct i915_hw_ppgtt *ppgtt)
1450 {
1451         struct drm_i915_private *dev_priv = dev->dev_private;
1452         int ret = 0;
1453
1454         ret = __hw_ppgtt_init(dev, ppgtt, false);
1455         if (ret == 0) {
1456                 kref_init(&ppgtt->ref);
1457                 drm_mm_init(&ppgtt->base.mm, ppgtt->base.start,
1458                             ppgtt->base.total);
1459                 i915_init_vm(dev_priv, &ppgtt->base);
1460         }
1461
1462         return ret;
1463 }
1464
1465 int i915_ppgtt_init_hw(struct drm_device *dev)
1466 {
1467         struct drm_i915_private *dev_priv = dev->dev_private;
1468         struct intel_engine_cs *ring;
1469         struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
1470         int i, ret = 0;
1471
1472         /* In the case of execlists, PPGTT is enabled by the context descriptor
1473          * and the PDPs are contained within the context itself.  We don't
1474          * need to do anything here. */
1475         if (i915.enable_execlists)
1476                 return 0;
1477
1478         if (!USES_PPGTT(dev))
1479                 return 0;
1480
1481         if (IS_GEN6(dev))
1482                 gen6_ppgtt_enable(dev);
1483         else if (IS_GEN7(dev))
1484                 gen7_ppgtt_enable(dev);
1485         else if (INTEL_INFO(dev)->gen >= 8)
1486                 gen8_ppgtt_enable(dev);
1487         else
1488                 MISSING_CASE(INTEL_INFO(dev)->gen);
1489
1490         if (ppgtt) {
1491                 for_each_ring(ring, dev_priv, i) {
1492                         ret = ppgtt->switch_mm(ppgtt, ring);
1493                         if (ret != 0)
1494                                 return ret;
1495                 }
1496         }
1497
1498         return ret;
1499 }
1500 struct i915_hw_ppgtt *
1501 i915_ppgtt_create(struct drm_device *dev, struct drm_i915_file_private *fpriv)
1502 {
1503         struct i915_hw_ppgtt *ppgtt;
1504         int ret;
1505
1506         ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
1507         if (!ppgtt)
1508                 return ERR_PTR(-ENOMEM);
1509
1510         ret = i915_ppgtt_init(dev, ppgtt);
1511         if (ret) {
1512                 kfree(ppgtt);
1513                 return ERR_PTR(ret);
1514         }
1515
1516         ppgtt->file_priv = fpriv;
1517
1518         trace_i915_ppgtt_create(&ppgtt->base);
1519
1520         return ppgtt;
1521 }
1522
1523 void  i915_ppgtt_release(struct kref *kref)
1524 {
1525         struct i915_hw_ppgtt *ppgtt =
1526                 container_of(kref, struct i915_hw_ppgtt, ref);
1527
1528         trace_i915_ppgtt_release(&ppgtt->base);
1529
1530         /* vmas should already be unbound */
1531         WARN_ON(!list_empty(&ppgtt->base.active_list));
1532         WARN_ON(!list_empty(&ppgtt->base.inactive_list));
1533
1534         list_del(&ppgtt->base.global_link);
1535         drm_mm_takedown(&ppgtt->base.mm);
1536
1537         ppgtt->base.cleanup(&ppgtt->base);
1538         kfree(ppgtt);
1539 }
1540
1541 static void
1542 ppgtt_bind_vma(struct i915_vma *vma,
1543                enum i915_cache_level cache_level,
1544                u32 flags)
1545 {
1546         /* Currently applicable only to VLV */
1547         if (vma->obj->gt_ro)
1548                 flags |= PTE_READ_ONLY;
1549
1550         vma->vm->insert_entries(vma->vm, vma->obj->pages, vma->node.start,
1551                                 cache_level, flags);
1552 }
1553
1554 static void ppgtt_unbind_vma(struct i915_vma *vma)
1555 {
1556         vma->vm->clear_range(vma->vm,
1557                              vma->node.start,
1558                              vma->obj->base.size,
1559                              true);
1560 }
1561
1562 extern int intel_iommu_gfx_mapped;
1563 /* Certain Gen5 chipsets require require idling the GPU before
1564  * unmapping anything from the GTT when VT-d is enabled.
1565  */
1566 static inline bool needs_idle_maps(struct drm_device *dev)
1567 {
1568 #ifdef CONFIG_INTEL_IOMMU
1569         /* Query intel_iommu to see if we need the workaround. Presumably that
1570          * was loaded first.
1571          */
1572         if (IS_GEN5(dev) && IS_MOBILE(dev) && intel_iommu_gfx_mapped)
1573                 return true;
1574 #endif
1575         return false;
1576 }
1577
1578 static bool do_idling(struct drm_i915_private *dev_priv)
1579 {
1580         bool ret = dev_priv->mm.interruptible;
1581
1582         if (unlikely(dev_priv->gtt.do_idle_maps)) {
1583                 dev_priv->mm.interruptible = false;
1584                 if (i915_gpu_idle(dev_priv->dev)) {
1585                         DRM_ERROR("Couldn't idle GPU\n");
1586                         /* Wait a bit, in hopes it avoids the hang */
1587                         udelay(10);
1588                 }
1589         }
1590
1591         return ret;
1592 }
1593
1594 static void undo_idling(struct drm_i915_private *dev_priv, bool interruptible)
1595 {
1596         if (unlikely(dev_priv->gtt.do_idle_maps))
1597                 dev_priv->mm.interruptible = interruptible;
1598 }
1599
1600 void i915_check_and_clear_faults(struct drm_device *dev)
1601 {
1602         struct drm_i915_private *dev_priv = dev->dev_private;
1603         struct intel_engine_cs *ring;
1604         int i;
1605
1606         if (INTEL_INFO(dev)->gen < 6)
1607                 return;
1608
1609         for_each_ring(ring, dev_priv, i) {
1610                 u32 fault_reg;
1611                 fault_reg = I915_READ(RING_FAULT_REG(ring));
1612                 if (fault_reg & RING_FAULT_VALID) {
1613                         DRM_DEBUG_DRIVER("Unexpected fault\n"
1614                                          "\tAddr: 0x%08lx\n"
1615                                          "\tAddress space: %s\n"
1616                                          "\tSource ID: %d\n"
1617                                          "\tType: %d\n",
1618                                          fault_reg & PAGE_MASK,
1619                                          fault_reg & RING_FAULT_GTTSEL_MASK ? "GGTT" : "PPGTT",
1620                                          RING_FAULT_SRCID(fault_reg),
1621                                          RING_FAULT_FAULT_TYPE(fault_reg));
1622                         I915_WRITE(RING_FAULT_REG(ring),
1623                                    fault_reg & ~RING_FAULT_VALID);
1624                 }
1625         }
1626         POSTING_READ(RING_FAULT_REG(&dev_priv->ring[RCS]));
1627 }
1628
1629 static void i915_ggtt_flush(struct drm_i915_private *dev_priv)
1630 {
1631         if (INTEL_INFO(dev_priv->dev)->gen < 6) {
1632                 intel_gtt_chipset_flush();
1633         } else {
1634                 I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
1635                 POSTING_READ(GFX_FLSH_CNTL_GEN6);
1636         }
1637 }
1638
1639 void i915_gem_suspend_gtt_mappings(struct drm_device *dev)
1640 {
1641         struct drm_i915_private *dev_priv = dev->dev_private;
1642
1643         /* Don't bother messing with faults pre GEN6 as we have little
1644          * documentation supporting that it's a good idea.
1645          */
1646         if (INTEL_INFO(dev)->gen < 6)
1647                 return;
1648
1649         i915_check_and_clear_faults(dev);
1650
1651         dev_priv->gtt.base.clear_range(&dev_priv->gtt.base,
1652                                        dev_priv->gtt.base.start,
1653                                        dev_priv->gtt.base.total,
1654                                        true);
1655
1656         i915_ggtt_flush(dev_priv);
1657 }
1658
1659 void i915_gem_restore_gtt_mappings(struct drm_device *dev)
1660 {
1661         struct drm_i915_private *dev_priv = dev->dev_private;
1662         struct drm_i915_gem_object *obj;
1663         struct i915_address_space *vm;
1664
1665         i915_check_and_clear_faults(dev);
1666
1667         /* First fill our portion of the GTT with scratch pages */
1668         dev_priv->gtt.base.clear_range(&dev_priv->gtt.base,
1669                                        dev_priv->gtt.base.start,
1670                                        dev_priv->gtt.base.total,
1671                                        true);
1672
1673         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
1674                 struct i915_vma *vma = i915_gem_obj_to_vma(obj,
1675                                                            &dev_priv->gtt.base);
1676                 if (!vma)
1677                         continue;
1678
1679                 i915_gem_clflush_object(obj, obj->pin_display);
1680                 /* The bind_vma code tries to be smart about tracking mappings.
1681                  * Unfortunately above, we've just wiped out the mappings
1682                  * without telling our object about it. So we need to fake it.
1683                  *
1684                  * Bind is not expected to fail since this is only called on
1685                  * resume and assumption is all requirements exist already.
1686                  */
1687                 vma->bound &= ~GLOBAL_BIND;
1688                 WARN_ON(i915_vma_bind(vma, obj->cache_level, GLOBAL_BIND));
1689         }
1690
1691
1692         if (INTEL_INFO(dev)->gen >= 8) {
1693                 if (IS_CHERRYVIEW(dev))
1694                         chv_setup_private_ppat(dev_priv);
1695                 else
1696                         bdw_setup_private_ppat(dev_priv);
1697
1698                 return;
1699         }
1700
1701         if (USES_PPGTT(dev)) {
1702                 list_for_each_entry(vm, &dev_priv->vm_list, global_link) {
1703                         /* TODO: Perhaps it shouldn't be gen6 specific */
1704
1705                         struct i915_hw_ppgtt *ppgtt =
1706                                         container_of(vm, struct i915_hw_ppgtt,
1707                                                      base);
1708
1709                         if (i915_is_ggtt(vm))
1710                                 ppgtt = dev_priv->mm.aliasing_ppgtt;
1711
1712                         gen6_write_page_range(dev_priv, &ppgtt->pd,
1713                                               0, ppgtt->base.total);
1714                 }
1715         }
1716
1717         i915_ggtt_flush(dev_priv);
1718 }
1719
1720 int i915_gem_gtt_prepare_object(struct drm_i915_gem_object *obj)
1721 {
1722         if (obj->has_dma_mapping)
1723                 return 0;
1724
1725         if (!dma_map_sg(&obj->base.dev->pdev->dev,
1726                         obj->pages->sgl, obj->pages->nents,
1727                         PCI_DMA_BIDIRECTIONAL))
1728                 return -ENOSPC;
1729
1730         return 0;
1731 }
1732
1733 static inline void gen8_set_pte(void __iomem *addr, gen8_pte_t pte)
1734 {
1735 #ifdef writeq
1736         writeq(pte, addr);
1737 #else
1738         iowrite32((u32)pte, addr);
1739         iowrite32(pte >> 32, addr + 4);
1740 #endif
1741 }
1742
1743 static void gen8_ggtt_insert_entries(struct i915_address_space *vm,
1744                                      struct sg_table *st,
1745                                      uint64_t start,
1746                                      enum i915_cache_level level, u32 unused)
1747 {
1748         struct drm_i915_private *dev_priv = vm->dev->dev_private;
1749         unsigned first_entry = start >> PAGE_SHIFT;
1750         gen8_pte_t __iomem *gtt_entries =
1751                 (gen8_pte_t __iomem *)dev_priv->gtt.gsm + first_entry;
1752         int i = 0;
1753         struct sg_page_iter sg_iter;
1754         dma_addr_t addr = 0; /* shut up gcc */
1755
1756         for_each_sg_page(st->sgl, &sg_iter, st->nents, 0) {
1757                 addr = sg_dma_address(sg_iter.sg) +
1758                         (sg_iter.sg_pgoffset << PAGE_SHIFT);
1759                 gen8_set_pte(&gtt_entries[i],
1760                              gen8_pte_encode(addr, level, true));
1761                 i++;
1762         }
1763
1764         /*
1765          * XXX: This serves as a posting read to make sure that the PTE has
1766          * actually been updated. There is some concern that even though
1767          * registers and PTEs are within the same BAR that they are potentially
1768          * of NUMA access patterns. Therefore, even with the way we assume
1769          * hardware should work, we must keep this posting read for paranoia.
1770          */
1771         if (i != 0)
1772                 WARN_ON(readq(&gtt_entries[i-1])
1773                         != gen8_pte_encode(addr, level, true));
1774
1775         /* This next bit makes the above posting read even more important. We
1776          * want to flush the TLBs only after we're certain all the PTE updates
1777          * have finished.
1778          */
1779         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
1780         POSTING_READ(GFX_FLSH_CNTL_GEN6);
1781 }
1782
1783 /*
1784  * Binds an object into the global gtt with the specified cache level. The object
1785  * will be accessible to the GPU via commands whose operands reference offsets
1786  * within the global GTT as well as accessible by the GPU through the GMADR
1787  * mapped BAR (dev_priv->mm.gtt->gtt).
1788  */
1789 static void gen6_ggtt_insert_entries(struct i915_address_space *vm,
1790                                      struct sg_table *st,
1791                                      uint64_t start,
1792                                      enum i915_cache_level level, u32 flags)
1793 {
1794         struct drm_i915_private *dev_priv = vm->dev->dev_private;
1795         unsigned first_entry = start >> PAGE_SHIFT;
1796         gen6_pte_t __iomem *gtt_entries =
1797                 (gen6_pte_t __iomem *)dev_priv->gtt.gsm + first_entry;
1798         int i = 0;
1799         struct sg_page_iter sg_iter;
1800         dma_addr_t addr = 0;
1801
1802         for_each_sg_page(st->sgl, &sg_iter, st->nents, 0) {
1803                 addr = sg_page_iter_dma_address(&sg_iter);
1804                 iowrite32(vm->pte_encode(addr, level, true, flags), &gtt_entries[i]);
1805                 i++;
1806         }
1807
1808         /* XXX: This serves as a posting read to make sure that the PTE has
1809          * actually been updated. There is some concern that even though
1810          * registers and PTEs are within the same BAR that they are potentially
1811          * of NUMA access patterns. Therefore, even with the way we assume
1812          * hardware should work, we must keep this posting read for paranoia.
1813          */
1814         if (i != 0) {
1815                 unsigned long gtt = readl(&gtt_entries[i-1]);
1816                 WARN_ON(gtt != vm->pte_encode(addr, level, true, flags));
1817         }
1818
1819         /* This next bit makes the above posting read even more important. We
1820          * want to flush the TLBs only after we're certain all the PTE updates
1821          * have finished.
1822          */
1823         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
1824         POSTING_READ(GFX_FLSH_CNTL_GEN6);
1825 }
1826
1827 static void gen8_ggtt_clear_range(struct i915_address_space *vm,
1828                                   uint64_t start,
1829                                   uint64_t length,
1830                                   bool use_scratch)
1831 {
1832         struct drm_i915_private *dev_priv = vm->dev->dev_private;
1833         unsigned first_entry = start >> PAGE_SHIFT;
1834         unsigned num_entries = length >> PAGE_SHIFT;
1835         gen8_pte_t scratch_pte, __iomem *gtt_base =
1836                 (gen8_pte_t __iomem *) dev_priv->gtt.gsm + first_entry;
1837         const int max_entries = gtt_total_entries(dev_priv->gtt) - first_entry;
1838         int i;
1839
1840         if (WARN(num_entries > max_entries,
1841                  "First entry = %d; Num entries = %d (max=%d)\n",
1842                  first_entry, num_entries, max_entries))
1843                 num_entries = max_entries;
1844
1845         scratch_pte = gen8_pte_encode(vm->scratch.addr,
1846                                       I915_CACHE_LLC,
1847                                       use_scratch);
1848         for (i = 0; i < num_entries; i++)
1849                 gen8_set_pte(&gtt_base[i], scratch_pte);
1850         readl(gtt_base);
1851 }
1852
1853 static void gen6_ggtt_clear_range(struct i915_address_space *vm,
1854                                   uint64_t start,
1855                                   uint64_t length,
1856                                   bool use_scratch)
1857 {
1858         struct drm_i915_private *dev_priv = vm->dev->dev_private;
1859         unsigned first_entry = start >> PAGE_SHIFT;
1860         unsigned num_entries = length >> PAGE_SHIFT;
1861         gen6_pte_t scratch_pte, __iomem *gtt_base =
1862                 (gen6_pte_t __iomem *) dev_priv->gtt.gsm + first_entry;
1863         const int max_entries = gtt_total_entries(dev_priv->gtt) - first_entry;
1864         int i;
1865
1866         if (WARN(num_entries > max_entries,
1867                  "First entry = %d; Num entries = %d (max=%d)\n",
1868                  first_entry, num_entries, max_entries))
1869                 num_entries = max_entries;
1870
1871         scratch_pte = vm->pte_encode(vm->scratch.addr, I915_CACHE_LLC, use_scratch, 0);
1872
1873         for (i = 0; i < num_entries; i++)
1874                 iowrite32(scratch_pte, &gtt_base[i]);
1875         readl(gtt_base);
1876 }
1877
1878
1879 static void i915_ggtt_bind_vma(struct i915_vma *vma,
1880                                enum i915_cache_level cache_level,
1881                                u32 unused)
1882 {
1883         const unsigned long entry = vma->node.start >> PAGE_SHIFT;
1884         unsigned int flags = (cache_level == I915_CACHE_NONE) ?
1885                 AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
1886
1887         BUG_ON(!i915_is_ggtt(vma->vm));
1888         intel_gtt_insert_sg_entries(vma->ggtt_view.pages, entry, flags);
1889         vma->bound = GLOBAL_BIND;
1890 }
1891
1892 static void i915_ggtt_clear_range(struct i915_address_space *vm,
1893                                   uint64_t start,
1894                                   uint64_t length,
1895                                   bool unused)
1896 {
1897         unsigned first_entry = start >> PAGE_SHIFT;
1898         unsigned num_entries = length >> PAGE_SHIFT;
1899         intel_gtt_clear_range(first_entry, num_entries);
1900 }
1901
1902 static void i915_ggtt_unbind_vma(struct i915_vma *vma)
1903 {
1904         const unsigned int first = vma->node.start >> PAGE_SHIFT;
1905         const unsigned int size = vma->obj->base.size >> PAGE_SHIFT;
1906
1907         BUG_ON(!i915_is_ggtt(vma->vm));
1908         vma->bound = 0;
1909         intel_gtt_clear_range(first, size);
1910 }
1911
1912 static void ggtt_bind_vma(struct i915_vma *vma,
1913                           enum i915_cache_level cache_level,
1914                           u32 flags)
1915 {
1916         struct drm_device *dev = vma->vm->dev;
1917         struct drm_i915_private *dev_priv = dev->dev_private;
1918         struct drm_i915_gem_object *obj = vma->obj;
1919         struct sg_table *pages = obj->pages;
1920
1921         /* Currently applicable only to VLV */
1922         if (obj->gt_ro)
1923                 flags |= PTE_READ_ONLY;
1924
1925         if (i915_is_ggtt(vma->vm))
1926                 pages = vma->ggtt_view.pages;
1927
1928         /* If there is no aliasing PPGTT, or the caller needs a global mapping,
1929          * or we have a global mapping already but the cacheability flags have
1930          * changed, set the global PTEs.
1931          *
1932          * If there is an aliasing PPGTT it is anecdotally faster, so use that
1933          * instead if none of the above hold true.
1934          *
1935          * NB: A global mapping should only be needed for special regions like
1936          * "gtt mappable", SNB errata, or if specified via special execbuf
1937          * flags. At all other times, the GPU will use the aliasing PPGTT.
1938          */
1939         if (!dev_priv->mm.aliasing_ppgtt || flags & GLOBAL_BIND) {
1940                 if (!(vma->bound & GLOBAL_BIND) ||
1941                     (cache_level != obj->cache_level)) {
1942                         vma->vm->insert_entries(vma->vm, pages,
1943                                                 vma->node.start,
1944                                                 cache_level, flags);
1945                         vma->bound |= GLOBAL_BIND;
1946                 }
1947         }
1948
1949         if (dev_priv->mm.aliasing_ppgtt &&
1950             (!(vma->bound & LOCAL_BIND) ||
1951              (cache_level != obj->cache_level))) {
1952                 struct i915_hw_ppgtt *appgtt = dev_priv->mm.aliasing_ppgtt;
1953                 appgtt->base.insert_entries(&appgtt->base, pages,
1954                                             vma->node.start,
1955                                             cache_level, flags);
1956                 vma->bound |= LOCAL_BIND;
1957         }
1958 }
1959
1960 static void ggtt_unbind_vma(struct i915_vma *vma)
1961 {
1962         struct drm_device *dev = vma->vm->dev;
1963         struct drm_i915_private *dev_priv = dev->dev_private;
1964         struct drm_i915_gem_object *obj = vma->obj;
1965
1966         if (vma->bound & GLOBAL_BIND) {
1967                 vma->vm->clear_range(vma->vm,
1968                                      vma->node.start,
1969                                      obj->base.size,
1970                                      true);
1971                 vma->bound &= ~GLOBAL_BIND;
1972         }
1973
1974         if (vma->bound & LOCAL_BIND) {
1975                 struct i915_hw_ppgtt *appgtt = dev_priv->mm.aliasing_ppgtt;
1976                 appgtt->base.clear_range(&appgtt->base,
1977                                          vma->node.start,
1978                                          obj->base.size,
1979                                          true);
1980                 vma->bound &= ~LOCAL_BIND;
1981         }
1982 }
1983
1984 void i915_gem_gtt_finish_object(struct drm_i915_gem_object *obj)
1985 {
1986         struct drm_device *dev = obj->base.dev;
1987         struct drm_i915_private *dev_priv = dev->dev_private;
1988         bool interruptible;
1989
1990         interruptible = do_idling(dev_priv);
1991
1992         if (!obj->has_dma_mapping)
1993                 dma_unmap_sg(&dev->pdev->dev,
1994                              obj->pages->sgl, obj->pages->nents,
1995                              PCI_DMA_BIDIRECTIONAL);
1996
1997         undo_idling(dev_priv, interruptible);
1998 }
1999
2000 static void i915_gtt_color_adjust(struct drm_mm_node *node,
2001                                   unsigned long color,
2002                                   u64 *start,
2003                                   u64 *end)
2004 {
2005         if (node->color != color)
2006                 *start += 4096;
2007
2008         if (!list_empty(&node->node_list)) {
2009                 node = list_entry(node->node_list.next,
2010                                   struct drm_mm_node,
2011                                   node_list);
2012                 if (node->allocated && node->color != color)
2013                         *end -= 4096;
2014         }
2015 }
2016
2017 static int i915_gem_setup_global_gtt(struct drm_device *dev,
2018                                      unsigned long start,
2019                                      unsigned long mappable_end,
2020                                      unsigned long end)
2021 {
2022         /* Let GEM Manage all of the aperture.
2023          *
2024          * However, leave one page at the end still bound to the scratch page.
2025          * There are a number of places where the hardware apparently prefetches
2026          * past the end of the object, and we've seen multiple hangs with the
2027          * GPU head pointer stuck in a batchbuffer bound at the last page of the
2028          * aperture.  One page should be enough to keep any prefetching inside
2029          * of the aperture.
2030          */
2031         struct drm_i915_private *dev_priv = dev->dev_private;
2032         struct i915_address_space *ggtt_vm = &dev_priv->gtt.base;
2033         struct drm_mm_node *entry;
2034         struct drm_i915_gem_object *obj;
2035         unsigned long hole_start, hole_end;
2036         int ret;
2037
2038         BUG_ON(mappable_end > end);
2039
2040         /* Subtract the guard page ... */
2041         drm_mm_init(&ggtt_vm->mm, start, end - start - PAGE_SIZE);
2042
2043         dev_priv->gtt.base.start = start;
2044         dev_priv->gtt.base.total = end - start;
2045
2046         if (intel_vgpu_active(dev)) {
2047                 ret = intel_vgt_balloon(dev);
2048                 if (ret)
2049                         return ret;
2050         }
2051
2052         if (!HAS_LLC(dev))
2053                 dev_priv->gtt.base.mm.color_adjust = i915_gtt_color_adjust;
2054
2055         /* Mark any preallocated objects as occupied */
2056         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
2057                 struct i915_vma *vma = i915_gem_obj_to_vma(obj, ggtt_vm);
2058
2059                 DRM_DEBUG_KMS("reserving preallocated space: %lx + %zx\n",
2060                               i915_gem_obj_ggtt_offset(obj), obj->base.size);
2061
2062                 WARN_ON(i915_gem_obj_ggtt_bound(obj));
2063                 ret = drm_mm_reserve_node(&ggtt_vm->mm, &vma->node);
2064                 if (ret) {
2065                         DRM_DEBUG_KMS("Reservation failed: %i\n", ret);
2066                         return ret;
2067                 }
2068                 vma->bound |= GLOBAL_BIND;
2069         }
2070
2071         /* Clear any non-preallocated blocks */
2072         drm_mm_for_each_hole(entry, &ggtt_vm->mm, hole_start, hole_end) {
2073                 DRM_DEBUG_KMS("clearing unused GTT space: [%lx, %lx]\n",
2074                               hole_start, hole_end);
2075                 ggtt_vm->clear_range(ggtt_vm, hole_start,
2076                                      hole_end - hole_start, true);
2077         }
2078
2079         /* And finally clear the reserved guard page */
2080         ggtt_vm->clear_range(ggtt_vm, end - PAGE_SIZE, PAGE_SIZE, true);
2081
2082         if (USES_PPGTT(dev) && !USES_FULL_PPGTT(dev)) {
2083                 struct i915_hw_ppgtt *ppgtt;
2084
2085                 ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
2086                 if (!ppgtt)
2087                         return -ENOMEM;
2088
2089                 ret = __hw_ppgtt_init(dev, ppgtt, true);
2090                 if (ret) {
2091                         kfree(ppgtt);
2092                         return ret;
2093                 }
2094
2095                 dev_priv->mm.aliasing_ppgtt = ppgtt;
2096         }
2097
2098         return 0;
2099 }
2100
2101 void i915_gem_init_global_gtt(struct drm_device *dev)
2102 {
2103         struct drm_i915_private *dev_priv = dev->dev_private;
2104         unsigned long gtt_size, mappable_size;
2105
2106         gtt_size = dev_priv->gtt.base.total;
2107         mappable_size = dev_priv->gtt.mappable_end;
2108
2109         i915_gem_setup_global_gtt(dev, 0, mappable_size, gtt_size);
2110 }
2111
2112 void i915_global_gtt_cleanup(struct drm_device *dev)
2113 {
2114         struct drm_i915_private *dev_priv = dev->dev_private;
2115         struct i915_address_space *vm = &dev_priv->gtt.base;
2116
2117         if (dev_priv->mm.aliasing_ppgtt) {
2118                 struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
2119
2120                 ppgtt->base.cleanup(&ppgtt->base);
2121         }
2122
2123         if (drm_mm_initialized(&vm->mm)) {
2124                 if (intel_vgpu_active(dev))
2125                         intel_vgt_deballoon();
2126
2127                 drm_mm_takedown(&vm->mm);
2128                 list_del(&vm->global_link);
2129         }
2130
2131         vm->cleanup(vm);
2132 }
2133
2134 static int setup_scratch_page(struct drm_device *dev)
2135 {
2136         struct drm_i915_private *dev_priv = dev->dev_private;
2137         struct page *page;
2138         dma_addr_t dma_addr;
2139
2140         page = alloc_page(GFP_KERNEL | GFP_DMA32 | __GFP_ZERO);
2141         if (page == NULL)
2142                 return -ENOMEM;
2143         set_pages_uc(page, 1);
2144
2145 #ifdef CONFIG_INTEL_IOMMU
2146         dma_addr = pci_map_page(dev->pdev, page, 0, PAGE_SIZE,
2147                                 PCI_DMA_BIDIRECTIONAL);
2148         if (pci_dma_mapping_error(dev->pdev, dma_addr))
2149                 return -EINVAL;
2150 #else
2151         dma_addr = page_to_phys(page);
2152 #endif
2153         dev_priv->gtt.base.scratch.page = page;
2154         dev_priv->gtt.base.scratch.addr = dma_addr;
2155
2156         return 0;
2157 }
2158
2159 static void teardown_scratch_page(struct drm_device *dev)
2160 {
2161         struct drm_i915_private *dev_priv = dev->dev_private;
2162         struct page *page = dev_priv->gtt.base.scratch.page;
2163
2164         set_pages_wb(page, 1);
2165         pci_unmap_page(dev->pdev, dev_priv->gtt.base.scratch.addr,
2166                        PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
2167         __free_page(page);
2168 }
2169
2170 static inline unsigned int gen6_get_total_gtt_size(u16 snb_gmch_ctl)
2171 {
2172         snb_gmch_ctl >>= SNB_GMCH_GGMS_SHIFT;
2173         snb_gmch_ctl &= SNB_GMCH_GGMS_MASK;
2174         return snb_gmch_ctl << 20;
2175 }
2176
2177 static inline unsigned int gen8_get_total_gtt_size(u16 bdw_gmch_ctl)
2178 {
2179         bdw_gmch_ctl >>= BDW_GMCH_GGMS_SHIFT;
2180         bdw_gmch_ctl &= BDW_GMCH_GGMS_MASK;
2181         if (bdw_gmch_ctl)
2182                 bdw_gmch_ctl = 1 << bdw_gmch_ctl;
2183
2184 #ifdef CONFIG_X86_32
2185         /* Limit 32b platforms to a 2GB GGTT: 4 << 20 / pte size * PAGE_SIZE */
2186         if (bdw_gmch_ctl > 4)
2187                 bdw_gmch_ctl = 4;
2188 #endif
2189
2190         return bdw_gmch_ctl << 20;
2191 }
2192
2193 static inline unsigned int chv_get_total_gtt_size(u16 gmch_ctrl)
2194 {
2195         gmch_ctrl >>= SNB_GMCH_GGMS_SHIFT;
2196         gmch_ctrl &= SNB_GMCH_GGMS_MASK;
2197
2198         if (gmch_ctrl)
2199                 return 1 << (20 + gmch_ctrl);
2200
2201         return 0;
2202 }
2203
2204 static inline size_t gen6_get_stolen_size(u16 snb_gmch_ctl)
2205 {
2206         snb_gmch_ctl >>= SNB_GMCH_GMS_SHIFT;
2207         snb_gmch_ctl &= SNB_GMCH_GMS_MASK;
2208         return snb_gmch_ctl << 25; /* 32 MB units */
2209 }
2210
2211 static inline size_t gen8_get_stolen_size(u16 bdw_gmch_ctl)
2212 {
2213         bdw_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
2214         bdw_gmch_ctl &= BDW_GMCH_GMS_MASK;
2215         return bdw_gmch_ctl << 25; /* 32 MB units */
2216 }
2217
2218 static size_t chv_get_stolen_size(u16 gmch_ctrl)
2219 {
2220         gmch_ctrl >>= SNB_GMCH_GMS_SHIFT;
2221         gmch_ctrl &= SNB_GMCH_GMS_MASK;
2222
2223         /*
2224          * 0x0  to 0x10: 32MB increments starting at 0MB
2225          * 0x11 to 0x16: 4MB increments starting at 8MB
2226          * 0x17 to 0x1d: 4MB increments start at 36MB
2227          */
2228         if (gmch_ctrl < 0x11)
2229                 return gmch_ctrl << 25;
2230         else if (gmch_ctrl < 0x17)
2231                 return (gmch_ctrl - 0x11 + 2) << 22;
2232         else
2233                 return (gmch_ctrl - 0x17 + 9) << 22;
2234 }
2235
2236 static size_t gen9_get_stolen_size(u16 gen9_gmch_ctl)
2237 {
2238         gen9_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
2239         gen9_gmch_ctl &= BDW_GMCH_GMS_MASK;
2240
2241         if (gen9_gmch_ctl < 0xf0)
2242                 return gen9_gmch_ctl << 25; /* 32 MB units */
2243         else
2244                 /* 4MB increments starting at 0xf0 for 4MB */
2245                 return (gen9_gmch_ctl - 0xf0 + 1) << 22;
2246 }
2247
2248 static int ggtt_probe_common(struct drm_device *dev,
2249                              size_t gtt_size)
2250 {
2251         struct drm_i915_private *dev_priv = dev->dev_private;
2252         phys_addr_t gtt_phys_addr;
2253         int ret;
2254
2255         /* For Modern GENs the PTEs and register space are split in the BAR */
2256         gtt_phys_addr = pci_resource_start(dev->pdev, 0) +
2257                 (pci_resource_len(dev->pdev, 0) / 2);
2258
2259         dev_priv->gtt.gsm = ioremap_wc(gtt_phys_addr, gtt_size);
2260         if (!dev_priv->gtt.gsm) {
2261                 DRM_ERROR("Failed to map the gtt page table\n");
2262                 return -ENOMEM;
2263         }
2264
2265         ret = setup_scratch_page(dev);
2266         if (ret) {
2267                 DRM_ERROR("Scratch setup failed\n");
2268                 /* iounmap will also get called at remove, but meh */
2269                 iounmap(dev_priv->gtt.gsm);
2270         }
2271
2272         return ret;
2273 }
2274
2275 /* The GGTT and PPGTT need a private PPAT setup in order to handle cacheability
2276  * bits. When using advanced contexts each context stores its own PAT, but
2277  * writing this data shouldn't be harmful even in those cases. */
2278 static void bdw_setup_private_ppat(struct drm_i915_private *dev_priv)
2279 {
2280         uint64_t pat;
2281
2282         pat = GEN8_PPAT(0, GEN8_PPAT_WB | GEN8_PPAT_LLC)     | /* for normal objects, no eLLC */
2283               GEN8_PPAT(1, GEN8_PPAT_WC | GEN8_PPAT_LLCELLC) | /* for something pointing to ptes? */
2284               GEN8_PPAT(2, GEN8_PPAT_WT | GEN8_PPAT_LLCELLC) | /* for scanout with eLLC */
2285               GEN8_PPAT(3, GEN8_PPAT_UC)                     | /* Uncached objects, mostly for scanout */
2286               GEN8_PPAT(4, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(0)) |
2287               GEN8_PPAT(5, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(1)) |
2288               GEN8_PPAT(6, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(2)) |
2289               GEN8_PPAT(7, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(3));
2290
2291         if (!USES_PPGTT(dev_priv->dev))
2292                 /* Spec: "For GGTT, there is NO pat_sel[2:0] from the entry,
2293                  * so RTL will always use the value corresponding to
2294                  * pat_sel = 000".
2295                  * So let's disable cache for GGTT to avoid screen corruptions.
2296                  * MOCS still can be used though.
2297                  * - System agent ggtt writes (i.e. cpu gtt mmaps) already work
2298                  * before this patch, i.e. the same uncached + snooping access
2299                  * like on gen6/7 seems to be in effect.
2300                  * - So this just fixes blitter/render access. Again it looks
2301                  * like it's not just uncached access, but uncached + snooping.
2302                  * So we can still hold onto all our assumptions wrt cpu
2303                  * clflushing on LLC machines.
2304                  */
2305                 pat = GEN8_PPAT(0, GEN8_PPAT_UC);
2306
2307         /* XXX: spec defines this as 2 distinct registers. It's unclear if a 64b
2308          * write would work. */
2309         I915_WRITE(GEN8_PRIVATE_PAT, pat);
2310         I915_WRITE(GEN8_PRIVATE_PAT + 4, pat >> 32);
2311 }
2312
2313 static void chv_setup_private_ppat(struct drm_i915_private *dev_priv)
2314 {
2315         uint64_t pat;
2316
2317         /*
2318          * Map WB on BDW to snooped on CHV.
2319          *
2320          * Only the snoop bit has meaning for CHV, the rest is
2321          * ignored.
2322          *
2323          * The hardware will never snoop for certain types of accesses:
2324          * - CPU GTT (GMADR->GGTT->no snoop->memory)
2325          * - PPGTT page tables
2326          * - some other special cycles
2327          *
2328          * As with BDW, we also need to consider the following for GT accesses:
2329          * "For GGTT, there is NO pat_sel[2:0] from the entry,
2330          * so RTL will always use the value corresponding to
2331          * pat_sel = 000".
2332          * Which means we must set the snoop bit in PAT entry 0
2333          * in order to keep the global status page working.
2334          */
2335         pat = GEN8_PPAT(0, CHV_PPAT_SNOOP) |
2336               GEN8_PPAT(1, 0) |
2337               GEN8_PPAT(2, 0) |
2338               GEN8_PPAT(3, 0) |
2339               GEN8_PPAT(4, CHV_PPAT_SNOOP) |
2340               GEN8_PPAT(5, CHV_PPAT_SNOOP) |
2341               GEN8_PPAT(6, CHV_PPAT_SNOOP) |
2342               GEN8_PPAT(7, CHV_PPAT_SNOOP);
2343
2344         I915_WRITE(GEN8_PRIVATE_PAT, pat);
2345         I915_WRITE(GEN8_PRIVATE_PAT + 4, pat >> 32);
2346 }
2347
2348 static int gen8_gmch_probe(struct drm_device *dev,
2349                            size_t *gtt_total,
2350                            size_t *stolen,
2351                            phys_addr_t *mappable_base,
2352                            unsigned long *mappable_end)
2353 {
2354         struct drm_i915_private *dev_priv = dev->dev_private;
2355         unsigned int gtt_size;
2356         u16 snb_gmch_ctl;
2357         int ret;
2358
2359         /* TODO: We're not aware of mappable constraints on gen8 yet */
2360         *mappable_base = pci_resource_start(dev->pdev, 2);
2361         *mappable_end = pci_resource_len(dev->pdev, 2);
2362
2363         if (!pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(39)))
2364                 pci_set_consistent_dma_mask(dev->pdev, DMA_BIT_MASK(39));
2365
2366         pci_read_config_word(dev->pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
2367
2368         if (INTEL_INFO(dev)->gen >= 9) {
2369                 *stolen = gen9_get_stolen_size(snb_gmch_ctl);
2370                 gtt_size = gen8_get_total_gtt_size(snb_gmch_ctl);
2371         } else if (IS_CHERRYVIEW(dev)) {
2372                 *stolen = chv_get_stolen_size(snb_gmch_ctl);
2373                 gtt_size = chv_get_total_gtt_size(snb_gmch_ctl);
2374         } else {
2375                 *stolen = gen8_get_stolen_size(snb_gmch_ctl);
2376                 gtt_size = gen8_get_total_gtt_size(snb_gmch_ctl);
2377         }
2378
2379         *gtt_total = (gtt_size / sizeof(gen8_pte_t)) << PAGE_SHIFT;
2380
2381         if (IS_CHERRYVIEW(dev))
2382                 chv_setup_private_ppat(dev_priv);
2383         else
2384                 bdw_setup_private_ppat(dev_priv);
2385
2386         ret = ggtt_probe_common(dev, gtt_size);
2387
2388         dev_priv->gtt.base.clear_range = gen8_ggtt_clear_range;
2389         dev_priv->gtt.base.insert_entries = gen8_ggtt_insert_entries;
2390
2391         return ret;
2392 }
2393
2394 static int gen6_gmch_probe(struct drm_device *dev,
2395                            size_t *gtt_total,
2396                            size_t *stolen,
2397                            phys_addr_t *mappable_base,
2398                            unsigned long *mappable_end)
2399 {
2400         struct drm_i915_private *dev_priv = dev->dev_private;
2401         unsigned int gtt_size;
2402         u16 snb_gmch_ctl;
2403         int ret;
2404
2405         *mappable_base = pci_resource_start(dev->pdev, 2);
2406         *mappable_end = pci_resource_len(dev->pdev, 2);
2407
2408         /* 64/512MB is the current min/max we actually know of, but this is just
2409          * a coarse sanity check.
2410          */
2411         if ((*mappable_end < (64<<20) || (*mappable_end > (512<<20)))) {
2412                 DRM_ERROR("Unknown GMADR size (%lx)\n",
2413                           dev_priv->gtt.mappable_end);
2414                 return -ENXIO;
2415         }
2416
2417         if (!pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(40)))
2418                 pci_set_consistent_dma_mask(dev->pdev, DMA_BIT_MASK(40));
2419         pci_read_config_word(dev->pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
2420
2421         *stolen = gen6_get_stolen_size(snb_gmch_ctl);
2422
2423         gtt_size = gen6_get_total_gtt_size(snb_gmch_ctl);
2424         *gtt_total = (gtt_size / sizeof(gen6_pte_t)) << PAGE_SHIFT;
2425
2426         ret = ggtt_probe_common(dev, gtt_size);
2427
2428         dev_priv->gtt.base.clear_range = gen6_ggtt_clear_range;
2429         dev_priv->gtt.base.insert_entries = gen6_ggtt_insert_entries;
2430
2431         return ret;
2432 }
2433
2434 static void gen6_gmch_remove(struct i915_address_space *vm)
2435 {
2436
2437         struct i915_gtt *gtt = container_of(vm, struct i915_gtt, base);
2438
2439         iounmap(gtt->gsm);
2440         teardown_scratch_page(vm->dev);
2441 }
2442
2443 static int i915_gmch_probe(struct drm_device *dev,
2444                            size_t *gtt_total,
2445                            size_t *stolen,
2446                            phys_addr_t *mappable_base,
2447                            unsigned long *mappable_end)
2448 {
2449         struct drm_i915_private *dev_priv = dev->dev_private;
2450         int ret;
2451
2452         ret = intel_gmch_probe(dev_priv->bridge_dev, dev_priv->dev->pdev, NULL);
2453         if (!ret) {
2454                 DRM_ERROR("failed to set up gmch\n");
2455                 return -EIO;
2456         }
2457
2458         intel_gtt_get(gtt_total, stolen, mappable_base, mappable_end);
2459
2460         dev_priv->gtt.do_idle_maps = needs_idle_maps(dev_priv->dev);
2461         dev_priv->gtt.base.clear_range = i915_ggtt_clear_range;
2462
2463         if (unlikely(dev_priv->gtt.do_idle_maps))
2464                 DRM_INFO("applying Ironlake quirks for intel_iommu\n");
2465
2466         return 0;
2467 }
2468
2469 static void i915_gmch_remove(struct i915_address_space *vm)
2470 {
2471         intel_gmch_remove();
2472 }
2473
2474 int i915_gem_gtt_init(struct drm_device *dev)
2475 {
2476         struct drm_i915_private *dev_priv = dev->dev_private;
2477         struct i915_gtt *gtt = &dev_priv->gtt;
2478         int ret;
2479
2480         if (INTEL_INFO(dev)->gen <= 5) {
2481                 gtt->gtt_probe = i915_gmch_probe;
2482                 gtt->base.cleanup = i915_gmch_remove;
2483         } else if (INTEL_INFO(dev)->gen < 8) {
2484                 gtt->gtt_probe = gen6_gmch_probe;
2485                 gtt->base.cleanup = gen6_gmch_remove;
2486                 if (IS_HASWELL(dev) && dev_priv->ellc_size)
2487                         gtt->base.pte_encode = iris_pte_encode;
2488                 else if (IS_HASWELL(dev))
2489                         gtt->base.pte_encode = hsw_pte_encode;
2490                 else if (IS_VALLEYVIEW(dev))
2491                         gtt->base.pte_encode = byt_pte_encode;
2492                 else if (INTEL_INFO(dev)->gen >= 7)
2493                         gtt->base.pte_encode = ivb_pte_encode;
2494                 else
2495                         gtt->base.pte_encode = snb_pte_encode;
2496         } else {
2497                 dev_priv->gtt.gtt_probe = gen8_gmch_probe;
2498                 dev_priv->gtt.base.cleanup = gen6_gmch_remove;
2499         }
2500
2501         ret = gtt->gtt_probe(dev, &gtt->base.total, &gtt->stolen_size,
2502                              &gtt->mappable_base, &gtt->mappable_end);
2503         if (ret)
2504                 return ret;
2505
2506         gtt->base.dev = dev;
2507
2508         /* GMADR is the PCI mmio aperture into the global GTT. */
2509         DRM_INFO("Memory usable by graphics device = %zdM\n",
2510                  gtt->base.total >> 20);
2511         DRM_DEBUG_DRIVER("GMADR size = %ldM\n", gtt->mappable_end >> 20);
2512         DRM_DEBUG_DRIVER("GTT stolen size = %zdM\n", gtt->stolen_size >> 20);
2513 #ifdef CONFIG_INTEL_IOMMU
2514         if (intel_iommu_gfx_mapped)
2515                 DRM_INFO("VT-d active for gfx access\n");
2516 #endif
2517         /*
2518          * i915.enable_ppgtt is read-only, so do an early pass to validate the
2519          * user's requested state against the hardware/driver capabilities.  We
2520          * do this now so that we can print out any log messages once rather
2521          * than every time we check intel_enable_ppgtt().
2522          */
2523         i915.enable_ppgtt = sanitize_enable_ppgtt(dev, i915.enable_ppgtt);
2524         DRM_DEBUG_DRIVER("ppgtt mode: %i\n", i915.enable_ppgtt);
2525
2526         return 0;
2527 }
2528
2529 static struct i915_vma *
2530 __i915_gem_vma_create(struct drm_i915_gem_object *obj,
2531                       struct i915_address_space *vm,
2532                       const struct i915_ggtt_view *ggtt_view)
2533 {
2534         struct i915_vma *vma;
2535
2536         if (WARN_ON(i915_is_ggtt(vm) != !!ggtt_view))
2537                 return ERR_PTR(-EINVAL);
2538         vma = kzalloc(sizeof(*vma), GFP_KERNEL);
2539         if (vma == NULL)
2540                 return ERR_PTR(-ENOMEM);
2541
2542         INIT_LIST_HEAD(&vma->vma_link);
2543         INIT_LIST_HEAD(&vma->mm_list);
2544         INIT_LIST_HEAD(&vma->exec_list);
2545         vma->vm = vm;
2546         vma->obj = obj;
2547
2548         if (INTEL_INFO(vm->dev)->gen >= 6) {
2549                 if (i915_is_ggtt(vm)) {
2550                         vma->ggtt_view = *ggtt_view;
2551
2552                         vma->unbind_vma = ggtt_unbind_vma;
2553                         vma->bind_vma = ggtt_bind_vma;
2554                 } else {
2555                         vma->unbind_vma = ppgtt_unbind_vma;
2556                         vma->bind_vma = ppgtt_bind_vma;
2557                 }
2558         } else {
2559                 BUG_ON(!i915_is_ggtt(vm));
2560                 vma->ggtt_view = *ggtt_view;
2561                 vma->unbind_vma = i915_ggtt_unbind_vma;
2562                 vma->bind_vma = i915_ggtt_bind_vma;
2563         }
2564
2565         list_add_tail(&vma->vma_link, &obj->vma_list);
2566         if (!i915_is_ggtt(vm))
2567                 i915_ppgtt_get(i915_vm_to_ppgtt(vm));
2568
2569         return vma;
2570 }
2571
2572 struct i915_vma *
2573 i915_gem_obj_lookup_or_create_vma(struct drm_i915_gem_object *obj,
2574                                   struct i915_address_space *vm)
2575 {
2576         struct i915_vma *vma;
2577
2578         vma = i915_gem_obj_to_vma(obj, vm);
2579         if (!vma)
2580                 vma = __i915_gem_vma_create(obj, vm,
2581                                             i915_is_ggtt(vm) ? &i915_ggtt_view_normal : NULL);
2582
2583         return vma;
2584 }
2585
2586 struct i915_vma *
2587 i915_gem_obj_lookup_or_create_ggtt_vma(struct drm_i915_gem_object *obj,
2588                                        const struct i915_ggtt_view *view)
2589 {
2590         struct i915_address_space *ggtt = i915_obj_to_ggtt(obj);
2591         struct i915_vma *vma;
2592
2593         if (WARN_ON(!view))
2594                 return ERR_PTR(-EINVAL);
2595
2596         vma = i915_gem_obj_to_ggtt_view(obj, view);
2597
2598         if (IS_ERR(vma))
2599                 return vma;
2600
2601         if (!vma)
2602                 vma = __i915_gem_vma_create(obj, ggtt, view);
2603
2604         return vma;
2605
2606 }
2607
2608 static void
2609 rotate_pages(dma_addr_t *in, unsigned int width, unsigned int height,
2610              struct sg_table *st)
2611 {
2612         unsigned int column, row;
2613         unsigned int src_idx;
2614         struct scatterlist *sg = st->sgl;
2615
2616         st->nents = 0;
2617
2618         for (column = 0; column < width; column++) {
2619                 src_idx = width * (height - 1) + column;
2620                 for (row = 0; row < height; row++) {
2621                         st->nents++;
2622                         /* We don't need the pages, but need to initialize
2623                          * the entries so the sg list can be happily traversed.
2624                          * The only thing we need are DMA addresses.
2625                          */
2626                         sg_set_page(sg, NULL, PAGE_SIZE, 0);
2627                         sg_dma_address(sg) = in[src_idx];
2628                         sg_dma_len(sg) = PAGE_SIZE;
2629                         sg = sg_next(sg);
2630                         src_idx -= width;
2631                 }
2632         }
2633 }
2634
2635 static struct sg_table *
2636 intel_rotate_fb_obj_pages(struct i915_ggtt_view *ggtt_view,
2637                           struct drm_i915_gem_object *obj)
2638 {
2639         struct drm_device *dev = obj->base.dev;
2640         struct intel_rotation_info *rot_info = &ggtt_view->rotation_info;
2641         unsigned long size, pages, rot_pages;
2642         struct sg_page_iter sg_iter;
2643         unsigned long i;
2644         dma_addr_t *page_addr_list;
2645         struct sg_table *st;
2646         unsigned int tile_pitch, tile_height;
2647         unsigned int width_pages, height_pages;
2648         int ret = -ENOMEM;
2649
2650         pages = obj->base.size / PAGE_SIZE;
2651
2652         /* Calculate tiling geometry. */
2653         tile_height = intel_tile_height(dev, rot_info->pixel_format,
2654                                         rot_info->fb_modifier);
2655         tile_pitch = PAGE_SIZE / tile_height;
2656         width_pages = DIV_ROUND_UP(rot_info->pitch, tile_pitch);
2657         height_pages = DIV_ROUND_UP(rot_info->height, tile_height);
2658         rot_pages = width_pages * height_pages;
2659         size = rot_pages * PAGE_SIZE;
2660
2661         /* Allocate a temporary list of source pages for random access. */
2662         page_addr_list = drm_malloc_ab(pages, sizeof(dma_addr_t));
2663         if (!page_addr_list)
2664                 return ERR_PTR(ret);
2665
2666         /* Allocate target SG list. */
2667         st = kmalloc(sizeof(*st), GFP_KERNEL);
2668         if (!st)
2669                 goto err_st_alloc;
2670
2671         ret = sg_alloc_table(st, rot_pages, GFP_KERNEL);
2672         if (ret)
2673                 goto err_sg_alloc;
2674
2675         /* Populate source page list from the object. */
2676         i = 0;
2677         for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents, 0) {
2678                 page_addr_list[i] = sg_page_iter_dma_address(&sg_iter);
2679                 i++;
2680         }
2681
2682         /* Rotate the pages. */
2683         rotate_pages(page_addr_list, width_pages, height_pages, st);
2684
2685         DRM_DEBUG_KMS(
2686                       "Created rotated page mapping for object size %lu (pitch=%u, height=%u, pixel_format=0x%x, %ux%u tiles, %lu pages).\n",
2687                       size, rot_info->pitch, rot_info->height,
2688                       rot_info->pixel_format, width_pages, height_pages,
2689                       rot_pages);
2690
2691         drm_free_large(page_addr_list);
2692
2693         return st;
2694
2695 err_sg_alloc:
2696         kfree(st);
2697 err_st_alloc:
2698         drm_free_large(page_addr_list);
2699
2700         DRM_DEBUG_KMS(
2701                       "Failed to create rotated mapping for object size %lu! (%d) (pitch=%u, height=%u, pixel_format=0x%x, %ux%u tiles, %lu pages)\n",
2702                       size, ret, rot_info->pitch, rot_info->height,
2703                       rot_info->pixel_format, width_pages, height_pages,
2704                       rot_pages);
2705         return ERR_PTR(ret);
2706 }
2707
2708 static inline int
2709 i915_get_ggtt_vma_pages(struct i915_vma *vma)
2710 {
2711         int ret = 0;
2712
2713         if (vma->ggtt_view.pages)
2714                 return 0;
2715
2716         if (vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL)
2717                 vma->ggtt_view.pages = vma->obj->pages;
2718         else if (vma->ggtt_view.type == I915_GGTT_VIEW_ROTATED)
2719                 vma->ggtt_view.pages =
2720                         intel_rotate_fb_obj_pages(&vma->ggtt_view, vma->obj);
2721         else
2722                 WARN_ONCE(1, "GGTT view %u not implemented!\n",
2723                           vma->ggtt_view.type);
2724
2725         if (!vma->ggtt_view.pages) {
2726                 DRM_ERROR("Failed to get pages for GGTT view type %u!\n",
2727                           vma->ggtt_view.type);
2728                 ret = -EINVAL;
2729         } else if (IS_ERR(vma->ggtt_view.pages)) {
2730                 ret = PTR_ERR(vma->ggtt_view.pages);
2731                 vma->ggtt_view.pages = NULL;
2732                 DRM_ERROR("Failed to get pages for VMA view type %u (%d)!\n",
2733                           vma->ggtt_view.type, ret);
2734         }
2735
2736         return ret;
2737 }
2738
2739 /**
2740  * i915_vma_bind - Sets up PTEs for an VMA in it's corresponding address space.
2741  * @vma: VMA to map
2742  * @cache_level: mapping cache level
2743  * @flags: flags like global or local mapping
2744  *
2745  * DMA addresses are taken from the scatter-gather table of this object (or of
2746  * this VMA in case of non-default GGTT views) and PTE entries set up.
2747  * Note that DMA addresses are also the only part of the SG table we care about.
2748  */
2749 int i915_vma_bind(struct i915_vma *vma, enum i915_cache_level cache_level,
2750                   u32 flags)
2751 {
2752         if (i915_is_ggtt(vma->vm)) {
2753                 int ret = i915_get_ggtt_vma_pages(vma);
2754
2755                 if (ret)
2756                         return ret;
2757         }
2758
2759         vma->bind_vma(vma, cache_level, flags);
2760
2761         return 0;
2762 }