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