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