agp/intel-gtt: reduce intel-gtt dependencies more
[platform/kernel/linux-rpi.git] / drivers / gpu / drm / i915 / gt / intel_ggtt.c
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2020 Intel Corporation
4  */
5
6 #include <linux/agp_backend.h>
7 #include <linux/stop_machine.h>
8
9 #include <asm/set_memory.h>
10 #include <asm/smp.h>
11
12 #include <drm/i915_drm.h>
13 #include <drm/intel-gtt.h>
14
15 #include "gem/i915_gem_lmem.h"
16
17 #include "intel_gt.h"
18 #include "i915_drv.h"
19 #include "i915_scatterlist.h"
20 #include "i915_vgpu.h"
21
22 #include "intel_gtt.h"
23 #include "gen8_ppgtt.h"
24
25 static int
26 i915_get_ggtt_vma_pages(struct i915_vma *vma);
27
28 static void i915_ggtt_color_adjust(const struct drm_mm_node *node,
29                                    unsigned long color,
30                                    u64 *start,
31                                    u64 *end)
32 {
33         if (i915_node_color_differs(node, color))
34                 *start += I915_GTT_PAGE_SIZE;
35
36         /*
37          * Also leave a space between the unallocated reserved node after the
38          * GTT and any objects within the GTT, i.e. we use the color adjustment
39          * to insert a guard page to prevent prefetches crossing over the
40          * GTT boundary.
41          */
42         node = list_next_entry(node, node_list);
43         if (node->color != color)
44                 *end -= I915_GTT_PAGE_SIZE;
45 }
46
47 static int ggtt_init_hw(struct i915_ggtt *ggtt)
48 {
49         struct drm_i915_private *i915 = ggtt->vm.i915;
50
51         i915_address_space_init(&ggtt->vm, VM_CLASS_GGTT);
52
53         ggtt->vm.is_ggtt = true;
54
55         /* Only VLV supports read-only GGTT mappings */
56         ggtt->vm.has_read_only = IS_VALLEYVIEW(i915);
57
58         if (!HAS_LLC(i915) && !HAS_PPGTT(i915))
59                 ggtt->vm.mm.color_adjust = i915_ggtt_color_adjust;
60
61         if (ggtt->mappable_end) {
62                 if (!io_mapping_init_wc(&ggtt->iomap,
63                                         ggtt->gmadr.start,
64                                         ggtt->mappable_end)) {
65                         ggtt->vm.cleanup(&ggtt->vm);
66                         return -EIO;
67                 }
68
69                 ggtt->mtrr = arch_phys_wc_add(ggtt->gmadr.start,
70                                               ggtt->mappable_end);
71         }
72
73         intel_ggtt_init_fences(ggtt);
74
75         return 0;
76 }
77
78 /**
79  * i915_ggtt_init_hw - Initialize GGTT hardware
80  * @i915: i915 device
81  */
82 int i915_ggtt_init_hw(struct drm_i915_private *i915)
83 {
84         int ret;
85
86         /*
87          * Note that we use page colouring to enforce a guard page at the
88          * end of the address space. This is required as the CS may prefetch
89          * beyond the end of the batch buffer, across the page boundary,
90          * and beyond the end of the GTT if we do not provide a guard.
91          */
92         ret = ggtt_init_hw(&i915->ggtt);
93         if (ret)
94                 return ret;
95
96         return 0;
97 }
98
99 /*
100  * Certain Gen5 chipsets require idling the GPU before
101  * unmapping anything from the GTT when VT-d is enabled.
102  */
103 static bool needs_idle_maps(struct drm_i915_private *i915)
104 {
105         /*
106          * Query intel_iommu to see if we need the workaround. Presumably that
107          * was loaded first.
108          */
109         if (!intel_vtd_active())
110                 return false;
111
112         if (GRAPHICS_VER(i915) == 5 && IS_MOBILE(i915))
113                 return true;
114
115         if (GRAPHICS_VER(i915) == 12)
116                 return true; /* XXX DMAR fault reason 7 */
117
118         return false;
119 }
120
121 /**
122  * i915_ggtt_suspend_vm - Suspend the memory mappings for a GGTT or DPT VM
123  * @vm: The VM to suspend the mappings for
124  *
125  * Suspend the memory mappings for all objects mapped to HW via the GGTT or a
126  * DPT page table.
127  */
128 void i915_ggtt_suspend_vm(struct i915_address_space *vm)
129 {
130         struct i915_vma *vma, *vn;
131         int open;
132
133         drm_WARN_ON(&vm->i915->drm, !vm->is_ggtt && !vm->is_dpt);
134
135         mutex_lock(&vm->mutex);
136
137         /* Skip rewriting PTE on VMA unbind. */
138         open = atomic_xchg(&vm->open, 0);
139
140         list_for_each_entry_safe(vma, vn, &vm->bound_list, vm_link) {
141                 GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
142                 i915_vma_wait_for_bind(vma);
143
144                 if (i915_vma_is_pinned(vma))
145                         continue;
146
147                 if (!i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND)) {
148                         __i915_vma_evict(vma);
149                         drm_mm_remove_node(&vma->node);
150                 }
151         }
152
153         vm->clear_range(vm, 0, vm->total);
154
155         atomic_set(&vm->open, open);
156
157         mutex_unlock(&vm->mutex);
158 }
159
160 void i915_ggtt_suspend(struct i915_ggtt *ggtt)
161 {
162         i915_ggtt_suspend_vm(&ggtt->vm);
163         ggtt->invalidate(ggtt);
164
165         intel_gt_check_and_clear_faults(ggtt->vm.gt);
166 }
167
168 void gen6_ggtt_invalidate(struct i915_ggtt *ggtt)
169 {
170         struct intel_uncore *uncore = ggtt->vm.gt->uncore;
171
172         spin_lock_irq(&uncore->lock);
173         intel_uncore_write_fw(uncore, GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
174         intel_uncore_read_fw(uncore, GFX_FLSH_CNTL_GEN6);
175         spin_unlock_irq(&uncore->lock);
176 }
177
178 static void gen8_ggtt_invalidate(struct i915_ggtt *ggtt)
179 {
180         struct intel_uncore *uncore = ggtt->vm.gt->uncore;
181
182         /*
183          * Note that as an uncached mmio write, this will flush the
184          * WCB of the writes into the GGTT before it triggers the invalidate.
185          */
186         intel_uncore_write_fw(uncore, GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
187 }
188
189 static void guc_ggtt_invalidate(struct i915_ggtt *ggtt)
190 {
191         struct intel_uncore *uncore = ggtt->vm.gt->uncore;
192         struct drm_i915_private *i915 = ggtt->vm.i915;
193
194         gen8_ggtt_invalidate(ggtt);
195
196         if (GRAPHICS_VER(i915) >= 12)
197                 intel_uncore_write_fw(uncore, GEN12_GUC_TLB_INV_CR,
198                                       GEN12_GUC_TLB_INV_CR_INVALIDATE);
199         else
200                 intel_uncore_write_fw(uncore, GEN8_GTCR, GEN8_GTCR_INVALIDATE);
201 }
202
203 static void gmch_ggtt_invalidate(struct i915_ggtt *ggtt)
204 {
205         intel_gtt_chipset_flush();
206 }
207
208 u64 gen8_ggtt_pte_encode(dma_addr_t addr,
209                          enum i915_cache_level level,
210                          u32 flags)
211 {
212         gen8_pte_t pte = addr | _PAGE_PRESENT;
213
214         if (flags & PTE_LM)
215                 pte |= GEN12_GGTT_PTE_LM;
216
217         return pte;
218 }
219
220 static void gen8_set_pte(void __iomem *addr, gen8_pte_t pte)
221 {
222         writeq(pte, addr);
223 }
224
225 static void gen8_ggtt_insert_page(struct i915_address_space *vm,
226                                   dma_addr_t addr,
227                                   u64 offset,
228                                   enum i915_cache_level level,
229                                   u32 flags)
230 {
231         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
232         gen8_pte_t __iomem *pte =
233                 (gen8_pte_t __iomem *)ggtt->gsm + offset / I915_GTT_PAGE_SIZE;
234
235         gen8_set_pte(pte, gen8_ggtt_pte_encode(addr, level, flags));
236
237         ggtt->invalidate(ggtt);
238 }
239
240 static void gen8_ggtt_insert_entries(struct i915_address_space *vm,
241                                      struct i915_vma *vma,
242                                      enum i915_cache_level level,
243                                      u32 flags)
244 {
245         const gen8_pte_t pte_encode = gen8_ggtt_pte_encode(0, level, flags);
246         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
247         gen8_pte_t __iomem *gte;
248         gen8_pte_t __iomem *end;
249         struct sgt_iter iter;
250         dma_addr_t addr;
251
252         /*
253          * Note that we ignore PTE_READ_ONLY here. The caller must be careful
254          * not to allow the user to override access to a read only page.
255          */
256
257         gte = (gen8_pte_t __iomem *)ggtt->gsm;
258         gte += vma->node.start / I915_GTT_PAGE_SIZE;
259         end = gte + vma->node.size / I915_GTT_PAGE_SIZE;
260
261         for_each_sgt_daddr(addr, iter, vma->pages)
262                 gen8_set_pte(gte++, pte_encode | addr);
263         GEM_BUG_ON(gte > end);
264
265         /* Fill the allocated but "unused" space beyond the end of the buffer */
266         while (gte < end)
267                 gen8_set_pte(gte++, vm->scratch[0]->encode);
268
269         /*
270          * We want to flush the TLBs only after we're certain all the PTE
271          * updates have finished.
272          */
273         ggtt->invalidate(ggtt);
274 }
275
276 static void gen6_ggtt_insert_page(struct i915_address_space *vm,
277                                   dma_addr_t addr,
278                                   u64 offset,
279                                   enum i915_cache_level level,
280                                   u32 flags)
281 {
282         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
283         gen6_pte_t __iomem *pte =
284                 (gen6_pte_t __iomem *)ggtt->gsm + offset / I915_GTT_PAGE_SIZE;
285
286         iowrite32(vm->pte_encode(addr, level, flags), pte);
287
288         ggtt->invalidate(ggtt);
289 }
290
291 /*
292  * Binds an object into the global gtt with the specified cache level.
293  * The object will be accessible to the GPU via commands whose operands
294  * reference offsets within the global GTT as well as accessible by the GPU
295  * through the GMADR mapped BAR (i915->mm.gtt->gtt).
296  */
297 static void gen6_ggtt_insert_entries(struct i915_address_space *vm,
298                                      struct i915_vma *vma,
299                                      enum i915_cache_level level,
300                                      u32 flags)
301 {
302         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
303         gen6_pte_t __iomem *gte;
304         gen6_pte_t __iomem *end;
305         struct sgt_iter iter;
306         dma_addr_t addr;
307
308         gte = (gen6_pte_t __iomem *)ggtt->gsm;
309         gte += vma->node.start / I915_GTT_PAGE_SIZE;
310         end = gte + vma->node.size / I915_GTT_PAGE_SIZE;
311
312         for_each_sgt_daddr(addr, iter, vma->pages)
313                 iowrite32(vm->pte_encode(addr, level, flags), gte++);
314         GEM_BUG_ON(gte > end);
315
316         /* Fill the allocated but "unused" space beyond the end of the buffer */
317         while (gte < end)
318                 iowrite32(vm->scratch[0]->encode, gte++);
319
320         /*
321          * We want to flush the TLBs only after we're certain all the PTE
322          * updates have finished.
323          */
324         ggtt->invalidate(ggtt);
325 }
326
327 static void nop_clear_range(struct i915_address_space *vm,
328                             u64 start, u64 length)
329 {
330 }
331
332 static void gen8_ggtt_clear_range(struct i915_address_space *vm,
333                                   u64 start, u64 length)
334 {
335         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
336         unsigned int first_entry = start / I915_GTT_PAGE_SIZE;
337         unsigned int num_entries = length / I915_GTT_PAGE_SIZE;
338         const gen8_pte_t scratch_pte = vm->scratch[0]->encode;
339         gen8_pte_t __iomem *gtt_base =
340                 (gen8_pte_t __iomem *)ggtt->gsm + first_entry;
341         const int max_entries = ggtt_total_entries(ggtt) - first_entry;
342         int i;
343
344         if (WARN(num_entries > max_entries,
345                  "First entry = %d; Num entries = %d (max=%d)\n",
346                  first_entry, num_entries, max_entries))
347                 num_entries = max_entries;
348
349         for (i = 0; i < num_entries; i++)
350                 gen8_set_pte(&gtt_base[i], scratch_pte);
351 }
352
353 static void bxt_vtd_ggtt_wa(struct i915_address_space *vm)
354 {
355         /*
356          * Make sure the internal GAM fifo has been cleared of all GTT
357          * writes before exiting stop_machine(). This guarantees that
358          * any aperture accesses waiting to start in another process
359          * cannot back up behind the GTT writes causing a hang.
360          * The register can be any arbitrary GAM register.
361          */
362         intel_uncore_posting_read_fw(vm->gt->uncore, GFX_FLSH_CNTL_GEN6);
363 }
364
365 struct insert_page {
366         struct i915_address_space *vm;
367         dma_addr_t addr;
368         u64 offset;
369         enum i915_cache_level level;
370 };
371
372 static int bxt_vtd_ggtt_insert_page__cb(void *_arg)
373 {
374         struct insert_page *arg = _arg;
375
376         gen8_ggtt_insert_page(arg->vm, arg->addr, arg->offset, arg->level, 0);
377         bxt_vtd_ggtt_wa(arg->vm);
378
379         return 0;
380 }
381
382 static void bxt_vtd_ggtt_insert_page__BKL(struct i915_address_space *vm,
383                                           dma_addr_t addr,
384                                           u64 offset,
385                                           enum i915_cache_level level,
386                                           u32 unused)
387 {
388         struct insert_page arg = { vm, addr, offset, level };
389
390         stop_machine(bxt_vtd_ggtt_insert_page__cb, &arg, NULL);
391 }
392
393 struct insert_entries {
394         struct i915_address_space *vm;
395         struct i915_vma *vma;
396         enum i915_cache_level level;
397         u32 flags;
398 };
399
400 static int bxt_vtd_ggtt_insert_entries__cb(void *_arg)
401 {
402         struct insert_entries *arg = _arg;
403
404         gen8_ggtt_insert_entries(arg->vm, arg->vma, arg->level, arg->flags);
405         bxt_vtd_ggtt_wa(arg->vm);
406
407         return 0;
408 }
409
410 static void bxt_vtd_ggtt_insert_entries__BKL(struct i915_address_space *vm,
411                                              struct i915_vma *vma,
412                                              enum i915_cache_level level,
413                                              u32 flags)
414 {
415         struct insert_entries arg = { vm, vma, level, flags };
416
417         stop_machine(bxt_vtd_ggtt_insert_entries__cb, &arg, NULL);
418 }
419
420 static void gen6_ggtt_clear_range(struct i915_address_space *vm,
421                                   u64 start, u64 length)
422 {
423         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
424         unsigned int first_entry = start / I915_GTT_PAGE_SIZE;
425         unsigned int num_entries = length / I915_GTT_PAGE_SIZE;
426         gen6_pte_t scratch_pte, __iomem *gtt_base =
427                 (gen6_pte_t __iomem *)ggtt->gsm + first_entry;
428         const int max_entries = ggtt_total_entries(ggtt) - first_entry;
429         int i;
430
431         if (WARN(num_entries > max_entries,
432                  "First entry = %d; Num entries = %d (max=%d)\n",
433                  first_entry, num_entries, max_entries))
434                 num_entries = max_entries;
435
436         scratch_pte = vm->scratch[0]->encode;
437         for (i = 0; i < num_entries; i++)
438                 iowrite32(scratch_pte, &gtt_base[i]);
439 }
440
441 static void i915_ggtt_insert_page(struct i915_address_space *vm,
442                                   dma_addr_t addr,
443                                   u64 offset,
444                                   enum i915_cache_level cache_level,
445                                   u32 unused)
446 {
447         unsigned int flags = (cache_level == I915_CACHE_NONE) ?
448                 AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
449
450         intel_gtt_insert_page(addr, offset >> PAGE_SHIFT, flags);
451 }
452
453 static void i915_ggtt_insert_entries(struct i915_address_space *vm,
454                                      struct i915_vma *vma,
455                                      enum i915_cache_level cache_level,
456                                      u32 unused)
457 {
458         unsigned int flags = (cache_level == I915_CACHE_NONE) ?
459                 AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
460
461         intel_gtt_insert_sg_entries(vma->pages, vma->node.start >> PAGE_SHIFT,
462                                     flags);
463 }
464
465 static void i915_ggtt_clear_range(struct i915_address_space *vm,
466                                   u64 start, u64 length)
467 {
468         intel_gtt_clear_range(start >> PAGE_SHIFT, length >> PAGE_SHIFT);
469 }
470
471 static void ggtt_bind_vma(struct i915_address_space *vm,
472                           struct i915_vm_pt_stash *stash,
473                           struct i915_vma *vma,
474                           enum i915_cache_level cache_level,
475                           u32 flags)
476 {
477         struct drm_i915_gem_object *obj = vma->obj;
478         u32 pte_flags;
479
480         if (i915_vma_is_bound(vma, ~flags & I915_VMA_BIND_MASK))
481                 return;
482
483         /* Applicable to VLV (gen8+ do not support RO in the GGTT) */
484         pte_flags = 0;
485         if (i915_gem_object_is_readonly(obj))
486                 pte_flags |= PTE_READ_ONLY;
487         if (i915_gem_object_is_lmem(obj))
488                 pte_flags |= PTE_LM;
489
490         vm->insert_entries(vm, vma, cache_level, pte_flags);
491         vma->page_sizes.gtt = I915_GTT_PAGE_SIZE;
492 }
493
494 static void ggtt_unbind_vma(struct i915_address_space *vm, struct i915_vma *vma)
495 {
496         vm->clear_range(vm, vma->node.start, vma->size);
497 }
498
499 static int ggtt_reserve_guc_top(struct i915_ggtt *ggtt)
500 {
501         u64 size;
502         int ret;
503
504         if (!intel_uc_uses_guc(&ggtt->vm.gt->uc))
505                 return 0;
506
507         GEM_BUG_ON(ggtt->vm.total <= GUC_GGTT_TOP);
508         size = ggtt->vm.total - GUC_GGTT_TOP;
509
510         ret = i915_gem_gtt_reserve(&ggtt->vm, &ggtt->uc_fw, size,
511                                    GUC_GGTT_TOP, I915_COLOR_UNEVICTABLE,
512                                    PIN_NOEVICT);
513         if (ret)
514                 drm_dbg(&ggtt->vm.i915->drm,
515                         "Failed to reserve top of GGTT for GuC\n");
516
517         return ret;
518 }
519
520 static void ggtt_release_guc_top(struct i915_ggtt *ggtt)
521 {
522         if (drm_mm_node_allocated(&ggtt->uc_fw))
523                 drm_mm_remove_node(&ggtt->uc_fw);
524 }
525
526 static void cleanup_init_ggtt(struct i915_ggtt *ggtt)
527 {
528         ggtt_release_guc_top(ggtt);
529         if (drm_mm_node_allocated(&ggtt->error_capture))
530                 drm_mm_remove_node(&ggtt->error_capture);
531         mutex_destroy(&ggtt->error_mutex);
532 }
533
534 static int init_ggtt(struct i915_ggtt *ggtt)
535 {
536         /*
537          * Let GEM Manage all of the aperture.
538          *
539          * However, leave one page at the end still bound to the scratch page.
540          * There are a number of places where the hardware apparently prefetches
541          * past the end of the object, and we've seen multiple hangs with the
542          * GPU head pointer stuck in a batchbuffer bound at the last page of the
543          * aperture.  One page should be enough to keep any prefetching inside
544          * of the aperture.
545          */
546         unsigned long hole_start, hole_end;
547         struct drm_mm_node *entry;
548         int ret;
549
550         /*
551          * GuC requires all resources that we're sharing with it to be placed in
552          * non-WOPCM memory. If GuC is not present or not in use we still need a
553          * small bias as ring wraparound at offset 0 sometimes hangs. No idea
554          * why.
555          */
556         ggtt->pin_bias = max_t(u32, I915_GTT_PAGE_SIZE,
557                                intel_wopcm_guc_size(&ggtt->vm.i915->wopcm));
558
559         ret = intel_vgt_balloon(ggtt);
560         if (ret)
561                 return ret;
562
563         mutex_init(&ggtt->error_mutex);
564         if (ggtt->mappable_end) {
565                 /*
566                  * Reserve a mappable slot for our lockless error capture.
567                  *
568                  * We strongly prefer taking address 0x0 in order to protect
569                  * other critical buffers against accidental overwrites,
570                  * as writing to address 0 is a very common mistake.
571                  *
572                  * Since 0 may already be in use by the system (e.g. the BIOS
573                  * framebuffer), we let the reservation fail quietly and hope
574                  * 0 remains reserved always.
575                  *
576                  * If we fail to reserve 0, and then fail to find any space
577                  * for an error-capture, remain silent. We can afford not
578                  * to reserve an error_capture node as we have fallback
579                  * paths, and we trust that 0 will remain reserved. However,
580                  * the only likely reason for failure to insert is a driver
581                  * bug, which we expect to cause other failures...
582                  */
583                 ggtt->error_capture.size = I915_GTT_PAGE_SIZE;
584                 ggtt->error_capture.color = I915_COLOR_UNEVICTABLE;
585                 if (drm_mm_reserve_node(&ggtt->vm.mm, &ggtt->error_capture))
586                         drm_mm_insert_node_in_range(&ggtt->vm.mm,
587                                                     &ggtt->error_capture,
588                                                     ggtt->error_capture.size, 0,
589                                                     ggtt->error_capture.color,
590                                                     0, ggtt->mappable_end,
591                                                     DRM_MM_INSERT_LOW);
592         }
593         if (drm_mm_node_allocated(&ggtt->error_capture))
594                 drm_dbg(&ggtt->vm.i915->drm,
595                         "Reserved GGTT:[%llx, %llx] for use by error capture\n",
596                         ggtt->error_capture.start,
597                         ggtt->error_capture.start + ggtt->error_capture.size);
598
599         /*
600          * The upper portion of the GuC address space has a sizeable hole
601          * (several MB) that is inaccessible by GuC. Reserve this range within
602          * GGTT as it can comfortably hold GuC/HuC firmware images.
603          */
604         ret = ggtt_reserve_guc_top(ggtt);
605         if (ret)
606                 goto err;
607
608         /* Clear any non-preallocated blocks */
609         drm_mm_for_each_hole(entry, &ggtt->vm.mm, hole_start, hole_end) {
610                 drm_dbg(&ggtt->vm.i915->drm,
611                         "clearing unused GTT space: [%lx, %lx]\n",
612                         hole_start, hole_end);
613                 ggtt->vm.clear_range(&ggtt->vm, hole_start,
614                                      hole_end - hole_start);
615         }
616
617         /* And finally clear the reserved guard page */
618         ggtt->vm.clear_range(&ggtt->vm, ggtt->vm.total - PAGE_SIZE, PAGE_SIZE);
619
620         return 0;
621
622 err:
623         cleanup_init_ggtt(ggtt);
624         return ret;
625 }
626
627 static void aliasing_gtt_bind_vma(struct i915_address_space *vm,
628                                   struct i915_vm_pt_stash *stash,
629                                   struct i915_vma *vma,
630                                   enum i915_cache_level cache_level,
631                                   u32 flags)
632 {
633         u32 pte_flags;
634
635         /* Currently applicable only to VLV */
636         pte_flags = 0;
637         if (i915_gem_object_is_readonly(vma->obj))
638                 pte_flags |= PTE_READ_ONLY;
639
640         if (flags & I915_VMA_LOCAL_BIND)
641                 ppgtt_bind_vma(&i915_vm_to_ggtt(vm)->alias->vm,
642                                stash, vma, cache_level, flags);
643
644         if (flags & I915_VMA_GLOBAL_BIND)
645                 vm->insert_entries(vm, vma, cache_level, pte_flags);
646 }
647
648 static void aliasing_gtt_unbind_vma(struct i915_address_space *vm,
649                                     struct i915_vma *vma)
650 {
651         if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
652                 vm->clear_range(vm, vma->node.start, vma->size);
653
654         if (i915_vma_is_bound(vma, I915_VMA_LOCAL_BIND))
655                 ppgtt_unbind_vma(&i915_vm_to_ggtt(vm)->alias->vm, vma);
656 }
657
658 static int init_aliasing_ppgtt(struct i915_ggtt *ggtt)
659 {
660         struct i915_vm_pt_stash stash = {};
661         struct i915_ppgtt *ppgtt;
662         int err;
663
664         ppgtt = i915_ppgtt_create(ggtt->vm.gt, 0);
665         if (IS_ERR(ppgtt))
666                 return PTR_ERR(ppgtt);
667
668         if (GEM_WARN_ON(ppgtt->vm.total < ggtt->vm.total)) {
669                 err = -ENODEV;
670                 goto err_ppgtt;
671         }
672
673         err = i915_vm_alloc_pt_stash(&ppgtt->vm, &stash, ggtt->vm.total);
674         if (err)
675                 goto err_ppgtt;
676
677         i915_gem_object_lock(ppgtt->vm.scratch[0], NULL);
678         err = i915_vm_map_pt_stash(&ppgtt->vm, &stash);
679         i915_gem_object_unlock(ppgtt->vm.scratch[0]);
680         if (err)
681                 goto err_stash;
682
683         /*
684          * Note we only pre-allocate as far as the end of the global
685          * GTT. On 48b / 4-level page-tables, the difference is very,
686          * very significant! We have to preallocate as GVT/vgpu does
687          * not like the page directory disappearing.
688          */
689         ppgtt->vm.allocate_va_range(&ppgtt->vm, &stash, 0, ggtt->vm.total);
690
691         ggtt->alias = ppgtt;
692         ggtt->vm.bind_async_flags |= ppgtt->vm.bind_async_flags;
693
694         GEM_BUG_ON(ggtt->vm.vma_ops.bind_vma != ggtt_bind_vma);
695         ggtt->vm.vma_ops.bind_vma = aliasing_gtt_bind_vma;
696
697         GEM_BUG_ON(ggtt->vm.vma_ops.unbind_vma != ggtt_unbind_vma);
698         ggtt->vm.vma_ops.unbind_vma = aliasing_gtt_unbind_vma;
699
700         i915_vm_free_pt_stash(&ppgtt->vm, &stash);
701         return 0;
702
703 err_stash:
704         i915_vm_free_pt_stash(&ppgtt->vm, &stash);
705 err_ppgtt:
706         i915_vm_put(&ppgtt->vm);
707         return err;
708 }
709
710 static void fini_aliasing_ppgtt(struct i915_ggtt *ggtt)
711 {
712         struct i915_ppgtt *ppgtt;
713
714         ppgtt = fetch_and_zero(&ggtt->alias);
715         if (!ppgtt)
716                 return;
717
718         i915_vm_put(&ppgtt->vm);
719
720         ggtt->vm.vma_ops.bind_vma   = ggtt_bind_vma;
721         ggtt->vm.vma_ops.unbind_vma = ggtt_unbind_vma;
722 }
723
724 int i915_init_ggtt(struct drm_i915_private *i915)
725 {
726         int ret;
727
728         ret = init_ggtt(&i915->ggtt);
729         if (ret)
730                 return ret;
731
732         if (INTEL_PPGTT(i915) == INTEL_PPGTT_ALIASING) {
733                 ret = init_aliasing_ppgtt(&i915->ggtt);
734                 if (ret)
735                         cleanup_init_ggtt(&i915->ggtt);
736         }
737
738         return 0;
739 }
740
741 static void ggtt_cleanup_hw(struct i915_ggtt *ggtt)
742 {
743         struct i915_vma *vma, *vn;
744
745         atomic_set(&ggtt->vm.open, 0);
746
747         flush_workqueue(ggtt->vm.i915->wq);
748
749         mutex_lock(&ggtt->vm.mutex);
750
751         list_for_each_entry_safe(vma, vn, &ggtt->vm.bound_list, vm_link)
752                 WARN_ON(__i915_vma_unbind(vma));
753
754         if (drm_mm_node_allocated(&ggtt->error_capture))
755                 drm_mm_remove_node(&ggtt->error_capture);
756         mutex_destroy(&ggtt->error_mutex);
757
758         ggtt_release_guc_top(ggtt);
759         intel_vgt_deballoon(ggtt);
760
761         ggtt->vm.cleanup(&ggtt->vm);
762
763         mutex_unlock(&ggtt->vm.mutex);
764         i915_address_space_fini(&ggtt->vm);
765
766         arch_phys_wc_del(ggtt->mtrr);
767
768         if (ggtt->iomap.size)
769                 io_mapping_fini(&ggtt->iomap);
770 }
771
772 /**
773  * i915_ggtt_driver_release - Clean up GGTT hardware initialization
774  * @i915: i915 device
775  */
776 void i915_ggtt_driver_release(struct drm_i915_private *i915)
777 {
778         struct i915_ggtt *ggtt = &i915->ggtt;
779
780         fini_aliasing_ppgtt(ggtt);
781
782         intel_ggtt_fini_fences(ggtt);
783         ggtt_cleanup_hw(ggtt);
784 }
785
786 /**
787  * i915_ggtt_driver_late_release - Cleanup of GGTT that needs to be done after
788  * all free objects have been drained.
789  * @i915: i915 device
790  */
791 void i915_ggtt_driver_late_release(struct drm_i915_private *i915)
792 {
793         struct i915_ggtt *ggtt = &i915->ggtt;
794
795         GEM_WARN_ON(kref_read(&ggtt->vm.resv_ref) != 1);
796         dma_resv_fini(&ggtt->vm._resv);
797 }
798
799 static unsigned int gen6_get_total_gtt_size(u16 snb_gmch_ctl)
800 {
801         snb_gmch_ctl >>= SNB_GMCH_GGMS_SHIFT;
802         snb_gmch_ctl &= SNB_GMCH_GGMS_MASK;
803         return snb_gmch_ctl << 20;
804 }
805
806 static unsigned int gen8_get_total_gtt_size(u16 bdw_gmch_ctl)
807 {
808         bdw_gmch_ctl >>= BDW_GMCH_GGMS_SHIFT;
809         bdw_gmch_ctl &= BDW_GMCH_GGMS_MASK;
810         if (bdw_gmch_ctl)
811                 bdw_gmch_ctl = 1 << bdw_gmch_ctl;
812
813 #ifdef CONFIG_X86_32
814         /* Limit 32b platforms to a 2GB GGTT: 4 << 20 / pte size * I915_GTT_PAGE_SIZE */
815         if (bdw_gmch_ctl > 4)
816                 bdw_gmch_ctl = 4;
817 #endif
818
819         return bdw_gmch_ctl << 20;
820 }
821
822 static unsigned int chv_get_total_gtt_size(u16 gmch_ctrl)
823 {
824         gmch_ctrl >>= SNB_GMCH_GGMS_SHIFT;
825         gmch_ctrl &= SNB_GMCH_GGMS_MASK;
826
827         if (gmch_ctrl)
828                 return 1 << (20 + gmch_ctrl);
829
830         return 0;
831 }
832
833 static unsigned int gen6_gttmmadr_size(struct drm_i915_private *i915)
834 {
835         /*
836          * GEN6: GTTMMADR size is 4MB and GTTADR starts at 2MB offset
837          * GEN8: GTTMMADR size is 16MB and GTTADR starts at 8MB offset
838          */
839         GEM_BUG_ON(GRAPHICS_VER(i915) < 6);
840         return (GRAPHICS_VER(i915) < 8) ? SZ_4M : SZ_16M;
841 }
842
843 static unsigned int gen6_gttadr_offset(struct drm_i915_private *i915)
844 {
845         return gen6_gttmmadr_size(i915) / 2;
846 }
847
848 static int ggtt_probe_common(struct i915_ggtt *ggtt, u64 size)
849 {
850         struct drm_i915_private *i915 = ggtt->vm.i915;
851         struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
852         phys_addr_t phys_addr;
853         u32 pte_flags;
854         int ret;
855
856         GEM_WARN_ON(pci_resource_len(pdev, 0) != gen6_gttmmadr_size(i915));
857         phys_addr = pci_resource_start(pdev, 0) + gen6_gttadr_offset(i915);
858
859         /*
860          * On BXT+/ICL+ writes larger than 64 bit to the GTT pagetable range
861          * will be dropped. For WC mappings in general we have 64 byte burst
862          * writes when the WC buffer is flushed, so we can't use it, but have to
863          * resort to an uncached mapping. The WC issue is easily caught by the
864          * readback check when writing GTT PTE entries.
865          */
866         if (IS_GEN9_LP(i915) || GRAPHICS_VER(i915) >= 11)
867                 ggtt->gsm = ioremap(phys_addr, size);
868         else
869                 ggtt->gsm = ioremap_wc(phys_addr, size);
870         if (!ggtt->gsm) {
871                 drm_err(&i915->drm, "Failed to map the ggtt page table\n");
872                 return -ENOMEM;
873         }
874
875         kref_init(&ggtt->vm.resv_ref);
876         ret = setup_scratch_page(&ggtt->vm);
877         if (ret) {
878                 drm_err(&i915->drm, "Scratch setup failed\n");
879                 /* iounmap will also get called at remove, but meh */
880                 iounmap(ggtt->gsm);
881                 return ret;
882         }
883
884         pte_flags = 0;
885         if (i915_gem_object_is_lmem(ggtt->vm.scratch[0]))
886                 pte_flags |= PTE_LM;
887
888         ggtt->vm.scratch[0]->encode =
889                 ggtt->vm.pte_encode(px_dma(ggtt->vm.scratch[0]),
890                                     I915_CACHE_NONE, pte_flags);
891
892         return 0;
893 }
894
895 int ggtt_set_pages(struct i915_vma *vma)
896 {
897         int ret;
898
899         GEM_BUG_ON(vma->pages);
900
901         ret = i915_get_ggtt_vma_pages(vma);
902         if (ret)
903                 return ret;
904
905         vma->page_sizes = vma->obj->mm.page_sizes;
906
907         return 0;
908 }
909
910 static void gen6_gmch_remove(struct i915_address_space *vm)
911 {
912         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
913
914         iounmap(ggtt->gsm);
915         free_scratch(vm);
916 }
917
918 static struct resource pci_resource(struct pci_dev *pdev, int bar)
919 {
920         return (struct resource)DEFINE_RES_MEM(pci_resource_start(pdev, bar),
921                                                pci_resource_len(pdev, bar));
922 }
923
924 static int gen8_gmch_probe(struct i915_ggtt *ggtt)
925 {
926         struct drm_i915_private *i915 = ggtt->vm.i915;
927         struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
928         unsigned int size;
929         u16 snb_gmch_ctl;
930
931         /* TODO: We're not aware of mappable constraints on gen8 yet */
932         if (!HAS_LMEM(i915)) {
933                 ggtt->gmadr = pci_resource(pdev, 2);
934                 ggtt->mappable_end = resource_size(&ggtt->gmadr);
935         }
936
937         pci_read_config_word(pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
938         if (IS_CHERRYVIEW(i915))
939                 size = chv_get_total_gtt_size(snb_gmch_ctl);
940         else
941                 size = gen8_get_total_gtt_size(snb_gmch_ctl);
942
943         ggtt->vm.alloc_pt_dma = alloc_pt_dma;
944         ggtt->vm.lmem_pt_obj_flags = I915_BO_ALLOC_PM_EARLY;
945
946         ggtt->vm.total = (size / sizeof(gen8_pte_t)) * I915_GTT_PAGE_SIZE;
947         ggtt->vm.cleanup = gen6_gmch_remove;
948         ggtt->vm.insert_page = gen8_ggtt_insert_page;
949         ggtt->vm.clear_range = nop_clear_range;
950         if (intel_scanout_needs_vtd_wa(i915))
951                 ggtt->vm.clear_range = gen8_ggtt_clear_range;
952
953         ggtt->vm.insert_entries = gen8_ggtt_insert_entries;
954
955         /*
956          * Serialize GTT updates with aperture access on BXT if VT-d is on,
957          * and always on CHV.
958          */
959         if (intel_vm_no_concurrent_access_wa(i915)) {
960                 ggtt->vm.insert_entries = bxt_vtd_ggtt_insert_entries__BKL;
961                 ggtt->vm.insert_page    = bxt_vtd_ggtt_insert_page__BKL;
962                 ggtt->vm.bind_async_flags =
963                         I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
964         }
965
966         ggtt->invalidate = gen8_ggtt_invalidate;
967
968         ggtt->vm.vma_ops.bind_vma    = ggtt_bind_vma;
969         ggtt->vm.vma_ops.unbind_vma  = ggtt_unbind_vma;
970         ggtt->vm.vma_ops.set_pages   = ggtt_set_pages;
971         ggtt->vm.vma_ops.clear_pages = clear_pages;
972
973         ggtt->vm.pte_encode = gen8_ggtt_pte_encode;
974
975         setup_private_pat(ggtt->vm.gt->uncore);
976
977         return ggtt_probe_common(ggtt, size);
978 }
979
980 static u64 snb_pte_encode(dma_addr_t addr,
981                           enum i915_cache_level level,
982                           u32 flags)
983 {
984         gen6_pte_t pte = GEN6_PTE_ADDR_ENCODE(addr) | GEN6_PTE_VALID;
985
986         switch (level) {
987         case I915_CACHE_L3_LLC:
988         case I915_CACHE_LLC:
989                 pte |= GEN6_PTE_CACHE_LLC;
990                 break;
991         case I915_CACHE_NONE:
992                 pte |= GEN6_PTE_UNCACHED;
993                 break;
994         default:
995                 MISSING_CASE(level);
996         }
997
998         return pte;
999 }
1000
1001 static u64 ivb_pte_encode(dma_addr_t addr,
1002                           enum i915_cache_level level,
1003                           u32 flags)
1004 {
1005         gen6_pte_t pte = GEN6_PTE_ADDR_ENCODE(addr) | GEN6_PTE_VALID;
1006
1007         switch (level) {
1008         case I915_CACHE_L3_LLC:
1009                 pte |= GEN7_PTE_CACHE_L3_LLC;
1010                 break;
1011         case I915_CACHE_LLC:
1012                 pte |= GEN6_PTE_CACHE_LLC;
1013                 break;
1014         case I915_CACHE_NONE:
1015                 pte |= GEN6_PTE_UNCACHED;
1016                 break;
1017         default:
1018                 MISSING_CASE(level);
1019         }
1020
1021         return pte;
1022 }
1023
1024 static u64 byt_pte_encode(dma_addr_t addr,
1025                           enum i915_cache_level level,
1026                           u32 flags)
1027 {
1028         gen6_pte_t pte = GEN6_PTE_ADDR_ENCODE(addr) | GEN6_PTE_VALID;
1029
1030         if (!(flags & PTE_READ_ONLY))
1031                 pte |= BYT_PTE_WRITEABLE;
1032
1033         if (level != I915_CACHE_NONE)
1034                 pte |= BYT_PTE_SNOOPED_BY_CPU_CACHES;
1035
1036         return pte;
1037 }
1038
1039 static u64 hsw_pte_encode(dma_addr_t addr,
1040                           enum i915_cache_level level,
1041                           u32 flags)
1042 {
1043         gen6_pte_t pte = HSW_PTE_ADDR_ENCODE(addr) | GEN6_PTE_VALID;
1044
1045         if (level != I915_CACHE_NONE)
1046                 pte |= HSW_WB_LLC_AGE3;
1047
1048         return pte;
1049 }
1050
1051 static u64 iris_pte_encode(dma_addr_t addr,
1052                            enum i915_cache_level level,
1053                            u32 flags)
1054 {
1055         gen6_pte_t pte = HSW_PTE_ADDR_ENCODE(addr) | GEN6_PTE_VALID;
1056
1057         switch (level) {
1058         case I915_CACHE_NONE:
1059                 break;
1060         case I915_CACHE_WT:
1061                 pte |= HSW_WT_ELLC_LLC_AGE3;
1062                 break;
1063         default:
1064                 pte |= HSW_WB_ELLC_LLC_AGE3;
1065                 break;
1066         }
1067
1068         return pte;
1069 }
1070
1071 static int gen6_gmch_probe(struct i915_ggtt *ggtt)
1072 {
1073         struct drm_i915_private *i915 = ggtt->vm.i915;
1074         struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
1075         unsigned int size;
1076         u16 snb_gmch_ctl;
1077
1078         ggtt->gmadr = pci_resource(pdev, 2);
1079         ggtt->mappable_end = resource_size(&ggtt->gmadr);
1080
1081         /*
1082          * 64/512MB is the current min/max we actually know of, but this is
1083          * just a coarse sanity check.
1084          */
1085         if (ggtt->mappable_end < (64<<20) || ggtt->mappable_end > (512<<20)) {
1086                 drm_err(&i915->drm, "Unknown GMADR size (%pa)\n",
1087                         &ggtt->mappable_end);
1088                 return -ENXIO;
1089         }
1090
1091         pci_read_config_word(pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
1092
1093         size = gen6_get_total_gtt_size(snb_gmch_ctl);
1094         ggtt->vm.total = (size / sizeof(gen6_pte_t)) * I915_GTT_PAGE_SIZE;
1095
1096         ggtt->vm.alloc_pt_dma = alloc_pt_dma;
1097
1098         ggtt->vm.clear_range = nop_clear_range;
1099         if (!HAS_FULL_PPGTT(i915) || intel_scanout_needs_vtd_wa(i915))
1100                 ggtt->vm.clear_range = gen6_ggtt_clear_range;
1101         ggtt->vm.insert_page = gen6_ggtt_insert_page;
1102         ggtt->vm.insert_entries = gen6_ggtt_insert_entries;
1103         ggtt->vm.cleanup = gen6_gmch_remove;
1104
1105         ggtt->invalidate = gen6_ggtt_invalidate;
1106
1107         if (HAS_EDRAM(i915))
1108                 ggtt->vm.pte_encode = iris_pte_encode;
1109         else if (IS_HASWELL(i915))
1110                 ggtt->vm.pte_encode = hsw_pte_encode;
1111         else if (IS_VALLEYVIEW(i915))
1112                 ggtt->vm.pte_encode = byt_pte_encode;
1113         else if (GRAPHICS_VER(i915) >= 7)
1114                 ggtt->vm.pte_encode = ivb_pte_encode;
1115         else
1116                 ggtt->vm.pte_encode = snb_pte_encode;
1117
1118         ggtt->vm.vma_ops.bind_vma    = ggtt_bind_vma;
1119         ggtt->vm.vma_ops.unbind_vma  = ggtt_unbind_vma;
1120         ggtt->vm.vma_ops.set_pages   = ggtt_set_pages;
1121         ggtt->vm.vma_ops.clear_pages = clear_pages;
1122
1123         return ggtt_probe_common(ggtt, size);
1124 }
1125
1126 static void i915_gmch_remove(struct i915_address_space *vm)
1127 {
1128         intel_gmch_remove();
1129 }
1130
1131 static int i915_gmch_probe(struct i915_ggtt *ggtt)
1132 {
1133         struct drm_i915_private *i915 = ggtt->vm.i915;
1134         phys_addr_t gmadr_base;
1135         int ret;
1136
1137         ret = intel_gmch_probe(i915->bridge_dev, to_pci_dev(i915->drm.dev), NULL);
1138         if (!ret) {
1139                 drm_err(&i915->drm, "failed to set up gmch\n");
1140                 return -EIO;
1141         }
1142
1143         intel_gtt_get(&ggtt->vm.total, &gmadr_base, &ggtt->mappable_end);
1144
1145         ggtt->gmadr =
1146                 (struct resource)DEFINE_RES_MEM(gmadr_base, ggtt->mappable_end);
1147
1148         ggtt->vm.alloc_pt_dma = alloc_pt_dma;
1149
1150         if (needs_idle_maps(i915)) {
1151                 drm_notice(&i915->drm,
1152                            "Flushing DMA requests before IOMMU unmaps; performance may be degraded\n");
1153                 ggtt->do_idle_maps = true;
1154         }
1155
1156         ggtt->vm.insert_page = i915_ggtt_insert_page;
1157         ggtt->vm.insert_entries = i915_ggtt_insert_entries;
1158         ggtt->vm.clear_range = i915_ggtt_clear_range;
1159         ggtt->vm.cleanup = i915_gmch_remove;
1160
1161         ggtt->invalidate = gmch_ggtt_invalidate;
1162
1163         ggtt->vm.vma_ops.bind_vma    = ggtt_bind_vma;
1164         ggtt->vm.vma_ops.unbind_vma  = ggtt_unbind_vma;
1165         ggtt->vm.vma_ops.set_pages   = ggtt_set_pages;
1166         ggtt->vm.vma_ops.clear_pages = clear_pages;
1167
1168         if (unlikely(ggtt->do_idle_maps))
1169                 drm_notice(&i915->drm,
1170                            "Applying Ironlake quirks for intel_iommu\n");
1171
1172         return 0;
1173 }
1174
1175 static int ggtt_probe_hw(struct i915_ggtt *ggtt, struct intel_gt *gt)
1176 {
1177         struct drm_i915_private *i915 = gt->i915;
1178         int ret;
1179
1180         ggtt->vm.gt = gt;
1181         ggtt->vm.i915 = i915;
1182         ggtt->vm.dma = i915->drm.dev;
1183         dma_resv_init(&ggtt->vm._resv);
1184
1185         if (GRAPHICS_VER(i915) <= 5)
1186                 ret = i915_gmch_probe(ggtt);
1187         else if (GRAPHICS_VER(i915) < 8)
1188                 ret = gen6_gmch_probe(ggtt);
1189         else
1190                 ret = gen8_gmch_probe(ggtt);
1191         if (ret) {
1192                 dma_resv_fini(&ggtt->vm._resv);
1193                 return ret;
1194         }
1195
1196         if ((ggtt->vm.total - 1) >> 32) {
1197                 drm_err(&i915->drm,
1198                         "We never expected a Global GTT with more than 32bits"
1199                         " of address space! Found %lldM!\n",
1200                         ggtt->vm.total >> 20);
1201                 ggtt->vm.total = 1ULL << 32;
1202                 ggtt->mappable_end =
1203                         min_t(u64, ggtt->mappable_end, ggtt->vm.total);
1204         }
1205
1206         if (ggtt->mappable_end > ggtt->vm.total) {
1207                 drm_err(&i915->drm,
1208                         "mappable aperture extends past end of GGTT,"
1209                         " aperture=%pa, total=%llx\n",
1210                         &ggtt->mappable_end, ggtt->vm.total);
1211                 ggtt->mappable_end = ggtt->vm.total;
1212         }
1213
1214         /* GMADR is the PCI mmio aperture into the global GTT. */
1215         drm_dbg(&i915->drm, "GGTT size = %lluM\n", ggtt->vm.total >> 20);
1216         drm_dbg(&i915->drm, "GMADR size = %lluM\n",
1217                 (u64)ggtt->mappable_end >> 20);
1218         drm_dbg(&i915->drm, "DSM size = %lluM\n",
1219                 (u64)resource_size(&intel_graphics_stolen_res) >> 20);
1220
1221         return 0;
1222 }
1223
1224 /**
1225  * i915_ggtt_probe_hw - Probe GGTT hardware location
1226  * @i915: i915 device
1227  */
1228 int i915_ggtt_probe_hw(struct drm_i915_private *i915)
1229 {
1230         int ret;
1231
1232         ret = ggtt_probe_hw(&i915->ggtt, &i915->gt);
1233         if (ret)
1234                 return ret;
1235
1236         if (intel_vtd_active())
1237                 drm_info(&i915->drm, "VT-d active for gfx access\n");
1238
1239         return 0;
1240 }
1241
1242 int i915_ggtt_enable_hw(struct drm_i915_private *i915)
1243 {
1244         if (GRAPHICS_VER(i915) < 6 && !intel_enable_gtt())
1245                 return -EIO;
1246
1247         return 0;
1248 }
1249
1250 void i915_ggtt_enable_guc(struct i915_ggtt *ggtt)
1251 {
1252         GEM_BUG_ON(ggtt->invalidate != gen8_ggtt_invalidate);
1253
1254         ggtt->invalidate = guc_ggtt_invalidate;
1255
1256         ggtt->invalidate(ggtt);
1257 }
1258
1259 void i915_ggtt_disable_guc(struct i915_ggtt *ggtt)
1260 {
1261         /* XXX Temporary pardon for error unload */
1262         if (ggtt->invalidate == gen8_ggtt_invalidate)
1263                 return;
1264
1265         /* We should only be called after i915_ggtt_enable_guc() */
1266         GEM_BUG_ON(ggtt->invalidate != guc_ggtt_invalidate);
1267
1268         ggtt->invalidate = gen8_ggtt_invalidate;
1269
1270         ggtt->invalidate(ggtt);
1271 }
1272
1273 /**
1274  * i915_ggtt_resume_vm - Restore the memory mappings for a GGTT or DPT VM
1275  * @vm: The VM to restore the mappings for
1276  *
1277  * Restore the memory mappings for all objects mapped to HW via the GGTT or a
1278  * DPT page table.
1279  *
1280  * Returns %true if restoring the mapping for any object that was in a write
1281  * domain before suspend.
1282  */
1283 bool i915_ggtt_resume_vm(struct i915_address_space *vm)
1284 {
1285         struct i915_vma *vma;
1286         bool write_domain_objs = false;
1287         int open;
1288
1289         drm_WARN_ON(&vm->i915->drm, !vm->is_ggtt && !vm->is_dpt);
1290
1291         /* First fill our portion of the GTT with scratch pages */
1292         vm->clear_range(vm, 0, vm->total);
1293
1294         /* Skip rewriting PTE on VMA unbind. */
1295         open = atomic_xchg(&vm->open, 0);
1296
1297         /* clflush objects bound into the GGTT and rebind them. */
1298         list_for_each_entry(vma, &vm->bound_list, vm_link) {
1299                 struct drm_i915_gem_object *obj = vma->obj;
1300                 unsigned int was_bound =
1301                         atomic_read(&vma->flags) & I915_VMA_BIND_MASK;
1302
1303                 GEM_BUG_ON(!was_bound);
1304                 vma->ops->bind_vma(vm, NULL, vma,
1305                                    obj ? obj->cache_level : 0,
1306                                    was_bound);
1307                 if (obj) { /* only used during resume => exclusive access */
1308                         write_domain_objs |= fetch_and_zero(&obj->write_domain);
1309                         obj->read_domains |= I915_GEM_DOMAIN_GTT;
1310                 }
1311         }
1312
1313         atomic_set(&vm->open, open);
1314
1315         return write_domain_objs;
1316 }
1317
1318 void i915_ggtt_resume(struct i915_ggtt *ggtt)
1319 {
1320         bool flush;
1321
1322         intel_gt_check_and_clear_faults(ggtt->vm.gt);
1323
1324         flush = i915_ggtt_resume_vm(&ggtt->vm);
1325
1326         ggtt->invalidate(ggtt);
1327
1328         if (flush)
1329                 wbinvd_on_all_cpus();
1330
1331         if (GRAPHICS_VER(ggtt->vm.i915) >= 8)
1332                 setup_private_pat(ggtt->vm.gt->uncore);
1333
1334         intel_ggtt_restore_fences(ggtt);
1335 }
1336
1337 static struct scatterlist *
1338 rotate_pages(struct drm_i915_gem_object *obj, unsigned int offset,
1339              unsigned int width, unsigned int height,
1340              unsigned int src_stride, unsigned int dst_stride,
1341              struct sg_table *st, struct scatterlist *sg)
1342 {
1343         unsigned int column, row;
1344         unsigned int src_idx;
1345
1346         for (column = 0; column < width; column++) {
1347                 unsigned int left;
1348
1349                 src_idx = src_stride * (height - 1) + column + offset;
1350                 for (row = 0; row < height; row++) {
1351                         st->nents++;
1352                         /*
1353                          * We don't need the pages, but need to initialize
1354                          * the entries so the sg list can be happily traversed.
1355                          * The only thing we need are DMA addresses.
1356                          */
1357                         sg_set_page(sg, NULL, I915_GTT_PAGE_SIZE, 0);
1358                         sg_dma_address(sg) =
1359                                 i915_gem_object_get_dma_address(obj, src_idx);
1360                         sg_dma_len(sg) = I915_GTT_PAGE_SIZE;
1361                         sg = sg_next(sg);
1362                         src_idx -= src_stride;
1363                 }
1364
1365                 left = (dst_stride - height) * I915_GTT_PAGE_SIZE;
1366
1367                 if (!left)
1368                         continue;
1369
1370                 st->nents++;
1371
1372                 /*
1373                  * The DE ignores the PTEs for the padding tiles, the sg entry
1374                  * here is just a conenience to indicate how many padding PTEs
1375                  * to insert at this spot.
1376                  */
1377                 sg_set_page(sg, NULL, left, 0);
1378                 sg_dma_address(sg) = 0;
1379                 sg_dma_len(sg) = left;
1380                 sg = sg_next(sg);
1381         }
1382
1383         return sg;
1384 }
1385
1386 static noinline struct sg_table *
1387 intel_rotate_pages(struct intel_rotation_info *rot_info,
1388                    struct drm_i915_gem_object *obj)
1389 {
1390         unsigned int size = intel_rotation_info_size(rot_info);
1391         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1392         struct sg_table *st;
1393         struct scatterlist *sg;
1394         int ret = -ENOMEM;
1395         int i;
1396
1397         /* Allocate target SG list. */
1398         st = kmalloc(sizeof(*st), GFP_KERNEL);
1399         if (!st)
1400                 goto err_st_alloc;
1401
1402         ret = sg_alloc_table(st, size, GFP_KERNEL);
1403         if (ret)
1404                 goto err_sg_alloc;
1405
1406         st->nents = 0;
1407         sg = st->sgl;
1408
1409         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1410                 sg = rotate_pages(obj, rot_info->plane[i].offset,
1411                                   rot_info->plane[i].width, rot_info->plane[i].height,
1412                                   rot_info->plane[i].src_stride,
1413                                   rot_info->plane[i].dst_stride,
1414                                   st, sg);
1415
1416         return st;
1417
1418 err_sg_alloc:
1419         kfree(st);
1420 err_st_alloc:
1421
1422         drm_dbg(&i915->drm, "Failed to create rotated mapping for object size %zu! (%ux%u tiles, %u pages)\n",
1423                 obj->base.size, rot_info->plane[0].width,
1424                 rot_info->plane[0].height, size);
1425
1426         return ERR_PTR(ret);
1427 }
1428
1429 static struct scatterlist *
1430 add_padding_pages(unsigned int count,
1431                   struct sg_table *st, struct scatterlist *sg)
1432 {
1433         st->nents++;
1434
1435         /*
1436          * The DE ignores the PTEs for the padding tiles, the sg entry
1437          * here is just a convenience to indicate how many padding PTEs
1438          * to insert at this spot.
1439          */
1440         sg_set_page(sg, NULL, count * I915_GTT_PAGE_SIZE, 0);
1441         sg_dma_address(sg) = 0;
1442         sg_dma_len(sg) = count * I915_GTT_PAGE_SIZE;
1443         sg = sg_next(sg);
1444
1445         return sg;
1446 }
1447
1448 static struct scatterlist *
1449 remap_tiled_color_plane_pages(struct drm_i915_gem_object *obj,
1450                               unsigned int offset, unsigned int alignment_pad,
1451                               unsigned int width, unsigned int height,
1452                               unsigned int src_stride, unsigned int dst_stride,
1453                               struct sg_table *st, struct scatterlist *sg,
1454                               unsigned int *gtt_offset)
1455 {
1456         unsigned int row;
1457
1458         if (!width || !height)
1459                 return sg;
1460
1461         if (alignment_pad)
1462                 sg = add_padding_pages(alignment_pad, st, sg);
1463
1464         for (row = 0; row < height; row++) {
1465                 unsigned int left = width * I915_GTT_PAGE_SIZE;
1466
1467                 while (left) {
1468                         dma_addr_t addr;
1469                         unsigned int length;
1470
1471                         /*
1472                          * We don't need the pages, but need to initialize
1473                          * the entries so the sg list can be happily traversed.
1474                          * The only thing we need are DMA addresses.
1475                          */
1476
1477                         addr = i915_gem_object_get_dma_address_len(obj, offset, &length);
1478
1479                         length = min(left, length);
1480
1481                         st->nents++;
1482
1483                         sg_set_page(sg, NULL, length, 0);
1484                         sg_dma_address(sg) = addr;
1485                         sg_dma_len(sg) = length;
1486                         sg = sg_next(sg);
1487
1488                         offset += length / I915_GTT_PAGE_SIZE;
1489                         left -= length;
1490                 }
1491
1492                 offset += src_stride - width;
1493
1494                 left = (dst_stride - width) * I915_GTT_PAGE_SIZE;
1495
1496                 if (!left)
1497                         continue;
1498
1499                 sg = add_padding_pages(left >> PAGE_SHIFT, st, sg);
1500         }
1501
1502         *gtt_offset += alignment_pad + dst_stride * height;
1503
1504         return sg;
1505 }
1506
1507 static struct scatterlist *
1508 remap_contiguous_pages(struct drm_i915_gem_object *obj,
1509                        unsigned int obj_offset,
1510                        unsigned int count,
1511                        struct sg_table *st, struct scatterlist *sg)
1512 {
1513         struct scatterlist *iter;
1514         unsigned int offset;
1515
1516         iter = i915_gem_object_get_sg_dma(obj, obj_offset, &offset);
1517         GEM_BUG_ON(!iter);
1518
1519         do {
1520                 unsigned int len;
1521
1522                 len = min(sg_dma_len(iter) - (offset << PAGE_SHIFT),
1523                           count << PAGE_SHIFT);
1524                 sg_set_page(sg, NULL, len, 0);
1525                 sg_dma_address(sg) =
1526                         sg_dma_address(iter) + (offset << PAGE_SHIFT);
1527                 sg_dma_len(sg) = len;
1528
1529                 st->nents++;
1530                 count -= len >> PAGE_SHIFT;
1531                 if (count == 0)
1532                         return sg;
1533
1534                 sg = __sg_next(sg);
1535                 iter = __sg_next(iter);
1536                 offset = 0;
1537         } while (1);
1538 }
1539
1540 static struct scatterlist *
1541 remap_linear_color_plane_pages(struct drm_i915_gem_object *obj,
1542                                unsigned int obj_offset, unsigned int alignment_pad,
1543                                unsigned int size,
1544                                struct sg_table *st, struct scatterlist *sg,
1545                                unsigned int *gtt_offset)
1546 {
1547         if (!size)
1548                 return sg;
1549
1550         if (alignment_pad)
1551                 sg = add_padding_pages(alignment_pad, st, sg);
1552
1553         sg = remap_contiguous_pages(obj, obj_offset, size, st, sg);
1554         sg = sg_next(sg);
1555
1556         *gtt_offset += alignment_pad + size;
1557
1558         return sg;
1559 }
1560
1561 static struct scatterlist *
1562 remap_color_plane_pages(const struct intel_remapped_info *rem_info,
1563                         struct drm_i915_gem_object *obj,
1564                         int color_plane,
1565                         struct sg_table *st, struct scatterlist *sg,
1566                         unsigned int *gtt_offset)
1567 {
1568         unsigned int alignment_pad = 0;
1569
1570         if (rem_info->plane_alignment)
1571                 alignment_pad = ALIGN(*gtt_offset, rem_info->plane_alignment) - *gtt_offset;
1572
1573         if (rem_info->plane[color_plane].linear)
1574                 sg = remap_linear_color_plane_pages(obj,
1575                                                     rem_info->plane[color_plane].offset,
1576                                                     alignment_pad,
1577                                                     rem_info->plane[color_plane].size,
1578                                                     st, sg,
1579                                                     gtt_offset);
1580
1581         else
1582                 sg = remap_tiled_color_plane_pages(obj,
1583                                                    rem_info->plane[color_plane].offset,
1584                                                    alignment_pad,
1585                                                    rem_info->plane[color_plane].width,
1586                                                    rem_info->plane[color_plane].height,
1587                                                    rem_info->plane[color_plane].src_stride,
1588                                                    rem_info->plane[color_plane].dst_stride,
1589                                                    st, sg,
1590                                                    gtt_offset);
1591
1592         return sg;
1593 }
1594
1595 static noinline struct sg_table *
1596 intel_remap_pages(struct intel_remapped_info *rem_info,
1597                   struct drm_i915_gem_object *obj)
1598 {
1599         unsigned int size = intel_remapped_info_size(rem_info);
1600         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1601         struct sg_table *st;
1602         struct scatterlist *sg;
1603         unsigned int gtt_offset = 0;
1604         int ret = -ENOMEM;
1605         int i;
1606
1607         /* Allocate target SG list. */
1608         st = kmalloc(sizeof(*st), GFP_KERNEL);
1609         if (!st)
1610                 goto err_st_alloc;
1611
1612         ret = sg_alloc_table(st, size, GFP_KERNEL);
1613         if (ret)
1614                 goto err_sg_alloc;
1615
1616         st->nents = 0;
1617         sg = st->sgl;
1618
1619         for (i = 0 ; i < ARRAY_SIZE(rem_info->plane); i++)
1620                 sg = remap_color_plane_pages(rem_info, obj, i, st, sg, &gtt_offset);
1621
1622         i915_sg_trim(st);
1623
1624         return st;
1625
1626 err_sg_alloc:
1627         kfree(st);
1628 err_st_alloc:
1629
1630         drm_dbg(&i915->drm, "Failed to create remapped mapping for object size %zu! (%ux%u tiles, %u pages)\n",
1631                 obj->base.size, rem_info->plane[0].width,
1632                 rem_info->plane[0].height, size);
1633
1634         return ERR_PTR(ret);
1635 }
1636
1637 static noinline struct sg_table *
1638 intel_partial_pages(const struct i915_ggtt_view *view,
1639                     struct drm_i915_gem_object *obj)
1640 {
1641         struct sg_table *st;
1642         struct scatterlist *sg;
1643         unsigned int count = view->partial.size;
1644         int ret = -ENOMEM;
1645
1646         st = kmalloc(sizeof(*st), GFP_KERNEL);
1647         if (!st)
1648                 goto err_st_alloc;
1649
1650         ret = sg_alloc_table(st, count, GFP_KERNEL);
1651         if (ret)
1652                 goto err_sg_alloc;
1653
1654         st->nents = 0;
1655
1656         sg = remap_contiguous_pages(obj, view->partial.offset, count, st, st->sgl);
1657
1658         sg_mark_end(sg);
1659         i915_sg_trim(st); /* Drop any unused tail entries. */
1660
1661         return st;
1662
1663 err_sg_alloc:
1664         kfree(st);
1665 err_st_alloc:
1666         return ERR_PTR(ret);
1667 }
1668
1669 static int
1670 i915_get_ggtt_vma_pages(struct i915_vma *vma)
1671 {
1672         int ret;
1673
1674         /*
1675          * The vma->pages are only valid within the lifespan of the borrowed
1676          * obj->mm.pages. When the obj->mm.pages sg_table is regenerated, so
1677          * must be the vma->pages. A simple rule is that vma->pages must only
1678          * be accessed when the obj->mm.pages are pinned.
1679          */
1680         GEM_BUG_ON(!i915_gem_object_has_pinned_pages(vma->obj));
1681
1682         switch (vma->ggtt_view.type) {
1683         default:
1684                 GEM_BUG_ON(vma->ggtt_view.type);
1685                 fallthrough;
1686         case I915_GGTT_VIEW_NORMAL:
1687                 vma->pages = vma->obj->mm.pages;
1688                 return 0;
1689
1690         case I915_GGTT_VIEW_ROTATED:
1691                 vma->pages =
1692                         intel_rotate_pages(&vma->ggtt_view.rotated, vma->obj);
1693                 break;
1694
1695         case I915_GGTT_VIEW_REMAPPED:
1696                 vma->pages =
1697                         intel_remap_pages(&vma->ggtt_view.remapped, vma->obj);
1698                 break;
1699
1700         case I915_GGTT_VIEW_PARTIAL:
1701                 vma->pages = intel_partial_pages(&vma->ggtt_view, vma->obj);
1702                 break;
1703         }
1704
1705         ret = 0;
1706         if (IS_ERR(vma->pages)) {
1707                 ret = PTR_ERR(vma->pages);
1708                 vma->pages = NULL;
1709                 drm_err(&vma->vm->i915->drm,
1710                         "Failed to get pages for VMA view type %u (%d)!\n",
1711                         vma->ggtt_view.type, ret);
1712         }
1713         return ret;
1714 }