drm/i915: Track GEN6 page table usage
[firefly-linux-kernel-4.4.55.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         return dma_mapping_error(device, *daddr);
315 }
316
317 static void unmap_and_free_pt(struct i915_page_table_entry *pt,
318                                struct drm_device *dev)
319 {
320         if (WARN_ON(!pt->page))
321                 return;
322
323         i915_dma_unmap_single(pt, dev);
324         __free_page(pt->page);
325         kfree(pt->used_ptes);
326         kfree(pt);
327 }
328
329 static struct i915_page_table_entry *alloc_pt_single(struct drm_device *dev)
330 {
331         struct i915_page_table_entry *pt;
332         const size_t count = INTEL_INFO(dev)->gen >= 8 ?
333                 GEN8_PTES : GEN6_PTES;
334         int ret = -ENOMEM;
335
336         pt = kzalloc(sizeof(*pt), GFP_KERNEL);
337         if (!pt)
338                 return ERR_PTR(-ENOMEM);
339
340         pt->used_ptes = kcalloc(BITS_TO_LONGS(count), sizeof(*pt->used_ptes),
341                                 GFP_KERNEL);
342
343         if (!pt->used_ptes)
344                 goto fail_bitmap;
345
346         pt->page = alloc_page(GFP_KERNEL | __GFP_ZERO);
347         if (!pt->page)
348                 goto fail_page;
349
350         ret = i915_dma_map_single(pt, dev);
351         if (ret)
352                 goto fail_dma;
353
354         return pt;
355
356 fail_dma:
357         __free_page(pt->page);
358 fail_page:
359         kfree(pt->used_ptes);
360 fail_bitmap:
361         kfree(pt);
362
363         return ERR_PTR(ret);
364 }
365
366 /**
367  * alloc_pt_range() - Allocate a multiple page tables
368  * @pd:         The page directory which will have at least @count entries
369  *              available to point to the allocated page tables.
370  * @pde:        First page directory entry for which we are allocating.
371  * @count:      Number of pages to allocate.
372  * @dev:        DRM device.
373  *
374  * Allocates multiple page table pages and sets the appropriate entries in the
375  * page table structure within the page directory. Function cleans up after
376  * itself on any failures.
377  *
378  * Return: 0 if allocation succeeded.
379  */
380 static int alloc_pt_range(struct i915_page_directory_entry *pd, uint16_t pde, size_t count,
381                   struct drm_device *dev)
382 {
383         int i, ret;
384
385         /* 512 is the max page tables per page_directory on any platform. */
386         if (WARN_ON(pde + count > I915_PDES))
387                 return -EINVAL;
388
389         for (i = pde; i < pde + count; i++) {
390                 struct i915_page_table_entry *pt = alloc_pt_single(dev);
391
392                 if (IS_ERR(pt)) {
393                         ret = PTR_ERR(pt);
394                         goto err_out;
395                 }
396                 WARN(pd->page_table[i],
397                      "Leaking page directory entry %d (%p)\n",
398                      i, pd->page_table[i]);
399                 pd->page_table[i] = pt;
400         }
401
402         return 0;
403
404 err_out:
405         while (i-- > pde)
406                 unmap_and_free_pt(pd->page_table[i], dev);
407         return ret;
408 }
409
410 static void unmap_and_free_pd(struct i915_page_directory_entry *pd)
411 {
412         if (pd->page) {
413                 __free_page(pd->page);
414                 kfree(pd);
415         }
416 }
417
418 static struct i915_page_directory_entry *alloc_pd_single(void)
419 {
420         struct i915_page_directory_entry *pd;
421
422         pd = kzalloc(sizeof(*pd), GFP_KERNEL);
423         if (!pd)
424                 return ERR_PTR(-ENOMEM);
425
426         pd->page = alloc_page(GFP_KERNEL | __GFP_ZERO);
427         if (!pd->page) {
428                 kfree(pd);
429                 return ERR_PTR(-ENOMEM);
430         }
431
432         return pd;
433 }
434
435 /* Broadwell Page Directory Pointer Descriptors */
436 static int gen8_write_pdp(struct intel_engine_cs *ring, unsigned entry,
437                            uint64_t val)
438 {
439         int ret;
440
441         BUG_ON(entry >= 4);
442
443         ret = intel_ring_begin(ring, 6);
444         if (ret)
445                 return ret;
446
447         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
448         intel_ring_emit(ring, GEN8_RING_PDP_UDW(ring, entry));
449         intel_ring_emit(ring, (u32)(val >> 32));
450         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
451         intel_ring_emit(ring, GEN8_RING_PDP_LDW(ring, entry));
452         intel_ring_emit(ring, (u32)(val));
453         intel_ring_advance(ring);
454
455         return 0;
456 }
457
458 static int gen8_mm_switch(struct i915_hw_ppgtt *ppgtt,
459                           struct intel_engine_cs *ring)
460 {
461         int i, ret;
462
463         /* bit of a hack to find the actual last used pd */
464         int used_pd = ppgtt->num_pd_entries / I915_PDES;
465
466         for (i = used_pd - 1; i >= 0; i--) {
467                 dma_addr_t addr = ppgtt->pdp.page_directory[i]->daddr;
468                 ret = gen8_write_pdp(ring, i, addr);
469                 if (ret)
470                         return ret;
471         }
472
473         return 0;
474 }
475
476 static void gen8_ppgtt_clear_range(struct i915_address_space *vm,
477                                    uint64_t start,
478                                    uint64_t length,
479                                    bool use_scratch)
480 {
481         struct i915_hw_ppgtt *ppgtt =
482                 container_of(vm, struct i915_hw_ppgtt, base);
483         gen8_pte_t *pt_vaddr, scratch_pte;
484         unsigned pdpe = start >> GEN8_PDPE_SHIFT & GEN8_PDPE_MASK;
485         unsigned pde = start >> GEN8_PDE_SHIFT & GEN8_PDE_MASK;
486         unsigned pte = start >> GEN8_PTE_SHIFT & GEN8_PTE_MASK;
487         unsigned num_entries = length >> PAGE_SHIFT;
488         unsigned last_pte, i;
489
490         scratch_pte = gen8_pte_encode(ppgtt->base.scratch.addr,
491                                       I915_CACHE_LLC, use_scratch);
492
493         while (num_entries) {
494                 struct i915_page_directory_entry *pd;
495                 struct i915_page_table_entry *pt;
496                 struct page *page_table;
497
498                 if (WARN_ON(!ppgtt->pdp.page_directory[pdpe]))
499                         continue;
500
501                 pd = ppgtt->pdp.page_directory[pdpe];
502
503                 if (WARN_ON(!pd->page_table[pde]))
504                         continue;
505
506                 pt = pd->page_table[pde];
507
508                 if (WARN_ON(!pt->page))
509                         continue;
510
511                 page_table = pt->page;
512
513                 last_pte = pte + num_entries;
514                 if (last_pte > GEN8_PTES)
515                         last_pte = GEN8_PTES;
516
517                 pt_vaddr = kmap_atomic(page_table);
518
519                 for (i = pte; i < last_pte; i++) {
520                         pt_vaddr[i] = scratch_pte;
521                         num_entries--;
522                 }
523
524                 if (!HAS_LLC(ppgtt->base.dev))
525                         drm_clflush_virt_range(pt_vaddr, PAGE_SIZE);
526                 kunmap_atomic(pt_vaddr);
527
528                 pte = 0;
529                 if (++pde == I915_PDES) {
530                         pdpe++;
531                         pde = 0;
532                 }
533         }
534 }
535
536 static void gen8_ppgtt_insert_entries(struct i915_address_space *vm,
537                                       struct sg_table *pages,
538                                       uint64_t start,
539                                       enum i915_cache_level cache_level, u32 unused)
540 {
541         struct i915_hw_ppgtt *ppgtt =
542                 container_of(vm, struct i915_hw_ppgtt, base);
543         gen8_pte_t *pt_vaddr;
544         unsigned pdpe = start >> GEN8_PDPE_SHIFT & GEN8_PDPE_MASK;
545         unsigned pde = start >> GEN8_PDE_SHIFT & GEN8_PDE_MASK;
546         unsigned pte = start >> GEN8_PTE_SHIFT & GEN8_PTE_MASK;
547         struct sg_page_iter sg_iter;
548
549         pt_vaddr = NULL;
550
551         for_each_sg_page(pages->sgl, &sg_iter, pages->nents, 0) {
552                 if (WARN_ON(pdpe >= GEN8_LEGACY_PDPES))
553                         break;
554
555                 if (pt_vaddr == NULL) {
556                         struct i915_page_directory_entry *pd = ppgtt->pdp.page_directory[pdpe];
557                         struct i915_page_table_entry *pt = pd->page_table[pde];
558                         struct page *page_table = pt->page;
559
560                         pt_vaddr = kmap_atomic(page_table);
561                 }
562
563                 pt_vaddr[pte] =
564                         gen8_pte_encode(sg_page_iter_dma_address(&sg_iter),
565                                         cache_level, true);
566                 if (++pte == GEN8_PTES) {
567                         if (!HAS_LLC(ppgtt->base.dev))
568                                 drm_clflush_virt_range(pt_vaddr, PAGE_SIZE);
569                         kunmap_atomic(pt_vaddr);
570                         pt_vaddr = NULL;
571                         if (++pde == I915_PDES) {
572                                 pdpe++;
573                                 pde = 0;
574                         }
575                         pte = 0;
576                 }
577         }
578         if (pt_vaddr) {
579                 if (!HAS_LLC(ppgtt->base.dev))
580                         drm_clflush_virt_range(pt_vaddr, PAGE_SIZE);
581                 kunmap_atomic(pt_vaddr);
582         }
583 }
584
585 static void gen8_free_page_tables(struct i915_page_directory_entry *pd, struct drm_device *dev)
586 {
587         int i;
588
589         if (!pd->page)
590                 return;
591
592         for (i = 0; i < I915_PDES; i++) {
593                 if (WARN_ON(!pd->page_table[i]))
594                         continue;
595
596                 unmap_and_free_pt(pd->page_table[i], dev);
597                 pd->page_table[i] = NULL;
598         }
599 }
600
601 static void gen8_ppgtt_free(struct i915_hw_ppgtt *ppgtt)
602 {
603         int i;
604
605         for (i = 0; i < ppgtt->num_pd_pages; i++) {
606                 if (WARN_ON(!ppgtt->pdp.page_directory[i]))
607                         continue;
608
609                 gen8_free_page_tables(ppgtt->pdp.page_directory[i], ppgtt->base.dev);
610                 unmap_and_free_pd(ppgtt->pdp.page_directory[i]);
611         }
612 }
613
614 static void gen8_ppgtt_unmap_pages(struct i915_hw_ppgtt *ppgtt)
615 {
616         struct pci_dev *hwdev = ppgtt->base.dev->pdev;
617         int i, j;
618
619         for (i = 0; i < ppgtt->num_pd_pages; i++) {
620                 /* TODO: In the future we'll support sparse mappings, so this
621                  * will have to change. */
622                 if (!ppgtt->pdp.page_directory[i]->daddr)
623                         continue;
624
625                 pci_unmap_page(hwdev, ppgtt->pdp.page_directory[i]->daddr, PAGE_SIZE,
626                                PCI_DMA_BIDIRECTIONAL);
627
628                 for (j = 0; j < I915_PDES; j++) {
629                         struct i915_page_directory_entry *pd = ppgtt->pdp.page_directory[i];
630                         struct i915_page_table_entry *pt;
631                         dma_addr_t addr;
632
633                         if (WARN_ON(!pd->page_table[j]))
634                                 continue;
635
636                         pt = pd->page_table[j];
637                         addr = pt->daddr;
638
639                         if (addr)
640                                 pci_unmap_page(hwdev, addr, PAGE_SIZE,
641                                                PCI_DMA_BIDIRECTIONAL);
642                 }
643         }
644 }
645
646 static void gen8_ppgtt_cleanup(struct i915_address_space *vm)
647 {
648         struct i915_hw_ppgtt *ppgtt =
649                 container_of(vm, struct i915_hw_ppgtt, base);
650
651         gen8_ppgtt_unmap_pages(ppgtt);
652         gen8_ppgtt_free(ppgtt);
653 }
654
655 static int gen8_ppgtt_allocate_page_tables(struct i915_hw_ppgtt *ppgtt)
656 {
657         int i, ret;
658
659         for (i = 0; i < ppgtt->num_pd_pages; i++) {
660                 ret = alloc_pt_range(ppgtt->pdp.page_directory[i],
661                                      0, I915_PDES, ppgtt->base.dev);
662                 if (ret)
663                         goto unwind_out;
664         }
665
666         return 0;
667
668 unwind_out:
669         while (i--)
670                 gen8_free_page_tables(ppgtt->pdp.page_directory[i], ppgtt->base.dev);
671
672         return -ENOMEM;
673 }
674
675 static int gen8_ppgtt_allocate_page_directories(struct i915_hw_ppgtt *ppgtt,
676                                                 const int max_pdp)
677 {
678         int i;
679
680         for (i = 0; i < max_pdp; i++) {
681                 ppgtt->pdp.page_directory[i] = alloc_pd_single();
682                 if (IS_ERR(ppgtt->pdp.page_directory[i]))
683                         goto unwind_out;
684         }
685
686         ppgtt->num_pd_pages = max_pdp;
687         BUG_ON(ppgtt->num_pd_pages > GEN8_LEGACY_PDPES);
688
689         return 0;
690
691 unwind_out:
692         while (i--)
693                 unmap_and_free_pd(ppgtt->pdp.page_directory[i]);
694
695         return -ENOMEM;
696 }
697
698 static int gen8_ppgtt_alloc(struct i915_hw_ppgtt *ppgtt,
699                             const int max_pdp)
700 {
701         int ret;
702
703         ret = gen8_ppgtt_allocate_page_directories(ppgtt, max_pdp);
704         if (ret)
705                 return ret;
706
707         ret = gen8_ppgtt_allocate_page_tables(ppgtt);
708         if (ret)
709                 goto err_out;
710
711         ppgtt->num_pd_entries = max_pdp * I915_PDES;
712
713         return 0;
714
715 err_out:
716         gen8_ppgtt_free(ppgtt);
717         return ret;
718 }
719
720 static int gen8_ppgtt_setup_page_directories(struct i915_hw_ppgtt *ppgtt,
721                                              const int pd)
722 {
723         dma_addr_t pd_addr;
724         int ret;
725
726         pd_addr = pci_map_page(ppgtt->base.dev->pdev,
727                                ppgtt->pdp.page_directory[pd]->page, 0,
728                                PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
729
730         ret = pci_dma_mapping_error(ppgtt->base.dev->pdev, pd_addr);
731         if (ret)
732                 return ret;
733
734         ppgtt->pdp.page_directory[pd]->daddr = pd_addr;
735
736         return 0;
737 }
738
739 static int gen8_ppgtt_setup_page_tables(struct i915_hw_ppgtt *ppgtt,
740                                         const int pd,
741                                         const int pt)
742 {
743         dma_addr_t pt_addr;
744         struct i915_page_directory_entry *pdir = ppgtt->pdp.page_directory[pd];
745         struct i915_page_table_entry *ptab = pdir->page_table[pt];
746         struct page *p = ptab->page;
747         int ret;
748
749         pt_addr = pci_map_page(ppgtt->base.dev->pdev,
750                                p, 0, PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
751         ret = pci_dma_mapping_error(ppgtt->base.dev->pdev, pt_addr);
752         if (ret)
753                 return ret;
754
755         ptab->daddr = pt_addr;
756
757         return 0;
758 }
759
760 /*
761  * GEN8 legacy ppgtt programming is accomplished through a max 4 PDP registers
762  * with a net effect resembling a 2-level page table in normal x86 terms. Each
763  * PDP represents 1GB of memory 4 * 512 * 512 * 4096 = 4GB legacy 32b address
764  * space.
765  *
766  * FIXME: split allocation into smaller pieces. For now we only ever do this
767  * once, but with full PPGTT, the multiple contiguous allocations will be bad.
768  * TODO: Do something with the size parameter
769  */
770 static int gen8_ppgtt_init(struct i915_hw_ppgtt *ppgtt, uint64_t size)
771 {
772         const int max_pdp = DIV_ROUND_UP(size, 1 << 30);
773         const int min_pt_pages = I915_PDES * max_pdp;
774         int i, j, ret;
775
776         if (size % (1<<30))
777                 DRM_INFO("Pages will be wasted unless GTT size (%llu) is divisible by 1GB\n", size);
778
779         /* 1. Do all our allocations for page directories and page tables.
780          * We allocate more than was asked so that we can point the unused parts
781          * to valid entries that point to scratch page. Dynamic page tables
782          * will fix this eventually.
783          */
784         ret = gen8_ppgtt_alloc(ppgtt, GEN8_LEGACY_PDPES);
785         if (ret)
786                 return ret;
787
788         /*
789          * 2. Create DMA mappings for the page directories and page tables.
790          */
791         for (i = 0; i < GEN8_LEGACY_PDPES; i++) {
792                 ret = gen8_ppgtt_setup_page_directories(ppgtt, i);
793                 if (ret)
794                         goto bail;
795
796                 for (j = 0; j < I915_PDES; j++) {
797                         ret = gen8_ppgtt_setup_page_tables(ppgtt, i, j);
798                         if (ret)
799                                 goto bail;
800                 }
801         }
802
803         /*
804          * 3. Map all the page directory entires to point to the page tables
805          * we've allocated.
806          *
807          * For now, the PPGTT helper functions all require that the PDEs are
808          * plugged in correctly. So we do that now/here. For aliasing PPGTT, we
809          * will never need to touch the PDEs again.
810          */
811         for (i = 0; i < GEN8_LEGACY_PDPES; i++) {
812                 struct i915_page_directory_entry *pd = ppgtt->pdp.page_directory[i];
813                 gen8_pde_t *pd_vaddr;
814                 pd_vaddr = kmap_atomic(ppgtt->pdp.page_directory[i]->page);
815                 for (j = 0; j < I915_PDES; j++) {
816                         struct i915_page_table_entry *pt = pd->page_table[j];
817                         dma_addr_t addr = pt->daddr;
818                         pd_vaddr[j] = gen8_pde_encode(ppgtt->base.dev, addr,
819                                                       I915_CACHE_LLC);
820                 }
821                 if (!HAS_LLC(ppgtt->base.dev))
822                         drm_clflush_virt_range(pd_vaddr, PAGE_SIZE);
823                 kunmap_atomic(pd_vaddr);
824         }
825
826         ppgtt->switch_mm = gen8_mm_switch;
827         ppgtt->base.clear_range = gen8_ppgtt_clear_range;
828         ppgtt->base.insert_entries = gen8_ppgtt_insert_entries;
829         ppgtt->base.cleanup = gen8_ppgtt_cleanup;
830         ppgtt->base.start = 0;
831
832         /* This is the area that we advertise as usable for the caller */
833         ppgtt->base.total = max_pdp * I915_PDES * GEN8_PTES * PAGE_SIZE;
834
835         /* Set all ptes to a valid scratch page. Also above requested space */
836         ppgtt->base.clear_range(&ppgtt->base, 0,
837                                 ppgtt->num_pd_pages * GEN8_PTES * PAGE_SIZE,
838                                 true);
839
840         DRM_DEBUG_DRIVER("Allocated %d pages for page directories (%d wasted)\n",
841                          ppgtt->num_pd_pages, ppgtt->num_pd_pages - max_pdp);
842         DRM_DEBUG_DRIVER("Allocated %d pages for page tables (%lld wasted)\n",
843                          ppgtt->num_pd_entries,
844                          (ppgtt->num_pd_entries - min_pt_pages) + size % (1<<30));
845         return 0;
846
847 bail:
848         gen8_ppgtt_unmap_pages(ppgtt);
849         gen8_ppgtt_free(ppgtt);
850         return ret;
851 }
852
853 static void gen6_dump_ppgtt(struct i915_hw_ppgtt *ppgtt, struct seq_file *m)
854 {
855         struct drm_i915_private *dev_priv = ppgtt->base.dev->dev_private;
856         struct i915_address_space *vm = &ppgtt->base;
857         gen6_pte_t __iomem *pd_addr;
858         gen6_pte_t scratch_pte;
859         uint32_t pd_entry;
860         int pte, pde;
861
862         scratch_pte = vm->pte_encode(vm->scratch.addr, I915_CACHE_LLC, true, 0);
863
864         pd_addr = (gen6_pte_t __iomem *)dev_priv->gtt.gsm +
865                 ppgtt->pd.pd_offset / sizeof(gen6_pte_t);
866
867         seq_printf(m, "  VM %p (pd_offset %x-%x):\n", vm,
868                    ppgtt->pd.pd_offset,
869                    ppgtt->pd.pd_offset + ppgtt->num_pd_entries);
870         for (pde = 0; pde < ppgtt->num_pd_entries; pde++) {
871                 u32 expected;
872                 gen6_pte_t *pt_vaddr;
873                 dma_addr_t pt_addr = ppgtt->pd.page_table[pde]->daddr;
874                 pd_entry = readl(pd_addr + pde);
875                 expected = (GEN6_PDE_ADDR_ENCODE(pt_addr) | GEN6_PDE_VALID);
876
877                 if (pd_entry != expected)
878                         seq_printf(m, "\tPDE #%d mismatch: Actual PDE: %x Expected PDE: %x\n",
879                                    pde,
880                                    pd_entry,
881                                    expected);
882                 seq_printf(m, "\tPDE: %x\n", pd_entry);
883
884                 pt_vaddr = kmap_atomic(ppgtt->pd.page_table[pde]->page);
885                 for (pte = 0; pte < GEN6_PTES; pte+=4) {
886                         unsigned long va =
887                                 (pde * PAGE_SIZE * GEN6_PTES) +
888                                 (pte * PAGE_SIZE);
889                         int i;
890                         bool found = false;
891                         for (i = 0; i < 4; i++)
892                                 if (pt_vaddr[pte + i] != scratch_pte)
893                                         found = true;
894                         if (!found)
895                                 continue;
896
897                         seq_printf(m, "\t\t0x%lx [%03d,%04d]: =", va, pde, pte);
898                         for (i = 0; i < 4; i++) {
899                                 if (pt_vaddr[pte + i] != scratch_pte)
900                                         seq_printf(m, " %08x", pt_vaddr[pte + i]);
901                                 else
902                                         seq_puts(m, "  SCRATCH ");
903                         }
904                         seq_puts(m, "\n");
905                 }
906                 kunmap_atomic(pt_vaddr);
907         }
908 }
909
910 /* Write pde (index) from the page directory @pd to the page table @pt */
911 static void gen6_write_pde(struct i915_page_directory_entry *pd,
912                             const int pde, struct i915_page_table_entry *pt)
913 {
914         /* Caller needs to make sure the write completes if necessary */
915         struct i915_hw_ppgtt *ppgtt =
916                 container_of(pd, struct i915_hw_ppgtt, pd);
917         u32 pd_entry;
918
919         pd_entry = GEN6_PDE_ADDR_ENCODE(pt->daddr);
920         pd_entry |= GEN6_PDE_VALID;
921
922         writel(pd_entry, ppgtt->pd_addr + pde);
923 }
924
925 /* Write all the page tables found in the ppgtt structure to incrementing page
926  * directories. */
927 static void gen6_write_page_range(struct drm_i915_private *dev_priv,
928                                   struct i915_page_directory_entry *pd,
929                                   uint32_t start, uint32_t length)
930 {
931         struct i915_page_table_entry *pt;
932         uint32_t pde, temp;
933
934         gen6_for_each_pde(pt, pd, start, length, temp, pde)
935                 gen6_write_pde(pd, pde, pt);
936
937         /* Make sure write is complete before other code can use this page
938          * table. Also require for WC mapped PTEs */
939         readl(dev_priv->gtt.gsm);
940 }
941
942 static uint32_t get_pd_offset(struct i915_hw_ppgtt *ppgtt)
943 {
944         BUG_ON(ppgtt->pd.pd_offset & 0x3f);
945
946         return (ppgtt->pd.pd_offset / 64) << 16;
947 }
948
949 static int hsw_mm_switch(struct i915_hw_ppgtt *ppgtt,
950                          struct intel_engine_cs *ring)
951 {
952         int ret;
953
954         /* NB: TLBs must be flushed and invalidated before a switch */
955         ret = ring->flush(ring, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
956         if (ret)
957                 return ret;
958
959         ret = intel_ring_begin(ring, 6);
960         if (ret)
961                 return ret;
962
963         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(2));
964         intel_ring_emit(ring, RING_PP_DIR_DCLV(ring));
965         intel_ring_emit(ring, PP_DIR_DCLV_2G);
966         intel_ring_emit(ring, RING_PP_DIR_BASE(ring));
967         intel_ring_emit(ring, get_pd_offset(ppgtt));
968         intel_ring_emit(ring, MI_NOOP);
969         intel_ring_advance(ring);
970
971         return 0;
972 }
973
974 static int vgpu_mm_switch(struct i915_hw_ppgtt *ppgtt,
975                           struct intel_engine_cs *ring)
976 {
977         struct drm_i915_private *dev_priv = to_i915(ppgtt->base.dev);
978
979         I915_WRITE(RING_PP_DIR_DCLV(ring), PP_DIR_DCLV_2G);
980         I915_WRITE(RING_PP_DIR_BASE(ring), get_pd_offset(ppgtt));
981         return 0;
982 }
983
984 static int gen7_mm_switch(struct i915_hw_ppgtt *ppgtt,
985                           struct intel_engine_cs *ring)
986 {
987         int ret;
988
989         /* NB: TLBs must be flushed and invalidated before a switch */
990         ret = ring->flush(ring, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
991         if (ret)
992                 return ret;
993
994         ret = intel_ring_begin(ring, 6);
995         if (ret)
996                 return ret;
997
998         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(2));
999         intel_ring_emit(ring, RING_PP_DIR_DCLV(ring));
1000         intel_ring_emit(ring, PP_DIR_DCLV_2G);
1001         intel_ring_emit(ring, RING_PP_DIR_BASE(ring));
1002         intel_ring_emit(ring, get_pd_offset(ppgtt));
1003         intel_ring_emit(ring, MI_NOOP);
1004         intel_ring_advance(ring);
1005
1006         /* XXX: RCS is the only one to auto invalidate the TLBs? */
1007         if (ring->id != RCS) {
1008                 ret = ring->flush(ring, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
1009                 if (ret)
1010                         return ret;
1011         }
1012
1013         return 0;
1014 }
1015
1016 static int gen6_mm_switch(struct i915_hw_ppgtt *ppgtt,
1017                           struct intel_engine_cs *ring)
1018 {
1019         struct drm_device *dev = ppgtt->base.dev;
1020         struct drm_i915_private *dev_priv = dev->dev_private;
1021
1022
1023         I915_WRITE(RING_PP_DIR_DCLV(ring), PP_DIR_DCLV_2G);
1024         I915_WRITE(RING_PP_DIR_BASE(ring), get_pd_offset(ppgtt));
1025
1026         POSTING_READ(RING_PP_DIR_DCLV(ring));
1027
1028         return 0;
1029 }
1030
1031 static void gen8_ppgtt_enable(struct drm_device *dev)
1032 {
1033         struct drm_i915_private *dev_priv = dev->dev_private;
1034         struct intel_engine_cs *ring;
1035         int j;
1036
1037         for_each_ring(ring, dev_priv, j) {
1038                 I915_WRITE(RING_MODE_GEN7(ring),
1039                            _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1040         }
1041 }
1042
1043 static void gen7_ppgtt_enable(struct drm_device *dev)
1044 {
1045         struct drm_i915_private *dev_priv = dev->dev_private;
1046         struct intel_engine_cs *ring;
1047         uint32_t ecochk, ecobits;
1048         int i;
1049
1050         ecobits = I915_READ(GAC_ECO_BITS);
1051         I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_PPGTT_CACHE64B);
1052
1053         ecochk = I915_READ(GAM_ECOCHK);
1054         if (IS_HASWELL(dev)) {
1055                 ecochk |= ECOCHK_PPGTT_WB_HSW;
1056         } else {
1057                 ecochk |= ECOCHK_PPGTT_LLC_IVB;
1058                 ecochk &= ~ECOCHK_PPGTT_GFDT_IVB;
1059         }
1060         I915_WRITE(GAM_ECOCHK, ecochk);
1061
1062         for_each_ring(ring, dev_priv, i) {
1063                 /* GFX_MODE is per-ring on gen7+ */
1064                 I915_WRITE(RING_MODE_GEN7(ring),
1065                            _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1066         }
1067 }
1068
1069 static void gen6_ppgtt_enable(struct drm_device *dev)
1070 {
1071         struct drm_i915_private *dev_priv = dev->dev_private;
1072         uint32_t ecochk, gab_ctl, ecobits;
1073
1074         ecobits = I915_READ(GAC_ECO_BITS);
1075         I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_SNB_BIT |
1076                    ECOBITS_PPGTT_CACHE64B);
1077
1078         gab_ctl = I915_READ(GAB_CTL);
1079         I915_WRITE(GAB_CTL, gab_ctl | GAB_CTL_CONT_AFTER_PAGEFAULT);
1080
1081         ecochk = I915_READ(GAM_ECOCHK);
1082         I915_WRITE(GAM_ECOCHK, ecochk | ECOCHK_SNB_BIT | ECOCHK_PPGTT_CACHE64B);
1083
1084         I915_WRITE(GFX_MODE, _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1085 }
1086
1087 /* PPGTT support for Sandybdrige/Gen6 and later */
1088 static void gen6_ppgtt_clear_range(struct i915_address_space *vm,
1089                                    uint64_t start,
1090                                    uint64_t length,
1091                                    bool use_scratch)
1092 {
1093         struct i915_hw_ppgtt *ppgtt =
1094                 container_of(vm, struct i915_hw_ppgtt, base);
1095         gen6_pte_t *pt_vaddr, scratch_pte;
1096         unsigned first_entry = start >> PAGE_SHIFT;
1097         unsigned num_entries = length >> PAGE_SHIFT;
1098         unsigned act_pt = first_entry / GEN6_PTES;
1099         unsigned first_pte = first_entry % GEN6_PTES;
1100         unsigned last_pte, i;
1101
1102         scratch_pte = vm->pte_encode(vm->scratch.addr, I915_CACHE_LLC, true, 0);
1103
1104         while (num_entries) {
1105                 last_pte = first_pte + num_entries;
1106                 if (last_pte > GEN6_PTES)
1107                         last_pte = GEN6_PTES;
1108
1109                 pt_vaddr = kmap_atomic(ppgtt->pd.page_table[act_pt]->page);
1110
1111                 for (i = first_pte; i < last_pte; i++)
1112                         pt_vaddr[i] = scratch_pte;
1113
1114                 kunmap_atomic(pt_vaddr);
1115
1116                 num_entries -= last_pte - first_pte;
1117                 first_pte = 0;
1118                 act_pt++;
1119         }
1120 }
1121
1122 static void gen6_ppgtt_insert_entries(struct i915_address_space *vm,
1123                                       struct sg_table *pages,
1124                                       uint64_t start,
1125                                       enum i915_cache_level cache_level, u32 flags)
1126 {
1127         struct i915_hw_ppgtt *ppgtt =
1128                 container_of(vm, struct i915_hw_ppgtt, base);
1129         gen6_pte_t *pt_vaddr;
1130         unsigned first_entry = start >> PAGE_SHIFT;
1131         unsigned act_pt = first_entry / GEN6_PTES;
1132         unsigned act_pte = first_entry % GEN6_PTES;
1133         struct sg_page_iter sg_iter;
1134
1135         pt_vaddr = NULL;
1136         for_each_sg_page(pages->sgl, &sg_iter, pages->nents, 0) {
1137                 if (pt_vaddr == NULL)
1138                         pt_vaddr = kmap_atomic(ppgtt->pd.page_table[act_pt]->page);
1139
1140                 pt_vaddr[act_pte] =
1141                         vm->pte_encode(sg_page_iter_dma_address(&sg_iter),
1142                                        cache_level, true, flags);
1143
1144                 if (++act_pte == GEN6_PTES) {
1145                         kunmap_atomic(pt_vaddr);
1146                         pt_vaddr = NULL;
1147                         act_pt++;
1148                         act_pte = 0;
1149                 }
1150         }
1151         if (pt_vaddr)
1152                 kunmap_atomic(pt_vaddr);
1153 }
1154
1155 static void gen6_ppgtt_unmap_pages(struct i915_hw_ppgtt *ppgtt)
1156 {
1157         int i;
1158
1159         for (i = 0; i < ppgtt->num_pd_entries; i++)
1160                 pci_unmap_page(ppgtt->base.dev->pdev,
1161                                ppgtt->pd.page_table[i]->daddr,
1162                                4096, PCI_DMA_BIDIRECTIONAL);
1163 }
1164
1165 static int gen6_alloc_va_range(struct i915_address_space *vm,
1166                                uint64_t start, uint64_t length)
1167 {
1168         struct i915_hw_ppgtt *ppgtt =
1169                                 container_of(vm, struct i915_hw_ppgtt, base);
1170         struct i915_page_table_entry *pt;
1171         uint32_t pde, temp;
1172
1173         gen6_for_each_pde(pt, &ppgtt->pd, start, length, temp, pde) {
1174                 DECLARE_BITMAP(tmp_bitmap, GEN6_PTES);
1175
1176                 bitmap_zero(tmp_bitmap, GEN6_PTES);
1177                 bitmap_set(tmp_bitmap, gen6_pte_index(start),
1178                            gen6_pte_count(start, length));
1179
1180                 bitmap_or(pt->used_ptes, pt->used_ptes, tmp_bitmap,
1181                                 GEN6_PTES);
1182         }
1183
1184         return 0;
1185 }
1186
1187 static void gen6_ppgtt_free(struct i915_hw_ppgtt *ppgtt)
1188 {
1189         int i;
1190
1191         for (i = 0; i < ppgtt->num_pd_entries; i++)
1192                 unmap_and_free_pt(ppgtt->pd.page_table[i], ppgtt->base.dev);
1193
1194         unmap_and_free_pd(&ppgtt->pd);
1195 }
1196
1197 static void gen6_ppgtt_cleanup(struct i915_address_space *vm)
1198 {
1199         struct i915_hw_ppgtt *ppgtt =
1200                 container_of(vm, struct i915_hw_ppgtt, base);
1201
1202         drm_mm_remove_node(&ppgtt->node);
1203
1204         gen6_ppgtt_unmap_pages(ppgtt);
1205         gen6_ppgtt_free(ppgtt);
1206 }
1207
1208 static int gen6_ppgtt_allocate_page_directories(struct i915_hw_ppgtt *ppgtt)
1209 {
1210         struct drm_device *dev = ppgtt->base.dev;
1211         struct drm_i915_private *dev_priv = dev->dev_private;
1212         bool retried = false;
1213         int ret;
1214
1215         /* PPGTT PDEs reside in the GGTT and consists of 512 entries. The
1216          * allocator works in address space sizes, so it's multiplied by page
1217          * size. We allocate at the top of the GTT to avoid fragmentation.
1218          */
1219         BUG_ON(!drm_mm_initialized(&dev_priv->gtt.base.mm));
1220 alloc:
1221         ret = drm_mm_insert_node_in_range_generic(&dev_priv->gtt.base.mm,
1222                                                   &ppgtt->node, GEN6_PD_SIZE,
1223                                                   GEN6_PD_ALIGN, 0,
1224                                                   0, dev_priv->gtt.base.total,
1225                                                   DRM_MM_TOPDOWN);
1226         if (ret == -ENOSPC && !retried) {
1227                 ret = i915_gem_evict_something(dev, &dev_priv->gtt.base,
1228                                                GEN6_PD_SIZE, GEN6_PD_ALIGN,
1229                                                I915_CACHE_NONE,
1230                                                0, dev_priv->gtt.base.total,
1231                                                0);
1232                 if (ret)
1233                         goto err_out;
1234
1235                 retried = true;
1236                 goto alloc;
1237         }
1238
1239         if (ret)
1240                 goto err_out;
1241
1242
1243         if (ppgtt->node.start < dev_priv->gtt.mappable_end)
1244                 DRM_DEBUG("Forced to use aperture for PDEs\n");
1245
1246         ppgtt->num_pd_entries = I915_PDES;
1247         return 0;
1248
1249 err_out:
1250         return ret;
1251 }
1252
1253 static int gen6_ppgtt_alloc(struct i915_hw_ppgtt *ppgtt)
1254 {
1255         int ret;
1256
1257         ret = gen6_ppgtt_allocate_page_directories(ppgtt);
1258         if (ret)
1259                 return ret;
1260
1261         ret = alloc_pt_range(&ppgtt->pd, 0, ppgtt->num_pd_entries,
1262                         ppgtt->base.dev);
1263
1264         if (ret) {
1265                 drm_mm_remove_node(&ppgtt->node);
1266                 return ret;
1267         }
1268
1269         return 0;
1270 }
1271
1272 static int gen6_ppgtt_init(struct i915_hw_ppgtt *ppgtt)
1273 {
1274         struct drm_device *dev = ppgtt->base.dev;
1275         struct drm_i915_private *dev_priv = dev->dev_private;
1276         int ret;
1277
1278         ppgtt->base.pte_encode = dev_priv->gtt.base.pte_encode;
1279         if (IS_GEN6(dev)) {
1280                 ppgtt->switch_mm = gen6_mm_switch;
1281         } else if (IS_HASWELL(dev)) {
1282                 ppgtt->switch_mm = hsw_mm_switch;
1283         } else if (IS_GEN7(dev)) {
1284                 ppgtt->switch_mm = gen7_mm_switch;
1285         } else
1286                 BUG();
1287
1288         if (intel_vgpu_active(dev))
1289                 ppgtt->switch_mm = vgpu_mm_switch;
1290
1291         ret = gen6_ppgtt_alloc(ppgtt);
1292         if (ret)
1293                 return ret;
1294
1295         ppgtt->base.allocate_va_range = gen6_alloc_va_range;
1296         ppgtt->base.clear_range = gen6_ppgtt_clear_range;
1297         ppgtt->base.insert_entries = gen6_ppgtt_insert_entries;
1298         ppgtt->base.cleanup = gen6_ppgtt_cleanup;
1299         ppgtt->base.start = 0;
1300         ppgtt->base.total = ppgtt->num_pd_entries * GEN6_PTES * PAGE_SIZE;
1301         ppgtt->debug_dump = gen6_dump_ppgtt;
1302
1303         ppgtt->pd.pd_offset =
1304                 ppgtt->node.start / PAGE_SIZE * sizeof(gen6_pte_t);
1305
1306         ppgtt->pd_addr = (gen6_pte_t __iomem *)dev_priv->gtt.gsm +
1307                 ppgtt->pd.pd_offset / sizeof(gen6_pte_t);
1308
1309         ppgtt->base.clear_range(&ppgtt->base, 0, ppgtt->base.total, true);
1310
1311         gen6_write_page_range(dev_priv, &ppgtt->pd, 0, ppgtt->base.total);
1312
1313         DRM_DEBUG_DRIVER("Allocated pde space (%lldM) at GTT entry: %llx\n",
1314                          ppgtt->node.size >> 20,
1315                          ppgtt->node.start / PAGE_SIZE);
1316
1317         DRM_DEBUG("Adding PPGTT at offset %x\n",
1318                   ppgtt->pd.pd_offset << 10);
1319
1320         return 0;
1321 }
1322
1323 static int __hw_ppgtt_init(struct drm_device *dev, struct i915_hw_ppgtt *ppgtt)
1324 {
1325         struct drm_i915_private *dev_priv = dev->dev_private;
1326
1327         ppgtt->base.dev = dev;
1328         ppgtt->base.scratch = dev_priv->gtt.base.scratch;
1329
1330         if (INTEL_INFO(dev)->gen < 8)
1331                 return gen6_ppgtt_init(ppgtt);
1332         else
1333                 return gen8_ppgtt_init(ppgtt, dev_priv->gtt.base.total);
1334 }
1335 int i915_ppgtt_init(struct drm_device *dev, struct i915_hw_ppgtt *ppgtt)
1336 {
1337         struct drm_i915_private *dev_priv = dev->dev_private;
1338         int ret = 0;
1339
1340         ret = __hw_ppgtt_init(dev, ppgtt);
1341         if (ret == 0) {
1342                 kref_init(&ppgtt->ref);
1343                 drm_mm_init(&ppgtt->base.mm, ppgtt->base.start,
1344                             ppgtt->base.total);
1345                 i915_init_vm(dev_priv, &ppgtt->base);
1346         }
1347
1348         return ret;
1349 }
1350
1351 int i915_ppgtt_init_hw(struct drm_device *dev)
1352 {
1353         struct drm_i915_private *dev_priv = dev->dev_private;
1354         struct intel_engine_cs *ring;
1355         struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
1356         int i, ret = 0;
1357
1358         /* In the case of execlists, PPGTT is enabled by the context descriptor
1359          * and the PDPs are contained within the context itself.  We don't
1360          * need to do anything here. */
1361         if (i915.enable_execlists)
1362                 return 0;
1363
1364         if (!USES_PPGTT(dev))
1365                 return 0;
1366
1367         if (IS_GEN6(dev))
1368                 gen6_ppgtt_enable(dev);
1369         else if (IS_GEN7(dev))
1370                 gen7_ppgtt_enable(dev);
1371         else if (INTEL_INFO(dev)->gen >= 8)
1372                 gen8_ppgtt_enable(dev);
1373         else
1374                 MISSING_CASE(INTEL_INFO(dev)->gen);
1375
1376         if (ppgtt) {
1377                 for_each_ring(ring, dev_priv, i) {
1378                         ret = ppgtt->switch_mm(ppgtt, ring);
1379                         if (ret != 0)
1380                                 return ret;
1381                 }
1382         }
1383
1384         return ret;
1385 }
1386 struct i915_hw_ppgtt *
1387 i915_ppgtt_create(struct drm_device *dev, struct drm_i915_file_private *fpriv)
1388 {
1389         struct i915_hw_ppgtt *ppgtt;
1390         int ret;
1391
1392         ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
1393         if (!ppgtt)
1394                 return ERR_PTR(-ENOMEM);
1395
1396         ret = i915_ppgtt_init(dev, ppgtt);
1397         if (ret) {
1398                 kfree(ppgtt);
1399                 return ERR_PTR(ret);
1400         }
1401
1402         ppgtt->file_priv = fpriv;
1403
1404         trace_i915_ppgtt_create(&ppgtt->base);
1405
1406         return ppgtt;
1407 }
1408
1409 void  i915_ppgtt_release(struct kref *kref)
1410 {
1411         struct i915_hw_ppgtt *ppgtt =
1412                 container_of(kref, struct i915_hw_ppgtt, ref);
1413
1414         trace_i915_ppgtt_release(&ppgtt->base);
1415
1416         /* vmas should already be unbound */
1417         WARN_ON(!list_empty(&ppgtt->base.active_list));
1418         WARN_ON(!list_empty(&ppgtt->base.inactive_list));
1419
1420         list_del(&ppgtt->base.global_link);
1421         drm_mm_takedown(&ppgtt->base.mm);
1422
1423         ppgtt->base.cleanup(&ppgtt->base);
1424         kfree(ppgtt);
1425 }
1426
1427 static void
1428 ppgtt_bind_vma(struct i915_vma *vma,
1429                enum i915_cache_level cache_level,
1430                u32 flags)
1431 {
1432         /* Currently applicable only to VLV */
1433         if (vma->obj->gt_ro)
1434                 flags |= PTE_READ_ONLY;
1435
1436         vma->vm->insert_entries(vma->vm, vma->obj->pages, vma->node.start,
1437                                 cache_level, flags);
1438 }
1439
1440 static void ppgtt_unbind_vma(struct i915_vma *vma)
1441 {
1442         vma->vm->clear_range(vma->vm,
1443                              vma->node.start,
1444                              vma->obj->base.size,
1445                              true);
1446 }
1447
1448 extern int intel_iommu_gfx_mapped;
1449 /* Certain Gen5 chipsets require require idling the GPU before
1450  * unmapping anything from the GTT when VT-d is enabled.
1451  */
1452 static inline bool needs_idle_maps(struct drm_device *dev)
1453 {
1454 #ifdef CONFIG_INTEL_IOMMU
1455         /* Query intel_iommu to see if we need the workaround. Presumably that
1456          * was loaded first.
1457          */
1458         if (IS_GEN5(dev) && IS_MOBILE(dev) && intel_iommu_gfx_mapped)
1459                 return true;
1460 #endif
1461         return false;
1462 }
1463
1464 static bool do_idling(struct drm_i915_private *dev_priv)
1465 {
1466         bool ret = dev_priv->mm.interruptible;
1467
1468         if (unlikely(dev_priv->gtt.do_idle_maps)) {
1469                 dev_priv->mm.interruptible = false;
1470                 if (i915_gpu_idle(dev_priv->dev)) {
1471                         DRM_ERROR("Couldn't idle GPU\n");
1472                         /* Wait a bit, in hopes it avoids the hang */
1473                         udelay(10);
1474                 }
1475         }
1476
1477         return ret;
1478 }
1479
1480 static void undo_idling(struct drm_i915_private *dev_priv, bool interruptible)
1481 {
1482         if (unlikely(dev_priv->gtt.do_idle_maps))
1483                 dev_priv->mm.interruptible = interruptible;
1484 }
1485
1486 void i915_check_and_clear_faults(struct drm_device *dev)
1487 {
1488         struct drm_i915_private *dev_priv = dev->dev_private;
1489         struct intel_engine_cs *ring;
1490         int i;
1491
1492         if (INTEL_INFO(dev)->gen < 6)
1493                 return;
1494
1495         for_each_ring(ring, dev_priv, i) {
1496                 u32 fault_reg;
1497                 fault_reg = I915_READ(RING_FAULT_REG(ring));
1498                 if (fault_reg & RING_FAULT_VALID) {
1499                         DRM_DEBUG_DRIVER("Unexpected fault\n"
1500                                          "\tAddr: 0x%08lx\n"
1501                                          "\tAddress space: %s\n"
1502                                          "\tSource ID: %d\n"
1503                                          "\tType: %d\n",
1504                                          fault_reg & PAGE_MASK,
1505                                          fault_reg & RING_FAULT_GTTSEL_MASK ? "GGTT" : "PPGTT",
1506                                          RING_FAULT_SRCID(fault_reg),
1507                                          RING_FAULT_FAULT_TYPE(fault_reg));
1508                         I915_WRITE(RING_FAULT_REG(ring),
1509                                    fault_reg & ~RING_FAULT_VALID);
1510                 }
1511         }
1512         POSTING_READ(RING_FAULT_REG(&dev_priv->ring[RCS]));
1513 }
1514
1515 static void i915_ggtt_flush(struct drm_i915_private *dev_priv)
1516 {
1517         if (INTEL_INFO(dev_priv->dev)->gen < 6) {
1518                 intel_gtt_chipset_flush();
1519         } else {
1520                 I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
1521                 POSTING_READ(GFX_FLSH_CNTL_GEN6);
1522         }
1523 }
1524
1525 void i915_gem_suspend_gtt_mappings(struct drm_device *dev)
1526 {
1527         struct drm_i915_private *dev_priv = dev->dev_private;
1528
1529         /* Don't bother messing with faults pre GEN6 as we have little
1530          * documentation supporting that it's a good idea.
1531          */
1532         if (INTEL_INFO(dev)->gen < 6)
1533                 return;
1534
1535         i915_check_and_clear_faults(dev);
1536
1537         dev_priv->gtt.base.clear_range(&dev_priv->gtt.base,
1538                                        dev_priv->gtt.base.start,
1539                                        dev_priv->gtt.base.total,
1540                                        true);
1541
1542         i915_ggtt_flush(dev_priv);
1543 }
1544
1545 void i915_gem_restore_gtt_mappings(struct drm_device *dev)
1546 {
1547         struct drm_i915_private *dev_priv = dev->dev_private;
1548         struct drm_i915_gem_object *obj;
1549         struct i915_address_space *vm;
1550
1551         i915_check_and_clear_faults(dev);
1552
1553         /* First fill our portion of the GTT with scratch pages */
1554         dev_priv->gtt.base.clear_range(&dev_priv->gtt.base,
1555                                        dev_priv->gtt.base.start,
1556                                        dev_priv->gtt.base.total,
1557                                        true);
1558
1559         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
1560                 struct i915_vma *vma = i915_gem_obj_to_vma(obj,
1561                                                            &dev_priv->gtt.base);
1562                 if (!vma)
1563                         continue;
1564
1565                 i915_gem_clflush_object(obj, obj->pin_display);
1566                 /* The bind_vma code tries to be smart about tracking mappings.
1567                  * Unfortunately above, we've just wiped out the mappings
1568                  * without telling our object about it. So we need to fake it.
1569                  *
1570                  * Bind is not expected to fail since this is only called on
1571                  * resume and assumption is all requirements exist already.
1572                  */
1573                 vma->bound &= ~GLOBAL_BIND;
1574                 WARN_ON(i915_vma_bind(vma, obj->cache_level, GLOBAL_BIND));
1575         }
1576
1577
1578         if (INTEL_INFO(dev)->gen >= 8) {
1579                 if (IS_CHERRYVIEW(dev))
1580                         chv_setup_private_ppat(dev_priv);
1581                 else
1582                         bdw_setup_private_ppat(dev_priv);
1583
1584                 return;
1585         }
1586
1587         if (USES_PPGTT(dev)) {
1588                 list_for_each_entry(vm, &dev_priv->vm_list, global_link) {
1589                         /* TODO: Perhaps it shouldn't be gen6 specific */
1590
1591                         struct i915_hw_ppgtt *ppgtt =
1592                                         container_of(vm, struct i915_hw_ppgtt,
1593                                                      base);
1594
1595                         if (i915_is_ggtt(vm))
1596                                 ppgtt = dev_priv->mm.aliasing_ppgtt;
1597
1598                         gen6_write_page_range(dev_priv, &ppgtt->pd,
1599                                               0, ppgtt->base.total);
1600                 }
1601         }
1602
1603         i915_ggtt_flush(dev_priv);
1604 }
1605
1606 int i915_gem_gtt_prepare_object(struct drm_i915_gem_object *obj)
1607 {
1608         if (obj->has_dma_mapping)
1609                 return 0;
1610
1611         if (!dma_map_sg(&obj->base.dev->pdev->dev,
1612                         obj->pages->sgl, obj->pages->nents,
1613                         PCI_DMA_BIDIRECTIONAL))
1614                 return -ENOSPC;
1615
1616         return 0;
1617 }
1618
1619 static inline void gen8_set_pte(void __iomem *addr, gen8_pte_t pte)
1620 {
1621 #ifdef writeq
1622         writeq(pte, addr);
1623 #else
1624         iowrite32((u32)pte, addr);
1625         iowrite32(pte >> 32, addr + 4);
1626 #endif
1627 }
1628
1629 static void gen8_ggtt_insert_entries(struct i915_address_space *vm,
1630                                      struct sg_table *st,
1631                                      uint64_t start,
1632                                      enum i915_cache_level level, u32 unused)
1633 {
1634         struct drm_i915_private *dev_priv = vm->dev->dev_private;
1635         unsigned first_entry = start >> PAGE_SHIFT;
1636         gen8_pte_t __iomem *gtt_entries =
1637                 (gen8_pte_t __iomem *)dev_priv->gtt.gsm + first_entry;
1638         int i = 0;
1639         struct sg_page_iter sg_iter;
1640         dma_addr_t addr = 0; /* shut up gcc */
1641
1642         for_each_sg_page(st->sgl, &sg_iter, st->nents, 0) {
1643                 addr = sg_dma_address(sg_iter.sg) +
1644                         (sg_iter.sg_pgoffset << PAGE_SHIFT);
1645                 gen8_set_pte(&gtt_entries[i],
1646                              gen8_pte_encode(addr, level, true));
1647                 i++;
1648         }
1649
1650         /*
1651          * XXX: This serves as a posting read to make sure that the PTE has
1652          * actually been updated. There is some concern that even though
1653          * registers and PTEs are within the same BAR that they are potentially
1654          * of NUMA access patterns. Therefore, even with the way we assume
1655          * hardware should work, we must keep this posting read for paranoia.
1656          */
1657         if (i != 0)
1658                 WARN_ON(readq(&gtt_entries[i-1])
1659                         != gen8_pte_encode(addr, level, true));
1660
1661         /* This next bit makes the above posting read even more important. We
1662          * want to flush the TLBs only after we're certain all the PTE updates
1663          * have finished.
1664          */
1665         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
1666         POSTING_READ(GFX_FLSH_CNTL_GEN6);
1667 }
1668
1669 /*
1670  * Binds an object into the global gtt with the specified cache level. The object
1671  * will be accessible to the GPU via commands whose operands reference offsets
1672  * within the global GTT as well as accessible by the GPU through the GMADR
1673  * mapped BAR (dev_priv->mm.gtt->gtt).
1674  */
1675 static void gen6_ggtt_insert_entries(struct i915_address_space *vm,
1676                                      struct sg_table *st,
1677                                      uint64_t start,
1678                                      enum i915_cache_level level, u32 flags)
1679 {
1680         struct drm_i915_private *dev_priv = vm->dev->dev_private;
1681         unsigned first_entry = start >> PAGE_SHIFT;
1682         gen6_pte_t __iomem *gtt_entries =
1683                 (gen6_pte_t __iomem *)dev_priv->gtt.gsm + first_entry;
1684         int i = 0;
1685         struct sg_page_iter sg_iter;
1686         dma_addr_t addr = 0;
1687
1688         for_each_sg_page(st->sgl, &sg_iter, st->nents, 0) {
1689                 addr = sg_page_iter_dma_address(&sg_iter);
1690                 iowrite32(vm->pte_encode(addr, level, true, flags), &gtt_entries[i]);
1691                 i++;
1692         }
1693
1694         /* XXX: This serves as a posting read to make sure that the PTE has
1695          * actually been updated. There is some concern that even though
1696          * registers and PTEs are within the same BAR that they are potentially
1697          * of NUMA access patterns. Therefore, even with the way we assume
1698          * hardware should work, we must keep this posting read for paranoia.
1699          */
1700         if (i != 0) {
1701                 unsigned long gtt = readl(&gtt_entries[i-1]);
1702                 WARN_ON(gtt != vm->pte_encode(addr, level, true, flags));
1703         }
1704
1705         /* This next bit makes the above posting read even more important. We
1706          * want to flush the TLBs only after we're certain all the PTE updates
1707          * have finished.
1708          */
1709         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
1710         POSTING_READ(GFX_FLSH_CNTL_GEN6);
1711 }
1712
1713 static void gen8_ggtt_clear_range(struct i915_address_space *vm,
1714                                   uint64_t start,
1715                                   uint64_t length,
1716                                   bool use_scratch)
1717 {
1718         struct drm_i915_private *dev_priv = vm->dev->dev_private;
1719         unsigned first_entry = start >> PAGE_SHIFT;
1720         unsigned num_entries = length >> PAGE_SHIFT;
1721         gen8_pte_t scratch_pte, __iomem *gtt_base =
1722                 (gen8_pte_t __iomem *) dev_priv->gtt.gsm + first_entry;
1723         const int max_entries = gtt_total_entries(dev_priv->gtt) - first_entry;
1724         int i;
1725
1726         if (WARN(num_entries > max_entries,
1727                  "First entry = %d; Num entries = %d (max=%d)\n",
1728                  first_entry, num_entries, max_entries))
1729                 num_entries = max_entries;
1730
1731         scratch_pte = gen8_pte_encode(vm->scratch.addr,
1732                                       I915_CACHE_LLC,
1733                                       use_scratch);
1734         for (i = 0; i < num_entries; i++)
1735                 gen8_set_pte(&gtt_base[i], scratch_pte);
1736         readl(gtt_base);
1737 }
1738
1739 static void gen6_ggtt_clear_range(struct i915_address_space *vm,
1740                                   uint64_t start,
1741                                   uint64_t length,
1742                                   bool use_scratch)
1743 {
1744         struct drm_i915_private *dev_priv = vm->dev->dev_private;
1745         unsigned first_entry = start >> PAGE_SHIFT;
1746         unsigned num_entries = length >> PAGE_SHIFT;
1747         gen6_pte_t scratch_pte, __iomem *gtt_base =
1748                 (gen6_pte_t __iomem *) dev_priv->gtt.gsm + first_entry;
1749         const int max_entries = gtt_total_entries(dev_priv->gtt) - first_entry;
1750         int i;
1751
1752         if (WARN(num_entries > max_entries,
1753                  "First entry = %d; Num entries = %d (max=%d)\n",
1754                  first_entry, num_entries, max_entries))
1755                 num_entries = max_entries;
1756
1757         scratch_pte = vm->pte_encode(vm->scratch.addr, I915_CACHE_LLC, use_scratch, 0);
1758
1759         for (i = 0; i < num_entries; i++)
1760                 iowrite32(scratch_pte, &gtt_base[i]);
1761         readl(gtt_base);
1762 }
1763
1764
1765 static void i915_ggtt_bind_vma(struct i915_vma *vma,
1766                                enum i915_cache_level cache_level,
1767                                u32 unused)
1768 {
1769         const unsigned long entry = vma->node.start >> PAGE_SHIFT;
1770         unsigned int flags = (cache_level == I915_CACHE_NONE) ?
1771                 AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
1772
1773         BUG_ON(!i915_is_ggtt(vma->vm));
1774         intel_gtt_insert_sg_entries(vma->ggtt_view.pages, entry, flags);
1775         vma->bound = GLOBAL_BIND;
1776 }
1777
1778 static void i915_ggtt_clear_range(struct i915_address_space *vm,
1779                                   uint64_t start,
1780                                   uint64_t length,
1781                                   bool unused)
1782 {
1783         unsigned first_entry = start >> PAGE_SHIFT;
1784         unsigned num_entries = length >> PAGE_SHIFT;
1785         intel_gtt_clear_range(first_entry, num_entries);
1786 }
1787
1788 static void i915_ggtt_unbind_vma(struct i915_vma *vma)
1789 {
1790         const unsigned int first = vma->node.start >> PAGE_SHIFT;
1791         const unsigned int size = vma->obj->base.size >> PAGE_SHIFT;
1792
1793         BUG_ON(!i915_is_ggtt(vma->vm));
1794         vma->bound = 0;
1795         intel_gtt_clear_range(first, size);
1796 }
1797
1798 static void ggtt_bind_vma(struct i915_vma *vma,
1799                           enum i915_cache_level cache_level,
1800                           u32 flags)
1801 {
1802         struct drm_device *dev = vma->vm->dev;
1803         struct drm_i915_private *dev_priv = dev->dev_private;
1804         struct drm_i915_gem_object *obj = vma->obj;
1805         struct sg_table *pages = obj->pages;
1806
1807         /* Currently applicable only to VLV */
1808         if (obj->gt_ro)
1809                 flags |= PTE_READ_ONLY;
1810
1811         if (i915_is_ggtt(vma->vm))
1812                 pages = vma->ggtt_view.pages;
1813
1814         /* If there is no aliasing PPGTT, or the caller needs a global mapping,
1815          * or we have a global mapping already but the cacheability flags have
1816          * changed, set the global PTEs.
1817          *
1818          * If there is an aliasing PPGTT it is anecdotally faster, so use that
1819          * instead if none of the above hold true.
1820          *
1821          * NB: A global mapping should only be needed for special regions like
1822          * "gtt mappable", SNB errata, or if specified via special execbuf
1823          * flags. At all other times, the GPU will use the aliasing PPGTT.
1824          */
1825         if (!dev_priv->mm.aliasing_ppgtt || flags & GLOBAL_BIND) {
1826                 if (!(vma->bound & GLOBAL_BIND) ||
1827                     (cache_level != obj->cache_level)) {
1828                         vma->vm->insert_entries(vma->vm, pages,
1829                                                 vma->node.start,
1830                                                 cache_level, flags);
1831                         vma->bound |= GLOBAL_BIND;
1832                 }
1833         }
1834
1835         if (dev_priv->mm.aliasing_ppgtt &&
1836             (!(vma->bound & LOCAL_BIND) ||
1837              (cache_level != obj->cache_level))) {
1838                 struct i915_hw_ppgtt *appgtt = dev_priv->mm.aliasing_ppgtt;
1839                 appgtt->base.insert_entries(&appgtt->base, pages,
1840                                             vma->node.start,
1841                                             cache_level, flags);
1842                 vma->bound |= LOCAL_BIND;
1843         }
1844 }
1845
1846 static void ggtt_unbind_vma(struct i915_vma *vma)
1847 {
1848         struct drm_device *dev = vma->vm->dev;
1849         struct drm_i915_private *dev_priv = dev->dev_private;
1850         struct drm_i915_gem_object *obj = vma->obj;
1851
1852         if (vma->bound & GLOBAL_BIND) {
1853                 vma->vm->clear_range(vma->vm,
1854                                      vma->node.start,
1855                                      obj->base.size,
1856                                      true);
1857                 vma->bound &= ~GLOBAL_BIND;
1858         }
1859
1860         if (vma->bound & LOCAL_BIND) {
1861                 struct i915_hw_ppgtt *appgtt = dev_priv->mm.aliasing_ppgtt;
1862                 appgtt->base.clear_range(&appgtt->base,
1863                                          vma->node.start,
1864                                          obj->base.size,
1865                                          true);
1866                 vma->bound &= ~LOCAL_BIND;
1867         }
1868 }
1869
1870 void i915_gem_gtt_finish_object(struct drm_i915_gem_object *obj)
1871 {
1872         struct drm_device *dev = obj->base.dev;
1873         struct drm_i915_private *dev_priv = dev->dev_private;
1874         bool interruptible;
1875
1876         interruptible = do_idling(dev_priv);
1877
1878         if (!obj->has_dma_mapping)
1879                 dma_unmap_sg(&dev->pdev->dev,
1880                              obj->pages->sgl, obj->pages->nents,
1881                              PCI_DMA_BIDIRECTIONAL);
1882
1883         undo_idling(dev_priv, interruptible);
1884 }
1885
1886 static void i915_gtt_color_adjust(struct drm_mm_node *node,
1887                                   unsigned long color,
1888                                   u64 *start,
1889                                   u64 *end)
1890 {
1891         if (node->color != color)
1892                 *start += 4096;
1893
1894         if (!list_empty(&node->node_list)) {
1895                 node = list_entry(node->node_list.next,
1896                                   struct drm_mm_node,
1897                                   node_list);
1898                 if (node->allocated && node->color != color)
1899                         *end -= 4096;
1900         }
1901 }
1902
1903 static int i915_gem_setup_global_gtt(struct drm_device *dev,
1904                                      unsigned long start,
1905                                      unsigned long mappable_end,
1906                                      unsigned long end)
1907 {
1908         /* Let GEM Manage all of the aperture.
1909          *
1910          * However, leave one page at the end still bound to the scratch page.
1911          * There are a number of places where the hardware apparently prefetches
1912          * past the end of the object, and we've seen multiple hangs with the
1913          * GPU head pointer stuck in a batchbuffer bound at the last page of the
1914          * aperture.  One page should be enough to keep any prefetching inside
1915          * of the aperture.
1916          */
1917         struct drm_i915_private *dev_priv = dev->dev_private;
1918         struct i915_address_space *ggtt_vm = &dev_priv->gtt.base;
1919         struct drm_mm_node *entry;
1920         struct drm_i915_gem_object *obj;
1921         unsigned long hole_start, hole_end;
1922         int ret;
1923
1924         BUG_ON(mappable_end > end);
1925
1926         /* Subtract the guard page ... */
1927         drm_mm_init(&ggtt_vm->mm, start, end - start - PAGE_SIZE);
1928
1929         dev_priv->gtt.base.start = start;
1930         dev_priv->gtt.base.total = end - start;
1931
1932         if (intel_vgpu_active(dev)) {
1933                 ret = intel_vgt_balloon(dev);
1934                 if (ret)
1935                         return ret;
1936         }
1937
1938         if (!HAS_LLC(dev))
1939                 dev_priv->gtt.base.mm.color_adjust = i915_gtt_color_adjust;
1940
1941         /* Mark any preallocated objects as occupied */
1942         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
1943                 struct i915_vma *vma = i915_gem_obj_to_vma(obj, ggtt_vm);
1944
1945                 DRM_DEBUG_KMS("reserving preallocated space: %lx + %zx\n",
1946                               i915_gem_obj_ggtt_offset(obj), obj->base.size);
1947
1948                 WARN_ON(i915_gem_obj_ggtt_bound(obj));
1949                 ret = drm_mm_reserve_node(&ggtt_vm->mm, &vma->node);
1950                 if (ret) {
1951                         DRM_DEBUG_KMS("Reservation failed: %i\n", ret);
1952                         return ret;
1953                 }
1954                 vma->bound |= GLOBAL_BIND;
1955         }
1956
1957         /* Clear any non-preallocated blocks */
1958         drm_mm_for_each_hole(entry, &ggtt_vm->mm, hole_start, hole_end) {
1959                 DRM_DEBUG_KMS("clearing unused GTT space: [%lx, %lx]\n",
1960                               hole_start, hole_end);
1961                 ggtt_vm->clear_range(ggtt_vm, hole_start,
1962                                      hole_end - hole_start, true);
1963         }
1964
1965         /* And finally clear the reserved guard page */
1966         ggtt_vm->clear_range(ggtt_vm, end - PAGE_SIZE, PAGE_SIZE, true);
1967
1968         if (USES_PPGTT(dev) && !USES_FULL_PPGTT(dev)) {
1969                 struct i915_hw_ppgtt *ppgtt;
1970
1971                 ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
1972                 if (!ppgtt)
1973                         return -ENOMEM;
1974
1975                 ret = __hw_ppgtt_init(dev, ppgtt);
1976                 if (ret != 0)
1977                         return ret;
1978
1979                 dev_priv->mm.aliasing_ppgtt = ppgtt;
1980         }
1981
1982         return 0;
1983 }
1984
1985 void i915_gem_init_global_gtt(struct drm_device *dev)
1986 {
1987         struct drm_i915_private *dev_priv = dev->dev_private;
1988         unsigned long gtt_size, mappable_size;
1989
1990         gtt_size = dev_priv->gtt.base.total;
1991         mappable_size = dev_priv->gtt.mappable_end;
1992
1993         i915_gem_setup_global_gtt(dev, 0, mappable_size, gtt_size);
1994 }
1995
1996 void i915_global_gtt_cleanup(struct drm_device *dev)
1997 {
1998         struct drm_i915_private *dev_priv = dev->dev_private;
1999         struct i915_address_space *vm = &dev_priv->gtt.base;
2000
2001         if (dev_priv->mm.aliasing_ppgtt) {
2002                 struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
2003
2004                 ppgtt->base.cleanup(&ppgtt->base);
2005         }
2006
2007         if (drm_mm_initialized(&vm->mm)) {
2008                 if (intel_vgpu_active(dev))
2009                         intel_vgt_deballoon();
2010
2011                 drm_mm_takedown(&vm->mm);
2012                 list_del(&vm->global_link);
2013         }
2014
2015         vm->cleanup(vm);
2016 }
2017
2018 static int setup_scratch_page(struct drm_device *dev)
2019 {
2020         struct drm_i915_private *dev_priv = dev->dev_private;
2021         struct page *page;
2022         dma_addr_t dma_addr;
2023
2024         page = alloc_page(GFP_KERNEL | GFP_DMA32 | __GFP_ZERO);
2025         if (page == NULL)
2026                 return -ENOMEM;
2027         set_pages_uc(page, 1);
2028
2029 #ifdef CONFIG_INTEL_IOMMU
2030         dma_addr = pci_map_page(dev->pdev, page, 0, PAGE_SIZE,
2031                                 PCI_DMA_BIDIRECTIONAL);
2032         if (pci_dma_mapping_error(dev->pdev, dma_addr))
2033                 return -EINVAL;
2034 #else
2035         dma_addr = page_to_phys(page);
2036 #endif
2037         dev_priv->gtt.base.scratch.page = page;
2038         dev_priv->gtt.base.scratch.addr = dma_addr;
2039
2040         return 0;
2041 }
2042
2043 static void teardown_scratch_page(struct drm_device *dev)
2044 {
2045         struct drm_i915_private *dev_priv = dev->dev_private;
2046         struct page *page = dev_priv->gtt.base.scratch.page;
2047
2048         set_pages_wb(page, 1);
2049         pci_unmap_page(dev->pdev, dev_priv->gtt.base.scratch.addr,
2050                        PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
2051         __free_page(page);
2052 }
2053
2054 static inline unsigned int gen6_get_total_gtt_size(u16 snb_gmch_ctl)
2055 {
2056         snb_gmch_ctl >>= SNB_GMCH_GGMS_SHIFT;
2057         snb_gmch_ctl &= SNB_GMCH_GGMS_MASK;
2058         return snb_gmch_ctl << 20;
2059 }
2060
2061 static inline unsigned int gen8_get_total_gtt_size(u16 bdw_gmch_ctl)
2062 {
2063         bdw_gmch_ctl >>= BDW_GMCH_GGMS_SHIFT;
2064         bdw_gmch_ctl &= BDW_GMCH_GGMS_MASK;
2065         if (bdw_gmch_ctl)
2066                 bdw_gmch_ctl = 1 << bdw_gmch_ctl;
2067
2068 #ifdef CONFIG_X86_32
2069         /* Limit 32b platforms to a 2GB GGTT: 4 << 20 / pte size * PAGE_SIZE */
2070         if (bdw_gmch_ctl > 4)
2071                 bdw_gmch_ctl = 4;
2072 #endif
2073
2074         return bdw_gmch_ctl << 20;
2075 }
2076
2077 static inline unsigned int chv_get_total_gtt_size(u16 gmch_ctrl)
2078 {
2079         gmch_ctrl >>= SNB_GMCH_GGMS_SHIFT;
2080         gmch_ctrl &= SNB_GMCH_GGMS_MASK;
2081
2082         if (gmch_ctrl)
2083                 return 1 << (20 + gmch_ctrl);
2084
2085         return 0;
2086 }
2087
2088 static inline size_t gen6_get_stolen_size(u16 snb_gmch_ctl)
2089 {
2090         snb_gmch_ctl >>= SNB_GMCH_GMS_SHIFT;
2091         snb_gmch_ctl &= SNB_GMCH_GMS_MASK;
2092         return snb_gmch_ctl << 25; /* 32 MB units */
2093 }
2094
2095 static inline size_t gen8_get_stolen_size(u16 bdw_gmch_ctl)
2096 {
2097         bdw_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
2098         bdw_gmch_ctl &= BDW_GMCH_GMS_MASK;
2099         return bdw_gmch_ctl << 25; /* 32 MB units */
2100 }
2101
2102 static size_t chv_get_stolen_size(u16 gmch_ctrl)
2103 {
2104         gmch_ctrl >>= SNB_GMCH_GMS_SHIFT;
2105         gmch_ctrl &= SNB_GMCH_GMS_MASK;
2106
2107         /*
2108          * 0x0  to 0x10: 32MB increments starting at 0MB
2109          * 0x11 to 0x16: 4MB increments starting at 8MB
2110          * 0x17 to 0x1d: 4MB increments start at 36MB
2111          */
2112         if (gmch_ctrl < 0x11)
2113                 return gmch_ctrl << 25;
2114         else if (gmch_ctrl < 0x17)
2115                 return (gmch_ctrl - 0x11 + 2) << 22;
2116         else
2117                 return (gmch_ctrl - 0x17 + 9) << 22;
2118 }
2119
2120 static size_t gen9_get_stolen_size(u16 gen9_gmch_ctl)
2121 {
2122         gen9_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
2123         gen9_gmch_ctl &= BDW_GMCH_GMS_MASK;
2124
2125         if (gen9_gmch_ctl < 0xf0)
2126                 return gen9_gmch_ctl << 25; /* 32 MB units */
2127         else
2128                 /* 4MB increments starting at 0xf0 for 4MB */
2129                 return (gen9_gmch_ctl - 0xf0 + 1) << 22;
2130 }
2131
2132 static int ggtt_probe_common(struct drm_device *dev,
2133                              size_t gtt_size)
2134 {
2135         struct drm_i915_private *dev_priv = dev->dev_private;
2136         phys_addr_t gtt_phys_addr;
2137         int ret;
2138
2139         /* For Modern GENs the PTEs and register space are split in the BAR */
2140         gtt_phys_addr = pci_resource_start(dev->pdev, 0) +
2141                 (pci_resource_len(dev->pdev, 0) / 2);
2142
2143         dev_priv->gtt.gsm = ioremap_wc(gtt_phys_addr, gtt_size);
2144         if (!dev_priv->gtt.gsm) {
2145                 DRM_ERROR("Failed to map the gtt page table\n");
2146                 return -ENOMEM;
2147         }
2148
2149         ret = setup_scratch_page(dev);
2150         if (ret) {
2151                 DRM_ERROR("Scratch setup failed\n");
2152                 /* iounmap will also get called at remove, but meh */
2153                 iounmap(dev_priv->gtt.gsm);
2154         }
2155
2156         return ret;
2157 }
2158
2159 /* The GGTT and PPGTT need a private PPAT setup in order to handle cacheability
2160  * bits. When using advanced contexts each context stores its own PAT, but
2161  * writing this data shouldn't be harmful even in those cases. */
2162 static void bdw_setup_private_ppat(struct drm_i915_private *dev_priv)
2163 {
2164         uint64_t pat;
2165
2166         pat = GEN8_PPAT(0, GEN8_PPAT_WB | GEN8_PPAT_LLC)     | /* for normal objects, no eLLC */
2167               GEN8_PPAT(1, GEN8_PPAT_WC | GEN8_PPAT_LLCELLC) | /* for something pointing to ptes? */
2168               GEN8_PPAT(2, GEN8_PPAT_WT | GEN8_PPAT_LLCELLC) | /* for scanout with eLLC */
2169               GEN8_PPAT(3, GEN8_PPAT_UC)                     | /* Uncached objects, mostly for scanout */
2170               GEN8_PPAT(4, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(0)) |
2171               GEN8_PPAT(5, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(1)) |
2172               GEN8_PPAT(6, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(2)) |
2173               GEN8_PPAT(7, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(3));
2174
2175         if (!USES_PPGTT(dev_priv->dev))
2176                 /* Spec: "For GGTT, there is NO pat_sel[2:0] from the entry,
2177                  * so RTL will always use the value corresponding to
2178                  * pat_sel = 000".
2179                  * So let's disable cache for GGTT to avoid screen corruptions.
2180                  * MOCS still can be used though.
2181                  * - System agent ggtt writes (i.e. cpu gtt mmaps) already work
2182                  * before this patch, i.e. the same uncached + snooping access
2183                  * like on gen6/7 seems to be in effect.
2184                  * - So this just fixes blitter/render access. Again it looks
2185                  * like it's not just uncached access, but uncached + snooping.
2186                  * So we can still hold onto all our assumptions wrt cpu
2187                  * clflushing on LLC machines.
2188                  */
2189                 pat = GEN8_PPAT(0, GEN8_PPAT_UC);
2190
2191         /* XXX: spec defines this as 2 distinct registers. It's unclear if a 64b
2192          * write would work. */
2193         I915_WRITE(GEN8_PRIVATE_PAT, pat);
2194         I915_WRITE(GEN8_PRIVATE_PAT + 4, pat >> 32);
2195 }
2196
2197 static void chv_setup_private_ppat(struct drm_i915_private *dev_priv)
2198 {
2199         uint64_t pat;
2200
2201         /*
2202          * Map WB on BDW to snooped on CHV.
2203          *
2204          * Only the snoop bit has meaning for CHV, the rest is
2205          * ignored.
2206          *
2207          * The hardware will never snoop for certain types of accesses:
2208          * - CPU GTT (GMADR->GGTT->no snoop->memory)
2209          * - PPGTT page tables
2210          * - some other special cycles
2211          *
2212          * As with BDW, we also need to consider the following for GT accesses:
2213          * "For GGTT, there is NO pat_sel[2:0] from the entry,
2214          * so RTL will always use the value corresponding to
2215          * pat_sel = 000".
2216          * Which means we must set the snoop bit in PAT entry 0
2217          * in order to keep the global status page working.
2218          */
2219         pat = GEN8_PPAT(0, CHV_PPAT_SNOOP) |
2220               GEN8_PPAT(1, 0) |
2221               GEN8_PPAT(2, 0) |
2222               GEN8_PPAT(3, 0) |
2223               GEN8_PPAT(4, CHV_PPAT_SNOOP) |
2224               GEN8_PPAT(5, CHV_PPAT_SNOOP) |
2225               GEN8_PPAT(6, CHV_PPAT_SNOOP) |
2226               GEN8_PPAT(7, CHV_PPAT_SNOOP);
2227
2228         I915_WRITE(GEN8_PRIVATE_PAT, pat);
2229         I915_WRITE(GEN8_PRIVATE_PAT + 4, pat >> 32);
2230 }
2231
2232 static int gen8_gmch_probe(struct drm_device *dev,
2233                            size_t *gtt_total,
2234                            size_t *stolen,
2235                            phys_addr_t *mappable_base,
2236                            unsigned long *mappable_end)
2237 {
2238         struct drm_i915_private *dev_priv = dev->dev_private;
2239         unsigned int gtt_size;
2240         u16 snb_gmch_ctl;
2241         int ret;
2242
2243         /* TODO: We're not aware of mappable constraints on gen8 yet */
2244         *mappable_base = pci_resource_start(dev->pdev, 2);
2245         *mappable_end = pci_resource_len(dev->pdev, 2);
2246
2247         if (!pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(39)))
2248                 pci_set_consistent_dma_mask(dev->pdev, DMA_BIT_MASK(39));
2249
2250         pci_read_config_word(dev->pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
2251
2252         if (INTEL_INFO(dev)->gen >= 9) {
2253                 *stolen = gen9_get_stolen_size(snb_gmch_ctl);
2254                 gtt_size = gen8_get_total_gtt_size(snb_gmch_ctl);
2255         } else if (IS_CHERRYVIEW(dev)) {
2256                 *stolen = chv_get_stolen_size(snb_gmch_ctl);
2257                 gtt_size = chv_get_total_gtt_size(snb_gmch_ctl);
2258         } else {
2259                 *stolen = gen8_get_stolen_size(snb_gmch_ctl);
2260                 gtt_size = gen8_get_total_gtt_size(snb_gmch_ctl);
2261         }
2262
2263         *gtt_total = (gtt_size / sizeof(gen8_pte_t)) << PAGE_SHIFT;
2264
2265         if (IS_CHERRYVIEW(dev))
2266                 chv_setup_private_ppat(dev_priv);
2267         else
2268                 bdw_setup_private_ppat(dev_priv);
2269
2270         ret = ggtt_probe_common(dev, gtt_size);
2271
2272         dev_priv->gtt.base.clear_range = gen8_ggtt_clear_range;
2273         dev_priv->gtt.base.insert_entries = gen8_ggtt_insert_entries;
2274
2275         return ret;
2276 }
2277
2278 static int gen6_gmch_probe(struct drm_device *dev,
2279                            size_t *gtt_total,
2280                            size_t *stolen,
2281                            phys_addr_t *mappable_base,
2282                            unsigned long *mappable_end)
2283 {
2284         struct drm_i915_private *dev_priv = dev->dev_private;
2285         unsigned int gtt_size;
2286         u16 snb_gmch_ctl;
2287         int ret;
2288
2289         *mappable_base = pci_resource_start(dev->pdev, 2);
2290         *mappable_end = pci_resource_len(dev->pdev, 2);
2291
2292         /* 64/512MB is the current min/max we actually know of, but this is just
2293          * a coarse sanity check.
2294          */
2295         if ((*mappable_end < (64<<20) || (*mappable_end > (512<<20)))) {
2296                 DRM_ERROR("Unknown GMADR size (%lx)\n",
2297                           dev_priv->gtt.mappable_end);
2298                 return -ENXIO;
2299         }
2300
2301         if (!pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(40)))
2302                 pci_set_consistent_dma_mask(dev->pdev, DMA_BIT_MASK(40));
2303         pci_read_config_word(dev->pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
2304
2305         *stolen = gen6_get_stolen_size(snb_gmch_ctl);
2306
2307         gtt_size = gen6_get_total_gtt_size(snb_gmch_ctl);
2308         *gtt_total = (gtt_size / sizeof(gen6_pte_t)) << PAGE_SHIFT;
2309
2310         ret = ggtt_probe_common(dev, gtt_size);
2311
2312         dev_priv->gtt.base.clear_range = gen6_ggtt_clear_range;
2313         dev_priv->gtt.base.insert_entries = gen6_ggtt_insert_entries;
2314
2315         return ret;
2316 }
2317
2318 static void gen6_gmch_remove(struct i915_address_space *vm)
2319 {
2320
2321         struct i915_gtt *gtt = container_of(vm, struct i915_gtt, base);
2322
2323         iounmap(gtt->gsm);
2324         teardown_scratch_page(vm->dev);
2325 }
2326
2327 static int i915_gmch_probe(struct drm_device *dev,
2328                            size_t *gtt_total,
2329                            size_t *stolen,
2330                            phys_addr_t *mappable_base,
2331                            unsigned long *mappable_end)
2332 {
2333         struct drm_i915_private *dev_priv = dev->dev_private;
2334         int ret;
2335
2336         ret = intel_gmch_probe(dev_priv->bridge_dev, dev_priv->dev->pdev, NULL);
2337         if (!ret) {
2338                 DRM_ERROR("failed to set up gmch\n");
2339                 return -EIO;
2340         }
2341
2342         intel_gtt_get(gtt_total, stolen, mappable_base, mappable_end);
2343
2344         dev_priv->gtt.do_idle_maps = needs_idle_maps(dev_priv->dev);
2345         dev_priv->gtt.base.clear_range = i915_ggtt_clear_range;
2346
2347         if (unlikely(dev_priv->gtt.do_idle_maps))
2348                 DRM_INFO("applying Ironlake quirks for intel_iommu\n");
2349
2350         return 0;
2351 }
2352
2353 static void i915_gmch_remove(struct i915_address_space *vm)
2354 {
2355         intel_gmch_remove();
2356 }
2357
2358 int i915_gem_gtt_init(struct drm_device *dev)
2359 {
2360         struct drm_i915_private *dev_priv = dev->dev_private;
2361         struct i915_gtt *gtt = &dev_priv->gtt;
2362         int ret;
2363
2364         if (INTEL_INFO(dev)->gen <= 5) {
2365                 gtt->gtt_probe = i915_gmch_probe;
2366                 gtt->base.cleanup = i915_gmch_remove;
2367         } else if (INTEL_INFO(dev)->gen < 8) {
2368                 gtt->gtt_probe = gen6_gmch_probe;
2369                 gtt->base.cleanup = gen6_gmch_remove;
2370                 if (IS_HASWELL(dev) && dev_priv->ellc_size)
2371                         gtt->base.pte_encode = iris_pte_encode;
2372                 else if (IS_HASWELL(dev))
2373                         gtt->base.pte_encode = hsw_pte_encode;
2374                 else if (IS_VALLEYVIEW(dev))
2375                         gtt->base.pte_encode = byt_pte_encode;
2376                 else if (INTEL_INFO(dev)->gen >= 7)
2377                         gtt->base.pte_encode = ivb_pte_encode;
2378                 else
2379                         gtt->base.pte_encode = snb_pte_encode;
2380         } else {
2381                 dev_priv->gtt.gtt_probe = gen8_gmch_probe;
2382                 dev_priv->gtt.base.cleanup = gen6_gmch_remove;
2383         }
2384
2385         ret = gtt->gtt_probe(dev, &gtt->base.total, &gtt->stolen_size,
2386                              &gtt->mappable_base, &gtt->mappable_end);
2387         if (ret)
2388                 return ret;
2389
2390         gtt->base.dev = dev;
2391
2392         /* GMADR is the PCI mmio aperture into the global GTT. */
2393         DRM_INFO("Memory usable by graphics device = %zdM\n",
2394                  gtt->base.total >> 20);
2395         DRM_DEBUG_DRIVER("GMADR size = %ldM\n", gtt->mappable_end >> 20);
2396         DRM_DEBUG_DRIVER("GTT stolen size = %zdM\n", gtt->stolen_size >> 20);
2397 #ifdef CONFIG_INTEL_IOMMU
2398         if (intel_iommu_gfx_mapped)
2399                 DRM_INFO("VT-d active for gfx access\n");
2400 #endif
2401         /*
2402          * i915.enable_ppgtt is read-only, so do an early pass to validate the
2403          * user's requested state against the hardware/driver capabilities.  We
2404          * do this now so that we can print out any log messages once rather
2405          * than every time we check intel_enable_ppgtt().
2406          */
2407         i915.enable_ppgtt = sanitize_enable_ppgtt(dev, i915.enable_ppgtt);
2408         DRM_DEBUG_DRIVER("ppgtt mode: %i\n", i915.enable_ppgtt);
2409
2410         return 0;
2411 }
2412
2413 static struct i915_vma *
2414 __i915_gem_vma_create(struct drm_i915_gem_object *obj,
2415                       struct i915_address_space *vm,
2416                       const struct i915_ggtt_view *ggtt_view)
2417 {
2418         struct i915_vma *vma;
2419
2420         if (WARN_ON(i915_is_ggtt(vm) != !!ggtt_view))
2421                 return ERR_PTR(-EINVAL);
2422         vma = kzalloc(sizeof(*vma), GFP_KERNEL);
2423         if (vma == NULL)
2424                 return ERR_PTR(-ENOMEM);
2425
2426         INIT_LIST_HEAD(&vma->vma_link);
2427         INIT_LIST_HEAD(&vma->mm_list);
2428         INIT_LIST_HEAD(&vma->exec_list);
2429         vma->vm = vm;
2430         vma->obj = obj;
2431
2432         if (INTEL_INFO(vm->dev)->gen >= 6) {
2433                 if (i915_is_ggtt(vm)) {
2434                         vma->ggtt_view = *ggtt_view;
2435
2436                         vma->unbind_vma = ggtt_unbind_vma;
2437                         vma->bind_vma = ggtt_bind_vma;
2438                 } else {
2439                         vma->unbind_vma = ppgtt_unbind_vma;
2440                         vma->bind_vma = ppgtt_bind_vma;
2441                 }
2442         } else {
2443                 BUG_ON(!i915_is_ggtt(vm));
2444                 vma->ggtt_view = *ggtt_view;
2445                 vma->unbind_vma = i915_ggtt_unbind_vma;
2446                 vma->bind_vma = i915_ggtt_bind_vma;
2447         }
2448
2449         list_add_tail(&vma->vma_link, &obj->vma_list);
2450         if (!i915_is_ggtt(vm))
2451                 i915_ppgtt_get(i915_vm_to_ppgtt(vm));
2452
2453         return vma;
2454 }
2455
2456 struct i915_vma *
2457 i915_gem_obj_lookup_or_create_vma(struct drm_i915_gem_object *obj,
2458                                   struct i915_address_space *vm)
2459 {
2460         struct i915_vma *vma;
2461
2462         vma = i915_gem_obj_to_vma(obj, vm);
2463         if (!vma)
2464                 vma = __i915_gem_vma_create(obj, vm,
2465                                             i915_is_ggtt(vm) ? &i915_ggtt_view_normal : NULL);
2466
2467         return vma;
2468 }
2469
2470 struct i915_vma *
2471 i915_gem_obj_lookup_or_create_ggtt_vma(struct drm_i915_gem_object *obj,
2472                                        const struct i915_ggtt_view *view)
2473 {
2474         struct i915_address_space *ggtt = i915_obj_to_ggtt(obj);
2475         struct i915_vma *vma;
2476
2477         if (WARN_ON(!view))
2478                 return ERR_PTR(-EINVAL);
2479
2480         vma = i915_gem_obj_to_ggtt_view(obj, view);
2481
2482         if (IS_ERR(vma))
2483                 return vma;
2484
2485         if (!vma)
2486                 vma = __i915_gem_vma_create(obj, ggtt, view);
2487
2488         return vma;
2489
2490 }
2491
2492
2493 static inline
2494 int i915_get_ggtt_vma_pages(struct i915_vma *vma)
2495 {
2496         if (vma->ggtt_view.pages)
2497                 return 0;
2498
2499         if (vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL)
2500                 vma->ggtt_view.pages = vma->obj->pages;
2501         else
2502                 WARN_ONCE(1, "GGTT view %u not implemented!\n",
2503                           vma->ggtt_view.type);
2504
2505         if (!vma->ggtt_view.pages) {
2506                 DRM_ERROR("Failed to get pages for GGTT view type %u!\n",
2507                           vma->ggtt_view.type);
2508                 return -EINVAL;
2509         }
2510
2511         return 0;
2512 }
2513
2514 /**
2515  * i915_vma_bind - Sets up PTEs for an VMA in it's corresponding address space.
2516  * @vma: VMA to map
2517  * @cache_level: mapping cache level
2518  * @flags: flags like global or local mapping
2519  *
2520  * DMA addresses are taken from the scatter-gather table of this object (or of
2521  * this VMA in case of non-default GGTT views) and PTE entries set up.
2522  * Note that DMA addresses are also the only part of the SG table we care about.
2523  */
2524 int i915_vma_bind(struct i915_vma *vma, enum i915_cache_level cache_level,
2525                   u32 flags)
2526 {
2527         if (i915_is_ggtt(vma->vm)) {
2528                 int ret = i915_get_ggtt_vma_pages(vma);
2529
2530                 if (ret)
2531                         return ret;
2532         }
2533
2534         vma->bind_vma(vma, cache_level, flags);
2535
2536         return 0;
2537 }