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