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