79ba485c5d4253689a94b115e2c0b2492f52bb97
[linux-2.6-microblaze.git] / drivers / gpu / drm / i915 / i915_gem_gtt.c
1 /*
2  * Copyright © 2010 Daniel Vetter
3  * Copyright © 2011-2014 Intel Corporation
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  *
24  */
25
26 #include <linux/slab.h> /* fault-inject.h is not standalone! */
27
28 #include <linux/fault-inject.h>
29 #include <linux/log2.h>
30 #include <linux/random.h>
31 #include <linux/seq_file.h>
32 #include <linux/stop_machine.h>
33
34 #include <asm/set_memory.h>
35
36 #include <drm/drmP.h>
37 #include <drm/i915_drm.h>
38
39 #include "i915_drv.h"
40 #include "i915_vgpu.h"
41 #include "i915_trace.h"
42 #include "intel_drv.h"
43 #include "intel_frontbuffer.h"
44
45 #define I915_GFP_DMA (GFP_KERNEL | __GFP_HIGHMEM)
46
47 /**
48  * DOC: Global GTT views
49  *
50  * Background and previous state
51  *
52  * Historically objects could exists (be bound) in global GTT space only as
53  * singular instances with a view representing all of the object's backing pages
54  * in a linear fashion. This view will be called a normal view.
55  *
56  * To support multiple views of the same object, where the number of mapped
57  * pages is not equal to the backing store, or where the layout of the pages
58  * is not linear, concept of a GGTT view was added.
59  *
60  * One example of an alternative view is a stereo display driven by a single
61  * image. In this case we would have a framebuffer looking like this
62  * (2x2 pages):
63  *
64  *    12
65  *    34
66  *
67  * Above would represent a normal GGTT view as normally mapped for GPU or CPU
68  * rendering. In contrast, fed to the display engine would be an alternative
69  * view which could look something like this:
70  *
71  *   1212
72  *   3434
73  *
74  * In this example both the size and layout of pages in the alternative view is
75  * different from the normal view.
76  *
77  * Implementation and usage
78  *
79  * GGTT views are implemented using VMAs and are distinguished via enum
80  * i915_ggtt_view_type and struct i915_ggtt_view.
81  *
82  * A new flavour of core GEM functions which work with GGTT bound objects were
83  * added with the _ggtt_ infix, and sometimes with _view postfix to avoid
84  * renaming  in large amounts of code. They take the struct i915_ggtt_view
85  * parameter encapsulating all metadata required to implement a view.
86  *
87  * As a helper for callers which are only interested in the normal view,
88  * globally const i915_ggtt_view_normal singleton instance exists. All old core
89  * GEM API functions, the ones not taking the view parameter, are operating on,
90  * or with the normal GGTT view.
91  *
92  * Code wanting to add or use a new GGTT view needs to:
93  *
94  * 1. Add a new enum with a suitable name.
95  * 2. Extend the metadata in the i915_ggtt_view structure if required.
96  * 3. Add support to i915_get_vma_pages().
97  *
98  * New views are required to build a scatter-gather table from within the
99  * i915_get_vma_pages function. This table is stored in the vma.ggtt_view and
100  * exists for the lifetime of an VMA.
101  *
102  * Core API is designed to have copy semantics which means that passed in
103  * struct i915_ggtt_view does not need to be persistent (left around after
104  * calling the core API functions).
105  *
106  */
107
108 static int
109 i915_get_ggtt_vma_pages(struct i915_vma *vma);
110
111 static void gen6_ggtt_invalidate(struct drm_i915_private *dev_priv)
112 {
113         /* Note that as an uncached mmio write, this should flush the
114          * WCB of the writes into the GGTT before it triggers the invalidate.
115          */
116         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
117 }
118
119 static void guc_ggtt_invalidate(struct drm_i915_private *dev_priv)
120 {
121         gen6_ggtt_invalidate(dev_priv);
122         I915_WRITE(GEN8_GTCR, GEN8_GTCR_INVALIDATE);
123 }
124
125 static void gmch_ggtt_invalidate(struct drm_i915_private *dev_priv)
126 {
127         intel_gtt_chipset_flush();
128 }
129
130 static inline void i915_ggtt_invalidate(struct drm_i915_private *i915)
131 {
132         i915->ggtt.invalidate(i915);
133 }
134
135 int intel_sanitize_enable_ppgtt(struct drm_i915_private *dev_priv,
136                                 int enable_ppgtt)
137 {
138         bool has_aliasing_ppgtt;
139         bool has_full_ppgtt;
140         bool has_full_48bit_ppgtt;
141
142         has_aliasing_ppgtt = dev_priv->info.has_aliasing_ppgtt;
143         has_full_ppgtt = dev_priv->info.has_full_ppgtt;
144         has_full_48bit_ppgtt = dev_priv->info.has_full_48bit_ppgtt;
145
146         if (intel_vgpu_active(dev_priv)) {
147                 /* GVT-g has no support for 32bit ppgtt */
148                 has_full_ppgtt = false;
149                 has_full_48bit_ppgtt = intel_vgpu_has_full_48bit_ppgtt(dev_priv);
150         }
151
152         if (!has_aliasing_ppgtt)
153                 return 0;
154
155         /*
156          * We don't allow disabling PPGTT for gen9+ as it's a requirement for
157          * execlists, the sole mechanism available to submit work.
158          */
159         if (enable_ppgtt == 0 && INTEL_GEN(dev_priv) < 9)
160                 return 0;
161
162         if (enable_ppgtt == 1)
163                 return 1;
164
165         if (enable_ppgtt == 2 && has_full_ppgtt)
166                 return 2;
167
168         if (enable_ppgtt == 3 && has_full_48bit_ppgtt)
169                 return 3;
170
171         /* Disable ppgtt on SNB if VT-d is on. */
172         if (IS_GEN6(dev_priv) && intel_vtd_active()) {
173                 DRM_INFO("Disabling PPGTT because VT-d is on\n");
174                 return 0;
175         }
176
177         /* Early VLV doesn't have this */
178         if (IS_VALLEYVIEW(dev_priv) && dev_priv->drm.pdev->revision < 0xb) {
179                 DRM_DEBUG_DRIVER("disabling PPGTT on pre-B3 step VLV\n");
180                 return 0;
181         }
182
183         if (INTEL_GEN(dev_priv) >= 8 && i915_modparams.enable_execlists) {
184                 if (has_full_48bit_ppgtt)
185                         return 3;
186
187                 if (has_full_ppgtt)
188                         return 2;
189         }
190
191         return has_aliasing_ppgtt ? 1 : 0;
192 }
193
194 static int ppgtt_bind_vma(struct i915_vma *vma,
195                           enum i915_cache_level cache_level,
196                           u32 unused)
197 {
198         u32 pte_flags;
199         int ret;
200
201         if (!(vma->flags & I915_VMA_LOCAL_BIND)) {
202                 ret = vma->vm->allocate_va_range(vma->vm, vma->node.start,
203                                                  vma->size);
204                 if (ret)
205                         return ret;
206         }
207
208         /* Currently applicable only to VLV */
209         pte_flags = 0;
210         if (vma->obj->gt_ro)
211                 pte_flags |= PTE_READ_ONLY;
212
213         vma->vm->insert_entries(vma->vm, vma, cache_level, pte_flags);
214
215         return 0;
216 }
217
218 static void ppgtt_unbind_vma(struct i915_vma *vma)
219 {
220         vma->vm->clear_range(vma->vm, vma->node.start, vma->size);
221 }
222
223 static int ppgtt_set_pages(struct i915_vma *vma)
224 {
225         GEM_BUG_ON(vma->pages);
226
227         vma->pages = vma->obj->mm.pages;
228
229         vma->page_sizes = vma->obj->mm.page_sizes;
230
231         return 0;
232 }
233
234 static void clear_pages(struct i915_vma *vma)
235 {
236         GEM_BUG_ON(!vma->pages);
237
238         if (vma->pages != vma->obj->mm.pages) {
239                 sg_free_table(vma->pages);
240                 kfree(vma->pages);
241         }
242         vma->pages = NULL;
243
244         memset(&vma->page_sizes, 0, sizeof(vma->page_sizes));
245 }
246
247 static gen8_pte_t gen8_pte_encode(dma_addr_t addr,
248                                   enum i915_cache_level level)
249 {
250         gen8_pte_t pte = _PAGE_PRESENT | _PAGE_RW;
251         pte |= addr;
252
253         switch (level) {
254         case I915_CACHE_NONE:
255                 pte |= PPAT_UNCACHED;
256                 break;
257         case I915_CACHE_WT:
258                 pte |= PPAT_DISPLAY_ELLC;
259                 break;
260         default:
261                 pte |= PPAT_CACHED;
262                 break;
263         }
264
265         return pte;
266 }
267
268 static gen8_pde_t gen8_pde_encode(const dma_addr_t addr,
269                                   const enum i915_cache_level level)
270 {
271         gen8_pde_t pde = _PAGE_PRESENT | _PAGE_RW;
272         pde |= addr;
273         if (level != I915_CACHE_NONE)
274                 pde |= PPAT_CACHED_PDE;
275         else
276                 pde |= PPAT_UNCACHED;
277         return pde;
278 }
279
280 #define gen8_pdpe_encode gen8_pde_encode
281 #define gen8_pml4e_encode gen8_pde_encode
282
283 static gen6_pte_t snb_pte_encode(dma_addr_t addr,
284                                  enum i915_cache_level level,
285                                  u32 unused)
286 {
287         gen6_pte_t pte = GEN6_PTE_VALID;
288         pte |= GEN6_PTE_ADDR_ENCODE(addr);
289
290         switch (level) {
291         case I915_CACHE_L3_LLC:
292         case I915_CACHE_LLC:
293                 pte |= GEN6_PTE_CACHE_LLC;
294                 break;
295         case I915_CACHE_NONE:
296                 pte |= GEN6_PTE_UNCACHED;
297                 break;
298         default:
299                 MISSING_CASE(level);
300         }
301
302         return pte;
303 }
304
305 static gen6_pte_t ivb_pte_encode(dma_addr_t addr,
306                                  enum i915_cache_level level,
307                                  u32 unused)
308 {
309         gen6_pte_t pte = GEN6_PTE_VALID;
310         pte |= GEN6_PTE_ADDR_ENCODE(addr);
311
312         switch (level) {
313         case I915_CACHE_L3_LLC:
314                 pte |= GEN7_PTE_CACHE_L3_LLC;
315                 break;
316         case I915_CACHE_LLC:
317                 pte |= GEN6_PTE_CACHE_LLC;
318                 break;
319         case I915_CACHE_NONE:
320                 pte |= GEN6_PTE_UNCACHED;
321                 break;
322         default:
323                 MISSING_CASE(level);
324         }
325
326         return pte;
327 }
328
329 static gen6_pte_t byt_pte_encode(dma_addr_t addr,
330                                  enum i915_cache_level level,
331                                  u32 flags)
332 {
333         gen6_pte_t pte = GEN6_PTE_VALID;
334         pte |= GEN6_PTE_ADDR_ENCODE(addr);
335
336         if (!(flags & PTE_READ_ONLY))
337                 pte |= BYT_PTE_WRITEABLE;
338
339         if (level != I915_CACHE_NONE)
340                 pte |= BYT_PTE_SNOOPED_BY_CPU_CACHES;
341
342         return pte;
343 }
344
345 static gen6_pte_t hsw_pte_encode(dma_addr_t addr,
346                                  enum i915_cache_level level,
347                                  u32 unused)
348 {
349         gen6_pte_t pte = GEN6_PTE_VALID;
350         pte |= HSW_PTE_ADDR_ENCODE(addr);
351
352         if (level != I915_CACHE_NONE)
353                 pte |= HSW_WB_LLC_AGE3;
354
355         return pte;
356 }
357
358 static gen6_pte_t iris_pte_encode(dma_addr_t addr,
359                                   enum i915_cache_level level,
360                                   u32 unused)
361 {
362         gen6_pte_t pte = GEN6_PTE_VALID;
363         pte |= HSW_PTE_ADDR_ENCODE(addr);
364
365         switch (level) {
366         case I915_CACHE_NONE:
367                 break;
368         case I915_CACHE_WT:
369                 pte |= HSW_WT_ELLC_LLC_AGE3;
370                 break;
371         default:
372                 pte |= HSW_WB_ELLC_LLC_AGE3;
373                 break;
374         }
375
376         return pte;
377 }
378
379 static struct page *vm_alloc_page(struct i915_address_space *vm, gfp_t gfp)
380 {
381         struct pagevec *pvec = &vm->free_pages;
382
383         if (I915_SELFTEST_ONLY(should_fail(&vm->fault_attr, 1)))
384                 i915_gem_shrink_all(vm->i915);
385
386         if (likely(pvec->nr))
387                 return pvec->pages[--pvec->nr];
388
389         if (!vm->pt_kmap_wc)
390                 return alloc_page(gfp);
391
392         /* A placeholder for a specific mutex to guard the WC stash */
393         lockdep_assert_held(&vm->i915->drm.struct_mutex);
394
395         /* Look in our global stash of WC pages... */
396         pvec = &vm->i915->mm.wc_stash;
397         if (likely(pvec->nr))
398                 return pvec->pages[--pvec->nr];
399
400         /* Otherwise batch allocate pages to amoritize cost of set_pages_wc. */
401         do {
402                 struct page *page;
403
404                 page = alloc_page(gfp);
405                 if (unlikely(!page))
406                         break;
407
408                 pvec->pages[pvec->nr++] = page;
409         } while (pagevec_space(pvec));
410
411         if (unlikely(!pvec->nr))
412                 return NULL;
413
414         set_pages_array_wc(pvec->pages, pvec->nr);
415
416         return pvec->pages[--pvec->nr];
417 }
418
419 static void vm_free_pages_release(struct i915_address_space *vm,
420                                   bool immediate)
421 {
422         struct pagevec *pvec = &vm->free_pages;
423
424         GEM_BUG_ON(!pagevec_count(pvec));
425
426         if (vm->pt_kmap_wc) {
427                 struct pagevec *stash = &vm->i915->mm.wc_stash;
428
429                 /* When we use WC, first fill up the global stash and then
430                  * only if full immediately free the overflow.
431                  */
432
433                 lockdep_assert_held(&vm->i915->drm.struct_mutex);
434                 if (pagevec_space(stash)) {
435                         do {
436                                 stash->pages[stash->nr++] =
437                                         pvec->pages[--pvec->nr];
438                                 if (!pvec->nr)
439                                         return;
440                         } while (pagevec_space(stash));
441
442                         /* As we have made some room in the VM's free_pages,
443                          * we can wait for it to fill again. Unless we are
444                          * inside i915_address_space_fini() and must
445                          * immediately release the pages!
446                          */
447                         if (!immediate)
448                                 return;
449                 }
450
451                 set_pages_array_wb(pvec->pages, pvec->nr);
452         }
453
454         __pagevec_release(pvec);
455 }
456
457 static void vm_free_page(struct i915_address_space *vm, struct page *page)
458 {
459         if (!pagevec_add(&vm->free_pages, page))
460                 vm_free_pages_release(vm, false);
461 }
462
463 static int __setup_page_dma(struct i915_address_space *vm,
464                             struct i915_page_dma *p,
465                             gfp_t gfp)
466 {
467         p->page = vm_alloc_page(vm, gfp | __GFP_NOWARN | __GFP_NORETRY);
468         if (unlikely(!p->page))
469                 return -ENOMEM;
470
471         p->daddr = dma_map_page(vm->dma, p->page, 0, PAGE_SIZE,
472                                 PCI_DMA_BIDIRECTIONAL);
473         if (unlikely(dma_mapping_error(vm->dma, p->daddr))) {
474                 vm_free_page(vm, p->page);
475                 return -ENOMEM;
476         }
477
478         return 0;
479 }
480
481 static int setup_page_dma(struct i915_address_space *vm,
482                           struct i915_page_dma *p)
483 {
484         return __setup_page_dma(vm, p, I915_GFP_DMA);
485 }
486
487 static void cleanup_page_dma(struct i915_address_space *vm,
488                              struct i915_page_dma *p)
489 {
490         dma_unmap_page(vm->dma, p->daddr, PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
491         vm_free_page(vm, p->page);
492 }
493
494 #define kmap_atomic_px(px) kmap_atomic(px_base(px)->page)
495
496 #define setup_px(vm, px) setup_page_dma((vm), px_base(px))
497 #define cleanup_px(vm, px) cleanup_page_dma((vm), px_base(px))
498 #define fill_px(ppgtt, px, v) fill_page_dma((vm), px_base(px), (v))
499 #define fill32_px(ppgtt, px, v) fill_page_dma_32((vm), px_base(px), (v))
500
501 static void fill_page_dma(struct i915_address_space *vm,
502                           struct i915_page_dma *p,
503                           const u64 val)
504 {
505         u64 * const vaddr = kmap_atomic(p->page);
506
507         memset64(vaddr, val, PAGE_SIZE / sizeof(val));
508
509         kunmap_atomic(vaddr);
510 }
511
512 static void fill_page_dma_32(struct i915_address_space *vm,
513                              struct i915_page_dma *p,
514                              const u32 v)
515 {
516         fill_page_dma(vm, p, (u64)v << 32 | v);
517 }
518
519 static int
520 setup_scratch_page(struct i915_address_space *vm, gfp_t gfp)
521 {
522         struct page *page;
523         dma_addr_t addr;
524
525         page = alloc_page(gfp | __GFP_ZERO);
526         if (unlikely(!page))
527                 return -ENOMEM;
528
529         addr = dma_map_page(vm->dma, page, 0, PAGE_SIZE,
530                             PCI_DMA_BIDIRECTIONAL);
531         if (unlikely(dma_mapping_error(vm->dma, addr))) {
532                 __free_page(page);
533                 return -ENOMEM;
534         }
535
536         vm->scratch_page.page = page;
537         vm->scratch_page.daddr = addr;
538         return 0;
539 }
540
541 static void cleanup_scratch_page(struct i915_address_space *vm)
542 {
543         struct i915_page_dma *p = &vm->scratch_page;
544
545         dma_unmap_page(vm->dma, p->daddr, PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
546         __free_page(p->page);
547 }
548
549 static struct i915_page_table *alloc_pt(struct i915_address_space *vm)
550 {
551         struct i915_page_table *pt;
552
553         pt = kmalloc(sizeof(*pt), GFP_KERNEL | __GFP_NOWARN);
554         if (unlikely(!pt))
555                 return ERR_PTR(-ENOMEM);
556
557         if (unlikely(setup_px(vm, pt))) {
558                 kfree(pt);
559                 return ERR_PTR(-ENOMEM);
560         }
561
562         pt->used_ptes = 0;
563         return pt;
564 }
565
566 static void free_pt(struct i915_address_space *vm, struct i915_page_table *pt)
567 {
568         cleanup_px(vm, pt);
569         kfree(pt);
570 }
571
572 static void gen8_initialize_pt(struct i915_address_space *vm,
573                                struct i915_page_table *pt)
574 {
575         fill_px(vm, pt,
576                 gen8_pte_encode(vm->scratch_page.daddr, I915_CACHE_LLC));
577 }
578
579 static void gen6_initialize_pt(struct i915_address_space *vm,
580                                struct i915_page_table *pt)
581 {
582         fill32_px(vm, pt,
583                   vm->pte_encode(vm->scratch_page.daddr, I915_CACHE_LLC, 0));
584 }
585
586 static struct i915_page_directory *alloc_pd(struct i915_address_space *vm)
587 {
588         struct i915_page_directory *pd;
589
590         pd = kzalloc(sizeof(*pd), GFP_KERNEL | __GFP_NOWARN);
591         if (unlikely(!pd))
592                 return ERR_PTR(-ENOMEM);
593
594         if (unlikely(setup_px(vm, pd))) {
595                 kfree(pd);
596                 return ERR_PTR(-ENOMEM);
597         }
598
599         pd->used_pdes = 0;
600         return pd;
601 }
602
603 static void free_pd(struct i915_address_space *vm,
604                     struct i915_page_directory *pd)
605 {
606         cleanup_px(vm, pd);
607         kfree(pd);
608 }
609
610 static void gen8_initialize_pd(struct i915_address_space *vm,
611                                struct i915_page_directory *pd)
612 {
613         unsigned int i;
614
615         fill_px(vm, pd,
616                 gen8_pde_encode(px_dma(vm->scratch_pt), I915_CACHE_LLC));
617         for (i = 0; i < I915_PDES; i++)
618                 pd->page_table[i] = vm->scratch_pt;
619 }
620
621 static int __pdp_init(struct i915_address_space *vm,
622                       struct i915_page_directory_pointer *pdp)
623 {
624         const unsigned int pdpes = i915_pdpes_per_pdp(vm);
625         unsigned int i;
626
627         pdp->page_directory = kmalloc_array(pdpes, sizeof(*pdp->page_directory),
628                                             GFP_KERNEL | __GFP_NOWARN);
629         if (unlikely(!pdp->page_directory))
630                 return -ENOMEM;
631
632         for (i = 0; i < pdpes; i++)
633                 pdp->page_directory[i] = vm->scratch_pd;
634
635         return 0;
636 }
637
638 static void __pdp_fini(struct i915_page_directory_pointer *pdp)
639 {
640         kfree(pdp->page_directory);
641         pdp->page_directory = NULL;
642 }
643
644 static inline bool use_4lvl(const struct i915_address_space *vm)
645 {
646         return i915_vm_is_48bit(vm);
647 }
648
649 static struct i915_page_directory_pointer *
650 alloc_pdp(struct i915_address_space *vm)
651 {
652         struct i915_page_directory_pointer *pdp;
653         int ret = -ENOMEM;
654
655         WARN_ON(!use_4lvl(vm));
656
657         pdp = kzalloc(sizeof(*pdp), GFP_KERNEL);
658         if (!pdp)
659                 return ERR_PTR(-ENOMEM);
660
661         ret = __pdp_init(vm, pdp);
662         if (ret)
663                 goto fail_bitmap;
664
665         ret = setup_px(vm, pdp);
666         if (ret)
667                 goto fail_page_m;
668
669         return pdp;
670
671 fail_page_m:
672         __pdp_fini(pdp);
673 fail_bitmap:
674         kfree(pdp);
675
676         return ERR_PTR(ret);
677 }
678
679 static void free_pdp(struct i915_address_space *vm,
680                      struct i915_page_directory_pointer *pdp)
681 {
682         __pdp_fini(pdp);
683
684         if (!use_4lvl(vm))
685                 return;
686
687         cleanup_px(vm, pdp);
688         kfree(pdp);
689 }
690
691 static void gen8_initialize_pdp(struct i915_address_space *vm,
692                                 struct i915_page_directory_pointer *pdp)
693 {
694         gen8_ppgtt_pdpe_t scratch_pdpe;
695
696         scratch_pdpe = gen8_pdpe_encode(px_dma(vm->scratch_pd), I915_CACHE_LLC);
697
698         fill_px(vm, pdp, scratch_pdpe);
699 }
700
701 static void gen8_initialize_pml4(struct i915_address_space *vm,
702                                  struct i915_pml4 *pml4)
703 {
704         unsigned int i;
705
706         fill_px(vm, pml4,
707                 gen8_pml4e_encode(px_dma(vm->scratch_pdp), I915_CACHE_LLC));
708         for (i = 0; i < GEN8_PML4ES_PER_PML4; i++)
709                 pml4->pdps[i] = vm->scratch_pdp;
710 }
711
712 /* Broadwell Page Directory Pointer Descriptors */
713 static int gen8_write_pdp(struct drm_i915_gem_request *req,
714                           unsigned entry,
715                           dma_addr_t addr)
716 {
717         struct intel_engine_cs *engine = req->engine;
718         u32 *cs;
719
720         BUG_ON(entry >= 4);
721
722         cs = intel_ring_begin(req, 6);
723         if (IS_ERR(cs))
724                 return PTR_ERR(cs);
725
726         *cs++ = MI_LOAD_REGISTER_IMM(1);
727         *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(engine, entry));
728         *cs++ = upper_32_bits(addr);
729         *cs++ = MI_LOAD_REGISTER_IMM(1);
730         *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(engine, entry));
731         *cs++ = lower_32_bits(addr);
732         intel_ring_advance(req, cs);
733
734         return 0;
735 }
736
737 static int gen8_mm_switch_3lvl(struct i915_hw_ppgtt *ppgtt,
738                                struct drm_i915_gem_request *req)
739 {
740         int i, ret;
741
742         for (i = GEN8_3LVL_PDPES - 1; i >= 0; i--) {
743                 const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
744
745                 ret = gen8_write_pdp(req, i, pd_daddr);
746                 if (ret)
747                         return ret;
748         }
749
750         return 0;
751 }
752
753 static int gen8_mm_switch_4lvl(struct i915_hw_ppgtt *ppgtt,
754                                struct drm_i915_gem_request *req)
755 {
756         return gen8_write_pdp(req, 0, px_dma(&ppgtt->pml4));
757 }
758
759 /* PDE TLBs are a pain to invalidate on GEN8+. When we modify
760  * the page table structures, we mark them dirty so that
761  * context switching/execlist queuing code takes extra steps
762  * to ensure that tlbs are flushed.
763  */
764 static void mark_tlbs_dirty(struct i915_hw_ppgtt *ppgtt)
765 {
766         ppgtt->pd_dirty_rings = INTEL_INFO(ppgtt->base.i915)->ring_mask;
767 }
768
769 /* Removes entries from a single page table, releasing it if it's empty.
770  * Caller can use the return value to update higher-level entries.
771  */
772 static bool gen8_ppgtt_clear_pt(struct i915_address_space *vm,
773                                 struct i915_page_table *pt,
774                                 u64 start, u64 length)
775 {
776         unsigned int num_entries = gen8_pte_count(start, length);
777         unsigned int pte = gen8_pte_index(start);
778         unsigned int pte_end = pte + num_entries;
779         const gen8_pte_t scratch_pte =
780                 gen8_pte_encode(vm->scratch_page.daddr, I915_CACHE_LLC);
781         gen8_pte_t *vaddr;
782
783         GEM_BUG_ON(num_entries > pt->used_ptes);
784
785         pt->used_ptes -= num_entries;
786         if (!pt->used_ptes)
787                 return true;
788
789         vaddr = kmap_atomic_px(pt);
790         while (pte < pte_end)
791                 vaddr[pte++] = scratch_pte;
792         kunmap_atomic(vaddr);
793
794         return false;
795 }
796
797 static void gen8_ppgtt_set_pde(struct i915_address_space *vm,
798                                struct i915_page_directory *pd,
799                                struct i915_page_table *pt,
800                                unsigned int pde)
801 {
802         gen8_pde_t *vaddr;
803
804         pd->page_table[pde] = pt;
805
806         vaddr = kmap_atomic_px(pd);
807         vaddr[pde] = gen8_pde_encode(px_dma(pt), I915_CACHE_LLC);
808         kunmap_atomic(vaddr);
809 }
810
811 static bool gen8_ppgtt_clear_pd(struct i915_address_space *vm,
812                                 struct i915_page_directory *pd,
813                                 u64 start, u64 length)
814 {
815         struct i915_page_table *pt;
816         u32 pde;
817
818         gen8_for_each_pde(pt, pd, start, length, pde) {
819                 GEM_BUG_ON(pt == vm->scratch_pt);
820
821                 if (!gen8_ppgtt_clear_pt(vm, pt, start, length))
822                         continue;
823
824                 gen8_ppgtt_set_pde(vm, pd, vm->scratch_pt, pde);
825                 GEM_BUG_ON(!pd->used_pdes);
826                 pd->used_pdes--;
827
828                 free_pt(vm, pt);
829         }
830
831         return !pd->used_pdes;
832 }
833
834 static void gen8_ppgtt_set_pdpe(struct i915_address_space *vm,
835                                 struct i915_page_directory_pointer *pdp,
836                                 struct i915_page_directory *pd,
837                                 unsigned int pdpe)
838 {
839         gen8_ppgtt_pdpe_t *vaddr;
840
841         pdp->page_directory[pdpe] = pd;
842         if (!use_4lvl(vm))
843                 return;
844
845         vaddr = kmap_atomic_px(pdp);
846         vaddr[pdpe] = gen8_pdpe_encode(px_dma(pd), I915_CACHE_LLC);
847         kunmap_atomic(vaddr);
848 }
849
850 /* Removes entries from a single page dir pointer, releasing it if it's empty.
851  * Caller can use the return value to update higher-level entries
852  */
853 static bool gen8_ppgtt_clear_pdp(struct i915_address_space *vm,
854                                  struct i915_page_directory_pointer *pdp,
855                                  u64 start, u64 length)
856 {
857         struct i915_page_directory *pd;
858         unsigned int pdpe;
859
860         gen8_for_each_pdpe(pd, pdp, start, length, pdpe) {
861                 GEM_BUG_ON(pd == vm->scratch_pd);
862
863                 if (!gen8_ppgtt_clear_pd(vm, pd, start, length))
864                         continue;
865
866                 gen8_ppgtt_set_pdpe(vm, pdp, vm->scratch_pd, pdpe);
867                 GEM_BUG_ON(!pdp->used_pdpes);
868                 pdp->used_pdpes--;
869
870                 free_pd(vm, pd);
871         }
872
873         return !pdp->used_pdpes;
874 }
875
876 static void gen8_ppgtt_clear_3lvl(struct i915_address_space *vm,
877                                   u64 start, u64 length)
878 {
879         gen8_ppgtt_clear_pdp(vm, &i915_vm_to_ppgtt(vm)->pdp, start, length);
880 }
881
882 static void gen8_ppgtt_set_pml4e(struct i915_pml4 *pml4,
883                                  struct i915_page_directory_pointer *pdp,
884                                  unsigned int pml4e)
885 {
886         gen8_ppgtt_pml4e_t *vaddr;
887
888         pml4->pdps[pml4e] = pdp;
889
890         vaddr = kmap_atomic_px(pml4);
891         vaddr[pml4e] = gen8_pml4e_encode(px_dma(pdp), I915_CACHE_LLC);
892         kunmap_atomic(vaddr);
893 }
894
895 /* Removes entries from a single pml4.
896  * This is the top-level structure in 4-level page tables used on gen8+.
897  * Empty entries are always scratch pml4e.
898  */
899 static void gen8_ppgtt_clear_4lvl(struct i915_address_space *vm,
900                                   u64 start, u64 length)
901 {
902         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
903         struct i915_pml4 *pml4 = &ppgtt->pml4;
904         struct i915_page_directory_pointer *pdp;
905         unsigned int pml4e;
906
907         GEM_BUG_ON(!use_4lvl(vm));
908
909         gen8_for_each_pml4e(pdp, pml4, start, length, pml4e) {
910                 GEM_BUG_ON(pdp == vm->scratch_pdp);
911
912                 if (!gen8_ppgtt_clear_pdp(vm, pdp, start, length))
913                         continue;
914
915                 gen8_ppgtt_set_pml4e(pml4, vm->scratch_pdp, pml4e);
916
917                 free_pdp(vm, pdp);
918         }
919 }
920
921 struct sgt_dma {
922         struct scatterlist *sg;
923         dma_addr_t dma, max;
924 };
925
926 struct gen8_insert_pte {
927         u16 pml4e;
928         u16 pdpe;
929         u16 pde;
930         u16 pte;
931 };
932
933 static __always_inline struct gen8_insert_pte gen8_insert_pte(u64 start)
934 {
935         return (struct gen8_insert_pte) {
936                  gen8_pml4e_index(start),
937                  gen8_pdpe_index(start),
938                  gen8_pde_index(start),
939                  gen8_pte_index(start),
940         };
941 }
942
943 static __always_inline bool
944 gen8_ppgtt_insert_pte_entries(struct i915_hw_ppgtt *ppgtt,
945                               struct i915_page_directory_pointer *pdp,
946                               struct sgt_dma *iter,
947                               struct gen8_insert_pte *idx,
948                               enum i915_cache_level cache_level)
949 {
950         struct i915_page_directory *pd;
951         const gen8_pte_t pte_encode = gen8_pte_encode(0, cache_level);
952         gen8_pte_t *vaddr;
953         bool ret;
954
955         GEM_BUG_ON(idx->pdpe >= i915_pdpes_per_pdp(&ppgtt->base));
956         pd = pdp->page_directory[idx->pdpe];
957         vaddr = kmap_atomic_px(pd->page_table[idx->pde]);
958         do {
959                 vaddr[idx->pte] = pte_encode | iter->dma;
960
961                 iter->dma += PAGE_SIZE;
962                 if (iter->dma >= iter->max) {
963                         iter->sg = __sg_next(iter->sg);
964                         if (!iter->sg) {
965                                 ret = false;
966                                 break;
967                         }
968
969                         iter->dma = sg_dma_address(iter->sg);
970                         iter->max = iter->dma + iter->sg->length;
971                 }
972
973                 if (++idx->pte == GEN8_PTES) {
974                         idx->pte = 0;
975
976                         if (++idx->pde == I915_PDES) {
977                                 idx->pde = 0;
978
979                                 /* Limited by sg length for 3lvl */
980                                 if (++idx->pdpe == GEN8_PML4ES_PER_PML4) {
981                                         idx->pdpe = 0;
982                                         ret = true;
983                                         break;
984                                 }
985
986                                 GEM_BUG_ON(idx->pdpe >= i915_pdpes_per_pdp(&ppgtt->base));
987                                 pd = pdp->page_directory[idx->pdpe];
988                         }
989
990                         kunmap_atomic(vaddr);
991                         vaddr = kmap_atomic_px(pd->page_table[idx->pde]);
992                 }
993         } while (1);
994         kunmap_atomic(vaddr);
995
996         return ret;
997 }
998
999 static void gen8_ppgtt_insert_3lvl(struct i915_address_space *vm,
1000                                    struct i915_vma *vma,
1001                                    enum i915_cache_level cache_level,
1002                                    u32 unused)
1003 {
1004         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1005         struct sgt_dma iter = {
1006                 .sg = vma->pages->sgl,
1007                 .dma = sg_dma_address(iter.sg),
1008                 .max = iter.dma + iter.sg->length,
1009         };
1010         struct gen8_insert_pte idx = gen8_insert_pte(vma->node.start);
1011
1012         gen8_ppgtt_insert_pte_entries(ppgtt, &ppgtt->pdp, &iter, &idx,
1013                                       cache_level);
1014 }
1015
1016 static void gen8_ppgtt_insert_huge_entries(struct i915_vma *vma,
1017                                            struct i915_page_directory_pointer **pdps,
1018                                            struct sgt_dma *iter,
1019                                            enum i915_cache_level cache_level)
1020 {
1021         const gen8_pte_t pte_encode = gen8_pte_encode(0, cache_level);
1022         u64 start = vma->node.start;
1023         dma_addr_t rem = iter->sg->length;
1024
1025         do {
1026                 struct gen8_insert_pte idx = gen8_insert_pte(start);
1027                 struct i915_page_directory_pointer *pdp = pdps[idx.pml4e];
1028                 struct i915_page_directory *pd = pdp->page_directory[idx.pdpe];
1029                 unsigned int page_size;
1030                 gen8_pte_t encode = pte_encode;
1031                 gen8_pte_t *vaddr;
1032                 u16 index, max;
1033
1034                 if (vma->page_sizes.sg & I915_GTT_PAGE_SIZE_2M &&
1035                     IS_ALIGNED(iter->dma, I915_GTT_PAGE_SIZE_2M) &&
1036                     rem >= I915_GTT_PAGE_SIZE_2M && !idx.pte) {
1037                         index = idx.pde;
1038                         max = I915_PDES;
1039                         page_size = I915_GTT_PAGE_SIZE_2M;
1040
1041                         encode |= GEN8_PDE_PS_2M;
1042
1043                         vaddr = kmap_atomic_px(pd);
1044                 } else {
1045                         struct i915_page_table *pt = pd->page_table[idx.pde];
1046
1047                         index = idx.pte;
1048                         max = GEN8_PTES;
1049                         page_size = I915_GTT_PAGE_SIZE;
1050
1051                         vaddr = kmap_atomic_px(pt);
1052                 }
1053
1054                 do {
1055                         GEM_BUG_ON(iter->sg->length < page_size);
1056                         vaddr[index++] = encode | iter->dma;
1057
1058                         start += page_size;
1059                         iter->dma += page_size;
1060                         rem -= page_size;
1061                         if (iter->dma >= iter->max) {
1062                                 iter->sg = __sg_next(iter->sg);
1063                                 if (!iter->sg)
1064                                         break;
1065
1066                                 rem = iter->sg->length;
1067                                 iter->dma = sg_dma_address(iter->sg);
1068                                 iter->max = iter->dma + rem;
1069
1070                                 if (unlikely(!IS_ALIGNED(iter->dma, page_size)))
1071                                         break;
1072                         }
1073                 } while (rem >= page_size && index < max);
1074
1075                 kunmap_atomic(vaddr);
1076         } while (iter->sg);
1077 }
1078
1079 static void gen8_ppgtt_insert_4lvl(struct i915_address_space *vm,
1080                                    struct i915_vma *vma,
1081                                    enum i915_cache_level cache_level,
1082                                    u32 unused)
1083 {
1084         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1085         struct sgt_dma iter = {
1086                 .sg = vma->pages->sgl,
1087                 .dma = sg_dma_address(iter.sg),
1088                 .max = iter.dma + iter.sg->length,
1089         };
1090         struct i915_page_directory_pointer **pdps = ppgtt->pml4.pdps;
1091
1092         if (vma->page_sizes.sg > I915_GTT_PAGE_SIZE) {
1093                 gen8_ppgtt_insert_huge_entries(vma, pdps, &iter, cache_level);
1094         } else {
1095                 struct gen8_insert_pte idx = gen8_insert_pte(vma->node.start);
1096
1097                 while (gen8_ppgtt_insert_pte_entries(ppgtt, pdps[idx.pml4e++],
1098                                                      &iter, &idx, cache_level))
1099                         GEM_BUG_ON(idx.pml4e >= GEN8_PML4ES_PER_PML4);
1100         }
1101 }
1102
1103 static void gen8_free_page_tables(struct i915_address_space *vm,
1104                                   struct i915_page_directory *pd)
1105 {
1106         int i;
1107
1108         if (!px_page(pd))
1109                 return;
1110
1111         for (i = 0; i < I915_PDES; i++) {
1112                 if (pd->page_table[i] != vm->scratch_pt)
1113                         free_pt(vm, pd->page_table[i]);
1114         }
1115 }
1116
1117 static int gen8_init_scratch(struct i915_address_space *vm)
1118 {
1119         int ret;
1120
1121         ret = setup_scratch_page(vm, I915_GFP_DMA);
1122         if (ret)
1123                 return ret;
1124
1125         vm->scratch_pt = alloc_pt(vm);
1126         if (IS_ERR(vm->scratch_pt)) {
1127                 ret = PTR_ERR(vm->scratch_pt);
1128                 goto free_scratch_page;
1129         }
1130
1131         vm->scratch_pd = alloc_pd(vm);
1132         if (IS_ERR(vm->scratch_pd)) {
1133                 ret = PTR_ERR(vm->scratch_pd);
1134                 goto free_pt;
1135         }
1136
1137         if (use_4lvl(vm)) {
1138                 vm->scratch_pdp = alloc_pdp(vm);
1139                 if (IS_ERR(vm->scratch_pdp)) {
1140                         ret = PTR_ERR(vm->scratch_pdp);
1141                         goto free_pd;
1142                 }
1143         }
1144
1145         gen8_initialize_pt(vm, vm->scratch_pt);
1146         gen8_initialize_pd(vm, vm->scratch_pd);
1147         if (use_4lvl(vm))
1148                 gen8_initialize_pdp(vm, vm->scratch_pdp);
1149
1150         return 0;
1151
1152 free_pd:
1153         free_pd(vm, vm->scratch_pd);
1154 free_pt:
1155         free_pt(vm, vm->scratch_pt);
1156 free_scratch_page:
1157         cleanup_scratch_page(vm);
1158
1159         return ret;
1160 }
1161
1162 static int gen8_ppgtt_notify_vgt(struct i915_hw_ppgtt *ppgtt, bool create)
1163 {
1164         struct i915_address_space *vm = &ppgtt->base;
1165         struct drm_i915_private *dev_priv = vm->i915;
1166         enum vgt_g2v_type msg;
1167         int i;
1168
1169         if (use_4lvl(vm)) {
1170                 const u64 daddr = px_dma(&ppgtt->pml4);
1171
1172                 I915_WRITE(vgtif_reg(pdp[0].lo), lower_32_bits(daddr));
1173                 I915_WRITE(vgtif_reg(pdp[0].hi), upper_32_bits(daddr));
1174
1175                 msg = (create ? VGT_G2V_PPGTT_L4_PAGE_TABLE_CREATE :
1176                                 VGT_G2V_PPGTT_L4_PAGE_TABLE_DESTROY);
1177         } else {
1178                 for (i = 0; i < GEN8_3LVL_PDPES; i++) {
1179                         const u64 daddr = i915_page_dir_dma_addr(ppgtt, i);
1180
1181                         I915_WRITE(vgtif_reg(pdp[i].lo), lower_32_bits(daddr));
1182                         I915_WRITE(vgtif_reg(pdp[i].hi), upper_32_bits(daddr));
1183                 }
1184
1185                 msg = (create ? VGT_G2V_PPGTT_L3_PAGE_TABLE_CREATE :
1186                                 VGT_G2V_PPGTT_L3_PAGE_TABLE_DESTROY);
1187         }
1188
1189         I915_WRITE(vgtif_reg(g2v_notify), msg);
1190
1191         return 0;
1192 }
1193
1194 static void gen8_free_scratch(struct i915_address_space *vm)
1195 {
1196         if (use_4lvl(vm))
1197                 free_pdp(vm, vm->scratch_pdp);
1198         free_pd(vm, vm->scratch_pd);
1199         free_pt(vm, vm->scratch_pt);
1200         cleanup_scratch_page(vm);
1201 }
1202
1203 static void gen8_ppgtt_cleanup_3lvl(struct i915_address_space *vm,
1204                                     struct i915_page_directory_pointer *pdp)
1205 {
1206         const unsigned int pdpes = i915_pdpes_per_pdp(vm);
1207         int i;
1208
1209         for (i = 0; i < pdpes; i++) {
1210                 if (pdp->page_directory[i] == vm->scratch_pd)
1211                         continue;
1212
1213                 gen8_free_page_tables(vm, pdp->page_directory[i]);
1214                 free_pd(vm, pdp->page_directory[i]);
1215         }
1216
1217         free_pdp(vm, pdp);
1218 }
1219
1220 static void gen8_ppgtt_cleanup_4lvl(struct i915_hw_ppgtt *ppgtt)
1221 {
1222         int i;
1223
1224         for (i = 0; i < GEN8_PML4ES_PER_PML4; i++) {
1225                 if (ppgtt->pml4.pdps[i] == ppgtt->base.scratch_pdp)
1226                         continue;
1227
1228                 gen8_ppgtt_cleanup_3lvl(&ppgtt->base, ppgtt->pml4.pdps[i]);
1229         }
1230
1231         cleanup_px(&ppgtt->base, &ppgtt->pml4);
1232 }
1233
1234 static void gen8_ppgtt_cleanup(struct i915_address_space *vm)
1235 {
1236         struct drm_i915_private *dev_priv = vm->i915;
1237         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1238
1239         if (intel_vgpu_active(dev_priv))
1240                 gen8_ppgtt_notify_vgt(ppgtt, false);
1241
1242         if (use_4lvl(vm))
1243                 gen8_ppgtt_cleanup_4lvl(ppgtt);
1244         else
1245                 gen8_ppgtt_cleanup_3lvl(&ppgtt->base, &ppgtt->pdp);
1246
1247         gen8_free_scratch(vm);
1248 }
1249
1250 static int gen8_ppgtt_alloc_pd(struct i915_address_space *vm,
1251                                struct i915_page_directory *pd,
1252                                u64 start, u64 length)
1253 {
1254         struct i915_page_table *pt;
1255         u64 from = start;
1256         unsigned int pde;
1257
1258         gen8_for_each_pde(pt, pd, start, length, pde) {
1259                 int count = gen8_pte_count(start, length);
1260
1261                 if (pt == vm->scratch_pt) {
1262                         pt = alloc_pt(vm);
1263                         if (IS_ERR(pt))
1264                                 goto unwind;
1265
1266                         if (count < GEN8_PTES)
1267                                 gen8_initialize_pt(vm, pt);
1268
1269                         gen8_ppgtt_set_pde(vm, pd, pt, pde);
1270                         pd->used_pdes++;
1271                         GEM_BUG_ON(pd->used_pdes > I915_PDES);
1272                 }
1273
1274                 pt->used_ptes += count;
1275         }
1276         return 0;
1277
1278 unwind:
1279         gen8_ppgtt_clear_pd(vm, pd, from, start - from);
1280         return -ENOMEM;
1281 }
1282
1283 static int gen8_ppgtt_alloc_pdp(struct i915_address_space *vm,
1284                                 struct i915_page_directory_pointer *pdp,
1285                                 u64 start, u64 length)
1286 {
1287         struct i915_page_directory *pd;
1288         u64 from = start;
1289         unsigned int pdpe;
1290         int ret;
1291
1292         gen8_for_each_pdpe(pd, pdp, start, length, pdpe) {
1293                 if (pd == vm->scratch_pd) {
1294                         pd = alloc_pd(vm);
1295                         if (IS_ERR(pd))
1296                                 goto unwind;
1297
1298                         gen8_initialize_pd(vm, pd);
1299                         gen8_ppgtt_set_pdpe(vm, pdp, pd, pdpe);
1300                         pdp->used_pdpes++;
1301                         GEM_BUG_ON(pdp->used_pdpes > i915_pdpes_per_pdp(vm));
1302
1303                         mark_tlbs_dirty(i915_vm_to_ppgtt(vm));
1304                 }
1305
1306                 ret = gen8_ppgtt_alloc_pd(vm, pd, start, length);
1307                 if (unlikely(ret))
1308                         goto unwind_pd;
1309         }
1310
1311         return 0;
1312
1313 unwind_pd:
1314         if (!pd->used_pdes) {
1315                 gen8_ppgtt_set_pdpe(vm, pdp, vm->scratch_pd, pdpe);
1316                 GEM_BUG_ON(!pdp->used_pdpes);
1317                 pdp->used_pdpes--;
1318                 free_pd(vm, pd);
1319         }
1320 unwind:
1321         gen8_ppgtt_clear_pdp(vm, pdp, from, start - from);
1322         return -ENOMEM;
1323 }
1324
1325 static int gen8_ppgtt_alloc_3lvl(struct i915_address_space *vm,
1326                                  u64 start, u64 length)
1327 {
1328         return gen8_ppgtt_alloc_pdp(vm,
1329                                     &i915_vm_to_ppgtt(vm)->pdp, start, length);
1330 }
1331
1332 static int gen8_ppgtt_alloc_4lvl(struct i915_address_space *vm,
1333                                  u64 start, u64 length)
1334 {
1335         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1336         struct i915_pml4 *pml4 = &ppgtt->pml4;
1337         struct i915_page_directory_pointer *pdp;
1338         u64 from = start;
1339         u32 pml4e;
1340         int ret;
1341
1342         gen8_for_each_pml4e(pdp, pml4, start, length, pml4e) {
1343                 if (pml4->pdps[pml4e] == vm->scratch_pdp) {
1344                         pdp = alloc_pdp(vm);
1345                         if (IS_ERR(pdp))
1346                                 goto unwind;
1347
1348                         gen8_initialize_pdp(vm, pdp);
1349                         gen8_ppgtt_set_pml4e(pml4, pdp, pml4e);
1350                 }
1351
1352                 ret = gen8_ppgtt_alloc_pdp(vm, pdp, start, length);
1353                 if (unlikely(ret))
1354                         goto unwind_pdp;
1355         }
1356
1357         return 0;
1358
1359 unwind_pdp:
1360         if (!pdp->used_pdpes) {
1361                 gen8_ppgtt_set_pml4e(pml4, vm->scratch_pdp, pml4e);
1362                 free_pdp(vm, pdp);
1363         }
1364 unwind:
1365         gen8_ppgtt_clear_4lvl(vm, from, start - from);
1366         return -ENOMEM;
1367 }
1368
1369 static void gen8_dump_pdp(struct i915_hw_ppgtt *ppgtt,
1370                           struct i915_page_directory_pointer *pdp,
1371                           u64 start, u64 length,
1372                           gen8_pte_t scratch_pte,
1373                           struct seq_file *m)
1374 {
1375         struct i915_address_space *vm = &ppgtt->base;
1376         struct i915_page_directory *pd;
1377         u32 pdpe;
1378
1379         gen8_for_each_pdpe(pd, pdp, start, length, pdpe) {
1380                 struct i915_page_table *pt;
1381                 u64 pd_len = length;
1382                 u64 pd_start = start;
1383                 u32 pde;
1384
1385                 if (pdp->page_directory[pdpe] == ppgtt->base.scratch_pd)
1386                         continue;
1387
1388                 seq_printf(m, "\tPDPE #%d\n", pdpe);
1389                 gen8_for_each_pde(pt, pd, pd_start, pd_len, pde) {
1390                         u32 pte;
1391                         gen8_pte_t *pt_vaddr;
1392
1393                         if (pd->page_table[pde] == ppgtt->base.scratch_pt)
1394                                 continue;
1395
1396                         pt_vaddr = kmap_atomic_px(pt);
1397                         for (pte = 0; pte < GEN8_PTES; pte += 4) {
1398                                 u64 va = (pdpe << GEN8_PDPE_SHIFT |
1399                                           pde << GEN8_PDE_SHIFT |
1400                                           pte << GEN8_PTE_SHIFT);
1401                                 int i;
1402                                 bool found = false;
1403
1404                                 for (i = 0; i < 4; i++)
1405                                         if (pt_vaddr[pte + i] != scratch_pte)
1406                                                 found = true;
1407                                 if (!found)
1408                                         continue;
1409
1410                                 seq_printf(m, "\t\t0x%llx [%03d,%03d,%04d]: =", va, pdpe, pde, pte);
1411                                 for (i = 0; i < 4; i++) {
1412                                         if (pt_vaddr[pte + i] != scratch_pte)
1413                                                 seq_printf(m, " %llx", pt_vaddr[pte + i]);
1414                                         else
1415                                                 seq_puts(m, "  SCRATCH ");
1416                                 }
1417                                 seq_puts(m, "\n");
1418                         }
1419                         kunmap_atomic(pt_vaddr);
1420                 }
1421         }
1422 }
1423
1424 static void gen8_dump_ppgtt(struct i915_hw_ppgtt *ppgtt, struct seq_file *m)
1425 {
1426         struct i915_address_space *vm = &ppgtt->base;
1427         const gen8_pte_t scratch_pte =
1428                 gen8_pte_encode(vm->scratch_page.daddr, I915_CACHE_LLC);
1429         u64 start = 0, length = ppgtt->base.total;
1430
1431         if (use_4lvl(vm)) {
1432                 u64 pml4e;
1433                 struct i915_pml4 *pml4 = &ppgtt->pml4;
1434                 struct i915_page_directory_pointer *pdp;
1435
1436                 gen8_for_each_pml4e(pdp, pml4, start, length, pml4e) {
1437                         if (pml4->pdps[pml4e] == ppgtt->base.scratch_pdp)
1438                                 continue;
1439
1440                         seq_printf(m, "    PML4E #%llu\n", pml4e);
1441                         gen8_dump_pdp(ppgtt, pdp, start, length, scratch_pte, m);
1442                 }
1443         } else {
1444                 gen8_dump_pdp(ppgtt, &ppgtt->pdp, start, length, scratch_pte, m);
1445         }
1446 }
1447
1448 static int gen8_preallocate_top_level_pdp(struct i915_hw_ppgtt *ppgtt)
1449 {
1450         struct i915_address_space *vm = &ppgtt->base;
1451         struct i915_page_directory_pointer *pdp = &ppgtt->pdp;
1452         struct i915_page_directory *pd;
1453         u64 start = 0, length = ppgtt->base.total;
1454         u64 from = start;
1455         unsigned int pdpe;
1456
1457         gen8_for_each_pdpe(pd, pdp, start, length, pdpe) {
1458                 pd = alloc_pd(vm);
1459                 if (IS_ERR(pd))
1460                         goto unwind;
1461
1462                 gen8_initialize_pd(vm, pd);
1463                 gen8_ppgtt_set_pdpe(vm, pdp, pd, pdpe);
1464                 pdp->used_pdpes++;
1465         }
1466
1467         pdp->used_pdpes++; /* never remove */
1468         return 0;
1469
1470 unwind:
1471         start -= from;
1472         gen8_for_each_pdpe(pd, pdp, from, start, pdpe) {
1473                 gen8_ppgtt_set_pdpe(vm, pdp, vm->scratch_pd, pdpe);
1474                 free_pd(vm, pd);
1475         }
1476         pdp->used_pdpes = 0;
1477         return -ENOMEM;
1478 }
1479
1480 /*
1481  * GEN8 legacy ppgtt programming is accomplished through a max 4 PDP registers
1482  * with a net effect resembling a 2-level page table in normal x86 terms. Each
1483  * PDP represents 1GB of memory 4 * 512 * 512 * 4096 = 4GB legacy 32b address
1484  * space.
1485  *
1486  */
1487 static int gen8_ppgtt_init(struct i915_hw_ppgtt *ppgtt)
1488 {
1489         struct i915_address_space *vm = &ppgtt->base;
1490         struct drm_i915_private *dev_priv = vm->i915;
1491         int ret;
1492
1493         ppgtt->base.total = USES_FULL_48BIT_PPGTT(dev_priv) ?
1494                 1ULL << 48 :
1495                 1ULL << 32;
1496
1497         /* There are only few exceptions for gen >=6. chv and bxt.
1498          * And we are not sure about the latter so play safe for now.
1499          */
1500         if (IS_CHERRYVIEW(dev_priv) || IS_BROXTON(dev_priv))
1501                 ppgtt->base.pt_kmap_wc = true;
1502
1503         ret = gen8_init_scratch(&ppgtt->base);
1504         if (ret) {
1505                 ppgtt->base.total = 0;
1506                 return ret;
1507         }
1508
1509         if (use_4lvl(vm)) {
1510                 ret = setup_px(&ppgtt->base, &ppgtt->pml4);
1511                 if (ret)
1512                         goto free_scratch;
1513
1514                 gen8_initialize_pml4(&ppgtt->base, &ppgtt->pml4);
1515
1516                 ppgtt->switch_mm = gen8_mm_switch_4lvl;
1517                 ppgtt->base.allocate_va_range = gen8_ppgtt_alloc_4lvl;
1518                 ppgtt->base.insert_entries = gen8_ppgtt_insert_4lvl;
1519                 ppgtt->base.clear_range = gen8_ppgtt_clear_4lvl;
1520         } else {
1521                 ret = __pdp_init(&ppgtt->base, &ppgtt->pdp);
1522                 if (ret)
1523                         goto free_scratch;
1524
1525                 if (intel_vgpu_active(dev_priv)) {
1526                         ret = gen8_preallocate_top_level_pdp(ppgtt);
1527                         if (ret) {
1528                                 __pdp_fini(&ppgtt->pdp);
1529                                 goto free_scratch;
1530                         }
1531                 }
1532
1533                 ppgtt->switch_mm = gen8_mm_switch_3lvl;
1534                 ppgtt->base.allocate_va_range = gen8_ppgtt_alloc_3lvl;
1535                 ppgtt->base.insert_entries = gen8_ppgtt_insert_3lvl;
1536                 ppgtt->base.clear_range = gen8_ppgtt_clear_3lvl;
1537         }
1538
1539         if (intel_vgpu_active(dev_priv))
1540                 gen8_ppgtt_notify_vgt(ppgtt, true);
1541
1542         ppgtt->base.cleanup = gen8_ppgtt_cleanup;
1543         ppgtt->base.unbind_vma = ppgtt_unbind_vma;
1544         ppgtt->base.bind_vma = ppgtt_bind_vma;
1545         ppgtt->base.set_pages = ppgtt_set_pages;
1546         ppgtt->base.clear_pages = clear_pages;
1547         ppgtt->debug_dump = gen8_dump_ppgtt;
1548
1549         return 0;
1550
1551 free_scratch:
1552         gen8_free_scratch(&ppgtt->base);
1553         return ret;
1554 }
1555
1556 static void gen6_dump_ppgtt(struct i915_hw_ppgtt *ppgtt, struct seq_file *m)
1557 {
1558         struct i915_address_space *vm = &ppgtt->base;
1559         struct i915_page_table *unused;
1560         gen6_pte_t scratch_pte;
1561         u32 pd_entry, pte, pde;
1562         u32 start = 0, length = ppgtt->base.total;
1563
1564         scratch_pte = vm->pte_encode(vm->scratch_page.daddr,
1565                                      I915_CACHE_LLC, 0);
1566
1567         gen6_for_each_pde(unused, &ppgtt->pd, start, length, pde) {
1568                 u32 expected;
1569                 gen6_pte_t *pt_vaddr;
1570                 const dma_addr_t pt_addr = px_dma(ppgtt->pd.page_table[pde]);
1571                 pd_entry = readl(ppgtt->pd_addr + pde);
1572                 expected = (GEN6_PDE_ADDR_ENCODE(pt_addr) | GEN6_PDE_VALID);
1573
1574                 if (pd_entry != expected)
1575                         seq_printf(m, "\tPDE #%d mismatch: Actual PDE: %x Expected PDE: %x\n",
1576                                    pde,
1577                                    pd_entry,
1578                                    expected);
1579                 seq_printf(m, "\tPDE: %x\n", pd_entry);
1580
1581                 pt_vaddr = kmap_atomic_px(ppgtt->pd.page_table[pde]);
1582
1583                 for (pte = 0; pte < GEN6_PTES; pte+=4) {
1584                         unsigned long va =
1585                                 (pde * PAGE_SIZE * GEN6_PTES) +
1586                                 (pte * PAGE_SIZE);
1587                         int i;
1588                         bool found = false;
1589                         for (i = 0; i < 4; i++)
1590                                 if (pt_vaddr[pte + i] != scratch_pte)
1591                                         found = true;
1592                         if (!found)
1593                                 continue;
1594
1595                         seq_printf(m, "\t\t0x%lx [%03d,%04d]: =", va, pde, pte);
1596                         for (i = 0; i < 4; i++) {
1597                                 if (pt_vaddr[pte + i] != scratch_pte)
1598                                         seq_printf(m, " %08x", pt_vaddr[pte + i]);
1599                                 else
1600                                         seq_puts(m, "  SCRATCH ");
1601                         }
1602                         seq_puts(m, "\n");
1603                 }
1604                 kunmap_atomic(pt_vaddr);
1605         }
1606 }
1607
1608 /* Write pde (index) from the page directory @pd to the page table @pt */
1609 static inline void gen6_write_pde(const struct i915_hw_ppgtt *ppgtt,
1610                                   const unsigned int pde,
1611                                   const struct i915_page_table *pt)
1612 {
1613         /* Caller needs to make sure the write completes if necessary */
1614         writel_relaxed(GEN6_PDE_ADDR_ENCODE(px_dma(pt)) | GEN6_PDE_VALID,
1615                        ppgtt->pd_addr + pde);
1616 }
1617
1618 /* Write all the page tables found in the ppgtt structure to incrementing page
1619  * directories. */
1620 static void gen6_write_page_range(struct i915_hw_ppgtt *ppgtt,
1621                                   u32 start, u32 length)
1622 {
1623         struct i915_page_table *pt;
1624         unsigned int pde;
1625
1626         gen6_for_each_pde(pt, &ppgtt->pd, start, length, pde)
1627                 gen6_write_pde(ppgtt, pde, pt);
1628
1629         mark_tlbs_dirty(ppgtt);
1630         wmb();
1631 }
1632
1633 static inline u32 get_pd_offset(struct i915_hw_ppgtt *ppgtt)
1634 {
1635         GEM_BUG_ON(ppgtt->pd.base.ggtt_offset & 0x3f);
1636         return ppgtt->pd.base.ggtt_offset << 10;
1637 }
1638
1639 static int hsw_mm_switch(struct i915_hw_ppgtt *ppgtt,
1640                          struct drm_i915_gem_request *req)
1641 {
1642         struct intel_engine_cs *engine = req->engine;
1643         u32 *cs;
1644
1645         /* NB: TLBs must be flushed and invalidated before a switch */
1646         cs = intel_ring_begin(req, 6);
1647         if (IS_ERR(cs))
1648                 return PTR_ERR(cs);
1649
1650         *cs++ = MI_LOAD_REGISTER_IMM(2);
1651         *cs++ = i915_mmio_reg_offset(RING_PP_DIR_DCLV(engine));
1652         *cs++ = PP_DIR_DCLV_2G;
1653         *cs++ = i915_mmio_reg_offset(RING_PP_DIR_BASE(engine));
1654         *cs++ = get_pd_offset(ppgtt);
1655         *cs++ = MI_NOOP;
1656         intel_ring_advance(req, cs);
1657
1658         return 0;
1659 }
1660
1661 static int gen7_mm_switch(struct i915_hw_ppgtt *ppgtt,
1662                           struct drm_i915_gem_request *req)
1663 {
1664         struct intel_engine_cs *engine = req->engine;
1665         u32 *cs;
1666
1667         /* NB: TLBs must be flushed and invalidated before a switch */
1668         cs = intel_ring_begin(req, 6);
1669         if (IS_ERR(cs))
1670                 return PTR_ERR(cs);
1671
1672         *cs++ = MI_LOAD_REGISTER_IMM(2);
1673         *cs++ = i915_mmio_reg_offset(RING_PP_DIR_DCLV(engine));
1674         *cs++ = PP_DIR_DCLV_2G;
1675         *cs++ = i915_mmio_reg_offset(RING_PP_DIR_BASE(engine));
1676         *cs++ = get_pd_offset(ppgtt);
1677         *cs++ = MI_NOOP;
1678         intel_ring_advance(req, cs);
1679
1680         return 0;
1681 }
1682
1683 static int gen6_mm_switch(struct i915_hw_ppgtt *ppgtt,
1684                           struct drm_i915_gem_request *req)
1685 {
1686         struct intel_engine_cs *engine = req->engine;
1687         struct drm_i915_private *dev_priv = req->i915;
1688
1689         I915_WRITE(RING_PP_DIR_DCLV(engine), PP_DIR_DCLV_2G);
1690         I915_WRITE(RING_PP_DIR_BASE(engine), get_pd_offset(ppgtt));
1691         return 0;
1692 }
1693
1694 static void gen8_ppgtt_enable(struct drm_i915_private *dev_priv)
1695 {
1696         struct intel_engine_cs *engine;
1697         enum intel_engine_id id;
1698
1699         for_each_engine(engine, dev_priv, id) {
1700                 u32 four_level = USES_FULL_48BIT_PPGTT(dev_priv) ?
1701                                  GEN8_GFX_PPGTT_48B : 0;
1702                 I915_WRITE(RING_MODE_GEN7(engine),
1703                            _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE | four_level));
1704         }
1705 }
1706
1707 static void gen7_ppgtt_enable(struct drm_i915_private *dev_priv)
1708 {
1709         struct intel_engine_cs *engine;
1710         u32 ecochk, ecobits;
1711         enum intel_engine_id id;
1712
1713         ecobits = I915_READ(GAC_ECO_BITS);
1714         I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_PPGTT_CACHE64B);
1715
1716         ecochk = I915_READ(GAM_ECOCHK);
1717         if (IS_HASWELL(dev_priv)) {
1718                 ecochk |= ECOCHK_PPGTT_WB_HSW;
1719         } else {
1720                 ecochk |= ECOCHK_PPGTT_LLC_IVB;
1721                 ecochk &= ~ECOCHK_PPGTT_GFDT_IVB;
1722         }
1723         I915_WRITE(GAM_ECOCHK, ecochk);
1724
1725         for_each_engine(engine, dev_priv, id) {
1726                 /* GFX_MODE is per-ring on gen7+ */
1727                 I915_WRITE(RING_MODE_GEN7(engine),
1728                            _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1729         }
1730 }
1731
1732 static void gen6_ppgtt_enable(struct drm_i915_private *dev_priv)
1733 {
1734         u32 ecochk, gab_ctl, ecobits;
1735
1736         ecobits = I915_READ(GAC_ECO_BITS);
1737         I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_SNB_BIT |
1738                    ECOBITS_PPGTT_CACHE64B);
1739
1740         gab_ctl = I915_READ(GAB_CTL);
1741         I915_WRITE(GAB_CTL, gab_ctl | GAB_CTL_CONT_AFTER_PAGEFAULT);
1742
1743         ecochk = I915_READ(GAM_ECOCHK);
1744         I915_WRITE(GAM_ECOCHK, ecochk | ECOCHK_SNB_BIT | ECOCHK_PPGTT_CACHE64B);
1745
1746         I915_WRITE(GFX_MODE, _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1747 }
1748
1749 /* PPGTT support for Sandybdrige/Gen6 and later */
1750 static void gen6_ppgtt_clear_range(struct i915_address_space *vm,
1751                                    u64 start, u64 length)
1752 {
1753         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1754         unsigned int first_entry = start >> PAGE_SHIFT;
1755         unsigned int pde = first_entry / GEN6_PTES;
1756         unsigned int pte = first_entry % GEN6_PTES;
1757         unsigned int num_entries = length >> PAGE_SHIFT;
1758         gen6_pte_t scratch_pte =
1759                 vm->pte_encode(vm->scratch_page.daddr, I915_CACHE_LLC, 0);
1760
1761         while (num_entries) {
1762                 struct i915_page_table *pt = ppgtt->pd.page_table[pde++];
1763                 unsigned int end = min(pte + num_entries, GEN6_PTES);
1764                 gen6_pte_t *vaddr;
1765
1766                 num_entries -= end - pte;
1767
1768                 /* Note that the hw doesn't support removing PDE on the fly
1769                  * (they are cached inside the context with no means to
1770                  * invalidate the cache), so we can only reset the PTE
1771                  * entries back to scratch.
1772                  */
1773
1774                 vaddr = kmap_atomic_px(pt);
1775                 do {
1776                         vaddr[pte++] = scratch_pte;
1777                 } while (pte < end);
1778                 kunmap_atomic(vaddr);
1779
1780                 pte = 0;
1781         }
1782 }
1783
1784 static void gen6_ppgtt_insert_entries(struct i915_address_space *vm,
1785                                       struct i915_vma *vma,
1786                                       enum i915_cache_level cache_level,
1787                                       u32 flags)
1788 {
1789         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1790         unsigned first_entry = vma->node.start >> PAGE_SHIFT;
1791         unsigned act_pt = first_entry / GEN6_PTES;
1792         unsigned act_pte = first_entry % GEN6_PTES;
1793         const u32 pte_encode = vm->pte_encode(0, cache_level, flags);
1794         struct sgt_dma iter;
1795         gen6_pte_t *vaddr;
1796
1797         vaddr = kmap_atomic_px(ppgtt->pd.page_table[act_pt]);
1798         iter.sg = vma->pages->sgl;
1799         iter.dma = sg_dma_address(iter.sg);
1800         iter.max = iter.dma + iter.sg->length;
1801         do {
1802                 vaddr[act_pte] = pte_encode | GEN6_PTE_ADDR_ENCODE(iter.dma);
1803
1804                 iter.dma += PAGE_SIZE;
1805                 if (iter.dma == iter.max) {
1806                         iter.sg = __sg_next(iter.sg);
1807                         if (!iter.sg)
1808                                 break;
1809
1810                         iter.dma = sg_dma_address(iter.sg);
1811                         iter.max = iter.dma + iter.sg->length;
1812                 }
1813
1814                 if (++act_pte == GEN6_PTES) {
1815                         kunmap_atomic(vaddr);
1816                         vaddr = kmap_atomic_px(ppgtt->pd.page_table[++act_pt]);
1817                         act_pte = 0;
1818                 }
1819         } while (1);
1820         kunmap_atomic(vaddr);
1821 }
1822
1823 static int gen6_alloc_va_range(struct i915_address_space *vm,
1824                                u64 start, u64 length)
1825 {
1826         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1827         struct i915_page_table *pt;
1828         u64 from = start;
1829         unsigned int pde;
1830         bool flush = false;
1831
1832         gen6_for_each_pde(pt, &ppgtt->pd, start, length, pde) {
1833                 if (pt == vm->scratch_pt) {
1834                         pt = alloc_pt(vm);
1835                         if (IS_ERR(pt))
1836                                 goto unwind_out;
1837
1838                         gen6_initialize_pt(vm, pt);
1839                         ppgtt->pd.page_table[pde] = pt;
1840                         gen6_write_pde(ppgtt, pde, pt);
1841                         flush = true;
1842                 }
1843         }
1844
1845         if (flush) {
1846                 mark_tlbs_dirty(ppgtt);
1847                 wmb();
1848         }
1849
1850         return 0;
1851
1852 unwind_out:
1853         gen6_ppgtt_clear_range(vm, from, start);
1854         return -ENOMEM;
1855 }
1856
1857 static int gen6_init_scratch(struct i915_address_space *vm)
1858 {
1859         int ret;
1860
1861         ret = setup_scratch_page(vm, I915_GFP_DMA);
1862         if (ret)
1863                 return ret;
1864
1865         vm->scratch_pt = alloc_pt(vm);
1866         if (IS_ERR(vm->scratch_pt)) {
1867                 cleanup_scratch_page(vm);
1868                 return PTR_ERR(vm->scratch_pt);
1869         }
1870
1871         gen6_initialize_pt(vm, vm->scratch_pt);
1872
1873         return 0;
1874 }
1875
1876 static void gen6_free_scratch(struct i915_address_space *vm)
1877 {
1878         free_pt(vm, vm->scratch_pt);
1879         cleanup_scratch_page(vm);
1880 }
1881
1882 static void gen6_ppgtt_cleanup(struct i915_address_space *vm)
1883 {
1884         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1885         struct i915_page_directory *pd = &ppgtt->pd;
1886         struct i915_page_table *pt;
1887         u32 pde;
1888
1889         drm_mm_remove_node(&ppgtt->node);
1890
1891         gen6_for_all_pdes(pt, pd, pde)
1892                 if (pt != vm->scratch_pt)
1893                         free_pt(vm, pt);
1894
1895         gen6_free_scratch(vm);
1896 }
1897
1898 static int gen6_ppgtt_allocate_page_directories(struct i915_hw_ppgtt *ppgtt)
1899 {
1900         struct i915_address_space *vm = &ppgtt->base;
1901         struct drm_i915_private *dev_priv = ppgtt->base.i915;
1902         struct i915_ggtt *ggtt = &dev_priv->ggtt;
1903         int ret;
1904
1905         /* PPGTT PDEs reside in the GGTT and consists of 512 entries. The
1906          * allocator works in address space sizes, so it's multiplied by page
1907          * size. We allocate at the top of the GTT to avoid fragmentation.
1908          */
1909         BUG_ON(!drm_mm_initialized(&ggtt->base.mm));
1910
1911         ret = gen6_init_scratch(vm);
1912         if (ret)
1913                 return ret;
1914
1915         ret = i915_gem_gtt_insert(&ggtt->base, &ppgtt->node,
1916                                   GEN6_PD_SIZE, GEN6_PD_ALIGN,
1917                                   I915_COLOR_UNEVICTABLE,
1918                                   0, ggtt->base.total,
1919                                   PIN_HIGH);
1920         if (ret)
1921                 goto err_out;
1922
1923         if (ppgtt->node.start < ggtt->mappable_end)
1924                 DRM_DEBUG("Forced to use aperture for PDEs\n");
1925
1926         ppgtt->pd.base.ggtt_offset =
1927                 ppgtt->node.start / PAGE_SIZE * sizeof(gen6_pte_t);
1928
1929         ppgtt->pd_addr = (gen6_pte_t __iomem *)ggtt->gsm +
1930                 ppgtt->pd.base.ggtt_offset / sizeof(gen6_pte_t);
1931
1932         return 0;
1933
1934 err_out:
1935         gen6_free_scratch(vm);
1936         return ret;
1937 }
1938
1939 static int gen6_ppgtt_alloc(struct i915_hw_ppgtt *ppgtt)
1940 {
1941         return gen6_ppgtt_allocate_page_directories(ppgtt);
1942 }
1943
1944 static void gen6_scratch_va_range(struct i915_hw_ppgtt *ppgtt,
1945                                   u64 start, u64 length)
1946 {
1947         struct i915_page_table *unused;
1948         u32 pde;
1949
1950         gen6_for_each_pde(unused, &ppgtt->pd, start, length, pde)
1951                 ppgtt->pd.page_table[pde] = ppgtt->base.scratch_pt;
1952 }
1953
1954 static int gen6_ppgtt_init(struct i915_hw_ppgtt *ppgtt)
1955 {
1956         struct drm_i915_private *dev_priv = ppgtt->base.i915;
1957         struct i915_ggtt *ggtt = &dev_priv->ggtt;
1958         int ret;
1959
1960         ppgtt->base.pte_encode = ggtt->base.pte_encode;
1961         if (intel_vgpu_active(dev_priv) || IS_GEN6(dev_priv))
1962                 ppgtt->switch_mm = gen6_mm_switch;
1963         else if (IS_HASWELL(dev_priv))
1964                 ppgtt->switch_mm = hsw_mm_switch;
1965         else if (IS_GEN7(dev_priv))
1966                 ppgtt->switch_mm = gen7_mm_switch;
1967         else
1968                 BUG();
1969
1970         ret = gen6_ppgtt_alloc(ppgtt);
1971         if (ret)
1972                 return ret;
1973
1974         ppgtt->base.total = I915_PDES * GEN6_PTES * PAGE_SIZE;
1975
1976         gen6_scratch_va_range(ppgtt, 0, ppgtt->base.total);
1977         gen6_write_page_range(ppgtt, 0, ppgtt->base.total);
1978
1979         ret = gen6_alloc_va_range(&ppgtt->base, 0, ppgtt->base.total);
1980         if (ret) {
1981                 gen6_ppgtt_cleanup(&ppgtt->base);
1982                 return ret;
1983         }
1984
1985         ppgtt->base.clear_range = gen6_ppgtt_clear_range;
1986         ppgtt->base.insert_entries = gen6_ppgtt_insert_entries;
1987         ppgtt->base.unbind_vma = ppgtt_unbind_vma;
1988         ppgtt->base.bind_vma = ppgtt_bind_vma;
1989         ppgtt->base.set_pages = ppgtt_set_pages;
1990         ppgtt->base.clear_pages = clear_pages;
1991         ppgtt->base.cleanup = gen6_ppgtt_cleanup;
1992         ppgtt->debug_dump = gen6_dump_ppgtt;
1993
1994         DRM_DEBUG_DRIVER("Allocated pde space (%lldM) at GTT entry: %llx\n",
1995                          ppgtt->node.size >> 20,
1996                          ppgtt->node.start / PAGE_SIZE);
1997
1998         DRM_DEBUG_DRIVER("Adding PPGTT at offset %x\n",
1999                          ppgtt->pd.base.ggtt_offset << 10);
2000
2001         return 0;
2002 }
2003
2004 static int __hw_ppgtt_init(struct i915_hw_ppgtt *ppgtt,
2005                            struct drm_i915_private *dev_priv)
2006 {
2007         ppgtt->base.i915 = dev_priv;
2008         ppgtt->base.dma = &dev_priv->drm.pdev->dev;
2009
2010         if (INTEL_INFO(dev_priv)->gen < 8)
2011                 return gen6_ppgtt_init(ppgtt);
2012         else
2013                 return gen8_ppgtt_init(ppgtt);
2014 }
2015
2016 static void i915_address_space_init(struct i915_address_space *vm,
2017                                     struct drm_i915_private *dev_priv,
2018                                     const char *name)
2019 {
2020         i915_gem_timeline_init(dev_priv, &vm->timeline, name);
2021
2022         drm_mm_init(&vm->mm, 0, vm->total);
2023         vm->mm.head_node.color = I915_COLOR_UNEVICTABLE;
2024
2025         INIT_LIST_HEAD(&vm->active_list);
2026         INIT_LIST_HEAD(&vm->inactive_list);
2027         INIT_LIST_HEAD(&vm->unbound_list);
2028
2029         list_add_tail(&vm->global_link, &dev_priv->vm_list);
2030         pagevec_init(&vm->free_pages, false);
2031 }
2032
2033 static void i915_address_space_fini(struct i915_address_space *vm)
2034 {
2035         if (pagevec_count(&vm->free_pages))
2036                 vm_free_pages_release(vm, true);
2037
2038         i915_gem_timeline_fini(&vm->timeline);
2039         drm_mm_takedown(&vm->mm);
2040         list_del(&vm->global_link);
2041 }
2042
2043 static void gtt_write_workarounds(struct drm_i915_private *dev_priv)
2044 {
2045         /* This function is for gtt related workarounds. This function is
2046          * called on driver load and after a GPU reset, so you can place
2047          * workarounds here even if they get overwritten by GPU reset.
2048          */
2049         /* WaIncreaseDefaultTLBEntries:chv,bdw,skl,bxt,kbl,glk,cfl,cnl */
2050         if (IS_BROADWELL(dev_priv))
2051                 I915_WRITE(GEN8_L3_LRA_1_GPGPU, GEN8_L3_LRA_1_GPGPU_DEFAULT_VALUE_BDW);
2052         else if (IS_CHERRYVIEW(dev_priv))
2053                 I915_WRITE(GEN8_L3_LRA_1_GPGPU, GEN8_L3_LRA_1_GPGPU_DEFAULT_VALUE_CHV);
2054         else if (IS_GEN9_BC(dev_priv) || IS_GEN10(dev_priv))
2055                 I915_WRITE(GEN8_L3_LRA_1_GPGPU, GEN9_L3_LRA_1_GPGPU_DEFAULT_VALUE_SKL);
2056         else if (IS_GEN9_LP(dev_priv))
2057                 I915_WRITE(GEN8_L3_LRA_1_GPGPU, GEN9_L3_LRA_1_GPGPU_DEFAULT_VALUE_BXT);
2058
2059         /*
2060          * To support 64K PTEs we need to first enable the use of the
2061          * Intermediate-Page-Size(IPS) bit of the PDE field via some magical
2062          * mmio, otherwise the page-walker will simply ignore the IPS bit. This
2063          * shouldn't be needed after GEN10.
2064          *
2065          * 64K pages were first introduced from BDW+, although technically they
2066          * only *work* from gen9+. For pre-BDW we instead have the option for
2067          * 32K pages, but we don't currently have any support for it in our
2068          * driver.
2069          */
2070         if (HAS_PAGE_SIZES(dev_priv, I915_GTT_PAGE_SIZE_64K) &&
2071             INTEL_GEN(dev_priv) <= 10)
2072                 I915_WRITE(GEN8_GAMW_ECO_DEV_RW_IA,
2073                            I915_READ(GEN8_GAMW_ECO_DEV_RW_IA) |
2074                            GAMW_ECO_ENABLE_64K_IPS_FIELD);
2075 }
2076
2077 int i915_ppgtt_init_hw(struct drm_i915_private *dev_priv)
2078 {
2079         gtt_write_workarounds(dev_priv);
2080
2081         /* In the case of execlists, PPGTT is enabled by the context descriptor
2082          * and the PDPs are contained within the context itself.  We don't
2083          * need to do anything here. */
2084         if (i915_modparams.enable_execlists)
2085                 return 0;
2086
2087         if (!USES_PPGTT(dev_priv))
2088                 return 0;
2089
2090         if (IS_GEN6(dev_priv))
2091                 gen6_ppgtt_enable(dev_priv);
2092         else if (IS_GEN7(dev_priv))
2093                 gen7_ppgtt_enable(dev_priv);
2094         else if (INTEL_GEN(dev_priv) >= 8)
2095                 gen8_ppgtt_enable(dev_priv);
2096         else
2097                 MISSING_CASE(INTEL_GEN(dev_priv));
2098
2099         return 0;
2100 }
2101
2102 struct i915_hw_ppgtt *
2103 i915_ppgtt_create(struct drm_i915_private *dev_priv,
2104                   struct drm_i915_file_private *fpriv,
2105                   const char *name)
2106 {
2107         struct i915_hw_ppgtt *ppgtt;
2108         int ret;
2109
2110         ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
2111         if (!ppgtt)
2112                 return ERR_PTR(-ENOMEM);
2113
2114         ret = __hw_ppgtt_init(ppgtt, dev_priv);
2115         if (ret) {
2116                 kfree(ppgtt);
2117                 return ERR_PTR(ret);
2118         }
2119
2120         kref_init(&ppgtt->ref);
2121         i915_address_space_init(&ppgtt->base, dev_priv, name);
2122         ppgtt->base.file = fpriv;
2123
2124         trace_i915_ppgtt_create(&ppgtt->base);
2125
2126         return ppgtt;
2127 }
2128
2129 void i915_ppgtt_close(struct i915_address_space *vm)
2130 {
2131         struct list_head *phases[] = {
2132                 &vm->active_list,
2133                 &vm->inactive_list,
2134                 &vm->unbound_list,
2135                 NULL,
2136         }, **phase;
2137
2138         GEM_BUG_ON(vm->closed);
2139         vm->closed = true;
2140
2141         for (phase = phases; *phase; phase++) {
2142                 struct i915_vma *vma, *vn;
2143
2144                 list_for_each_entry_safe(vma, vn, *phase, vm_link)
2145                         if (!i915_vma_is_closed(vma))
2146                                 i915_vma_close(vma);
2147         }
2148 }
2149
2150 void i915_ppgtt_release(struct kref *kref)
2151 {
2152         struct i915_hw_ppgtt *ppgtt =
2153                 container_of(kref, struct i915_hw_ppgtt, ref);
2154
2155         trace_i915_ppgtt_release(&ppgtt->base);
2156
2157         /* vmas should already be unbound and destroyed */
2158         WARN_ON(!list_empty(&ppgtt->base.active_list));
2159         WARN_ON(!list_empty(&ppgtt->base.inactive_list));
2160         WARN_ON(!list_empty(&ppgtt->base.unbound_list));
2161
2162         ppgtt->base.cleanup(&ppgtt->base);
2163         i915_address_space_fini(&ppgtt->base);
2164         kfree(ppgtt);
2165 }
2166
2167 /* Certain Gen5 chipsets require require idling the GPU before
2168  * unmapping anything from the GTT when VT-d is enabled.
2169  */
2170 static bool needs_idle_maps(struct drm_i915_private *dev_priv)
2171 {
2172         /* Query intel_iommu to see if we need the workaround. Presumably that
2173          * was loaded first.
2174          */
2175         return IS_GEN5(dev_priv) && IS_MOBILE(dev_priv) && intel_vtd_active();
2176 }
2177
2178 void i915_check_and_clear_faults(struct drm_i915_private *dev_priv)
2179 {
2180         struct intel_engine_cs *engine;
2181         enum intel_engine_id id;
2182
2183         if (INTEL_INFO(dev_priv)->gen < 6)
2184                 return;
2185
2186         for_each_engine(engine, dev_priv, id) {
2187                 u32 fault_reg;
2188                 fault_reg = I915_READ(RING_FAULT_REG(engine));
2189                 if (fault_reg & RING_FAULT_VALID) {
2190                         DRM_DEBUG_DRIVER("Unexpected fault\n"
2191                                          "\tAddr: 0x%08lx\n"
2192                                          "\tAddress space: %s\n"
2193                                          "\tSource ID: %d\n"
2194                                          "\tType: %d\n",
2195                                          fault_reg & PAGE_MASK,
2196                                          fault_reg & RING_FAULT_GTTSEL_MASK ? "GGTT" : "PPGTT",
2197                                          RING_FAULT_SRCID(fault_reg),
2198                                          RING_FAULT_FAULT_TYPE(fault_reg));
2199                         I915_WRITE(RING_FAULT_REG(engine),
2200                                    fault_reg & ~RING_FAULT_VALID);
2201                 }
2202         }
2203
2204         /* Engine specific init may not have been done till this point. */
2205         if (dev_priv->engine[RCS])
2206                 POSTING_READ(RING_FAULT_REG(dev_priv->engine[RCS]));
2207 }
2208
2209 void i915_gem_suspend_gtt_mappings(struct drm_i915_private *dev_priv)
2210 {
2211         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2212
2213         /* Don't bother messing with faults pre GEN6 as we have little
2214          * documentation supporting that it's a good idea.
2215          */
2216         if (INTEL_GEN(dev_priv) < 6)
2217                 return;
2218
2219         i915_check_and_clear_faults(dev_priv);
2220
2221         ggtt->base.clear_range(&ggtt->base, 0, ggtt->base.total);
2222
2223         i915_ggtt_invalidate(dev_priv);
2224 }
2225
2226 int i915_gem_gtt_prepare_pages(struct drm_i915_gem_object *obj,
2227                                struct sg_table *pages)
2228 {
2229         do {
2230                 if (dma_map_sg(&obj->base.dev->pdev->dev,
2231                                pages->sgl, pages->nents,
2232                                PCI_DMA_BIDIRECTIONAL))
2233                         return 0;
2234
2235                 /* If the DMA remap fails, one cause can be that we have
2236                  * too many objects pinned in a small remapping table,
2237                  * such as swiotlb. Incrementally purge all other objects and
2238                  * try again - if there are no more pages to remove from
2239                  * the DMA remapper, i915_gem_shrink will return 0.
2240                  */
2241                 GEM_BUG_ON(obj->mm.pages == pages);
2242         } while (i915_gem_shrink(to_i915(obj->base.dev),
2243                                  obj->base.size >> PAGE_SHIFT, NULL,
2244                                  I915_SHRINK_BOUND |
2245                                  I915_SHRINK_UNBOUND |
2246                                  I915_SHRINK_ACTIVE));
2247
2248         return -ENOSPC;
2249 }
2250
2251 static void gen8_set_pte(void __iomem *addr, gen8_pte_t pte)
2252 {
2253         writeq(pte, addr);
2254 }
2255
2256 static void gen8_ggtt_insert_page(struct i915_address_space *vm,
2257                                   dma_addr_t addr,
2258                                   u64 offset,
2259                                   enum i915_cache_level level,
2260                                   u32 unused)
2261 {
2262         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2263         gen8_pte_t __iomem *pte =
2264                 (gen8_pte_t __iomem *)ggtt->gsm + (offset >> PAGE_SHIFT);
2265
2266         gen8_set_pte(pte, gen8_pte_encode(addr, level));
2267
2268         ggtt->invalidate(vm->i915);
2269 }
2270
2271 static void gen8_ggtt_insert_entries(struct i915_address_space *vm,
2272                                      struct i915_vma *vma,
2273                                      enum i915_cache_level level,
2274                                      u32 unused)
2275 {
2276         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2277         struct sgt_iter sgt_iter;
2278         gen8_pte_t __iomem *gtt_entries;
2279         const gen8_pte_t pte_encode = gen8_pte_encode(0, level);
2280         dma_addr_t addr;
2281
2282         gtt_entries = (gen8_pte_t __iomem *)ggtt->gsm;
2283         gtt_entries += vma->node.start >> PAGE_SHIFT;
2284         for_each_sgt_dma(addr, sgt_iter, vma->pages)
2285                 gen8_set_pte(gtt_entries++, pte_encode | addr);
2286
2287         wmb();
2288
2289         /* This next bit makes the above posting read even more important. We
2290          * want to flush the TLBs only after we're certain all the PTE updates
2291          * have finished.
2292          */
2293         ggtt->invalidate(vm->i915);
2294 }
2295
2296 static void gen6_ggtt_insert_page(struct i915_address_space *vm,
2297                                   dma_addr_t addr,
2298                                   u64 offset,
2299                                   enum i915_cache_level level,
2300                                   u32 flags)
2301 {
2302         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2303         gen6_pte_t __iomem *pte =
2304                 (gen6_pte_t __iomem *)ggtt->gsm + (offset >> PAGE_SHIFT);
2305
2306         iowrite32(vm->pte_encode(addr, level, flags), pte);
2307
2308         ggtt->invalidate(vm->i915);
2309 }
2310
2311 /*
2312  * Binds an object into the global gtt with the specified cache level. The object
2313  * will be accessible to the GPU via commands whose operands reference offsets
2314  * within the global GTT as well as accessible by the GPU through the GMADR
2315  * mapped BAR (dev_priv->mm.gtt->gtt).
2316  */
2317 static void gen6_ggtt_insert_entries(struct i915_address_space *vm,
2318                                      struct i915_vma *vma,
2319                                      enum i915_cache_level level,
2320                                      u32 flags)
2321 {
2322         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2323         gen6_pte_t __iomem *entries = (gen6_pte_t __iomem *)ggtt->gsm;
2324         unsigned int i = vma->node.start >> PAGE_SHIFT;
2325         struct sgt_iter iter;
2326         dma_addr_t addr;
2327         for_each_sgt_dma(addr, iter, vma->pages)
2328                 iowrite32(vm->pte_encode(addr, level, flags), &entries[i++]);
2329         wmb();
2330
2331         /* This next bit makes the above posting read even more important. We
2332          * want to flush the TLBs only after we're certain all the PTE updates
2333          * have finished.
2334          */
2335         ggtt->invalidate(vm->i915);
2336 }
2337
2338 static void nop_clear_range(struct i915_address_space *vm,
2339                             u64 start, u64 length)
2340 {
2341 }
2342
2343 static void gen8_ggtt_clear_range(struct i915_address_space *vm,
2344                                   u64 start, u64 length)
2345 {
2346         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2347         unsigned first_entry = start >> PAGE_SHIFT;
2348         unsigned num_entries = length >> PAGE_SHIFT;
2349         const gen8_pte_t scratch_pte =
2350                 gen8_pte_encode(vm->scratch_page.daddr, I915_CACHE_LLC);
2351         gen8_pte_t __iomem *gtt_base =
2352                 (gen8_pte_t __iomem *)ggtt->gsm + first_entry;
2353         const int max_entries = ggtt_total_entries(ggtt) - first_entry;
2354         int i;
2355
2356         if (WARN(num_entries > max_entries,
2357                  "First entry = %d; Num entries = %d (max=%d)\n",
2358                  first_entry, num_entries, max_entries))
2359                 num_entries = max_entries;
2360
2361         for (i = 0; i < num_entries; i++)
2362                 gen8_set_pte(&gtt_base[i], scratch_pte);
2363 }
2364
2365 static void bxt_vtd_ggtt_wa(struct i915_address_space *vm)
2366 {
2367         struct drm_i915_private *dev_priv = vm->i915;
2368
2369         /*
2370          * Make sure the internal GAM fifo has been cleared of all GTT
2371          * writes before exiting stop_machine(). This guarantees that
2372          * any aperture accesses waiting to start in another process
2373          * cannot back up behind the GTT writes causing a hang.
2374          * The register can be any arbitrary GAM register.
2375          */
2376         POSTING_READ(GFX_FLSH_CNTL_GEN6);
2377 }
2378
2379 struct insert_page {
2380         struct i915_address_space *vm;
2381         dma_addr_t addr;
2382         u64 offset;
2383         enum i915_cache_level level;
2384 };
2385
2386 static int bxt_vtd_ggtt_insert_page__cb(void *_arg)
2387 {
2388         struct insert_page *arg = _arg;
2389
2390         gen8_ggtt_insert_page(arg->vm, arg->addr, arg->offset, arg->level, 0);
2391         bxt_vtd_ggtt_wa(arg->vm);
2392
2393         return 0;
2394 }
2395
2396 static void bxt_vtd_ggtt_insert_page__BKL(struct i915_address_space *vm,
2397                                           dma_addr_t addr,
2398                                           u64 offset,
2399                                           enum i915_cache_level level,
2400                                           u32 unused)
2401 {
2402         struct insert_page arg = { vm, addr, offset, level };
2403
2404         stop_machine(bxt_vtd_ggtt_insert_page__cb, &arg, NULL);
2405 }
2406
2407 struct insert_entries {
2408         struct i915_address_space *vm;
2409         struct i915_vma *vma;
2410         enum i915_cache_level level;
2411 };
2412
2413 static int bxt_vtd_ggtt_insert_entries__cb(void *_arg)
2414 {
2415         struct insert_entries *arg = _arg;
2416
2417         gen8_ggtt_insert_entries(arg->vm, arg->vma, arg->level, 0);
2418         bxt_vtd_ggtt_wa(arg->vm);
2419
2420         return 0;
2421 }
2422
2423 static void bxt_vtd_ggtt_insert_entries__BKL(struct i915_address_space *vm,
2424                                              struct i915_vma *vma,
2425                                              enum i915_cache_level level,
2426                                              u32 unused)
2427 {
2428         struct insert_entries arg = { vm, vma, level };
2429
2430         stop_machine(bxt_vtd_ggtt_insert_entries__cb, &arg, NULL);
2431 }
2432
2433 struct clear_range {
2434         struct i915_address_space *vm;
2435         u64 start;
2436         u64 length;
2437 };
2438
2439 static int bxt_vtd_ggtt_clear_range__cb(void *_arg)
2440 {
2441         struct clear_range *arg = _arg;
2442
2443         gen8_ggtt_clear_range(arg->vm, arg->start, arg->length);
2444         bxt_vtd_ggtt_wa(arg->vm);
2445
2446         return 0;
2447 }
2448
2449 static void bxt_vtd_ggtt_clear_range__BKL(struct i915_address_space *vm,
2450                                           u64 start,
2451                                           u64 length)
2452 {
2453         struct clear_range arg = { vm, start, length };
2454
2455         stop_machine(bxt_vtd_ggtt_clear_range__cb, &arg, NULL);
2456 }
2457
2458 static void gen6_ggtt_clear_range(struct i915_address_space *vm,
2459                                   u64 start, u64 length)
2460 {
2461         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2462         unsigned first_entry = start >> PAGE_SHIFT;
2463         unsigned num_entries = length >> PAGE_SHIFT;
2464         gen6_pte_t scratch_pte, __iomem *gtt_base =
2465                 (gen6_pte_t __iomem *)ggtt->gsm + first_entry;
2466         const int max_entries = ggtt_total_entries(ggtt) - first_entry;
2467         int i;
2468
2469         if (WARN(num_entries > max_entries,
2470                  "First entry = %d; Num entries = %d (max=%d)\n",
2471                  first_entry, num_entries, max_entries))
2472                 num_entries = max_entries;
2473
2474         scratch_pte = vm->pte_encode(vm->scratch_page.daddr,
2475                                      I915_CACHE_LLC, 0);
2476
2477         for (i = 0; i < num_entries; i++)
2478                 iowrite32(scratch_pte, &gtt_base[i]);
2479 }
2480
2481 static void i915_ggtt_insert_page(struct i915_address_space *vm,
2482                                   dma_addr_t addr,
2483                                   u64 offset,
2484                                   enum i915_cache_level cache_level,
2485                                   u32 unused)
2486 {
2487         unsigned int flags = (cache_level == I915_CACHE_NONE) ?
2488                 AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
2489
2490         intel_gtt_insert_page(addr, offset >> PAGE_SHIFT, flags);
2491 }
2492
2493 static void i915_ggtt_insert_entries(struct i915_address_space *vm,
2494                                      struct i915_vma *vma,
2495                                      enum i915_cache_level cache_level,
2496                                      u32 unused)
2497 {
2498         unsigned int flags = (cache_level == I915_CACHE_NONE) ?
2499                 AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
2500
2501         intel_gtt_insert_sg_entries(vma->pages, vma->node.start >> PAGE_SHIFT,
2502                                     flags);
2503 }
2504
2505 static void i915_ggtt_clear_range(struct i915_address_space *vm,
2506                                   u64 start, u64 length)
2507 {
2508         intel_gtt_clear_range(start >> PAGE_SHIFT, length >> PAGE_SHIFT);
2509 }
2510
2511 static int ggtt_bind_vma(struct i915_vma *vma,
2512                          enum i915_cache_level cache_level,
2513                          u32 flags)
2514 {
2515         struct drm_i915_private *i915 = vma->vm->i915;
2516         struct drm_i915_gem_object *obj = vma->obj;
2517         u32 pte_flags;
2518
2519         /* Currently applicable only to VLV */
2520         pte_flags = 0;
2521         if (obj->gt_ro)
2522                 pte_flags |= PTE_READ_ONLY;
2523
2524         intel_runtime_pm_get(i915);
2525         vma->vm->insert_entries(vma->vm, vma, cache_level, pte_flags);
2526         intel_runtime_pm_put(i915);
2527
2528         /*
2529          * Without aliasing PPGTT there's no difference between
2530          * GLOBAL/LOCAL_BIND, it's all the same ptes. Hence unconditionally
2531          * upgrade to both bound if we bind either to avoid double-binding.
2532          */
2533         vma->flags |= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
2534
2535         return 0;
2536 }
2537
2538 static void ggtt_unbind_vma(struct i915_vma *vma)
2539 {
2540         struct drm_i915_private *i915 = vma->vm->i915;
2541
2542         intel_runtime_pm_get(i915);
2543         vma->vm->clear_range(vma->vm, vma->node.start, vma->size);
2544         intel_runtime_pm_put(i915);
2545 }
2546
2547 static int aliasing_gtt_bind_vma(struct i915_vma *vma,
2548                                  enum i915_cache_level cache_level,
2549                                  u32 flags)
2550 {
2551         struct drm_i915_private *i915 = vma->vm->i915;
2552         u32 pte_flags;
2553         int ret;
2554
2555         /* Currently applicable only to VLV */
2556         pte_flags = 0;
2557         if (vma->obj->gt_ro)
2558                 pte_flags |= PTE_READ_ONLY;
2559
2560         if (flags & I915_VMA_LOCAL_BIND) {
2561                 struct i915_hw_ppgtt *appgtt = i915->mm.aliasing_ppgtt;
2562
2563                 if (!(vma->flags & I915_VMA_LOCAL_BIND) &&
2564                     appgtt->base.allocate_va_range) {
2565                         ret = appgtt->base.allocate_va_range(&appgtt->base,
2566                                                              vma->node.start,
2567                                                              vma->size);
2568                         if (ret)
2569                                 return ret;
2570                 }
2571
2572                 appgtt->base.insert_entries(&appgtt->base, vma, cache_level,
2573                                             pte_flags);
2574         }
2575
2576         if (flags & I915_VMA_GLOBAL_BIND) {
2577                 intel_runtime_pm_get(i915);
2578                 vma->vm->insert_entries(vma->vm, vma, cache_level, pte_flags);
2579                 intel_runtime_pm_put(i915);
2580         }
2581
2582         return 0;
2583 }
2584
2585 static void aliasing_gtt_unbind_vma(struct i915_vma *vma)
2586 {
2587         struct drm_i915_private *i915 = vma->vm->i915;
2588
2589         if (vma->flags & I915_VMA_GLOBAL_BIND) {
2590                 intel_runtime_pm_get(i915);
2591                 vma->vm->clear_range(vma->vm, vma->node.start, vma->size);
2592                 intel_runtime_pm_put(i915);
2593         }
2594
2595         if (vma->flags & I915_VMA_LOCAL_BIND) {
2596                 struct i915_address_space *vm = &i915->mm.aliasing_ppgtt->base;
2597
2598                 vm->clear_range(vm, vma->node.start, vma->size);
2599         }
2600 }
2601
2602 void i915_gem_gtt_finish_pages(struct drm_i915_gem_object *obj,
2603                                struct sg_table *pages)
2604 {
2605         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2606         struct device *kdev = &dev_priv->drm.pdev->dev;
2607         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2608
2609         if (unlikely(ggtt->do_idle_maps)) {
2610                 if (i915_gem_wait_for_idle(dev_priv, 0)) {
2611                         DRM_ERROR("Failed to wait for idle; VT'd may hang.\n");
2612                         /* Wait a bit, in hopes it avoids the hang */
2613                         udelay(10);
2614                 }
2615         }
2616
2617         dma_unmap_sg(kdev, pages->sgl, pages->nents, PCI_DMA_BIDIRECTIONAL);
2618 }
2619
2620 static int ggtt_set_pages(struct i915_vma *vma)
2621 {
2622         int ret;
2623
2624         GEM_BUG_ON(vma->pages);
2625
2626         ret = i915_get_ggtt_vma_pages(vma);
2627         if (ret)
2628                 return ret;
2629
2630         vma->page_sizes = vma->obj->mm.page_sizes;
2631
2632         return 0;
2633 }
2634
2635 static void i915_gtt_color_adjust(const struct drm_mm_node *node,
2636                                   unsigned long color,
2637                                   u64 *start,
2638                                   u64 *end)
2639 {
2640         if (node->allocated && node->color != color)
2641                 *start += I915_GTT_PAGE_SIZE;
2642
2643         /* Also leave a space between the unallocated reserved node after the
2644          * GTT and any objects within the GTT, i.e. we use the color adjustment
2645          * to insert a guard page to prevent prefetches crossing over the
2646          * GTT boundary.
2647          */
2648         node = list_next_entry(node, node_list);
2649         if (node->color != color)
2650                 *end -= I915_GTT_PAGE_SIZE;
2651 }
2652
2653 int i915_gem_init_aliasing_ppgtt(struct drm_i915_private *i915)
2654 {
2655         struct i915_ggtt *ggtt = &i915->ggtt;
2656         struct i915_hw_ppgtt *ppgtt;
2657         int err;
2658
2659         ppgtt = i915_ppgtt_create(i915, ERR_PTR(-EPERM), "[alias]");
2660         if (IS_ERR(ppgtt))
2661                 return PTR_ERR(ppgtt);
2662
2663         if (WARN_ON(ppgtt->base.total < ggtt->base.total)) {
2664                 err = -ENODEV;
2665                 goto err_ppgtt;
2666         }
2667
2668         if (ppgtt->base.allocate_va_range) {
2669                 /* Note we only pre-allocate as far as the end of the global
2670                  * GTT. On 48b / 4-level page-tables, the difference is very,
2671                  * very significant! We have to preallocate as GVT/vgpu does
2672                  * not like the page directory disappearing.
2673                  */
2674                 err = ppgtt->base.allocate_va_range(&ppgtt->base,
2675                                                     0, ggtt->base.total);
2676                 if (err)
2677                         goto err_ppgtt;
2678         }
2679
2680         i915->mm.aliasing_ppgtt = ppgtt;
2681
2682         WARN_ON(ggtt->base.bind_vma != ggtt_bind_vma);
2683         ggtt->base.bind_vma = aliasing_gtt_bind_vma;
2684
2685         WARN_ON(ggtt->base.unbind_vma != ggtt_unbind_vma);
2686         ggtt->base.unbind_vma = aliasing_gtt_unbind_vma;
2687
2688         return 0;
2689
2690 err_ppgtt:
2691         i915_ppgtt_put(ppgtt);
2692         return err;
2693 }
2694
2695 void i915_gem_fini_aliasing_ppgtt(struct drm_i915_private *i915)
2696 {
2697         struct i915_ggtt *ggtt = &i915->ggtt;
2698         struct i915_hw_ppgtt *ppgtt;
2699
2700         ppgtt = fetch_and_zero(&i915->mm.aliasing_ppgtt);
2701         if (!ppgtt)
2702                 return;
2703
2704         i915_ppgtt_put(ppgtt);
2705
2706         ggtt->base.bind_vma = ggtt_bind_vma;
2707         ggtt->base.unbind_vma = ggtt_unbind_vma;
2708 }
2709
2710 int i915_gem_init_ggtt(struct drm_i915_private *dev_priv)
2711 {
2712         /* Let GEM Manage all of the aperture.
2713          *
2714          * However, leave one page at the end still bound to the scratch page.
2715          * There are a number of places where the hardware apparently prefetches
2716          * past the end of the object, and we've seen multiple hangs with the
2717          * GPU head pointer stuck in a batchbuffer bound at the last page of the
2718          * aperture.  One page should be enough to keep any prefetching inside
2719          * of the aperture.
2720          */
2721         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2722         unsigned long hole_start, hole_end;
2723         struct drm_mm_node *entry;
2724         int ret;
2725
2726         ret = intel_vgt_balloon(dev_priv);
2727         if (ret)
2728                 return ret;
2729
2730         /* Reserve a mappable slot for our lockless error capture */
2731         ret = drm_mm_insert_node_in_range(&ggtt->base.mm, &ggtt->error_capture,
2732                                           PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
2733                                           0, ggtt->mappable_end,
2734                                           DRM_MM_INSERT_LOW);
2735         if (ret)
2736                 return ret;
2737
2738         /* Clear any non-preallocated blocks */
2739         drm_mm_for_each_hole(entry, &ggtt->base.mm, hole_start, hole_end) {
2740                 DRM_DEBUG_KMS("clearing unused GTT space: [%lx, %lx]\n",
2741                               hole_start, hole_end);
2742                 ggtt->base.clear_range(&ggtt->base, hole_start,
2743                                        hole_end - hole_start);
2744         }
2745
2746         /* And finally clear the reserved guard page */
2747         ggtt->base.clear_range(&ggtt->base,
2748                                ggtt->base.total - PAGE_SIZE, PAGE_SIZE);
2749
2750         if (USES_PPGTT(dev_priv) && !USES_FULL_PPGTT(dev_priv)) {
2751                 ret = i915_gem_init_aliasing_ppgtt(dev_priv);
2752                 if (ret)
2753                         goto err;
2754         }
2755
2756         return 0;
2757
2758 err:
2759         drm_mm_remove_node(&ggtt->error_capture);
2760         return ret;
2761 }
2762
2763 /**
2764  * i915_ggtt_cleanup_hw - Clean up GGTT hardware initialization
2765  * @dev_priv: i915 device
2766  */
2767 void i915_ggtt_cleanup_hw(struct drm_i915_private *dev_priv)
2768 {
2769         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2770         struct i915_vma *vma, *vn;
2771         struct pagevec *pvec;
2772
2773         ggtt->base.closed = true;
2774
2775         mutex_lock(&dev_priv->drm.struct_mutex);
2776         WARN_ON(!list_empty(&ggtt->base.active_list));
2777         list_for_each_entry_safe(vma, vn, &ggtt->base.inactive_list, vm_link)
2778                 WARN_ON(i915_vma_unbind(vma));
2779         mutex_unlock(&dev_priv->drm.struct_mutex);
2780
2781         i915_gem_cleanup_stolen(&dev_priv->drm);
2782
2783         mutex_lock(&dev_priv->drm.struct_mutex);
2784         i915_gem_fini_aliasing_ppgtt(dev_priv);
2785
2786         if (drm_mm_node_allocated(&ggtt->error_capture))
2787                 drm_mm_remove_node(&ggtt->error_capture);
2788
2789         if (drm_mm_initialized(&ggtt->base.mm)) {
2790                 intel_vgt_deballoon(dev_priv);
2791                 i915_address_space_fini(&ggtt->base);
2792         }
2793
2794         ggtt->base.cleanup(&ggtt->base);
2795
2796         pvec = &dev_priv->mm.wc_stash;
2797         if (pvec->nr) {
2798                 set_pages_array_wb(pvec->pages, pvec->nr);
2799                 __pagevec_release(pvec);
2800         }
2801
2802         mutex_unlock(&dev_priv->drm.struct_mutex);
2803
2804         arch_phys_wc_del(ggtt->mtrr);
2805         io_mapping_fini(&ggtt->mappable);
2806 }
2807
2808 static unsigned int gen6_get_total_gtt_size(u16 snb_gmch_ctl)
2809 {
2810         snb_gmch_ctl >>= SNB_GMCH_GGMS_SHIFT;
2811         snb_gmch_ctl &= SNB_GMCH_GGMS_MASK;
2812         return snb_gmch_ctl << 20;
2813 }
2814
2815 static unsigned int gen8_get_total_gtt_size(u16 bdw_gmch_ctl)
2816 {
2817         bdw_gmch_ctl >>= BDW_GMCH_GGMS_SHIFT;
2818         bdw_gmch_ctl &= BDW_GMCH_GGMS_MASK;
2819         if (bdw_gmch_ctl)
2820                 bdw_gmch_ctl = 1 << bdw_gmch_ctl;
2821
2822 #ifdef CONFIG_X86_32
2823         /* Limit 32b platforms to a 2GB GGTT: 4 << 20 / pte size * PAGE_SIZE */
2824         if (bdw_gmch_ctl > 4)
2825                 bdw_gmch_ctl = 4;
2826 #endif
2827
2828         return bdw_gmch_ctl << 20;
2829 }
2830
2831 static unsigned int chv_get_total_gtt_size(u16 gmch_ctrl)
2832 {
2833         gmch_ctrl >>= SNB_GMCH_GGMS_SHIFT;
2834         gmch_ctrl &= SNB_GMCH_GGMS_MASK;
2835
2836         if (gmch_ctrl)
2837                 return 1 << (20 + gmch_ctrl);
2838
2839         return 0;
2840 }
2841
2842 static size_t gen6_get_stolen_size(u16 snb_gmch_ctl)
2843 {
2844         snb_gmch_ctl >>= SNB_GMCH_GMS_SHIFT;
2845         snb_gmch_ctl &= SNB_GMCH_GMS_MASK;
2846         return (size_t)snb_gmch_ctl << 25; /* 32 MB units */
2847 }
2848
2849 static size_t gen8_get_stolen_size(u16 bdw_gmch_ctl)
2850 {
2851         bdw_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
2852         bdw_gmch_ctl &= BDW_GMCH_GMS_MASK;
2853         return (size_t)bdw_gmch_ctl << 25; /* 32 MB units */
2854 }
2855
2856 static size_t chv_get_stolen_size(u16 gmch_ctrl)
2857 {
2858         gmch_ctrl >>= SNB_GMCH_GMS_SHIFT;
2859         gmch_ctrl &= SNB_GMCH_GMS_MASK;
2860
2861         /*
2862          * 0x0  to 0x10: 32MB increments starting at 0MB
2863          * 0x11 to 0x16: 4MB increments starting at 8MB
2864          * 0x17 to 0x1d: 4MB increments start at 36MB
2865          */
2866         if (gmch_ctrl < 0x11)
2867                 return (size_t)gmch_ctrl << 25;
2868         else if (gmch_ctrl < 0x17)
2869                 return (size_t)(gmch_ctrl - 0x11 + 2) << 22;
2870         else
2871                 return (size_t)(gmch_ctrl - 0x17 + 9) << 22;
2872 }
2873
2874 static size_t gen9_get_stolen_size(u16 gen9_gmch_ctl)
2875 {
2876         gen9_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
2877         gen9_gmch_ctl &= BDW_GMCH_GMS_MASK;
2878
2879         if (gen9_gmch_ctl < 0xf0)
2880                 return (size_t)gen9_gmch_ctl << 25; /* 32 MB units */
2881         else
2882                 /* 4MB increments starting at 0xf0 for 4MB */
2883                 return (size_t)(gen9_gmch_ctl - 0xf0 + 1) << 22;
2884 }
2885
2886 static int ggtt_probe_common(struct i915_ggtt *ggtt, u64 size)
2887 {
2888         struct drm_i915_private *dev_priv = ggtt->base.i915;
2889         struct pci_dev *pdev = dev_priv->drm.pdev;
2890         phys_addr_t phys_addr;
2891         int ret;
2892
2893         /* For Modern GENs the PTEs and register space are split in the BAR */
2894         phys_addr = pci_resource_start(pdev, 0) + pci_resource_len(pdev, 0) / 2;
2895
2896         /*
2897          * On BXT+/CNL+ writes larger than 64 bit to the GTT pagetable range
2898          * will be dropped. For WC mappings in general we have 64 byte burst
2899          * writes when the WC buffer is flushed, so we can't use it, but have to
2900          * resort to an uncached mapping. The WC issue is easily caught by the
2901          * readback check when writing GTT PTE entries.
2902          */
2903         if (IS_GEN9_LP(dev_priv) || INTEL_GEN(dev_priv) >= 10)
2904                 ggtt->gsm = ioremap_nocache(phys_addr, size);
2905         else
2906                 ggtt->gsm = ioremap_wc(phys_addr, size);
2907         if (!ggtt->gsm) {
2908                 DRM_ERROR("Failed to map the ggtt page table\n");
2909                 return -ENOMEM;
2910         }
2911
2912         ret = setup_scratch_page(&ggtt->base, GFP_DMA32);
2913         if (ret) {
2914                 DRM_ERROR("Scratch setup failed\n");
2915                 /* iounmap will also get called at remove, but meh */
2916                 iounmap(ggtt->gsm);
2917                 return ret;
2918         }
2919
2920         return 0;
2921 }
2922
2923 static struct intel_ppat_entry *
2924 __alloc_ppat_entry(struct intel_ppat *ppat, unsigned int index, u8 value)
2925 {
2926         struct intel_ppat_entry *entry = &ppat->entries[index];
2927
2928         GEM_BUG_ON(index >= ppat->max_entries);
2929         GEM_BUG_ON(test_bit(index, ppat->used));
2930
2931         entry->ppat = ppat;
2932         entry->value = value;
2933         kref_init(&entry->ref);
2934         set_bit(index, ppat->used);
2935         set_bit(index, ppat->dirty);
2936
2937         return entry;
2938 }
2939
2940 static void __free_ppat_entry(struct intel_ppat_entry *entry)
2941 {
2942         struct intel_ppat *ppat = entry->ppat;
2943         unsigned int index = entry - ppat->entries;
2944
2945         GEM_BUG_ON(index >= ppat->max_entries);
2946         GEM_BUG_ON(!test_bit(index, ppat->used));
2947
2948         entry->value = ppat->clear_value;
2949         clear_bit(index, ppat->used);
2950         set_bit(index, ppat->dirty);
2951 }
2952
2953 /**
2954  * intel_ppat_get - get a usable PPAT entry
2955  * @i915: i915 device instance
2956  * @value: the PPAT value required by the caller
2957  *
2958  * The function tries to search if there is an existing PPAT entry which
2959  * matches with the required value. If perfectly matched, the existing PPAT
2960  * entry will be used. If only partially matched, it will try to check if
2961  * there is any available PPAT index. If yes, it will allocate a new PPAT
2962  * index for the required entry and update the HW. If not, the partially
2963  * matched entry will be used.
2964  */
2965 const struct intel_ppat_entry *
2966 intel_ppat_get(struct drm_i915_private *i915, u8 value)
2967 {
2968         struct intel_ppat *ppat = &i915->ppat;
2969         struct intel_ppat_entry *entry;
2970         unsigned int scanned, best_score;
2971         int i;
2972
2973         GEM_BUG_ON(!ppat->max_entries);
2974
2975         scanned = best_score = 0;
2976         for_each_set_bit(i, ppat->used, ppat->max_entries) {
2977                 unsigned int score;
2978
2979                 score = ppat->match(ppat->entries[i].value, value);
2980                 if (score > best_score) {
2981                         entry = &ppat->entries[i];
2982                         if (score == INTEL_PPAT_PERFECT_MATCH) {
2983                                 kref_get(&entry->ref);
2984                                 return entry;
2985                         }
2986                         best_score = score;
2987                 }
2988                 scanned++;
2989         }
2990
2991         if (scanned == ppat->max_entries) {
2992                 if (!best_score)
2993                         return ERR_PTR(-ENOSPC);
2994
2995                 kref_get(&entry->ref);
2996                 return entry;
2997         }
2998
2999         i = find_first_zero_bit(ppat->used, ppat->max_entries);
3000         entry = __alloc_ppat_entry(ppat, i, value);
3001         ppat->update_hw(i915);
3002         return entry;
3003 }
3004
3005 static void release_ppat(struct kref *kref)
3006 {
3007         struct intel_ppat_entry *entry =
3008                 container_of(kref, struct intel_ppat_entry, ref);
3009         struct drm_i915_private *i915 = entry->ppat->i915;
3010
3011         __free_ppat_entry(entry);
3012         entry->ppat->update_hw(i915);
3013 }
3014
3015 /**
3016  * intel_ppat_put - put back the PPAT entry got from intel_ppat_get()
3017  * @entry: an intel PPAT entry
3018  *
3019  * Put back the PPAT entry got from intel_ppat_get(). If the PPAT index of the
3020  * entry is dynamically allocated, its reference count will be decreased. Once
3021  * the reference count becomes into zero, the PPAT index becomes free again.
3022  */
3023 void intel_ppat_put(const struct intel_ppat_entry *entry)
3024 {
3025         struct intel_ppat *ppat = entry->ppat;
3026         unsigned int index = entry - ppat->entries;
3027
3028         GEM_BUG_ON(!ppat->max_entries);
3029
3030         kref_put(&ppat->entries[index].ref, release_ppat);
3031 }
3032
3033 static void cnl_private_pat_update_hw(struct drm_i915_private *dev_priv)
3034 {
3035         struct intel_ppat *ppat = &dev_priv->ppat;
3036         int i;
3037
3038         for_each_set_bit(i, ppat->dirty, ppat->max_entries) {
3039                 I915_WRITE(GEN10_PAT_INDEX(i), ppat->entries[i].value);
3040                 clear_bit(i, ppat->dirty);
3041         }
3042 }
3043
3044 static void bdw_private_pat_update_hw(struct drm_i915_private *dev_priv)
3045 {
3046         struct intel_ppat *ppat = &dev_priv->ppat;
3047         u64 pat = 0;
3048         int i;
3049
3050         for (i = 0; i < ppat->max_entries; i++)
3051                 pat |= GEN8_PPAT(i, ppat->entries[i].value);
3052
3053         bitmap_clear(ppat->dirty, 0, ppat->max_entries);
3054
3055         I915_WRITE(GEN8_PRIVATE_PAT_LO, lower_32_bits(pat));
3056         I915_WRITE(GEN8_PRIVATE_PAT_HI, upper_32_bits(pat));
3057 }
3058
3059 static unsigned int bdw_private_pat_match(u8 src, u8 dst)
3060 {
3061         unsigned int score = 0;
3062         enum {
3063                 AGE_MATCH = BIT(0),
3064                 TC_MATCH = BIT(1),
3065                 CA_MATCH = BIT(2),
3066         };
3067
3068         /* Cache attribute has to be matched. */
3069         if (GEN8_PPAT_GET_CA(src) != GEN8_PPAT_GET_CA(dst))
3070                 return 0;
3071
3072         score |= CA_MATCH;
3073
3074         if (GEN8_PPAT_GET_TC(src) == GEN8_PPAT_GET_TC(dst))
3075                 score |= TC_MATCH;
3076
3077         if (GEN8_PPAT_GET_AGE(src) == GEN8_PPAT_GET_AGE(dst))
3078                 score |= AGE_MATCH;
3079
3080         if (score == (AGE_MATCH | TC_MATCH | CA_MATCH))
3081                 return INTEL_PPAT_PERFECT_MATCH;
3082
3083         return score;
3084 }
3085
3086 static unsigned int chv_private_pat_match(u8 src, u8 dst)
3087 {
3088         return (CHV_PPAT_GET_SNOOP(src) == CHV_PPAT_GET_SNOOP(dst)) ?
3089                 INTEL_PPAT_PERFECT_MATCH : 0;
3090 }
3091
3092 static void cnl_setup_private_ppat(struct intel_ppat *ppat)
3093 {
3094         ppat->max_entries = 8;
3095         ppat->update_hw = cnl_private_pat_update_hw;
3096         ppat->match = bdw_private_pat_match;
3097         ppat->clear_value = GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(3);
3098
3099         /* XXX: spec is unclear if this is still needed for CNL+ */
3100         if (!USES_PPGTT(ppat->i915)) {
3101                 __alloc_ppat_entry(ppat, 0, GEN8_PPAT_UC);
3102                 return;
3103         }
3104
3105         __alloc_ppat_entry(ppat, 0, GEN8_PPAT_WB | GEN8_PPAT_LLC);
3106         __alloc_ppat_entry(ppat, 1, GEN8_PPAT_WC | GEN8_PPAT_LLCELLC);
3107         __alloc_ppat_entry(ppat, 2, GEN8_PPAT_WT | GEN8_PPAT_LLCELLC);
3108         __alloc_ppat_entry(ppat, 3, GEN8_PPAT_UC);
3109         __alloc_ppat_entry(ppat, 4, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(0));
3110         __alloc_ppat_entry(ppat, 5, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(1));
3111         __alloc_ppat_entry(ppat, 6, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(2));
3112         __alloc_ppat_entry(ppat, 7, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(3));
3113 }
3114
3115 /* The GGTT and PPGTT need a private PPAT setup in order to handle cacheability
3116  * bits. When using advanced contexts each context stores its own PAT, but
3117  * writing this data shouldn't be harmful even in those cases. */
3118 static void bdw_setup_private_ppat(struct intel_ppat *ppat)
3119 {
3120         ppat->max_entries = 8;
3121         ppat->update_hw = bdw_private_pat_update_hw;
3122         ppat->match = bdw_private_pat_match;
3123         ppat->clear_value = GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(3);
3124
3125         if (!USES_PPGTT(ppat->i915)) {
3126                 /* Spec: "For GGTT, there is NO pat_sel[2:0] from the entry,
3127                  * so RTL will always use the value corresponding to
3128                  * pat_sel = 000".
3129                  * So let's disable cache for GGTT to avoid screen corruptions.
3130                  * MOCS still can be used though.
3131                  * - System agent ggtt writes (i.e. cpu gtt mmaps) already work
3132                  * before this patch, i.e. the same uncached + snooping access
3133                  * like on gen6/7 seems to be in effect.
3134                  * - So this just fixes blitter/render access. Again it looks
3135                  * like it's not just uncached access, but uncached + snooping.
3136                  * So we can still hold onto all our assumptions wrt cpu
3137                  * clflushing on LLC machines.
3138                  */
3139                 __alloc_ppat_entry(ppat, 0, GEN8_PPAT_UC);
3140                 return;
3141         }
3142
3143         __alloc_ppat_entry(ppat, 0, GEN8_PPAT_WB | GEN8_PPAT_LLC);      /* for normal objects, no eLLC */
3144         __alloc_ppat_entry(ppat, 1, GEN8_PPAT_WC | GEN8_PPAT_LLCELLC);  /* for something pointing to ptes? */
3145         __alloc_ppat_entry(ppat, 2, GEN8_PPAT_WT | GEN8_PPAT_LLCELLC);  /* for scanout with eLLC */
3146         __alloc_ppat_entry(ppat, 3, GEN8_PPAT_UC);                      /* Uncached objects, mostly for scanout */
3147         __alloc_ppat_entry(ppat, 4, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(0));
3148         __alloc_ppat_entry(ppat, 5, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(1));
3149         __alloc_ppat_entry(ppat, 6, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(2));
3150         __alloc_ppat_entry(ppat, 7, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(3));
3151 }
3152
3153 static void chv_setup_private_ppat(struct intel_ppat *ppat)
3154 {
3155         ppat->max_entries = 8;
3156         ppat->update_hw = bdw_private_pat_update_hw;
3157         ppat->match = chv_private_pat_match;
3158         ppat->clear_value = CHV_PPAT_SNOOP;
3159
3160         /*
3161          * Map WB on BDW to snooped on CHV.
3162          *
3163          * Only the snoop bit has meaning for CHV, the rest is
3164          * ignored.
3165          *
3166          * The hardware will never snoop for certain types of accesses:
3167          * - CPU GTT (GMADR->GGTT->no snoop->memory)
3168          * - PPGTT page tables
3169          * - some other special cycles
3170          *
3171          * As with BDW, we also need to consider the following for GT accesses:
3172          * "For GGTT, there is NO pat_sel[2:0] from the entry,
3173          * so RTL will always use the value corresponding to
3174          * pat_sel = 000".
3175          * Which means we must set the snoop bit in PAT entry 0
3176          * in order to keep the global status page working.
3177          */
3178
3179         __alloc_ppat_entry(ppat, 0, CHV_PPAT_SNOOP);
3180         __alloc_ppat_entry(ppat, 1, 0);
3181         __alloc_ppat_entry(ppat, 2, 0);
3182         __alloc_ppat_entry(ppat, 3, 0);
3183         __alloc_ppat_entry(ppat, 4, CHV_PPAT_SNOOP);
3184         __alloc_ppat_entry(ppat, 5, CHV_PPAT_SNOOP);
3185         __alloc_ppat_entry(ppat, 6, CHV_PPAT_SNOOP);
3186         __alloc_ppat_entry(ppat, 7, CHV_PPAT_SNOOP);
3187 }
3188
3189 static void gen6_gmch_remove(struct i915_address_space *vm)
3190 {
3191         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
3192
3193         iounmap(ggtt->gsm);
3194         cleanup_scratch_page(vm);
3195 }
3196
3197 static void setup_private_pat(struct drm_i915_private *dev_priv)
3198 {
3199         struct intel_ppat *ppat = &dev_priv->ppat;
3200         int i;
3201
3202         ppat->i915 = dev_priv;
3203
3204         if (INTEL_GEN(dev_priv) >= 10)
3205                 cnl_setup_private_ppat(ppat);
3206         else if (IS_CHERRYVIEW(dev_priv) || IS_GEN9_LP(dev_priv))
3207                 chv_setup_private_ppat(ppat);
3208         else
3209                 bdw_setup_private_ppat(ppat);
3210
3211         GEM_BUG_ON(ppat->max_entries > INTEL_MAX_PPAT_ENTRIES);
3212
3213         for_each_clear_bit(i, ppat->used, ppat->max_entries) {
3214                 ppat->entries[i].value = ppat->clear_value;
3215                 ppat->entries[i].ppat = ppat;
3216                 set_bit(i, ppat->dirty);
3217         }
3218
3219         ppat->update_hw(dev_priv);
3220 }
3221
3222 static int gen8_gmch_probe(struct i915_ggtt *ggtt)
3223 {
3224         struct drm_i915_private *dev_priv = ggtt->base.i915;
3225         struct pci_dev *pdev = dev_priv->drm.pdev;
3226         unsigned int size;
3227         u16 snb_gmch_ctl;
3228         int err;
3229
3230         /* TODO: We're not aware of mappable constraints on gen8 yet */
3231         ggtt->mappable_base = pci_resource_start(pdev, 2);
3232         ggtt->mappable_end = pci_resource_len(pdev, 2);
3233
3234         err = pci_set_dma_mask(pdev, DMA_BIT_MASK(39));
3235         if (!err)
3236                 err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(39));
3237         if (err)
3238                 DRM_ERROR("Can't set DMA mask/consistent mask (%d)\n", err);
3239
3240         pci_read_config_word(pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
3241
3242         if (INTEL_GEN(dev_priv) >= 9) {
3243                 ggtt->stolen_size = gen9_get_stolen_size(snb_gmch_ctl);
3244                 size = gen8_get_total_gtt_size(snb_gmch_ctl);
3245         } else if (IS_CHERRYVIEW(dev_priv)) {
3246                 ggtt->stolen_size = chv_get_stolen_size(snb_gmch_ctl);
3247                 size = chv_get_total_gtt_size(snb_gmch_ctl);
3248         } else {
3249                 ggtt->stolen_size = gen8_get_stolen_size(snb_gmch_ctl);
3250                 size = gen8_get_total_gtt_size(snb_gmch_ctl);
3251         }
3252
3253         ggtt->base.total = (size / sizeof(gen8_pte_t)) << PAGE_SHIFT;
3254         ggtt->base.cleanup = gen6_gmch_remove;
3255         ggtt->base.bind_vma = ggtt_bind_vma;
3256         ggtt->base.unbind_vma = ggtt_unbind_vma;
3257         ggtt->base.set_pages = ggtt_set_pages;
3258         ggtt->base.clear_pages = clear_pages;
3259         ggtt->base.insert_page = gen8_ggtt_insert_page;
3260         ggtt->base.clear_range = nop_clear_range;
3261         if (!USES_FULL_PPGTT(dev_priv) || intel_scanout_needs_vtd_wa(dev_priv))
3262                 ggtt->base.clear_range = gen8_ggtt_clear_range;
3263
3264         ggtt->base.insert_entries = gen8_ggtt_insert_entries;
3265
3266         /* Serialize GTT updates with aperture access on BXT if VT-d is on. */
3267         if (intel_ggtt_update_needs_vtd_wa(dev_priv)) {
3268                 ggtt->base.insert_entries = bxt_vtd_ggtt_insert_entries__BKL;
3269                 ggtt->base.insert_page    = bxt_vtd_ggtt_insert_page__BKL;
3270                 if (ggtt->base.clear_range != nop_clear_range)
3271                         ggtt->base.clear_range = bxt_vtd_ggtt_clear_range__BKL;
3272         }
3273
3274         ggtt->invalidate = gen6_ggtt_invalidate;
3275
3276         setup_private_pat(dev_priv);
3277
3278         return ggtt_probe_common(ggtt, size);
3279 }
3280
3281 static int gen6_gmch_probe(struct i915_ggtt *ggtt)
3282 {
3283         struct drm_i915_private *dev_priv = ggtt->base.i915;
3284         struct pci_dev *pdev = dev_priv->drm.pdev;
3285         unsigned int size;
3286         u16 snb_gmch_ctl;
3287         int err;
3288
3289         ggtt->mappable_base = pci_resource_start(pdev, 2);
3290         ggtt->mappable_end = pci_resource_len(pdev, 2);
3291
3292         /* 64/512MB is the current min/max we actually know of, but this is just
3293          * a coarse sanity check.
3294          */
3295         if (ggtt->mappable_end < (64<<20) || ggtt->mappable_end > (512<<20)) {
3296                 DRM_ERROR("Unknown GMADR size (%llx)\n", ggtt->mappable_end);
3297                 return -ENXIO;
3298         }
3299
3300         err = pci_set_dma_mask(pdev, DMA_BIT_MASK(40));
3301         if (!err)
3302                 err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(40));
3303         if (err)
3304                 DRM_ERROR("Can't set DMA mask/consistent mask (%d)\n", err);
3305         pci_read_config_word(pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
3306
3307         ggtt->stolen_size = gen6_get_stolen_size(snb_gmch_ctl);
3308
3309         size = gen6_get_total_gtt_size(snb_gmch_ctl);
3310         ggtt->base.total = (size / sizeof(gen6_pte_t)) << PAGE_SHIFT;
3311
3312         ggtt->base.clear_range = gen6_ggtt_clear_range;
3313         ggtt->base.insert_page = gen6_ggtt_insert_page;
3314         ggtt->base.insert_entries = gen6_ggtt_insert_entries;
3315         ggtt->base.bind_vma = ggtt_bind_vma;
3316         ggtt->base.unbind_vma = ggtt_unbind_vma;
3317         ggtt->base.set_pages = ggtt_set_pages;
3318         ggtt->base.clear_pages = clear_pages;
3319         ggtt->base.cleanup = gen6_gmch_remove;
3320
3321         ggtt->invalidate = gen6_ggtt_invalidate;
3322
3323         if (HAS_EDRAM(dev_priv))
3324                 ggtt->base.pte_encode = iris_pte_encode;
3325         else if (IS_HASWELL(dev_priv))
3326                 ggtt->base.pte_encode = hsw_pte_encode;
3327         else if (IS_VALLEYVIEW(dev_priv))
3328                 ggtt->base.pte_encode = byt_pte_encode;
3329         else if (INTEL_GEN(dev_priv) >= 7)
3330                 ggtt->base.pte_encode = ivb_pte_encode;
3331         else
3332                 ggtt->base.pte_encode = snb_pte_encode;
3333
3334         return ggtt_probe_common(ggtt, size);
3335 }
3336
3337 static void i915_gmch_remove(struct i915_address_space *vm)
3338 {
3339         intel_gmch_remove();
3340 }
3341
3342 static int i915_gmch_probe(struct i915_ggtt *ggtt)
3343 {
3344         struct drm_i915_private *dev_priv = ggtt->base.i915;
3345         int ret;
3346
3347         ret = intel_gmch_probe(dev_priv->bridge_dev, dev_priv->drm.pdev, NULL);
3348         if (!ret) {
3349                 DRM_ERROR("failed to set up gmch\n");
3350                 return -EIO;
3351         }
3352
3353         intel_gtt_get(&ggtt->base.total,
3354                       &ggtt->stolen_size,
3355                       &ggtt->mappable_base,
3356                       &ggtt->mappable_end);
3357
3358         ggtt->do_idle_maps = needs_idle_maps(dev_priv);
3359         ggtt->base.insert_page = i915_ggtt_insert_page;
3360         ggtt->base.insert_entries = i915_ggtt_insert_entries;
3361         ggtt->base.clear_range = i915_ggtt_clear_range;
3362         ggtt->base.bind_vma = ggtt_bind_vma;
3363         ggtt->base.unbind_vma = ggtt_unbind_vma;
3364         ggtt->base.set_pages = ggtt_set_pages;
3365         ggtt->base.clear_pages = clear_pages;
3366         ggtt->base.cleanup = i915_gmch_remove;
3367
3368         ggtt->invalidate = gmch_ggtt_invalidate;
3369
3370         if (unlikely(ggtt->do_idle_maps))
3371                 DRM_INFO("applying Ironlake quirks for intel_iommu\n");
3372
3373         return 0;
3374 }
3375
3376 /**
3377  * i915_ggtt_probe_hw - Probe GGTT hardware location
3378  * @dev_priv: i915 device
3379  */
3380 int i915_ggtt_probe_hw(struct drm_i915_private *dev_priv)
3381 {
3382         struct i915_ggtt *ggtt = &dev_priv->ggtt;
3383         int ret;
3384
3385         ggtt->base.i915 = dev_priv;
3386         ggtt->base.dma = &dev_priv->drm.pdev->dev;
3387
3388         if (INTEL_GEN(dev_priv) <= 5)
3389                 ret = i915_gmch_probe(ggtt);
3390         else if (INTEL_GEN(dev_priv) < 8)
3391                 ret = gen6_gmch_probe(ggtt);
3392         else
3393                 ret = gen8_gmch_probe(ggtt);
3394         if (ret)
3395                 return ret;
3396
3397         /* Trim the GGTT to fit the GuC mappable upper range (when enabled).
3398          * This is easier than doing range restriction on the fly, as we
3399          * currently don't have any bits spare to pass in this upper
3400          * restriction!
3401          */
3402         if (HAS_GUC(dev_priv) && i915_modparams.enable_guc_loading) {
3403                 ggtt->base.total = min_t(u64, ggtt->base.total, GUC_GGTT_TOP);
3404                 ggtt->mappable_end = min(ggtt->mappable_end, ggtt->base.total);
3405         }
3406
3407         if ((ggtt->base.total - 1) >> 32) {
3408                 DRM_ERROR("We never expected a Global GTT with more than 32bits"
3409                           " of address space! Found %lldM!\n",
3410                           ggtt->base.total >> 20);
3411                 ggtt->base.total = 1ULL << 32;
3412                 ggtt->mappable_end = min(ggtt->mappable_end, ggtt->base.total);
3413         }
3414
3415         if (ggtt->mappable_end > ggtt->base.total) {
3416                 DRM_ERROR("mappable aperture extends past end of GGTT,"
3417                           " aperture=%llx, total=%llx\n",
3418                           ggtt->mappable_end, ggtt->base.total);
3419                 ggtt->mappable_end = ggtt->base.total;
3420         }
3421
3422         /* GMADR is the PCI mmio aperture into the global GTT. */
3423         DRM_INFO("Memory usable by graphics device = %lluM\n",
3424                  ggtt->base.total >> 20);
3425         DRM_DEBUG_DRIVER("GMADR size = %lldM\n", ggtt->mappable_end >> 20);
3426         DRM_DEBUG_DRIVER("GTT stolen size = %uM\n", ggtt->stolen_size >> 20);
3427         if (intel_vtd_active())
3428                 DRM_INFO("VT-d active for gfx access\n");
3429
3430         return 0;
3431 }
3432
3433 /**
3434  * i915_ggtt_init_hw - Initialize GGTT hardware
3435  * @dev_priv: i915 device
3436  */
3437 int i915_ggtt_init_hw(struct drm_i915_private *dev_priv)
3438 {
3439         struct i915_ggtt *ggtt = &dev_priv->ggtt;
3440         int ret;
3441
3442         INIT_LIST_HEAD(&dev_priv->vm_list);
3443
3444         /* Note that we use page colouring to enforce a guard page at the
3445          * end of the address space. This is required as the CS may prefetch
3446          * beyond the end of the batch buffer, across the page boundary,
3447          * and beyond the end of the GTT if we do not provide a guard.
3448          */
3449         mutex_lock(&dev_priv->drm.struct_mutex);
3450         i915_address_space_init(&ggtt->base, dev_priv, "[global]");
3451         if (!HAS_LLC(dev_priv) && !USES_PPGTT(dev_priv))
3452                 ggtt->base.mm.color_adjust = i915_gtt_color_adjust;
3453         mutex_unlock(&dev_priv->drm.struct_mutex);
3454
3455         if (!io_mapping_init_wc(&dev_priv->ggtt.mappable,
3456                                 dev_priv->ggtt.mappable_base,
3457                                 dev_priv->ggtt.mappable_end)) {
3458                 ret = -EIO;
3459                 goto out_gtt_cleanup;
3460         }
3461
3462         ggtt->mtrr = arch_phys_wc_add(ggtt->mappable_base, ggtt->mappable_end);
3463
3464         /*
3465          * Initialise stolen early so that we may reserve preallocated
3466          * objects for the BIOS to KMS transition.
3467          */
3468         ret = i915_gem_init_stolen(dev_priv);
3469         if (ret)
3470                 goto out_gtt_cleanup;
3471
3472         return 0;
3473
3474 out_gtt_cleanup:
3475         ggtt->base.cleanup(&ggtt->base);
3476         return ret;
3477 }
3478
3479 int i915_ggtt_enable_hw(struct drm_i915_private *dev_priv)
3480 {
3481         if (INTEL_GEN(dev_priv) < 6 && !intel_enable_gtt())
3482                 return -EIO;
3483
3484         return 0;
3485 }
3486
3487 void i915_ggtt_enable_guc(struct drm_i915_private *i915)
3488 {
3489         GEM_BUG_ON(i915->ggtt.invalidate != gen6_ggtt_invalidate);
3490
3491         i915->ggtt.invalidate = guc_ggtt_invalidate;
3492 }
3493
3494 void i915_ggtt_disable_guc(struct drm_i915_private *i915)
3495 {
3496         /* We should only be called after i915_ggtt_enable_guc() */
3497         GEM_BUG_ON(i915->ggtt.invalidate != guc_ggtt_invalidate);
3498
3499         i915->ggtt.invalidate = gen6_ggtt_invalidate;
3500 }
3501
3502 void i915_gem_restore_gtt_mappings(struct drm_i915_private *dev_priv)
3503 {
3504         struct i915_ggtt *ggtt = &dev_priv->ggtt;
3505         struct drm_i915_gem_object *obj, *on;
3506
3507         i915_check_and_clear_faults(dev_priv);
3508
3509         /* First fill our portion of the GTT with scratch pages */
3510         ggtt->base.clear_range(&ggtt->base, 0, ggtt->base.total);
3511
3512         ggtt->base.closed = true; /* skip rewriting PTE on VMA unbind */
3513
3514         /* clflush objects bound into the GGTT and rebind them. */
3515         list_for_each_entry_safe(obj, on,
3516                                  &dev_priv->mm.bound_list, global_link) {
3517                 bool ggtt_bound = false;
3518                 struct i915_vma *vma;
3519
3520                 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3521                         if (vma->vm != &ggtt->base)
3522                                 continue;
3523
3524                         if (!i915_vma_unbind(vma))
3525                                 continue;
3526
3527                         WARN_ON(i915_vma_bind(vma, obj->cache_level,
3528                                               PIN_UPDATE));
3529                         ggtt_bound = true;
3530                 }
3531
3532                 if (ggtt_bound)
3533                         WARN_ON(i915_gem_object_set_to_gtt_domain(obj, false));
3534         }
3535
3536         ggtt->base.closed = false;
3537
3538         if (INTEL_GEN(dev_priv) >= 8) {
3539                 struct intel_ppat *ppat = &dev_priv->ppat;
3540
3541                 bitmap_set(ppat->dirty, 0, ppat->max_entries);
3542                 dev_priv->ppat.update_hw(dev_priv);
3543                 return;
3544         }
3545
3546         if (USES_PPGTT(dev_priv)) {
3547                 struct i915_address_space *vm;
3548
3549                 list_for_each_entry(vm, &dev_priv->vm_list, global_link) {
3550                         struct i915_hw_ppgtt *ppgtt;
3551
3552                         if (i915_is_ggtt(vm))
3553                                 ppgtt = dev_priv->mm.aliasing_ppgtt;
3554                         else
3555                                 ppgtt = i915_vm_to_ppgtt(vm);
3556
3557                         gen6_write_page_range(ppgtt, 0, ppgtt->base.total);
3558                 }
3559         }
3560
3561         i915_ggtt_invalidate(dev_priv);
3562 }
3563
3564 static struct scatterlist *
3565 rotate_pages(const dma_addr_t *in, unsigned int offset,
3566              unsigned int width, unsigned int height,
3567              unsigned int stride,
3568              struct sg_table *st, struct scatterlist *sg)
3569 {
3570         unsigned int column, row;
3571         unsigned int src_idx;
3572
3573         for (column = 0; column < width; column++) {
3574                 src_idx = stride * (height - 1) + column;
3575                 for (row = 0; row < height; row++) {
3576                         st->nents++;
3577                         /* We don't need the pages, but need to initialize
3578                          * the entries so the sg list can be happily traversed.
3579                          * The only thing we need are DMA addresses.
3580                          */
3581                         sg_set_page(sg, NULL, PAGE_SIZE, 0);
3582                         sg_dma_address(sg) = in[offset + src_idx];
3583                         sg_dma_len(sg) = PAGE_SIZE;
3584                         sg = sg_next(sg);
3585                         src_idx -= stride;
3586                 }
3587         }
3588
3589         return sg;
3590 }
3591
3592 static noinline struct sg_table *
3593 intel_rotate_pages(struct intel_rotation_info *rot_info,
3594                    struct drm_i915_gem_object *obj)
3595 {
3596         const unsigned long n_pages = obj->base.size / PAGE_SIZE;
3597         unsigned int size = intel_rotation_info_size(rot_info);
3598         struct sgt_iter sgt_iter;
3599         dma_addr_t dma_addr;
3600         unsigned long i;
3601         dma_addr_t *page_addr_list;
3602         struct sg_table *st;
3603         struct scatterlist *sg;
3604         int ret = -ENOMEM;
3605
3606         /* Allocate a temporary list of source pages for random access. */
3607         page_addr_list = kvmalloc_array(n_pages,
3608                                         sizeof(dma_addr_t),
3609                                         GFP_KERNEL);
3610         if (!page_addr_list)
3611                 return ERR_PTR(ret);
3612
3613         /* Allocate target SG list. */
3614         st = kmalloc(sizeof(*st), GFP_KERNEL);
3615         if (!st)
3616                 goto err_st_alloc;
3617
3618         ret = sg_alloc_table(st, size, GFP_KERNEL);
3619         if (ret)
3620                 goto err_sg_alloc;
3621
3622         /* Populate source page list from the object. */
3623         i = 0;
3624         for_each_sgt_dma(dma_addr, sgt_iter, obj->mm.pages)
3625                 page_addr_list[i++] = dma_addr;
3626
3627         GEM_BUG_ON(i != n_pages);
3628         st->nents = 0;
3629         sg = st->sgl;
3630
3631         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++) {
3632                 sg = rotate_pages(page_addr_list, rot_info->plane[i].offset,
3633                                   rot_info->plane[i].width, rot_info->plane[i].height,
3634                                   rot_info->plane[i].stride, st, sg);
3635         }
3636
3637         DRM_DEBUG_KMS("Created rotated page mapping for object size %zu (%ux%u tiles, %u pages)\n",
3638                       obj->base.size, rot_info->plane[0].width, rot_info->plane[0].height, size);
3639
3640         kvfree(page_addr_list);
3641
3642         return st;
3643
3644 err_sg_alloc:
3645         kfree(st);
3646 err_st_alloc:
3647         kvfree(page_addr_list);
3648
3649         DRM_DEBUG_KMS("Failed to create rotated mapping for object size %zu! (%ux%u tiles, %u pages)\n",
3650                       obj->base.size, rot_info->plane[0].width, rot_info->plane[0].height, size);
3651
3652         return ERR_PTR(ret);
3653 }
3654
3655 static noinline struct sg_table *
3656 intel_partial_pages(const struct i915_ggtt_view *view,
3657                     struct drm_i915_gem_object *obj)
3658 {
3659         struct sg_table *st;
3660         struct scatterlist *sg, *iter;
3661         unsigned int count = view->partial.size;
3662         unsigned int offset;
3663         int ret = -ENOMEM;
3664
3665         st = kmalloc(sizeof(*st), GFP_KERNEL);
3666         if (!st)
3667                 goto err_st_alloc;
3668
3669         ret = sg_alloc_table(st, count, GFP_KERNEL);
3670         if (ret)
3671                 goto err_sg_alloc;
3672
3673         iter = i915_gem_object_get_sg(obj, view->partial.offset, &offset);
3674         GEM_BUG_ON(!iter);
3675
3676         sg = st->sgl;
3677         st->nents = 0;
3678         do {
3679                 unsigned int len;
3680
3681                 len = min(iter->length - (offset << PAGE_SHIFT),
3682                           count << PAGE_SHIFT);
3683                 sg_set_page(sg, NULL, len, 0);
3684                 sg_dma_address(sg) =
3685                         sg_dma_address(iter) + (offset << PAGE_SHIFT);
3686                 sg_dma_len(sg) = len;
3687
3688                 st->nents++;
3689                 count -= len >> PAGE_SHIFT;
3690                 if (count == 0) {
3691                         sg_mark_end(sg);
3692                         return st;
3693                 }
3694
3695                 sg = __sg_next(sg);
3696                 iter = __sg_next(iter);
3697                 offset = 0;
3698         } while (1);
3699
3700 err_sg_alloc:
3701         kfree(st);
3702 err_st_alloc:
3703         return ERR_PTR(ret);
3704 }
3705
3706 static int
3707 i915_get_ggtt_vma_pages(struct i915_vma *vma)
3708 {
3709         int ret;
3710
3711         /* The vma->pages are only valid within the lifespan of the borrowed
3712          * obj->mm.pages. When the obj->mm.pages sg_table is regenerated, so
3713          * must be the vma->pages. A simple rule is that vma->pages must only
3714          * be accessed when the obj->mm.pages are pinned.
3715          */
3716         GEM_BUG_ON(!i915_gem_object_has_pinned_pages(vma->obj));
3717
3718         switch (vma->ggtt_view.type) {
3719         case I915_GGTT_VIEW_NORMAL:
3720                 vma->pages = vma->obj->mm.pages;
3721                 return 0;
3722
3723         case I915_GGTT_VIEW_ROTATED:
3724                 vma->pages =
3725                         intel_rotate_pages(&vma->ggtt_view.rotated, vma->obj);
3726                 break;
3727
3728         case I915_GGTT_VIEW_PARTIAL:
3729                 vma->pages = intel_partial_pages(&vma->ggtt_view, vma->obj);
3730                 break;
3731
3732         default:
3733                 WARN_ONCE(1, "GGTT view %u not implemented!\n",
3734                           vma->ggtt_view.type);
3735                 return -EINVAL;
3736         }
3737
3738         ret = 0;
3739         if (unlikely(IS_ERR(vma->pages))) {
3740                 ret = PTR_ERR(vma->pages);
3741                 vma->pages = NULL;
3742                 DRM_ERROR("Failed to get pages for VMA view type %u (%d)!\n",
3743                           vma->ggtt_view.type, ret);
3744         }
3745         return ret;
3746 }
3747
3748 /**
3749  * i915_gem_gtt_reserve - reserve a node in an address_space (GTT)
3750  * @vm: the &struct i915_address_space
3751  * @node: the &struct drm_mm_node (typically i915_vma.mode)
3752  * @size: how much space to allocate inside the GTT,
3753  *        must be #I915_GTT_PAGE_SIZE aligned
3754  * @offset: where to insert inside the GTT,
3755  *          must be #I915_GTT_MIN_ALIGNMENT aligned, and the node
3756  *          (@offset + @size) must fit within the address space
3757  * @color: color to apply to node, if this node is not from a VMA,
3758  *         color must be #I915_COLOR_UNEVICTABLE
3759  * @flags: control search and eviction behaviour
3760  *
3761  * i915_gem_gtt_reserve() tries to insert the @node at the exact @offset inside
3762  * the address space (using @size and @color). If the @node does not fit, it
3763  * tries to evict any overlapping nodes from the GTT, including any
3764  * neighbouring nodes if the colors do not match (to ensure guard pages between
3765  * differing domains). See i915_gem_evict_for_node() for the gory details
3766  * on the eviction algorithm. #PIN_NONBLOCK may used to prevent waiting on
3767  * evicting active overlapping objects, and any overlapping node that is pinned
3768  * or marked as unevictable will also result in failure.
3769  *
3770  * Returns: 0 on success, -ENOSPC if no suitable hole is found, -EINTR if
3771  * asked to wait for eviction and interrupted.
3772  */
3773 int i915_gem_gtt_reserve(struct i915_address_space *vm,
3774                          struct drm_mm_node *node,
3775                          u64 size, u64 offset, unsigned long color,
3776                          unsigned int flags)
3777 {
3778         int err;
3779
3780         GEM_BUG_ON(!size);
3781         GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
3782         GEM_BUG_ON(!IS_ALIGNED(offset, I915_GTT_MIN_ALIGNMENT));
3783         GEM_BUG_ON(range_overflows(offset, size, vm->total));
3784         GEM_BUG_ON(vm == &vm->i915->mm.aliasing_ppgtt->base);
3785         GEM_BUG_ON(drm_mm_node_allocated(node));
3786
3787         node->size = size;
3788         node->start = offset;
3789         node->color = color;
3790
3791         err = drm_mm_reserve_node(&vm->mm, node);
3792         if (err != -ENOSPC)
3793                 return err;
3794
3795         if (flags & PIN_NOEVICT)
3796                 return -ENOSPC;
3797
3798         err = i915_gem_evict_for_node(vm, node, flags);
3799         if (err == 0)
3800                 err = drm_mm_reserve_node(&vm->mm, node);
3801
3802         return err;
3803 }
3804
3805 static u64 random_offset(u64 start, u64 end, u64 len, u64 align)
3806 {
3807         u64 range, addr;
3808
3809         GEM_BUG_ON(range_overflows(start, len, end));
3810         GEM_BUG_ON(round_up(start, align) > round_down(end - len, align));
3811
3812         range = round_down(end - len, align) - round_up(start, align);
3813         if (range) {
3814                 if (sizeof(unsigned long) == sizeof(u64)) {
3815                         addr = get_random_long();
3816                 } else {
3817                         addr = get_random_int();
3818                         if (range > U32_MAX) {
3819                                 addr <<= 32;
3820                                 addr |= get_random_int();
3821                         }
3822                 }
3823                 div64_u64_rem(addr, range, &addr);
3824                 start += addr;
3825         }
3826
3827         return round_up(start, align);
3828 }
3829
3830 /**
3831  * i915_gem_gtt_insert - insert a node into an address_space (GTT)
3832  * @vm: the &struct i915_address_space
3833  * @node: the &struct drm_mm_node (typically i915_vma.node)
3834  * @size: how much space to allocate inside the GTT,
3835  *        must be #I915_GTT_PAGE_SIZE aligned
3836  * @alignment: required alignment of starting offset, may be 0 but
3837  *             if specified, this must be a power-of-two and at least
3838  *             #I915_GTT_MIN_ALIGNMENT
3839  * @color: color to apply to node
3840  * @start: start of any range restriction inside GTT (0 for all),
3841  *         must be #I915_GTT_PAGE_SIZE aligned
3842  * @end: end of any range restriction inside GTT (U64_MAX for all),
3843  *       must be #I915_GTT_PAGE_SIZE aligned if not U64_MAX
3844  * @flags: control search and eviction behaviour
3845  *
3846  * i915_gem_gtt_insert() first searches for an available hole into which
3847  * is can insert the node. The hole address is aligned to @alignment and
3848  * its @size must then fit entirely within the [@start, @end] bounds. The
3849  * nodes on either side of the hole must match @color, or else a guard page
3850  * will be inserted between the two nodes (or the node evicted). If no
3851  * suitable hole is found, first a victim is randomly selected and tested
3852  * for eviction, otherwise then the LRU list of objects within the GTT
3853  * is scanned to find the first set of replacement nodes to create the hole.
3854  * Those old overlapping nodes are evicted from the GTT (and so must be
3855  * rebound before any future use). Any node that is currently pinned cannot
3856  * be evicted (see i915_vma_pin()). Similar if the node's VMA is currently
3857  * active and #PIN_NONBLOCK is specified, that node is also skipped when
3858  * searching for an eviction candidate. See i915_gem_evict_something() for
3859  * the gory details on the eviction algorithm.
3860  *
3861  * Returns: 0 on success, -ENOSPC if no suitable hole is found, -EINTR if
3862  * asked to wait for eviction and interrupted.
3863  */
3864 int i915_gem_gtt_insert(struct i915_address_space *vm,
3865                         struct drm_mm_node *node,
3866                         u64 size, u64 alignment, unsigned long color,
3867                         u64 start, u64 end, unsigned int flags)
3868 {
3869         enum drm_mm_insert_mode mode;
3870         u64 offset;
3871         int err;
3872
3873         lockdep_assert_held(&vm->i915->drm.struct_mutex);
3874         GEM_BUG_ON(!size);
3875         GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
3876         GEM_BUG_ON(alignment && !is_power_of_2(alignment));
3877         GEM_BUG_ON(alignment && !IS_ALIGNED(alignment, I915_GTT_MIN_ALIGNMENT));
3878         GEM_BUG_ON(start >= end);
3879         GEM_BUG_ON(start > 0  && !IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
3880         GEM_BUG_ON(end < U64_MAX && !IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
3881         GEM_BUG_ON(vm == &vm->i915->mm.aliasing_ppgtt->base);
3882         GEM_BUG_ON(drm_mm_node_allocated(node));
3883
3884         if (unlikely(range_overflows(start, size, end)))
3885                 return -ENOSPC;
3886
3887         if (unlikely(round_up(start, alignment) > round_down(end - size, alignment)))
3888                 return -ENOSPC;
3889
3890         mode = DRM_MM_INSERT_BEST;
3891         if (flags & PIN_HIGH)
3892                 mode = DRM_MM_INSERT_HIGH;
3893         if (flags & PIN_MAPPABLE)
3894                 mode = DRM_MM_INSERT_LOW;
3895
3896         /* We only allocate in PAGE_SIZE/GTT_PAGE_SIZE (4096) chunks,
3897          * so we know that we always have a minimum alignment of 4096.
3898          * The drm_mm range manager is optimised to return results
3899          * with zero alignment, so where possible use the optimal
3900          * path.
3901          */
3902         BUILD_BUG_ON(I915_GTT_MIN_ALIGNMENT > I915_GTT_PAGE_SIZE);
3903         if (alignment <= I915_GTT_MIN_ALIGNMENT)
3904                 alignment = 0;
3905
3906         err = drm_mm_insert_node_in_range(&vm->mm, node,
3907                                           size, alignment, color,
3908                                           start, end, mode);
3909         if (err != -ENOSPC)
3910                 return err;
3911
3912         if (flags & PIN_NOEVICT)
3913                 return -ENOSPC;
3914
3915         /* No free space, pick a slot at random.
3916          *
3917          * There is a pathological case here using a GTT shared between
3918          * mmap and GPU (i.e. ggtt/aliasing_ppgtt but not full-ppgtt):
3919          *
3920          *    |<-- 256 MiB aperture -->||<-- 1792 MiB unmappable -->|
3921          *         (64k objects)             (448k objects)
3922          *
3923          * Now imagine that the eviction LRU is ordered top-down (just because
3924          * pathology meets real life), and that we need to evict an object to
3925          * make room inside the aperture. The eviction scan then has to walk
3926          * the 448k list before it finds one within range. And now imagine that
3927          * it has to search for a new hole between every byte inside the memcpy,
3928          * for several simultaneous clients.
3929          *
3930          * On a full-ppgtt system, if we have run out of available space, there
3931          * will be lots and lots of objects in the eviction list! Again,
3932          * searching that LRU list may be slow if we are also applying any
3933          * range restrictions (e.g. restriction to low 4GiB) and so, for
3934          * simplicity and similarilty between different GTT, try the single
3935          * random replacement first.
3936          */
3937         offset = random_offset(start, end,
3938                                size, alignment ?: I915_GTT_MIN_ALIGNMENT);
3939         err = i915_gem_gtt_reserve(vm, node, size, offset, color, flags);
3940         if (err != -ENOSPC)
3941                 return err;
3942
3943         /* Randomly selected placement is pinned, do a search */
3944         err = i915_gem_evict_something(vm, size, alignment, color,
3945                                        start, end, flags);
3946         if (err)
3947                 return err;
3948
3949         return drm_mm_insert_node_in_range(&vm->mm, node,
3950                                            size, alignment, color,
3951                                            start, end, DRM_MM_INSERT_EVICT);
3952 }
3953
3954 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
3955 #include "selftests/mock_gtt.c"
3956 #include "selftests/i915_gem_gtt.c"
3957 #endif