]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c
drm/amdgpu: correctly sign extend 48bit addresses v3
[linux.git] / drivers / gpu / drm / amd / amdgpu / amdgpu_vm.c
1 /*
2  * Copyright 2008 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors: Dave Airlie
25  *          Alex Deucher
26  *          Jerome Glisse
27  */
28 #include <linux/dma-fence-array.h>
29 #include <linux/interval_tree_generic.h>
30 #include <linux/idr.h>
31 #include <drm/drmP.h>
32 #include <drm/amdgpu_drm.h>
33 #include "amdgpu.h"
34 #include "amdgpu_trace.h"
35 #include "amdgpu_amdkfd.h"
36 #include "amdgpu_gmc.h"
37
38 /**
39  * DOC: GPUVM
40  *
41  * GPUVM is similar to the legacy gart on older asics, however
42  * rather than there being a single global gart table
43  * for the entire GPU, there are multiple VM page tables active
44  * at any given time.  The VM page tables can contain a mix
45  * vram pages and system memory pages and system memory pages
46  * can be mapped as snooped (cached system pages) or unsnooped
47  * (uncached system pages).
48  * Each VM has an ID associated with it and there is a page table
49  * associated with each VMID.  When execting a command buffer,
50  * the kernel tells the the ring what VMID to use for that command
51  * buffer.  VMIDs are allocated dynamically as commands are submitted.
52  * The userspace drivers maintain their own address space and the kernel
53  * sets up their pages tables accordingly when they submit their
54  * command buffers and a VMID is assigned.
55  * Cayman/Trinity support up to 8 active VMs at any given time;
56  * SI supports 16.
57  */
58
59 #define START(node) ((node)->start)
60 #define LAST(node) ((node)->last)
61
62 INTERVAL_TREE_DEFINE(struct amdgpu_bo_va_mapping, rb, uint64_t, __subtree_last,
63                      START, LAST, static, amdgpu_vm_it)
64
65 #undef START
66 #undef LAST
67
68 /**
69  * struct amdgpu_pte_update_params - Local structure
70  *
71  * Encapsulate some VM table update parameters to reduce
72  * the number of function parameters
73  *
74  */
75 struct amdgpu_pte_update_params {
76
77         /**
78          * @adev: amdgpu device we do this update for
79          */
80         struct amdgpu_device *adev;
81
82         /**
83          * @vm: optional amdgpu_vm we do this update for
84          */
85         struct amdgpu_vm *vm;
86
87         /**
88          * @src: address where to copy page table entries from
89          */
90         uint64_t src;
91
92         /**
93          * @ib: indirect buffer to fill with commands
94          */
95         struct amdgpu_ib *ib;
96
97         /**
98          * @func: Function which actually does the update
99          */
100         void (*func)(struct amdgpu_pte_update_params *params,
101                      struct amdgpu_bo *bo, uint64_t pe,
102                      uint64_t addr, unsigned count, uint32_t incr,
103                      uint64_t flags);
104         /**
105          * @pages_addr:
106          *
107          * DMA addresses to use for mapping, used during VM update by CPU
108          */
109         dma_addr_t *pages_addr;
110
111         /**
112          * @kptr:
113          *
114          * Kernel pointer of PD/PT BO that needs to be updated,
115          * used during VM update by CPU
116          */
117         void *kptr;
118 };
119
120 /**
121  * struct amdgpu_prt_cb - Helper to disable partial resident texture feature from a fence callback
122  */
123 struct amdgpu_prt_cb {
124
125         /**
126          * @adev: amdgpu device
127          */
128         struct amdgpu_device *adev;
129
130         /**
131          * @cb: callback
132          */
133         struct dma_fence_cb cb;
134 };
135
136 /**
137  * amdgpu_vm_level_shift - return the addr shift for each level
138  *
139  * @adev: amdgpu_device pointer
140  * @level: VMPT level
141  *
142  * Returns:
143  * The number of bits the pfn needs to be right shifted for a level.
144  */
145 static unsigned amdgpu_vm_level_shift(struct amdgpu_device *adev,
146                                       unsigned level)
147 {
148         unsigned shift = 0xff;
149
150         switch (level) {
151         case AMDGPU_VM_PDB2:
152         case AMDGPU_VM_PDB1:
153         case AMDGPU_VM_PDB0:
154                 shift = 9 * (AMDGPU_VM_PDB0 - level) +
155                         adev->vm_manager.block_size;
156                 break;
157         case AMDGPU_VM_PTB:
158                 shift = 0;
159                 break;
160         default:
161                 dev_err(adev->dev, "the level%d isn't supported.\n", level);
162         }
163
164         return shift;
165 }
166
167 /**
168  * amdgpu_vm_num_entries - return the number of entries in a PD/PT
169  *
170  * @adev: amdgpu_device pointer
171  * @level: VMPT level
172  *
173  * Returns:
174  * The number of entries in a page directory or page table.
175  */
176 static unsigned amdgpu_vm_num_entries(struct amdgpu_device *adev,
177                                       unsigned level)
178 {
179         unsigned shift = amdgpu_vm_level_shift(adev,
180                                                adev->vm_manager.root_level);
181
182         if (level == adev->vm_manager.root_level)
183                 /* For the root directory */
184                 return round_up(adev->vm_manager.max_pfn, 1 << shift) >> shift;
185         else if (level != AMDGPU_VM_PTB)
186                 /* Everything in between */
187                 return 512;
188         else
189                 /* For the page tables on the leaves */
190                 return AMDGPU_VM_PTE_COUNT(adev);
191 }
192
193 /**
194  * amdgpu_vm_bo_size - returns the size of the BOs in bytes
195  *
196  * @adev: amdgpu_device pointer
197  * @level: VMPT level
198  *
199  * Returns:
200  * The size of the BO for a page directory or page table in bytes.
201  */
202 static unsigned amdgpu_vm_bo_size(struct amdgpu_device *adev, unsigned level)
203 {
204         return AMDGPU_GPU_PAGE_ALIGN(amdgpu_vm_num_entries(adev, level) * 8);
205 }
206
207 /**
208  * amdgpu_vm_bo_evicted - vm_bo is evicted
209  *
210  * @vm_bo: vm_bo which is evicted
211  *
212  * State for PDs/PTs and per VM BOs which are not at the location they should
213  * be.
214  */
215 static void amdgpu_vm_bo_evicted(struct amdgpu_vm_bo_base *vm_bo)
216 {
217         struct amdgpu_vm *vm = vm_bo->vm;
218         struct amdgpu_bo *bo = vm_bo->bo;
219
220         vm_bo->moved = true;
221         if (bo->tbo.type == ttm_bo_type_kernel)
222                 list_move(&vm_bo->vm_status, &vm->evicted);
223         else
224                 list_move_tail(&vm_bo->vm_status, &vm->evicted);
225 }
226
227 /**
228  * amdgpu_vm_bo_relocated - vm_bo is reloacted
229  *
230  * @vm_bo: vm_bo which is relocated
231  *
232  * State for PDs/PTs which needs to update their parent PD.
233  */
234 static void amdgpu_vm_bo_relocated(struct amdgpu_vm_bo_base *vm_bo)
235 {
236         list_move(&vm_bo->vm_status, &vm_bo->vm->relocated);
237 }
238
239 /**
240  * amdgpu_vm_bo_moved - vm_bo is moved
241  *
242  * @vm_bo: vm_bo which is moved
243  *
244  * State for per VM BOs which are moved, but that change is not yet reflected
245  * in the page tables.
246  */
247 static void amdgpu_vm_bo_moved(struct amdgpu_vm_bo_base *vm_bo)
248 {
249         list_move(&vm_bo->vm_status, &vm_bo->vm->moved);
250 }
251
252 /**
253  * amdgpu_vm_bo_idle - vm_bo is idle
254  *
255  * @vm_bo: vm_bo which is now idle
256  *
257  * State for PDs/PTs and per VM BOs which have gone through the state machine
258  * and are now idle.
259  */
260 static void amdgpu_vm_bo_idle(struct amdgpu_vm_bo_base *vm_bo)
261 {
262         list_move(&vm_bo->vm_status, &vm_bo->vm->idle);
263         vm_bo->moved = false;
264 }
265
266 /**
267  * amdgpu_vm_bo_invalidated - vm_bo is invalidated
268  *
269  * @vm_bo: vm_bo which is now invalidated
270  *
271  * State for normal BOs which are invalidated and that change not yet reflected
272  * in the PTs.
273  */
274 static void amdgpu_vm_bo_invalidated(struct amdgpu_vm_bo_base *vm_bo)
275 {
276         spin_lock(&vm_bo->vm->invalidated_lock);
277         list_move(&vm_bo->vm_status, &vm_bo->vm->invalidated);
278         spin_unlock(&vm_bo->vm->invalidated_lock);
279 }
280
281 /**
282  * amdgpu_vm_bo_done - vm_bo is done
283  *
284  * @vm_bo: vm_bo which is now done
285  *
286  * State for normal BOs which are invalidated and that change has been updated
287  * in the PTs.
288  */
289 static void amdgpu_vm_bo_done(struct amdgpu_vm_bo_base *vm_bo)
290 {
291         spin_lock(&vm_bo->vm->invalidated_lock);
292         list_del_init(&vm_bo->vm_status);
293         spin_unlock(&vm_bo->vm->invalidated_lock);
294 }
295
296 /**
297  * amdgpu_vm_bo_base_init - Adds bo to the list of bos associated with the vm
298  *
299  * @base: base structure for tracking BO usage in a VM
300  * @vm: vm to which bo is to be added
301  * @bo: amdgpu buffer object
302  *
303  * Initialize a bo_va_base structure and add it to the appropriate lists
304  *
305  */
306 static void amdgpu_vm_bo_base_init(struct amdgpu_vm_bo_base *base,
307                                    struct amdgpu_vm *vm,
308                                    struct amdgpu_bo *bo)
309 {
310         base->vm = vm;
311         base->bo = bo;
312         INIT_LIST_HEAD(&base->bo_list);
313         INIT_LIST_HEAD(&base->vm_status);
314
315         if (!bo)
316                 return;
317         list_add_tail(&base->bo_list, &bo->va);
318
319         if (bo->tbo.resv != vm->root.base.bo->tbo.resv)
320                 return;
321
322         vm->bulk_moveable = false;
323         if (bo->tbo.type == ttm_bo_type_kernel)
324                 amdgpu_vm_bo_relocated(base);
325         else
326                 amdgpu_vm_bo_idle(base);
327
328         if (bo->preferred_domains &
329             amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type))
330                 return;
331
332         /*
333          * we checked all the prerequisites, but it looks like this per vm bo
334          * is currently evicted. add the bo to the evicted list to make sure it
335          * is validated on next vm use to avoid fault.
336          * */
337         amdgpu_vm_bo_evicted(base);
338 }
339
340 /**
341  * amdgpu_vm_get_pd_bo - add the VM PD to a validation list
342  *
343  * @vm: vm providing the BOs
344  * @validated: head of validation list
345  * @entry: entry to add
346  *
347  * Add the page directory to the list of BOs to
348  * validate for command submission.
349  */
350 void amdgpu_vm_get_pd_bo(struct amdgpu_vm *vm,
351                          struct list_head *validated,
352                          struct amdgpu_bo_list_entry *entry)
353 {
354         entry->robj = vm->root.base.bo;
355         entry->priority = 0;
356         entry->tv.bo = &entry->robj->tbo;
357         entry->tv.shared = true;
358         entry->user_pages = NULL;
359         list_add(&entry->tv.head, validated);
360 }
361
362 /**
363  * amdgpu_vm_move_to_lru_tail - move all BOs to the end of LRU
364  *
365  * @adev: amdgpu device pointer
366  * @vm: vm providing the BOs
367  *
368  * Move all BOs to the end of LRU and remember their positions to put them
369  * together.
370  */
371 void amdgpu_vm_move_to_lru_tail(struct amdgpu_device *adev,
372                                 struct amdgpu_vm *vm)
373 {
374         struct ttm_bo_global *glob = adev->mman.bdev.glob;
375         struct amdgpu_vm_bo_base *bo_base;
376
377         if (vm->bulk_moveable) {
378                 spin_lock(&glob->lru_lock);
379                 ttm_bo_bulk_move_lru_tail(&vm->lru_bulk_move);
380                 spin_unlock(&glob->lru_lock);
381                 return;
382         }
383
384         memset(&vm->lru_bulk_move, 0, sizeof(vm->lru_bulk_move));
385
386         spin_lock(&glob->lru_lock);
387         list_for_each_entry(bo_base, &vm->idle, vm_status) {
388                 struct amdgpu_bo *bo = bo_base->bo;
389
390                 if (!bo->parent)
391                         continue;
392
393                 ttm_bo_move_to_lru_tail(&bo->tbo, &vm->lru_bulk_move);
394                 if (bo->shadow)
395                         ttm_bo_move_to_lru_tail(&bo->shadow->tbo,
396                                                 &vm->lru_bulk_move);
397         }
398         spin_unlock(&glob->lru_lock);
399
400         vm->bulk_moveable = true;
401 }
402
403 /**
404  * amdgpu_vm_validate_pt_bos - validate the page table BOs
405  *
406  * @adev: amdgpu device pointer
407  * @vm: vm providing the BOs
408  * @validate: callback to do the validation
409  * @param: parameter for the validation callback
410  *
411  * Validate the page table BOs on command submission if neccessary.
412  *
413  * Returns:
414  * Validation result.
415  */
416 int amdgpu_vm_validate_pt_bos(struct amdgpu_device *adev, struct amdgpu_vm *vm,
417                               int (*validate)(void *p, struct amdgpu_bo *bo),
418                               void *param)
419 {
420         struct amdgpu_vm_bo_base *bo_base, *tmp;
421         int r = 0;
422
423         vm->bulk_moveable &= list_empty(&vm->evicted);
424
425         list_for_each_entry_safe(bo_base, tmp, &vm->evicted, vm_status) {
426                 struct amdgpu_bo *bo = bo_base->bo;
427
428                 r = validate(param, bo);
429                 if (r)
430                         break;
431
432                 if (bo->tbo.type != ttm_bo_type_kernel) {
433                         amdgpu_vm_bo_moved(bo_base);
434                 } else {
435                         if (vm->use_cpu_for_update)
436                                 r = amdgpu_bo_kmap(bo, NULL);
437                         else
438                                 r = amdgpu_ttm_alloc_gart(&bo->tbo);
439                         if (r)
440                                 break;
441                         amdgpu_vm_bo_relocated(bo_base);
442                 }
443         }
444
445         return r;
446 }
447
448 /**
449  * amdgpu_vm_ready - check VM is ready for updates
450  *
451  * @vm: VM to check
452  *
453  * Check if all VM PDs/PTs are ready for updates
454  *
455  * Returns:
456  * True if eviction list is empty.
457  */
458 bool amdgpu_vm_ready(struct amdgpu_vm *vm)
459 {
460         return list_empty(&vm->evicted);
461 }
462
463 /**
464  * amdgpu_vm_clear_bo - initially clear the PDs/PTs
465  *
466  * @adev: amdgpu_device pointer
467  * @vm: VM to clear BO from
468  * @bo: BO to clear
469  * @level: level this BO is at
470  * @pte_support_ats: indicate ATS support from PTE
471  *
472  * Root PD needs to be reserved when calling this.
473  *
474  * Returns:
475  * 0 on success, errno otherwise.
476  */
477 static int amdgpu_vm_clear_bo(struct amdgpu_device *adev,
478                               struct amdgpu_vm *vm, struct amdgpu_bo *bo,
479                               unsigned level, bool pte_support_ats)
480 {
481         struct ttm_operation_ctx ctx = { true, false };
482         struct dma_fence *fence = NULL;
483         unsigned entries, ats_entries;
484         struct amdgpu_ring *ring;
485         struct amdgpu_job *job;
486         uint64_t addr;
487         int r;
488
489         entries = amdgpu_bo_size(bo) / 8;
490
491         if (pte_support_ats) {
492                 if (level == adev->vm_manager.root_level) {
493                         ats_entries = amdgpu_vm_level_shift(adev, level);
494                         ats_entries += AMDGPU_GPU_PAGE_SHIFT;
495                         ats_entries = AMDGPU_GMC_HOLE_START >> ats_entries;
496                         ats_entries = min(ats_entries, entries);
497                         entries -= ats_entries;
498                 } else {
499                         ats_entries = entries;
500                         entries = 0;
501                 }
502         } else {
503                 ats_entries = 0;
504         }
505
506         ring = container_of(vm->entity.rq->sched, struct amdgpu_ring, sched);
507
508         r = reservation_object_reserve_shared(bo->tbo.resv);
509         if (r)
510                 return r;
511
512         r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
513         if (r)
514                 goto error;
515
516         r = amdgpu_ttm_alloc_gart(&bo->tbo);
517         if (r)
518                 return r;
519
520         r = amdgpu_job_alloc_with_ib(adev, 64, &job);
521         if (r)
522                 goto error;
523
524         addr = amdgpu_bo_gpu_offset(bo);
525         if (ats_entries) {
526                 uint64_t ats_value;
527
528                 ats_value = AMDGPU_PTE_DEFAULT_ATC;
529                 if (level != AMDGPU_VM_PTB)
530                         ats_value |= AMDGPU_PDE_PTE;
531
532                 amdgpu_vm_set_pte_pde(adev, &job->ibs[0], addr, 0,
533                                       ats_entries, 0, ats_value);
534                 addr += ats_entries * 8;
535         }
536
537         if (entries)
538                 amdgpu_vm_set_pte_pde(adev, &job->ibs[0], addr, 0,
539                                       entries, 0, 0);
540
541         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
542
543         WARN_ON(job->ibs[0].length_dw > 64);
544         r = amdgpu_sync_resv(adev, &job->sync, bo->tbo.resv,
545                              AMDGPU_FENCE_OWNER_UNDEFINED, false);
546         if (r)
547                 goto error_free;
548
549         r = amdgpu_job_submit(job, &vm->entity, AMDGPU_FENCE_OWNER_UNDEFINED,
550                               &fence);
551         if (r)
552                 goto error_free;
553
554         amdgpu_bo_fence(bo, fence, true);
555         dma_fence_put(fence);
556
557         if (bo->shadow)
558                 return amdgpu_vm_clear_bo(adev, vm, bo->shadow,
559                                           level, pte_support_ats);
560
561         return 0;
562
563 error_free:
564         amdgpu_job_free(job);
565
566 error:
567         return r;
568 }
569
570 /**
571  * amdgpu_vm_bo_param - fill in parameters for PD/PT allocation
572  *
573  * @adev: amdgpu_device pointer
574  * @vm: requesting vm
575  * @bp: resulting BO allocation parameters
576  */
577 static void amdgpu_vm_bo_param(struct amdgpu_device *adev, struct amdgpu_vm *vm,
578                                int level, struct amdgpu_bo_param *bp)
579 {
580         memset(bp, 0, sizeof(*bp));
581
582         bp->size = amdgpu_vm_bo_size(adev, level);
583         bp->byte_align = AMDGPU_GPU_PAGE_SIZE;
584         bp->domain = AMDGPU_GEM_DOMAIN_VRAM;
585         if (bp->size <= PAGE_SIZE && adev->asic_type >= CHIP_VEGA10 &&
586             adev->flags & AMD_IS_APU)
587                 bp->domain |= AMDGPU_GEM_DOMAIN_GTT;
588         bp->domain = amdgpu_bo_get_preferred_pin_domain(adev, bp->domain);
589         bp->flags = AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS |
590                 AMDGPU_GEM_CREATE_CPU_GTT_USWC;
591         if (vm->use_cpu_for_update)
592                 bp->flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
593         else
594                 bp->flags |= AMDGPU_GEM_CREATE_SHADOW |
595                         AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
596         bp->type = ttm_bo_type_kernel;
597         if (vm->root.base.bo)
598                 bp->resv = vm->root.base.bo->tbo.resv;
599 }
600
601 /**
602  * amdgpu_vm_alloc_levels - allocate the PD/PT levels
603  *
604  * @adev: amdgpu_device pointer
605  * @vm: requested vm
606  * @parent: parent PT
607  * @saddr: start of the address range
608  * @eaddr: end of the address range
609  * @level: VMPT level
610  * @ats: indicate ATS support from PTE
611  *
612  * Make sure the page directories and page tables are allocated
613  *
614  * Returns:
615  * 0 on success, errno otherwise.
616  */
617 static int amdgpu_vm_alloc_levels(struct amdgpu_device *adev,
618                                   struct amdgpu_vm *vm,
619                                   struct amdgpu_vm_pt *parent,
620                                   uint64_t saddr, uint64_t eaddr,
621                                   unsigned level, bool ats)
622 {
623         unsigned shift = amdgpu_vm_level_shift(adev, level);
624         struct amdgpu_bo_param bp;
625         unsigned pt_idx, from, to;
626         int r;
627
628         if (!parent->entries) {
629                 unsigned num_entries = amdgpu_vm_num_entries(adev, level);
630
631                 parent->entries = kvmalloc_array(num_entries,
632                                                    sizeof(struct amdgpu_vm_pt),
633                                                    GFP_KERNEL | __GFP_ZERO);
634                 if (!parent->entries)
635                         return -ENOMEM;
636         }
637
638         from = saddr >> shift;
639         to = eaddr >> shift;
640         if (from >= amdgpu_vm_num_entries(adev, level) ||
641             to >= amdgpu_vm_num_entries(adev, level))
642                 return -EINVAL;
643
644         ++level;
645         saddr = saddr & ((1 << shift) - 1);
646         eaddr = eaddr & ((1 << shift) - 1);
647
648         amdgpu_vm_bo_param(adev, vm, level, &bp);
649
650         /* walk over the address space and allocate the page tables */
651         for (pt_idx = from; pt_idx <= to; ++pt_idx) {
652                 struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
653                 struct amdgpu_bo *pt;
654
655                 if (!entry->base.bo) {
656                         r = amdgpu_bo_create(adev, &bp, &pt);
657                         if (r)
658                                 return r;
659
660                         r = amdgpu_vm_clear_bo(adev, vm, pt, level, ats);
661                         if (r) {
662                                 amdgpu_bo_unref(&pt->shadow);
663                                 amdgpu_bo_unref(&pt);
664                                 return r;
665                         }
666
667                         if (vm->use_cpu_for_update) {
668                                 r = amdgpu_bo_kmap(pt, NULL);
669                                 if (r) {
670                                         amdgpu_bo_unref(&pt->shadow);
671                                         amdgpu_bo_unref(&pt);
672                                         return r;
673                                 }
674                         }
675
676                         /* Keep a reference to the root directory to avoid
677                         * freeing them up in the wrong order.
678                         */
679                         pt->parent = amdgpu_bo_ref(parent->base.bo);
680
681                         amdgpu_vm_bo_base_init(&entry->base, vm, pt);
682                 }
683
684                 if (level < AMDGPU_VM_PTB) {
685                         uint64_t sub_saddr = (pt_idx == from) ? saddr : 0;
686                         uint64_t sub_eaddr = (pt_idx == to) ? eaddr :
687                                 ((1 << shift) - 1);
688                         r = amdgpu_vm_alloc_levels(adev, vm, entry, sub_saddr,
689                                                    sub_eaddr, level, ats);
690                         if (r)
691                                 return r;
692                 }
693         }
694
695         return 0;
696 }
697
698 /**
699  * amdgpu_vm_alloc_pts - Allocate page tables.
700  *
701  * @adev: amdgpu_device pointer
702  * @vm: VM to allocate page tables for
703  * @saddr: Start address which needs to be allocated
704  * @size: Size from start address we need.
705  *
706  * Make sure the page tables are allocated.
707  *
708  * Returns:
709  * 0 on success, errno otherwise.
710  */
711 int amdgpu_vm_alloc_pts(struct amdgpu_device *adev,
712                         struct amdgpu_vm *vm,
713                         uint64_t saddr, uint64_t size)
714 {
715         uint64_t eaddr;
716         bool ats = false;
717
718         /* validate the parameters */
719         if (saddr & AMDGPU_GPU_PAGE_MASK || size & AMDGPU_GPU_PAGE_MASK)
720                 return -EINVAL;
721
722         eaddr = saddr + size - 1;
723
724         if (vm->pte_support_ats)
725                 ats = saddr < AMDGPU_GMC_HOLE_START;
726
727         saddr /= AMDGPU_GPU_PAGE_SIZE;
728         eaddr /= AMDGPU_GPU_PAGE_SIZE;
729
730         if (eaddr >= adev->vm_manager.max_pfn) {
731                 dev_err(adev->dev, "va above limit (0x%08llX >= 0x%08llX)\n",
732                         eaddr, adev->vm_manager.max_pfn);
733                 return -EINVAL;
734         }
735
736         return amdgpu_vm_alloc_levels(adev, vm, &vm->root, saddr, eaddr,
737                                       adev->vm_manager.root_level, ats);
738 }
739
740 /**
741  * amdgpu_vm_check_compute_bug - check whether asic has compute vm bug
742  *
743  * @adev: amdgpu_device pointer
744  */
745 void amdgpu_vm_check_compute_bug(struct amdgpu_device *adev)
746 {
747         const struct amdgpu_ip_block *ip_block;
748         bool has_compute_vm_bug;
749         struct amdgpu_ring *ring;
750         int i;
751
752         has_compute_vm_bug = false;
753
754         ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
755         if (ip_block) {
756                 /* Compute has a VM bug for GFX version < 7.
757                    Compute has a VM bug for GFX 8 MEC firmware version < 673.*/
758                 if (ip_block->version->major <= 7)
759                         has_compute_vm_bug = true;
760                 else if (ip_block->version->major == 8)
761                         if (adev->gfx.mec_fw_version < 673)
762                                 has_compute_vm_bug = true;
763         }
764
765         for (i = 0; i < adev->num_rings; i++) {
766                 ring = adev->rings[i];
767                 if (ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE)
768                         /* only compute rings */
769                         ring->has_compute_vm_bug = has_compute_vm_bug;
770                 else
771                         ring->has_compute_vm_bug = false;
772         }
773 }
774
775 /**
776  * amdgpu_vm_need_pipeline_sync - Check if pipe sync is needed for job.
777  *
778  * @ring: ring on which the job will be submitted
779  * @job: job to submit
780  *
781  * Returns:
782  * True if sync is needed.
783  */
784 bool amdgpu_vm_need_pipeline_sync(struct amdgpu_ring *ring,
785                                   struct amdgpu_job *job)
786 {
787         struct amdgpu_device *adev = ring->adev;
788         unsigned vmhub = ring->funcs->vmhub;
789         struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
790         struct amdgpu_vmid *id;
791         bool gds_switch_needed;
792         bool vm_flush_needed = job->vm_needs_flush || ring->has_compute_vm_bug;
793
794         if (job->vmid == 0)
795                 return false;
796         id = &id_mgr->ids[job->vmid];
797         gds_switch_needed = ring->funcs->emit_gds_switch && (
798                 id->gds_base != job->gds_base ||
799                 id->gds_size != job->gds_size ||
800                 id->gws_base != job->gws_base ||
801                 id->gws_size != job->gws_size ||
802                 id->oa_base != job->oa_base ||
803                 id->oa_size != job->oa_size);
804
805         if (amdgpu_vmid_had_gpu_reset(adev, id))
806                 return true;
807
808         return vm_flush_needed || gds_switch_needed;
809 }
810
811 /**
812  * amdgpu_vm_flush - hardware flush the vm
813  *
814  * @ring: ring to use for flush
815  * @job:  related job
816  * @need_pipe_sync: is pipe sync needed
817  *
818  * Emit a VM flush when it is necessary.
819  *
820  * Returns:
821  * 0 on success, errno otherwise.
822  */
823 int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job, bool need_pipe_sync)
824 {
825         struct amdgpu_device *adev = ring->adev;
826         unsigned vmhub = ring->funcs->vmhub;
827         struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
828         struct amdgpu_vmid *id = &id_mgr->ids[job->vmid];
829         bool gds_switch_needed = ring->funcs->emit_gds_switch && (
830                 id->gds_base != job->gds_base ||
831                 id->gds_size != job->gds_size ||
832                 id->gws_base != job->gws_base ||
833                 id->gws_size != job->gws_size ||
834                 id->oa_base != job->oa_base ||
835                 id->oa_size != job->oa_size);
836         bool vm_flush_needed = job->vm_needs_flush;
837         bool pasid_mapping_needed = id->pasid != job->pasid ||
838                 !id->pasid_mapping ||
839                 !dma_fence_is_signaled(id->pasid_mapping);
840         struct dma_fence *fence = NULL;
841         unsigned patch_offset = 0;
842         int r;
843
844         if (amdgpu_vmid_had_gpu_reset(adev, id)) {
845                 gds_switch_needed = true;
846                 vm_flush_needed = true;
847                 pasid_mapping_needed = true;
848         }
849
850         gds_switch_needed &= !!ring->funcs->emit_gds_switch;
851         vm_flush_needed &= !!ring->funcs->emit_vm_flush;
852         pasid_mapping_needed &= adev->gmc.gmc_funcs->emit_pasid_mapping &&
853                 ring->funcs->emit_wreg;
854
855         if (!vm_flush_needed && !gds_switch_needed && !need_pipe_sync)
856                 return 0;
857
858         if (ring->funcs->init_cond_exec)
859                 patch_offset = amdgpu_ring_init_cond_exec(ring);
860
861         if (need_pipe_sync)
862                 amdgpu_ring_emit_pipeline_sync(ring);
863
864         if (vm_flush_needed) {
865                 trace_amdgpu_vm_flush(ring, job->vmid, job->vm_pd_addr);
866                 amdgpu_ring_emit_vm_flush(ring, job->vmid, job->vm_pd_addr);
867         }
868
869         if (pasid_mapping_needed)
870                 amdgpu_gmc_emit_pasid_mapping(ring, job->vmid, job->pasid);
871
872         if (vm_flush_needed || pasid_mapping_needed) {
873                 r = amdgpu_fence_emit(ring, &fence, 0);
874                 if (r)
875                         return r;
876         }
877
878         if (vm_flush_needed) {
879                 mutex_lock(&id_mgr->lock);
880                 dma_fence_put(id->last_flush);
881                 id->last_flush = dma_fence_get(fence);
882                 id->current_gpu_reset_count =
883                         atomic_read(&adev->gpu_reset_counter);
884                 mutex_unlock(&id_mgr->lock);
885         }
886
887         if (pasid_mapping_needed) {
888                 id->pasid = job->pasid;
889                 dma_fence_put(id->pasid_mapping);
890                 id->pasid_mapping = dma_fence_get(fence);
891         }
892         dma_fence_put(fence);
893
894         if (ring->funcs->emit_gds_switch && gds_switch_needed) {
895                 id->gds_base = job->gds_base;
896                 id->gds_size = job->gds_size;
897                 id->gws_base = job->gws_base;
898                 id->gws_size = job->gws_size;
899                 id->oa_base = job->oa_base;
900                 id->oa_size = job->oa_size;
901                 amdgpu_ring_emit_gds_switch(ring, job->vmid, job->gds_base,
902                                             job->gds_size, job->gws_base,
903                                             job->gws_size, job->oa_base,
904                                             job->oa_size);
905         }
906
907         if (ring->funcs->patch_cond_exec)
908                 amdgpu_ring_patch_cond_exec(ring, patch_offset);
909
910         /* the double SWITCH_BUFFER here *cannot* be skipped by COND_EXEC */
911         if (ring->funcs->emit_switch_buffer) {
912                 amdgpu_ring_emit_switch_buffer(ring);
913                 amdgpu_ring_emit_switch_buffer(ring);
914         }
915         return 0;
916 }
917
918 /**
919  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
920  *
921  * @vm: requested vm
922  * @bo: requested buffer object
923  *
924  * Find @bo inside the requested vm.
925  * Search inside the @bos vm list for the requested vm
926  * Returns the found bo_va or NULL if none is found
927  *
928  * Object has to be reserved!
929  *
930  * Returns:
931  * Found bo_va or NULL.
932  */
933 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
934                                        struct amdgpu_bo *bo)
935 {
936         struct amdgpu_bo_va *bo_va;
937
938         list_for_each_entry(bo_va, &bo->va, base.bo_list) {
939                 if (bo_va->base.vm == vm) {
940                         return bo_va;
941                 }
942         }
943         return NULL;
944 }
945
946 /**
947  * amdgpu_vm_do_set_ptes - helper to call the right asic function
948  *
949  * @params: see amdgpu_pte_update_params definition
950  * @bo: PD/PT to update
951  * @pe: addr of the page entry
952  * @addr: dst addr to write into pe
953  * @count: number of page entries to update
954  * @incr: increase next addr by incr bytes
955  * @flags: hw access flags
956  *
957  * Traces the parameters and calls the right asic functions
958  * to setup the page table using the DMA.
959  */
960 static void amdgpu_vm_do_set_ptes(struct amdgpu_pte_update_params *params,
961                                   struct amdgpu_bo *bo,
962                                   uint64_t pe, uint64_t addr,
963                                   unsigned count, uint32_t incr,
964                                   uint64_t flags)
965 {
966         pe += amdgpu_bo_gpu_offset(bo);
967         trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
968
969         if (count < 3) {
970                 amdgpu_vm_write_pte(params->adev, params->ib, pe,
971                                     addr | flags, count, incr);
972
973         } else {
974                 amdgpu_vm_set_pte_pde(params->adev, params->ib, pe, addr,
975                                       count, incr, flags);
976         }
977 }
978
979 /**
980  * amdgpu_vm_do_copy_ptes - copy the PTEs from the GART
981  *
982  * @params: see amdgpu_pte_update_params definition
983  * @bo: PD/PT to update
984  * @pe: addr of the page entry
985  * @addr: dst addr to write into pe
986  * @count: number of page entries to update
987  * @incr: increase next addr by incr bytes
988  * @flags: hw access flags
989  *
990  * Traces the parameters and calls the DMA function to copy the PTEs.
991  */
992 static void amdgpu_vm_do_copy_ptes(struct amdgpu_pte_update_params *params,
993                                    struct amdgpu_bo *bo,
994                                    uint64_t pe, uint64_t addr,
995                                    unsigned count, uint32_t incr,
996                                    uint64_t flags)
997 {
998         uint64_t src = (params->src + (addr >> 12) * 8);
999
1000         pe += amdgpu_bo_gpu_offset(bo);
1001         trace_amdgpu_vm_copy_ptes(pe, src, count);
1002
1003         amdgpu_vm_copy_pte(params->adev, params->ib, pe, src, count);
1004 }
1005
1006 /**
1007  * amdgpu_vm_map_gart - Resolve gart mapping of addr
1008  *
1009  * @pages_addr: optional DMA address to use for lookup
1010  * @addr: the unmapped addr
1011  *
1012  * Look up the physical address of the page that the pte resolves
1013  * to.
1014  *
1015  * Returns:
1016  * The pointer for the page table entry.
1017  */
1018 static uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
1019 {
1020         uint64_t result;
1021
1022         /* page table offset */
1023         result = pages_addr[addr >> PAGE_SHIFT];
1024
1025         /* in case cpu page size != gpu page size*/
1026         result |= addr & (~PAGE_MASK);
1027
1028         result &= 0xFFFFFFFFFFFFF000ULL;
1029
1030         return result;
1031 }
1032
1033 /**
1034  * amdgpu_vm_cpu_set_ptes - helper to update page tables via CPU
1035  *
1036  * @params: see amdgpu_pte_update_params definition
1037  * @bo: PD/PT to update
1038  * @pe: kmap addr of the page entry
1039  * @addr: dst addr to write into pe
1040  * @count: number of page entries to update
1041  * @incr: increase next addr by incr bytes
1042  * @flags: hw access flags
1043  *
1044  * Write count number of PT/PD entries directly.
1045  */
1046 static void amdgpu_vm_cpu_set_ptes(struct amdgpu_pte_update_params *params,
1047                                    struct amdgpu_bo *bo,
1048                                    uint64_t pe, uint64_t addr,
1049                                    unsigned count, uint32_t incr,
1050                                    uint64_t flags)
1051 {
1052         unsigned int i;
1053         uint64_t value;
1054
1055         pe += (unsigned long)amdgpu_bo_kptr(bo);
1056
1057         trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
1058
1059         for (i = 0; i < count; i++) {
1060                 value = params->pages_addr ?
1061                         amdgpu_vm_map_gart(params->pages_addr, addr) :
1062                         addr;
1063                 amdgpu_gmc_set_pte_pde(params->adev, (void *)(uintptr_t)pe,
1064                                        i, value, flags);
1065                 addr += incr;
1066         }
1067 }
1068
1069
1070 /**
1071  * amdgpu_vm_wait_pd - Wait for PT BOs to be free.
1072  *
1073  * @adev: amdgpu_device pointer
1074  * @vm: related vm
1075  * @owner: fence owner
1076  *
1077  * Returns:
1078  * 0 on success, errno otherwise.
1079  */
1080 static int amdgpu_vm_wait_pd(struct amdgpu_device *adev, struct amdgpu_vm *vm,
1081                              void *owner)
1082 {
1083         struct amdgpu_sync sync;
1084         int r;
1085
1086         amdgpu_sync_create(&sync);
1087         amdgpu_sync_resv(adev, &sync, vm->root.base.bo->tbo.resv, owner, false);
1088         r = amdgpu_sync_wait(&sync, true);
1089         amdgpu_sync_free(&sync);
1090
1091         return r;
1092 }
1093
1094 /*
1095  * amdgpu_vm_update_pde - update a single level in the hierarchy
1096  *
1097  * @param: parameters for the update
1098  * @vm: requested vm
1099  * @parent: parent directory
1100  * @entry: entry to update
1101  *
1102  * Makes sure the requested entry in parent is up to date.
1103  */
1104 static void amdgpu_vm_update_pde(struct amdgpu_pte_update_params *params,
1105                                  struct amdgpu_vm *vm,
1106                                  struct amdgpu_vm_pt *parent,
1107                                  struct amdgpu_vm_pt *entry)
1108 {
1109         struct amdgpu_bo *bo = parent->base.bo, *pbo;
1110         uint64_t pde, pt, flags;
1111         unsigned level;
1112
1113         /* Don't update huge pages here */
1114         if (entry->huge)
1115                 return;
1116
1117         for (level = 0, pbo = bo->parent; pbo; ++level)
1118                 pbo = pbo->parent;
1119
1120         level += params->adev->vm_manager.root_level;
1121         amdgpu_gmc_get_pde_for_bo(entry->base.bo, level, &pt, &flags);
1122         pde = (entry - parent->entries) * 8;
1123         if (bo->shadow)
1124                 params->func(params, bo->shadow, pde, pt, 1, 0, flags);
1125         params->func(params, bo, pde, pt, 1, 0, flags);
1126 }
1127
1128 /*
1129  * amdgpu_vm_invalidate_level - mark all PD levels as invalid
1130  *
1131  * @adev: amdgpu_device pointer
1132  * @vm: related vm
1133  * @parent: parent PD
1134  * @level: VMPT level
1135  *
1136  * Mark all PD level as invalid after an error.
1137  */
1138 static void amdgpu_vm_invalidate_level(struct amdgpu_device *adev,
1139                                        struct amdgpu_vm *vm,
1140                                        struct amdgpu_vm_pt *parent,
1141                                        unsigned level)
1142 {
1143         unsigned pt_idx, num_entries;
1144
1145         /*
1146          * Recurse into the subdirectories. This recursion is harmless because
1147          * we only have a maximum of 5 layers.
1148          */
1149         num_entries = amdgpu_vm_num_entries(adev, level);
1150         for (pt_idx = 0; pt_idx < num_entries; ++pt_idx) {
1151                 struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
1152
1153                 if (!entry->base.bo)
1154                         continue;
1155
1156                 if (!entry->base.moved)
1157                         amdgpu_vm_bo_relocated(&entry->base);
1158                 amdgpu_vm_invalidate_level(adev, vm, entry, level + 1);
1159         }
1160 }
1161
1162 /*
1163  * amdgpu_vm_update_directories - make sure that all directories are valid
1164  *
1165  * @adev: amdgpu_device pointer
1166  * @vm: requested vm
1167  *
1168  * Makes sure all directories are up to date.
1169  *
1170  * Returns:
1171  * 0 for success, error for failure.
1172  */
1173 int amdgpu_vm_update_directories(struct amdgpu_device *adev,
1174                                  struct amdgpu_vm *vm)
1175 {
1176         struct amdgpu_pte_update_params params;
1177         struct amdgpu_job *job;
1178         unsigned ndw = 0;
1179         int r = 0;
1180
1181         if (list_empty(&vm->relocated))
1182                 return 0;
1183
1184 restart:
1185         memset(&params, 0, sizeof(params));
1186         params.adev = adev;
1187
1188         if (vm->use_cpu_for_update) {
1189                 r = amdgpu_vm_wait_pd(adev, vm, AMDGPU_FENCE_OWNER_VM);
1190                 if (unlikely(r))
1191                         return r;
1192
1193                 params.func = amdgpu_vm_cpu_set_ptes;
1194         } else {
1195                 ndw = 512 * 8;
1196                 r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1197                 if (r)
1198                         return r;
1199
1200                 params.ib = &job->ibs[0];
1201                 params.func = amdgpu_vm_do_set_ptes;
1202         }
1203
1204         while (!list_empty(&vm->relocated)) {
1205                 struct amdgpu_vm_bo_base *bo_base, *parent;
1206                 struct amdgpu_vm_pt *pt, *entry;
1207                 struct amdgpu_bo *bo;
1208
1209                 bo_base = list_first_entry(&vm->relocated,
1210                                            struct amdgpu_vm_bo_base,
1211                                            vm_status);
1212                 amdgpu_vm_bo_idle(bo_base);
1213
1214                 bo = bo_base->bo->parent;
1215                 if (!bo)
1216                         continue;
1217
1218                 parent = list_first_entry(&bo->va, struct amdgpu_vm_bo_base,
1219                                           bo_list);
1220                 pt = container_of(parent, struct amdgpu_vm_pt, base);
1221                 entry = container_of(bo_base, struct amdgpu_vm_pt, base);
1222
1223                 amdgpu_vm_update_pde(&params, vm, pt, entry);
1224
1225                 if (!vm->use_cpu_for_update &&
1226                     (ndw - params.ib->length_dw) < 32)
1227                         break;
1228         }
1229
1230         if (vm->use_cpu_for_update) {
1231                 /* Flush HDP */
1232                 mb();
1233                 amdgpu_asic_flush_hdp(adev, NULL);
1234         } else if (params.ib->length_dw == 0) {
1235                 amdgpu_job_free(job);
1236         } else {
1237                 struct amdgpu_bo *root = vm->root.base.bo;
1238                 struct amdgpu_ring *ring;
1239                 struct dma_fence *fence;
1240
1241                 ring = container_of(vm->entity.rq->sched, struct amdgpu_ring,
1242                                     sched);
1243
1244                 amdgpu_ring_pad_ib(ring, params.ib);
1245                 amdgpu_sync_resv(adev, &job->sync, root->tbo.resv,
1246                                  AMDGPU_FENCE_OWNER_VM, false);
1247                 WARN_ON(params.ib->length_dw > ndw);
1248                 r = amdgpu_job_submit(job, &vm->entity, AMDGPU_FENCE_OWNER_VM,
1249                                       &fence);
1250                 if (r)
1251                         goto error;
1252
1253                 amdgpu_bo_fence(root, fence, true);
1254                 dma_fence_put(vm->last_update);
1255                 vm->last_update = fence;
1256         }
1257
1258         if (!list_empty(&vm->relocated))
1259                 goto restart;
1260
1261         return 0;
1262
1263 error:
1264         amdgpu_vm_invalidate_level(adev, vm, &vm->root,
1265                                    adev->vm_manager.root_level);
1266         amdgpu_job_free(job);
1267         return r;
1268 }
1269
1270 /**
1271  * amdgpu_vm_find_entry - find the entry for an address
1272  *
1273  * @p: see amdgpu_pte_update_params definition
1274  * @addr: virtual address in question
1275  * @entry: resulting entry or NULL
1276  * @parent: parent entry
1277  *
1278  * Find the vm_pt entry and it's parent for the given address.
1279  */
1280 void amdgpu_vm_get_entry(struct amdgpu_pte_update_params *p, uint64_t addr,
1281                          struct amdgpu_vm_pt **entry,
1282                          struct amdgpu_vm_pt **parent)
1283 {
1284         unsigned level = p->adev->vm_manager.root_level;
1285
1286         *parent = NULL;
1287         *entry = &p->vm->root;
1288         while ((*entry)->entries) {
1289                 unsigned shift = amdgpu_vm_level_shift(p->adev, level++);
1290
1291                 *parent = *entry;
1292                 *entry = &(*entry)->entries[addr >> shift];
1293                 addr &= (1ULL << shift) - 1;
1294         }
1295
1296         if (level != AMDGPU_VM_PTB)
1297                 *entry = NULL;
1298 }
1299
1300 /**
1301  * amdgpu_vm_handle_huge_pages - handle updating the PD with huge pages
1302  *
1303  * @p: see amdgpu_pte_update_params definition
1304  * @entry: vm_pt entry to check
1305  * @parent: parent entry
1306  * @nptes: number of PTEs updated with this operation
1307  * @dst: destination address where the PTEs should point to
1308  * @flags: access flags fro the PTEs
1309  *
1310  * Check if we can update the PD with a huge page.
1311  */
1312 static void amdgpu_vm_handle_huge_pages(struct amdgpu_pte_update_params *p,
1313                                         struct amdgpu_vm_pt *entry,
1314                                         struct amdgpu_vm_pt *parent,
1315                                         unsigned nptes, uint64_t dst,
1316                                         uint64_t flags)
1317 {
1318         uint64_t pde;
1319
1320         /* In the case of a mixed PT the PDE must point to it*/
1321         if (p->adev->asic_type >= CHIP_VEGA10 && !p->src &&
1322             nptes == AMDGPU_VM_PTE_COUNT(p->adev)) {
1323                 /* Set the huge page flag to stop scanning at this PDE */
1324                 flags |= AMDGPU_PDE_PTE;
1325         }
1326
1327         if (!(flags & AMDGPU_PDE_PTE)) {
1328                 if (entry->huge) {
1329                         /* Add the entry to the relocated list to update it. */
1330                         entry->huge = false;
1331                         amdgpu_vm_bo_relocated(&entry->base);
1332                 }
1333                 return;
1334         }
1335
1336         entry->huge = true;
1337         amdgpu_gmc_get_vm_pde(p->adev, AMDGPU_VM_PDB0, &dst, &flags);
1338
1339         pde = (entry - parent->entries) * 8;
1340         if (parent->base.bo->shadow)
1341                 p->func(p, parent->base.bo->shadow, pde, dst, 1, 0, flags);
1342         p->func(p, parent->base.bo, pde, dst, 1, 0, flags);
1343 }
1344
1345 /**
1346  * amdgpu_vm_update_ptes - make sure that page tables are valid
1347  *
1348  * @params: see amdgpu_pte_update_params definition
1349  * @start: start of GPU address range
1350  * @end: end of GPU address range
1351  * @dst: destination address to map to, the next dst inside the function
1352  * @flags: mapping flags
1353  *
1354  * Update the page tables in the range @start - @end.
1355  *
1356  * Returns:
1357  * 0 for success, -EINVAL for failure.
1358  */
1359 static int amdgpu_vm_update_ptes(struct amdgpu_pte_update_params *params,
1360                                   uint64_t start, uint64_t end,
1361                                   uint64_t dst, uint64_t flags)
1362 {
1363         struct amdgpu_device *adev = params->adev;
1364         const uint64_t mask = AMDGPU_VM_PTE_COUNT(adev) - 1;
1365
1366         uint64_t addr, pe_start;
1367         struct amdgpu_bo *pt;
1368         unsigned nptes;
1369
1370         /* walk over the address space and update the page tables */
1371         for (addr = start; addr < end; addr += nptes,
1372              dst += nptes * AMDGPU_GPU_PAGE_SIZE) {
1373                 struct amdgpu_vm_pt *entry, *parent;
1374
1375                 amdgpu_vm_get_entry(params, addr, &entry, &parent);
1376                 if (!entry)
1377                         return -ENOENT;
1378
1379                 if ((addr & ~mask) == (end & ~mask))
1380                         nptes = end - addr;
1381                 else
1382                         nptes = AMDGPU_VM_PTE_COUNT(adev) - (addr & mask);
1383
1384                 amdgpu_vm_handle_huge_pages(params, entry, parent,
1385                                             nptes, dst, flags);
1386                 /* We don't need to update PTEs for huge pages */
1387                 if (entry->huge)
1388                         continue;
1389
1390                 pt = entry->base.bo;
1391                 pe_start = (addr & mask) * 8;
1392                 if (pt->shadow)
1393                         params->func(params, pt->shadow, pe_start, dst, nptes,
1394                                      AMDGPU_GPU_PAGE_SIZE, flags);
1395                 params->func(params, pt, pe_start, dst, nptes,
1396                              AMDGPU_GPU_PAGE_SIZE, flags);
1397         }
1398
1399         return 0;
1400 }
1401
1402 /*
1403  * amdgpu_vm_frag_ptes - add fragment information to PTEs
1404  *
1405  * @params: see amdgpu_pte_update_params definition
1406  * @vm: requested vm
1407  * @start: first PTE to handle
1408  * @end: last PTE to handle
1409  * @dst: addr those PTEs should point to
1410  * @flags: hw mapping flags
1411  *
1412  * Returns:
1413  * 0 for success, -EINVAL for failure.
1414  */
1415 static int amdgpu_vm_frag_ptes(struct amdgpu_pte_update_params  *params,
1416                                 uint64_t start, uint64_t end,
1417                                 uint64_t dst, uint64_t flags)
1418 {
1419         /**
1420          * The MC L1 TLB supports variable sized pages, based on a fragment
1421          * field in the PTE. When this field is set to a non-zero value, page
1422          * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
1423          * flags are considered valid for all PTEs within the fragment range
1424          * and corresponding mappings are assumed to be physically contiguous.
1425          *
1426          * The L1 TLB can store a single PTE for the whole fragment,
1427          * significantly increasing the space available for translation
1428          * caching. This leads to large improvements in throughput when the
1429          * TLB is under pressure.
1430          *
1431          * The L2 TLB distributes small and large fragments into two
1432          * asymmetric partitions. The large fragment cache is significantly
1433          * larger. Thus, we try to use large fragments wherever possible.
1434          * Userspace can support this by aligning virtual base address and
1435          * allocation size to the fragment size.
1436          */
1437         unsigned max_frag = params->adev->vm_manager.fragment_size;
1438         int r;
1439
1440         /* system pages are non continuously */
1441         if (params->src || !(flags & AMDGPU_PTE_VALID))
1442                 return amdgpu_vm_update_ptes(params, start, end, dst, flags);
1443
1444         while (start != end) {
1445                 uint64_t frag_flags, frag_end;
1446                 unsigned frag;
1447
1448                 /* This intentionally wraps around if no bit is set */
1449                 frag = min((unsigned)ffs(start) - 1,
1450                            (unsigned)fls64(end - start) - 1);
1451                 if (frag >= max_frag) {
1452                         frag_flags = AMDGPU_PTE_FRAG(max_frag);
1453                         frag_end = end & ~((1ULL << max_frag) - 1);
1454                 } else {
1455                         frag_flags = AMDGPU_PTE_FRAG(frag);
1456                         frag_end = start + (1 << frag);
1457                 }
1458
1459                 r = amdgpu_vm_update_ptes(params, start, frag_end, dst,
1460                                           flags | frag_flags);
1461                 if (r)
1462                         return r;
1463
1464                 dst += (frag_end - start) * AMDGPU_GPU_PAGE_SIZE;
1465                 start = frag_end;
1466         }
1467
1468         return 0;
1469 }
1470
1471 /**
1472  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
1473  *
1474  * @adev: amdgpu_device pointer
1475  * @exclusive: fence we need to sync to
1476  * @pages_addr: DMA addresses to use for mapping
1477  * @vm: requested vm
1478  * @start: start of mapped range
1479  * @last: last mapped entry
1480  * @flags: flags for the entries
1481  * @addr: addr to set the area to
1482  * @fence: optional resulting fence
1483  *
1484  * Fill in the page table entries between @start and @last.
1485  *
1486  * Returns:
1487  * 0 for success, -EINVAL for failure.
1488  */
1489 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
1490                                        struct dma_fence *exclusive,
1491                                        dma_addr_t *pages_addr,
1492                                        struct amdgpu_vm *vm,
1493                                        uint64_t start, uint64_t last,
1494                                        uint64_t flags, uint64_t addr,
1495                                        struct dma_fence **fence)
1496 {
1497         struct amdgpu_ring *ring;
1498         void *owner = AMDGPU_FENCE_OWNER_VM;
1499         unsigned nptes, ncmds, ndw;
1500         struct amdgpu_job *job;
1501         struct amdgpu_pte_update_params params;
1502         struct dma_fence *f = NULL;
1503         int r;
1504
1505         memset(&params, 0, sizeof(params));
1506         params.adev = adev;
1507         params.vm = vm;
1508
1509         /* sync to everything on unmapping */
1510         if (!(flags & AMDGPU_PTE_VALID))
1511                 owner = AMDGPU_FENCE_OWNER_UNDEFINED;
1512
1513         if (vm->use_cpu_for_update) {
1514                 /* params.src is used as flag to indicate system Memory */
1515                 if (pages_addr)
1516                         params.src = ~0;
1517
1518                 /* Wait for PT BOs to be free. PTs share the same resv. object
1519                  * as the root PD BO
1520                  */
1521                 r = amdgpu_vm_wait_pd(adev, vm, owner);
1522                 if (unlikely(r))
1523                         return r;
1524
1525                 params.func = amdgpu_vm_cpu_set_ptes;
1526                 params.pages_addr = pages_addr;
1527                 return amdgpu_vm_frag_ptes(&params, start, last + 1,
1528                                            addr, flags);
1529         }
1530
1531         ring = container_of(vm->entity.rq->sched, struct amdgpu_ring, sched);
1532
1533         nptes = last - start + 1;
1534
1535         /*
1536          * reserve space for two commands every (1 << BLOCK_SIZE)
1537          *  entries or 2k dwords (whatever is smaller)
1538          *
1539          * The second command is for the shadow pagetables.
1540          */
1541         if (vm->root.base.bo->shadow)
1542                 ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1) * 2;
1543         else
1544                 ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1);
1545
1546         /* padding, etc. */
1547         ndw = 64;
1548
1549         if (pages_addr) {
1550                 /* copy commands needed */
1551                 ndw += ncmds * adev->vm_manager.vm_pte_funcs->copy_pte_num_dw;
1552
1553                 /* and also PTEs */
1554                 ndw += nptes * 2;
1555
1556                 params.func = amdgpu_vm_do_copy_ptes;
1557
1558         } else {
1559                 /* set page commands needed */
1560                 ndw += ncmds * 10;
1561
1562                 /* extra commands for begin/end fragments */
1563                 if (vm->root.base.bo->shadow)
1564                         ndw += 2 * 10 * adev->vm_manager.fragment_size * 2;
1565                 else
1566                         ndw += 2 * 10 * adev->vm_manager.fragment_size;
1567
1568                 params.func = amdgpu_vm_do_set_ptes;
1569         }
1570
1571         r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1572         if (r)
1573                 return r;
1574
1575         params.ib = &job->ibs[0];
1576
1577         if (pages_addr) {
1578                 uint64_t *pte;
1579                 unsigned i;
1580
1581                 /* Put the PTEs at the end of the IB. */
1582                 i = ndw - nptes * 2;
1583                 pte= (uint64_t *)&(job->ibs->ptr[i]);
1584                 params.src = job->ibs->gpu_addr + i * 4;
1585
1586                 for (i = 0; i < nptes; ++i) {
1587                         pte[i] = amdgpu_vm_map_gart(pages_addr, addr + i *
1588                                                     AMDGPU_GPU_PAGE_SIZE);
1589                         pte[i] |= flags;
1590                 }
1591                 addr = 0;
1592         }
1593
1594         r = amdgpu_sync_fence(adev, &job->sync, exclusive, false);
1595         if (r)
1596                 goto error_free;
1597
1598         r = amdgpu_sync_resv(adev, &job->sync, vm->root.base.bo->tbo.resv,
1599                              owner, false);
1600         if (r)
1601                 goto error_free;
1602
1603         r = reservation_object_reserve_shared(vm->root.base.bo->tbo.resv);
1604         if (r)
1605                 goto error_free;
1606
1607         r = amdgpu_vm_frag_ptes(&params, start, last + 1, addr, flags);
1608         if (r)
1609                 goto error_free;
1610
1611         amdgpu_ring_pad_ib(ring, params.ib);
1612         WARN_ON(params.ib->length_dw > ndw);
1613         r = amdgpu_job_submit(job, &vm->entity, AMDGPU_FENCE_OWNER_VM, &f);
1614         if (r)
1615                 goto error_free;
1616
1617         amdgpu_bo_fence(vm->root.base.bo, f, true);
1618         dma_fence_put(*fence);
1619         *fence = f;
1620         return 0;
1621
1622 error_free:
1623         amdgpu_job_free(job);
1624         return r;
1625 }
1626
1627 /**
1628  * amdgpu_vm_bo_split_mapping - split a mapping into smaller chunks
1629  *
1630  * @adev: amdgpu_device pointer
1631  * @exclusive: fence we need to sync to
1632  * @pages_addr: DMA addresses to use for mapping
1633  * @vm: requested vm
1634  * @mapping: mapped range and flags to use for the update
1635  * @flags: HW flags for the mapping
1636  * @nodes: array of drm_mm_nodes with the MC addresses
1637  * @fence: optional resulting fence
1638  *
1639  * Split the mapping into smaller chunks so that each update fits
1640  * into a SDMA IB.
1641  *
1642  * Returns:
1643  * 0 for success, -EINVAL for failure.
1644  */
1645 static int amdgpu_vm_bo_split_mapping(struct amdgpu_device *adev,
1646                                       struct dma_fence *exclusive,
1647                                       dma_addr_t *pages_addr,
1648                                       struct amdgpu_vm *vm,
1649                                       struct amdgpu_bo_va_mapping *mapping,
1650                                       uint64_t flags,
1651                                       struct drm_mm_node *nodes,
1652                                       struct dma_fence **fence)
1653 {
1654         unsigned min_linear_pages = 1 << adev->vm_manager.fragment_size;
1655         uint64_t pfn, start = mapping->start;
1656         int r;
1657
1658         /* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1659          * but in case of something, we filter the flags in first place
1660          */
1661         if (!(mapping->flags & AMDGPU_PTE_READABLE))
1662                 flags &= ~AMDGPU_PTE_READABLE;
1663         if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1664                 flags &= ~AMDGPU_PTE_WRITEABLE;
1665
1666         flags &= ~AMDGPU_PTE_EXECUTABLE;
1667         flags |= mapping->flags & AMDGPU_PTE_EXECUTABLE;
1668
1669         flags &= ~AMDGPU_PTE_MTYPE_MASK;
1670         flags |= (mapping->flags & AMDGPU_PTE_MTYPE_MASK);
1671
1672         if ((mapping->flags & AMDGPU_PTE_PRT) &&
1673             (adev->asic_type >= CHIP_VEGA10)) {
1674                 flags |= AMDGPU_PTE_PRT;
1675                 flags &= ~AMDGPU_PTE_VALID;
1676         }
1677
1678         trace_amdgpu_vm_bo_update(mapping);
1679
1680         pfn = mapping->offset >> PAGE_SHIFT;
1681         if (nodes) {
1682                 while (pfn >= nodes->size) {
1683                         pfn -= nodes->size;
1684                         ++nodes;
1685                 }
1686         }
1687
1688         do {
1689                 dma_addr_t *dma_addr = NULL;
1690                 uint64_t max_entries;
1691                 uint64_t addr, last;
1692
1693                 if (nodes) {
1694                         addr = nodes->start << PAGE_SHIFT;
1695                         max_entries = (nodes->size - pfn) *
1696                                 AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1697                 } else {
1698                         addr = 0;
1699                         max_entries = S64_MAX;
1700                 }
1701
1702                 if (pages_addr) {
1703                         uint64_t count;
1704
1705                         max_entries = min(max_entries, 16ull * 1024ull);
1706                         for (count = 1;
1707                              count < max_entries / AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1708                              ++count) {
1709                                 uint64_t idx = pfn + count;
1710
1711                                 if (pages_addr[idx] !=
1712                                     (pages_addr[idx - 1] + PAGE_SIZE))
1713                                         break;
1714                         }
1715
1716                         if (count < min_linear_pages) {
1717                                 addr = pfn << PAGE_SHIFT;
1718                                 dma_addr = pages_addr;
1719                         } else {
1720                                 addr = pages_addr[pfn];
1721                                 max_entries = count * AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1722                         }
1723
1724                 } else if (flags & AMDGPU_PTE_VALID) {
1725                         addr += adev->vm_manager.vram_base_offset;
1726                         addr += pfn << PAGE_SHIFT;
1727                 }
1728
1729                 last = min((uint64_t)mapping->last, start + max_entries - 1);
1730                 r = amdgpu_vm_bo_update_mapping(adev, exclusive, dma_addr, vm,
1731                                                 start, last, flags, addr,
1732                                                 fence);
1733                 if (r)
1734                         return r;
1735
1736                 pfn += (last - start + 1) / AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1737                 if (nodes && nodes->size == pfn) {
1738                         pfn = 0;
1739                         ++nodes;
1740                 }
1741                 start = last + 1;
1742
1743         } while (unlikely(start != mapping->last + 1));
1744
1745         return 0;
1746 }
1747
1748 /**
1749  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
1750  *
1751  * @adev: amdgpu_device pointer
1752  * @bo_va: requested BO and VM object
1753  * @clear: if true clear the entries
1754  *
1755  * Fill in the page table entries for @bo_va.
1756  *
1757  * Returns:
1758  * 0 for success, -EINVAL for failure.
1759  */
1760 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
1761                         struct amdgpu_bo_va *bo_va,
1762                         bool clear)
1763 {
1764         struct amdgpu_bo *bo = bo_va->base.bo;
1765         struct amdgpu_vm *vm = bo_va->base.vm;
1766         struct amdgpu_bo_va_mapping *mapping;
1767         dma_addr_t *pages_addr = NULL;
1768         struct ttm_mem_reg *mem;
1769         struct drm_mm_node *nodes;
1770         struct dma_fence *exclusive, **last_update;
1771         uint64_t flags;
1772         int r;
1773
1774         if (clear || !bo) {
1775                 mem = NULL;
1776                 nodes = NULL;
1777                 exclusive = NULL;
1778         } else {
1779                 struct ttm_dma_tt *ttm;
1780
1781                 mem = &bo->tbo.mem;
1782                 nodes = mem->mm_node;
1783                 if (mem->mem_type == TTM_PL_TT) {
1784                         ttm = container_of(bo->tbo.ttm, struct ttm_dma_tt, ttm);
1785                         pages_addr = ttm->dma_address;
1786                 }
1787                 exclusive = reservation_object_get_excl(bo->tbo.resv);
1788         }
1789
1790         if (bo)
1791                 flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, mem);
1792         else
1793                 flags = 0x0;
1794
1795         if (clear || (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv))
1796                 last_update = &vm->last_update;
1797         else
1798                 last_update = &bo_va->last_pt_update;
1799
1800         if (!clear && bo_va->base.moved) {
1801                 bo_va->base.moved = false;
1802                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1803
1804         } else if (bo_va->cleared != clear) {
1805                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1806         }
1807
1808         list_for_each_entry(mapping, &bo_va->invalids, list) {
1809                 r = amdgpu_vm_bo_split_mapping(adev, exclusive, pages_addr, vm,
1810                                                mapping, flags, nodes,
1811                                                last_update);
1812                 if (r)
1813                         return r;
1814         }
1815
1816         if (vm->use_cpu_for_update) {
1817                 /* Flush HDP */
1818                 mb();
1819                 amdgpu_asic_flush_hdp(adev, NULL);
1820         }
1821
1822         /* If the BO is not in its preferred location add it back to
1823          * the evicted list so that it gets validated again on the
1824          * next command submission.
1825          */
1826         if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
1827                 uint32_t mem_type = bo->tbo.mem.mem_type;
1828
1829                 if (!(bo->preferred_domains & amdgpu_mem_type_to_domain(mem_type)))
1830                         amdgpu_vm_bo_evicted(&bo_va->base);
1831                 else
1832                         amdgpu_vm_bo_idle(&bo_va->base);
1833         } else {
1834                 amdgpu_vm_bo_done(&bo_va->base);
1835         }
1836
1837         list_splice_init(&bo_va->invalids, &bo_va->valids);
1838         bo_va->cleared = clear;
1839
1840         if (trace_amdgpu_vm_bo_mapping_enabled()) {
1841                 list_for_each_entry(mapping, &bo_va->valids, list)
1842                         trace_amdgpu_vm_bo_mapping(mapping);
1843         }
1844
1845         return 0;
1846 }
1847
1848 /**
1849  * amdgpu_vm_update_prt_state - update the global PRT state
1850  *
1851  * @adev: amdgpu_device pointer
1852  */
1853 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
1854 {
1855         unsigned long flags;
1856         bool enable;
1857
1858         spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
1859         enable = !!atomic_read(&adev->vm_manager.num_prt_users);
1860         adev->gmc.gmc_funcs->set_prt(adev, enable);
1861         spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
1862 }
1863
1864 /**
1865  * amdgpu_vm_prt_get - add a PRT user
1866  *
1867  * @adev: amdgpu_device pointer
1868  */
1869 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
1870 {
1871         if (!adev->gmc.gmc_funcs->set_prt)
1872                 return;
1873
1874         if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
1875                 amdgpu_vm_update_prt_state(adev);
1876 }
1877
1878 /**
1879  * amdgpu_vm_prt_put - drop a PRT user
1880  *
1881  * @adev: amdgpu_device pointer
1882  */
1883 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
1884 {
1885         if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
1886                 amdgpu_vm_update_prt_state(adev);
1887 }
1888
1889 /**
1890  * amdgpu_vm_prt_cb - callback for updating the PRT status
1891  *
1892  * @fence: fence for the callback
1893  * @_cb: the callback function
1894  */
1895 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
1896 {
1897         struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
1898
1899         amdgpu_vm_prt_put(cb->adev);
1900         kfree(cb);
1901 }
1902
1903 /**
1904  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
1905  *
1906  * @adev: amdgpu_device pointer
1907  * @fence: fence for the callback
1908  */
1909 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
1910                                  struct dma_fence *fence)
1911 {
1912         struct amdgpu_prt_cb *cb;
1913
1914         if (!adev->gmc.gmc_funcs->set_prt)
1915                 return;
1916
1917         cb = kmalloc(sizeof(struct amdgpu_prt_cb), GFP_KERNEL);
1918         if (!cb) {
1919                 /* Last resort when we are OOM */
1920                 if (fence)
1921                         dma_fence_wait(fence, false);
1922
1923                 amdgpu_vm_prt_put(adev);
1924         } else {
1925                 cb->adev = adev;
1926                 if (!fence || dma_fence_add_callback(fence, &cb->cb,
1927                                                      amdgpu_vm_prt_cb))
1928                         amdgpu_vm_prt_cb(fence, &cb->cb);
1929         }
1930 }
1931
1932 /**
1933  * amdgpu_vm_free_mapping - free a mapping
1934  *
1935  * @adev: amdgpu_device pointer
1936  * @vm: requested vm
1937  * @mapping: mapping to be freed
1938  * @fence: fence of the unmap operation
1939  *
1940  * Free a mapping and make sure we decrease the PRT usage count if applicable.
1941  */
1942 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
1943                                    struct amdgpu_vm *vm,
1944                                    struct amdgpu_bo_va_mapping *mapping,
1945                                    struct dma_fence *fence)
1946 {
1947         if (mapping->flags & AMDGPU_PTE_PRT)
1948                 amdgpu_vm_add_prt_cb(adev, fence);
1949         kfree(mapping);
1950 }
1951
1952 /**
1953  * amdgpu_vm_prt_fini - finish all prt mappings
1954  *
1955  * @adev: amdgpu_device pointer
1956  * @vm: requested vm
1957  *
1958  * Register a cleanup callback to disable PRT support after VM dies.
1959  */
1960 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1961 {
1962         struct reservation_object *resv = vm->root.base.bo->tbo.resv;
1963         struct dma_fence *excl, **shared;
1964         unsigned i, shared_count;
1965         int r;
1966
1967         r = reservation_object_get_fences_rcu(resv, &excl,
1968                                               &shared_count, &shared);
1969         if (r) {
1970                 /* Not enough memory to grab the fence list, as last resort
1971                  * block for all the fences to complete.
1972                  */
1973                 reservation_object_wait_timeout_rcu(resv, true, false,
1974                                                     MAX_SCHEDULE_TIMEOUT);
1975                 return;
1976         }
1977
1978         /* Add a callback for each fence in the reservation object */
1979         amdgpu_vm_prt_get(adev);
1980         amdgpu_vm_add_prt_cb(adev, excl);
1981
1982         for (i = 0; i < shared_count; ++i) {
1983                 amdgpu_vm_prt_get(adev);
1984                 amdgpu_vm_add_prt_cb(adev, shared[i]);
1985         }
1986
1987         kfree(shared);
1988 }
1989
1990 /**
1991  * amdgpu_vm_clear_freed - clear freed BOs in the PT
1992  *
1993  * @adev: amdgpu_device pointer
1994  * @vm: requested vm
1995  * @fence: optional resulting fence (unchanged if no work needed to be done
1996  * or if an error occurred)
1997  *
1998  * Make sure all freed BOs are cleared in the PT.
1999  * PTs have to be reserved and mutex must be locked!
2000  *
2001  * Returns:
2002  * 0 for success.
2003  *
2004  */
2005 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
2006                           struct amdgpu_vm *vm,
2007                           struct dma_fence **fence)
2008 {
2009         struct amdgpu_bo_va_mapping *mapping;
2010         uint64_t init_pte_value = 0;
2011         struct dma_fence *f = NULL;
2012         int r;
2013
2014         while (!list_empty(&vm->freed)) {
2015                 mapping = list_first_entry(&vm->freed,
2016                         struct amdgpu_bo_va_mapping, list);
2017                 list_del(&mapping->list);
2018
2019                 if (vm->pte_support_ats &&
2020                     mapping->start < AMDGPU_GMC_HOLE_START)
2021                         init_pte_value = AMDGPU_PTE_DEFAULT_ATC;
2022
2023                 r = amdgpu_vm_bo_update_mapping(adev, NULL, NULL, vm,
2024                                                 mapping->start, mapping->last,
2025                                                 init_pte_value, 0, &f);
2026                 amdgpu_vm_free_mapping(adev, vm, mapping, f);
2027                 if (r) {
2028                         dma_fence_put(f);
2029                         return r;
2030                 }
2031         }
2032
2033         if (fence && f) {
2034                 dma_fence_put(*fence);
2035                 *fence = f;
2036         } else {
2037                 dma_fence_put(f);
2038         }
2039
2040         return 0;
2041
2042 }
2043
2044 /**
2045  * amdgpu_vm_handle_moved - handle moved BOs in the PT
2046  *
2047  * @adev: amdgpu_device pointer
2048  * @vm: requested vm
2049  *
2050  * Make sure all BOs which are moved are updated in the PTs.
2051  *
2052  * Returns:
2053  * 0 for success.
2054  *
2055  * PTs have to be reserved!
2056  */
2057 int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
2058                            struct amdgpu_vm *vm)
2059 {
2060         struct amdgpu_bo_va *bo_va, *tmp;
2061         struct reservation_object *resv;
2062         bool clear;
2063         int r;
2064
2065         list_for_each_entry_safe(bo_va, tmp, &vm->moved, base.vm_status) {
2066                 /* Per VM BOs never need to bo cleared in the page tables */
2067                 r = amdgpu_vm_bo_update(adev, bo_va, false);
2068                 if (r)
2069                         return r;
2070         }
2071
2072         spin_lock(&vm->invalidated_lock);
2073         while (!list_empty(&vm->invalidated)) {
2074                 bo_va = list_first_entry(&vm->invalidated, struct amdgpu_bo_va,
2075                                          base.vm_status);
2076                 resv = bo_va->base.bo->tbo.resv;
2077                 spin_unlock(&vm->invalidated_lock);
2078
2079                 /* Try to reserve the BO to avoid clearing its ptes */
2080                 if (!amdgpu_vm_debug && reservation_object_trylock(resv))
2081                         clear = false;
2082                 /* Somebody else is using the BO right now */
2083                 else
2084                         clear = true;
2085
2086                 r = amdgpu_vm_bo_update(adev, bo_va, clear);
2087                 if (r)
2088                         return r;
2089
2090                 if (!clear)
2091                         reservation_object_unlock(resv);
2092                 spin_lock(&vm->invalidated_lock);
2093         }
2094         spin_unlock(&vm->invalidated_lock);
2095
2096         return 0;
2097 }
2098
2099 /**
2100  * amdgpu_vm_bo_add - add a bo to a specific vm
2101  *
2102  * @adev: amdgpu_device pointer
2103  * @vm: requested vm
2104  * @bo: amdgpu buffer object
2105  *
2106  * Add @bo into the requested vm.
2107  * Add @bo to the list of bos associated with the vm
2108  *
2109  * Returns:
2110  * Newly added bo_va or NULL for failure
2111  *
2112  * Object has to be reserved!
2113  */
2114 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
2115                                       struct amdgpu_vm *vm,
2116                                       struct amdgpu_bo *bo)
2117 {
2118         struct amdgpu_bo_va *bo_va;
2119
2120         bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
2121         if (bo_va == NULL) {
2122                 return NULL;
2123         }
2124         amdgpu_vm_bo_base_init(&bo_va->base, vm, bo);
2125
2126         bo_va->ref_count = 1;
2127         INIT_LIST_HEAD(&bo_va->valids);
2128         INIT_LIST_HEAD(&bo_va->invalids);
2129
2130         return bo_va;
2131 }
2132
2133
2134 /**
2135  * amdgpu_vm_bo_insert_mapping - insert a new mapping
2136  *
2137  * @adev: amdgpu_device pointer
2138  * @bo_va: bo_va to store the address
2139  * @mapping: the mapping to insert
2140  *
2141  * Insert a new mapping into all structures.
2142  */
2143 static void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev,
2144                                     struct amdgpu_bo_va *bo_va,
2145                                     struct amdgpu_bo_va_mapping *mapping)
2146 {
2147         struct amdgpu_vm *vm = bo_va->base.vm;
2148         struct amdgpu_bo *bo = bo_va->base.bo;
2149
2150         mapping->bo_va = bo_va;
2151         list_add(&mapping->list, &bo_va->invalids);
2152         amdgpu_vm_it_insert(mapping, &vm->va);
2153
2154         if (mapping->flags & AMDGPU_PTE_PRT)
2155                 amdgpu_vm_prt_get(adev);
2156
2157         if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv &&
2158             !bo_va->base.moved) {
2159                 list_move(&bo_va->base.vm_status, &vm->moved);
2160         }
2161         trace_amdgpu_vm_bo_map(bo_va, mapping);
2162 }
2163
2164 /**
2165  * amdgpu_vm_bo_map - map bo inside a vm
2166  *
2167  * @adev: amdgpu_device pointer
2168  * @bo_va: bo_va to store the address
2169  * @saddr: where to map the BO
2170  * @offset: requested offset in the BO
2171  * @size: BO size in bytes
2172  * @flags: attributes of pages (read/write/valid/etc.)
2173  *
2174  * Add a mapping of the BO at the specefied addr into the VM.
2175  *
2176  * Returns:
2177  * 0 for success, error for failure.
2178  *
2179  * Object has to be reserved and unreserved outside!
2180  */
2181 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
2182                      struct amdgpu_bo_va *bo_va,
2183                      uint64_t saddr, uint64_t offset,
2184                      uint64_t size, uint64_t flags)
2185 {
2186         struct amdgpu_bo_va_mapping *mapping, *tmp;
2187         struct amdgpu_bo *bo = bo_va->base.bo;
2188         struct amdgpu_vm *vm = bo_va->base.vm;
2189         uint64_t eaddr;
2190
2191         /* validate the parameters */
2192         if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
2193             size == 0 || size & AMDGPU_GPU_PAGE_MASK)
2194                 return -EINVAL;
2195
2196         /* make sure object fit at this offset */
2197         eaddr = saddr + size - 1;
2198         if (saddr >= eaddr ||
2199             (bo && offset + size > amdgpu_bo_size(bo)))
2200                 return -EINVAL;
2201
2202         saddr /= AMDGPU_GPU_PAGE_SIZE;
2203         eaddr /= AMDGPU_GPU_PAGE_SIZE;
2204
2205         tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2206         if (tmp) {
2207                 /* bo and tmp overlap, invalid addr */
2208                 dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
2209                         "0x%010Lx-0x%010Lx\n", bo, saddr, eaddr,
2210                         tmp->start, tmp->last + 1);
2211                 return -EINVAL;
2212         }
2213
2214         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2215         if (!mapping)
2216                 return -ENOMEM;
2217
2218         mapping->start = saddr;
2219         mapping->last = eaddr;
2220         mapping->offset = offset;
2221         mapping->flags = flags;
2222
2223         amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
2224
2225         return 0;
2226 }
2227
2228 /**
2229  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
2230  *
2231  * @adev: amdgpu_device pointer
2232  * @bo_va: bo_va to store the address
2233  * @saddr: where to map the BO
2234  * @offset: requested offset in the BO
2235  * @size: BO size in bytes
2236  * @flags: attributes of pages (read/write/valid/etc.)
2237  *
2238  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
2239  * mappings as we do so.
2240  *
2241  * Returns:
2242  * 0 for success, error for failure.
2243  *
2244  * Object has to be reserved and unreserved outside!
2245  */
2246 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
2247                              struct amdgpu_bo_va *bo_va,
2248                              uint64_t saddr, uint64_t offset,
2249                              uint64_t size, uint64_t flags)
2250 {
2251         struct amdgpu_bo_va_mapping *mapping;
2252         struct amdgpu_bo *bo = bo_va->base.bo;
2253         uint64_t eaddr;
2254         int r;
2255
2256         /* validate the parameters */
2257         if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
2258             size == 0 || size & AMDGPU_GPU_PAGE_MASK)
2259                 return -EINVAL;
2260
2261         /* make sure object fit at this offset */
2262         eaddr = saddr + size - 1;
2263         if (saddr >= eaddr ||
2264             (bo && offset + size > amdgpu_bo_size(bo)))
2265                 return -EINVAL;
2266
2267         /* Allocate all the needed memory */
2268         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2269         if (!mapping)
2270                 return -ENOMEM;
2271
2272         r = amdgpu_vm_bo_clear_mappings(adev, bo_va->base.vm, saddr, size);
2273         if (r) {
2274                 kfree(mapping);
2275                 return r;
2276         }
2277
2278         saddr /= AMDGPU_GPU_PAGE_SIZE;
2279         eaddr /= AMDGPU_GPU_PAGE_SIZE;
2280
2281         mapping->start = saddr;
2282         mapping->last = eaddr;
2283         mapping->offset = offset;
2284         mapping->flags = flags;
2285
2286         amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
2287
2288         return 0;
2289 }
2290
2291 /**
2292  * amdgpu_vm_bo_unmap - remove bo mapping from vm
2293  *
2294  * @adev: amdgpu_device pointer
2295  * @bo_va: bo_va to remove the address from
2296  * @saddr: where to the BO is mapped
2297  *
2298  * Remove a mapping of the BO at the specefied addr from the VM.
2299  *
2300  * Returns:
2301  * 0 for success, error for failure.
2302  *
2303  * Object has to be reserved and unreserved outside!
2304  */
2305 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
2306                        struct amdgpu_bo_va *bo_va,
2307                        uint64_t saddr)
2308 {
2309         struct amdgpu_bo_va_mapping *mapping;
2310         struct amdgpu_vm *vm = bo_va->base.vm;
2311         bool valid = true;
2312
2313         saddr /= AMDGPU_GPU_PAGE_SIZE;
2314
2315         list_for_each_entry(mapping, &bo_va->valids, list) {
2316                 if (mapping->start == saddr)
2317                         break;
2318         }
2319
2320         if (&mapping->list == &bo_va->valids) {
2321                 valid = false;
2322
2323                 list_for_each_entry(mapping, &bo_va->invalids, list) {
2324                         if (mapping->start == saddr)
2325                                 break;
2326                 }
2327
2328                 if (&mapping->list == &bo_va->invalids)
2329                         return -ENOENT;
2330         }
2331
2332         list_del(&mapping->list);
2333         amdgpu_vm_it_remove(mapping, &vm->va);
2334         mapping->bo_va = NULL;
2335         trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2336
2337         if (valid)
2338                 list_add(&mapping->list, &vm->freed);
2339         else
2340                 amdgpu_vm_free_mapping(adev, vm, mapping,
2341                                        bo_va->last_pt_update);
2342
2343         return 0;
2344 }
2345
2346 /**
2347  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
2348  *
2349  * @adev: amdgpu_device pointer
2350  * @vm: VM structure to use
2351  * @saddr: start of the range
2352  * @size: size of the range
2353  *
2354  * Remove all mappings in a range, split them as appropriate.
2355  *
2356  * Returns:
2357  * 0 for success, error for failure.
2358  */
2359 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
2360                                 struct amdgpu_vm *vm,
2361                                 uint64_t saddr, uint64_t size)
2362 {
2363         struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
2364         LIST_HEAD(removed);
2365         uint64_t eaddr;
2366
2367         eaddr = saddr + size - 1;
2368         saddr /= AMDGPU_GPU_PAGE_SIZE;
2369         eaddr /= AMDGPU_GPU_PAGE_SIZE;
2370
2371         /* Allocate all the needed memory */
2372         before = kzalloc(sizeof(*before), GFP_KERNEL);
2373         if (!before)
2374                 return -ENOMEM;
2375         INIT_LIST_HEAD(&before->list);
2376
2377         after = kzalloc(sizeof(*after), GFP_KERNEL);
2378         if (!after) {
2379                 kfree(before);
2380                 return -ENOMEM;
2381         }
2382         INIT_LIST_HEAD(&after->list);
2383
2384         /* Now gather all removed mappings */
2385         tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2386         while (tmp) {
2387                 /* Remember mapping split at the start */
2388                 if (tmp->start < saddr) {
2389                         before->start = tmp->start;
2390                         before->last = saddr - 1;
2391                         before->offset = tmp->offset;
2392                         before->flags = tmp->flags;
2393                         before->bo_va = tmp->bo_va;
2394                         list_add(&before->list, &tmp->bo_va->invalids);
2395                 }
2396
2397                 /* Remember mapping split at the end */
2398                 if (tmp->last > eaddr) {
2399                         after->start = eaddr + 1;
2400                         after->last = tmp->last;
2401                         after->offset = tmp->offset;
2402                         after->offset += after->start - tmp->start;
2403                         after->flags = tmp->flags;
2404                         after->bo_va = tmp->bo_va;
2405                         list_add(&after->list, &tmp->bo_va->invalids);
2406                 }
2407
2408                 list_del(&tmp->list);
2409                 list_add(&tmp->list, &removed);
2410
2411                 tmp = amdgpu_vm_it_iter_next(tmp, saddr, eaddr);
2412         }
2413
2414         /* And free them up */
2415         list_for_each_entry_safe(tmp, next, &removed, list) {
2416                 amdgpu_vm_it_remove(tmp, &vm->va);
2417                 list_del(&tmp->list);
2418
2419                 if (tmp->start < saddr)
2420                     tmp->start = saddr;
2421                 if (tmp->last > eaddr)
2422                     tmp->last = eaddr;
2423
2424                 tmp->bo_va = NULL;
2425                 list_add(&tmp->list, &vm->freed);
2426                 trace_amdgpu_vm_bo_unmap(NULL, tmp);
2427         }
2428
2429         /* Insert partial mapping before the range */
2430         if (!list_empty(&before->list)) {
2431                 amdgpu_vm_it_insert(before, &vm->va);
2432                 if (before->flags & AMDGPU_PTE_PRT)
2433                         amdgpu_vm_prt_get(adev);
2434         } else {
2435                 kfree(before);
2436         }
2437
2438         /* Insert partial mapping after the range */
2439         if (!list_empty(&after->list)) {
2440                 amdgpu_vm_it_insert(after, &vm->va);
2441                 if (after->flags & AMDGPU_PTE_PRT)
2442                         amdgpu_vm_prt_get(adev);
2443         } else {
2444                 kfree(after);
2445         }
2446
2447         return 0;
2448 }
2449
2450 /**
2451  * amdgpu_vm_bo_lookup_mapping - find mapping by address
2452  *
2453  * @vm: the requested VM
2454  * @addr: the address
2455  *
2456  * Find a mapping by it's address.
2457  *
2458  * Returns:
2459  * The amdgpu_bo_va_mapping matching for addr or NULL
2460  *
2461  */
2462 struct amdgpu_bo_va_mapping *amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm,
2463                                                          uint64_t addr)
2464 {
2465         return amdgpu_vm_it_iter_first(&vm->va, addr, addr);
2466 }
2467
2468 /**
2469  * amdgpu_vm_bo_trace_cs - trace all reserved mappings
2470  *
2471  * @vm: the requested vm
2472  * @ticket: CS ticket
2473  *
2474  * Trace all mappings of BOs reserved during a command submission.
2475  */
2476 void amdgpu_vm_bo_trace_cs(struct amdgpu_vm *vm, struct ww_acquire_ctx *ticket)
2477 {
2478         struct amdgpu_bo_va_mapping *mapping;
2479
2480         if (!trace_amdgpu_vm_bo_cs_enabled())
2481                 return;
2482
2483         for (mapping = amdgpu_vm_it_iter_first(&vm->va, 0, U64_MAX); mapping;
2484              mapping = amdgpu_vm_it_iter_next(mapping, 0, U64_MAX)) {
2485                 if (mapping->bo_va && mapping->bo_va->base.bo) {
2486                         struct amdgpu_bo *bo;
2487
2488                         bo = mapping->bo_va->base.bo;
2489                         if (READ_ONCE(bo->tbo.resv->lock.ctx) != ticket)
2490                                 continue;
2491                 }
2492
2493                 trace_amdgpu_vm_bo_cs(mapping);
2494         }
2495 }
2496
2497 /**
2498  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
2499  *
2500  * @adev: amdgpu_device pointer
2501  * @bo_va: requested bo_va
2502  *
2503  * Remove @bo_va->bo from the requested vm.
2504  *
2505  * Object have to be reserved!
2506  */
2507 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
2508                       struct amdgpu_bo_va *bo_va)
2509 {
2510         struct amdgpu_bo_va_mapping *mapping, *next;
2511         struct amdgpu_vm *vm = bo_va->base.vm;
2512
2513         list_del(&bo_va->base.bo_list);
2514
2515         spin_lock(&vm->invalidated_lock);
2516         list_del(&bo_va->base.vm_status);
2517         spin_unlock(&vm->invalidated_lock);
2518
2519         list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
2520                 list_del(&mapping->list);
2521                 amdgpu_vm_it_remove(mapping, &vm->va);
2522                 mapping->bo_va = NULL;
2523                 trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2524                 list_add(&mapping->list, &vm->freed);
2525         }
2526         list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
2527                 list_del(&mapping->list);
2528                 amdgpu_vm_it_remove(mapping, &vm->va);
2529                 amdgpu_vm_free_mapping(adev, vm, mapping,
2530                                        bo_va->last_pt_update);
2531         }
2532
2533         dma_fence_put(bo_va->last_pt_update);
2534         kfree(bo_va);
2535 }
2536
2537 /**
2538  * amdgpu_vm_bo_invalidate - mark the bo as invalid
2539  *
2540  * @adev: amdgpu_device pointer
2541  * @bo: amdgpu buffer object
2542  * @evicted: is the BO evicted
2543  *
2544  * Mark @bo as invalid.
2545  */
2546 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
2547                              struct amdgpu_bo *bo, bool evicted)
2548 {
2549         struct amdgpu_vm_bo_base *bo_base;
2550
2551         /* shadow bo doesn't have bo base, its validation needs its parent */
2552         if (bo->parent && bo->parent->shadow == bo)
2553                 bo = bo->parent;
2554
2555         list_for_each_entry(bo_base, &bo->va, bo_list) {
2556                 struct amdgpu_vm *vm = bo_base->vm;
2557
2558                 if (evicted && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
2559                         amdgpu_vm_bo_evicted(bo_base);
2560                         continue;
2561                 }
2562
2563                 if (bo_base->moved)
2564                         continue;
2565                 bo_base->moved = true;
2566
2567                 if (bo->tbo.type == ttm_bo_type_kernel)
2568                         amdgpu_vm_bo_relocated(bo_base);
2569                 else if (bo->tbo.resv == vm->root.base.bo->tbo.resv)
2570                         amdgpu_vm_bo_moved(bo_base);
2571                 else
2572                         amdgpu_vm_bo_invalidated(bo_base);
2573         }
2574 }
2575
2576 /**
2577  * amdgpu_vm_get_block_size - calculate VM page table size as power of two
2578  *
2579  * @vm_size: VM size
2580  *
2581  * Returns:
2582  * VM page table as power of two
2583  */
2584 static uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
2585 {
2586         /* Total bits covered by PD + PTs */
2587         unsigned bits = ilog2(vm_size) + 18;
2588
2589         /* Make sure the PD is 4K in size up to 8GB address space.
2590            Above that split equal between PD and PTs */
2591         if (vm_size <= 8)
2592                 return (bits - 9);
2593         else
2594                 return ((bits + 3) / 2);
2595 }
2596
2597 /**
2598  * amdgpu_vm_adjust_size - adjust vm size, block size and fragment size
2599  *
2600  * @adev: amdgpu_device pointer
2601  * @min_vm_size: the minimum vm size in GB if it's set auto
2602  * @fragment_size_default: Default PTE fragment size
2603  * @max_level: max VMPT level
2604  * @max_bits: max address space size in bits
2605  *
2606  */
2607 void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint32_t min_vm_size,
2608                            uint32_t fragment_size_default, unsigned max_level,
2609                            unsigned max_bits)
2610 {
2611         unsigned int max_size = 1 << (max_bits - 30);
2612         unsigned int vm_size;
2613         uint64_t tmp;
2614
2615         /* adjust vm size first */
2616         if (amdgpu_vm_size != -1) {
2617                 vm_size = amdgpu_vm_size;
2618                 if (vm_size > max_size) {
2619                         dev_warn(adev->dev, "VM size (%d) too large, max is %u GB\n",
2620                                  amdgpu_vm_size, max_size);
2621                         vm_size = max_size;
2622                 }
2623         } else {
2624                 struct sysinfo si;
2625                 unsigned int phys_ram_gb;
2626
2627                 /* Optimal VM size depends on the amount of physical
2628                  * RAM available. Underlying requirements and
2629                  * assumptions:
2630                  *
2631                  *  - Need to map system memory and VRAM from all GPUs
2632                  *     - VRAM from other GPUs not known here
2633                  *     - Assume VRAM <= system memory
2634                  *  - On GFX8 and older, VM space can be segmented for
2635                  *    different MTYPEs
2636                  *  - Need to allow room for fragmentation, guard pages etc.
2637                  *
2638                  * This adds up to a rough guess of system memory x3.
2639                  * Round up to power of two to maximize the available
2640                  * VM size with the given page table size.
2641                  */
2642                 si_meminfo(&si);
2643                 phys_ram_gb = ((uint64_t)si.totalram * si.mem_unit +
2644                                (1 << 30) - 1) >> 30;
2645                 vm_size = roundup_pow_of_two(
2646                         min(max(phys_ram_gb * 3, min_vm_size), max_size));
2647         }
2648
2649         adev->vm_manager.max_pfn = (uint64_t)vm_size << 18;
2650
2651         tmp = roundup_pow_of_two(adev->vm_manager.max_pfn);
2652         if (amdgpu_vm_block_size != -1)
2653                 tmp >>= amdgpu_vm_block_size - 9;
2654         tmp = DIV_ROUND_UP(fls64(tmp) - 1, 9) - 1;
2655         adev->vm_manager.num_level = min(max_level, (unsigned)tmp);
2656         switch (adev->vm_manager.num_level) {
2657         case 3:
2658                 adev->vm_manager.root_level = AMDGPU_VM_PDB2;
2659                 break;
2660         case 2:
2661                 adev->vm_manager.root_level = AMDGPU_VM_PDB1;
2662                 break;
2663         case 1:
2664                 adev->vm_manager.root_level = AMDGPU_VM_PDB0;
2665                 break;
2666         default:
2667                 dev_err(adev->dev, "VMPT only supports 2~4+1 levels\n");
2668         }
2669         /* block size depends on vm size and hw setup*/
2670         if (amdgpu_vm_block_size != -1)
2671                 adev->vm_manager.block_size =
2672                         min((unsigned)amdgpu_vm_block_size, max_bits
2673                             - AMDGPU_GPU_PAGE_SHIFT
2674                             - 9 * adev->vm_manager.num_level);
2675         else if (adev->vm_manager.num_level > 1)
2676                 adev->vm_manager.block_size = 9;
2677         else
2678                 adev->vm_manager.block_size = amdgpu_vm_get_block_size(tmp);
2679
2680         if (amdgpu_vm_fragment_size == -1)
2681                 adev->vm_manager.fragment_size = fragment_size_default;
2682         else
2683                 adev->vm_manager.fragment_size = amdgpu_vm_fragment_size;
2684
2685         DRM_INFO("vm size is %u GB, %u levels, block size is %u-bit, fragment size is %u-bit\n",
2686                  vm_size, adev->vm_manager.num_level + 1,
2687                  adev->vm_manager.block_size,
2688                  adev->vm_manager.fragment_size);
2689 }
2690
2691 /**
2692  * amdgpu_vm_init - initialize a vm instance
2693  *
2694  * @adev: amdgpu_device pointer
2695  * @vm: requested vm
2696  * @vm_context: Indicates if it GFX or Compute context
2697  * @pasid: Process address space identifier
2698  *
2699  * Init @vm fields.
2700  *
2701  * Returns:
2702  * 0 for success, error for failure.
2703  */
2704 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm,
2705                    int vm_context, unsigned int pasid)
2706 {
2707         struct amdgpu_bo_param bp;
2708         struct amdgpu_bo *root;
2709         int r, i;
2710
2711         vm->va = RB_ROOT_CACHED;
2712         for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2713                 vm->reserved_vmid[i] = NULL;
2714         INIT_LIST_HEAD(&vm->evicted);
2715         INIT_LIST_HEAD(&vm->relocated);
2716         INIT_LIST_HEAD(&vm->moved);
2717         INIT_LIST_HEAD(&vm->idle);
2718         INIT_LIST_HEAD(&vm->invalidated);
2719         spin_lock_init(&vm->invalidated_lock);
2720         INIT_LIST_HEAD(&vm->freed);
2721
2722         /* create scheduler entity for page table updates */
2723         r = drm_sched_entity_init(&vm->entity, adev->vm_manager.vm_pte_rqs,
2724                                   adev->vm_manager.vm_pte_num_rqs, NULL);
2725         if (r)
2726                 return r;
2727
2728         vm->pte_support_ats = false;
2729
2730         if (vm_context == AMDGPU_VM_CONTEXT_COMPUTE) {
2731                 vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2732                                                 AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2733
2734                 if (adev->asic_type == CHIP_RAVEN)
2735                         vm->pte_support_ats = true;
2736         } else {
2737                 vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2738                                                 AMDGPU_VM_USE_CPU_FOR_GFX);
2739         }
2740         DRM_DEBUG_DRIVER("VM update mode is %s\n",
2741                          vm->use_cpu_for_update ? "CPU" : "SDMA");
2742         WARN_ONCE((vm->use_cpu_for_update & !amdgpu_gmc_vram_full_visible(&adev->gmc)),
2743                   "CPU update of VM recommended only for large BAR system\n");
2744         vm->last_update = NULL;
2745
2746         amdgpu_vm_bo_param(adev, vm, adev->vm_manager.root_level, &bp);
2747         r = amdgpu_bo_create(adev, &bp, &root);
2748         if (r)
2749                 goto error_free_sched_entity;
2750
2751         r = amdgpu_bo_reserve(root, true);
2752         if (r)
2753                 goto error_free_root;
2754
2755         r = amdgpu_vm_clear_bo(adev, vm, root,
2756                                adev->vm_manager.root_level,
2757                                vm->pte_support_ats);
2758         if (r)
2759                 goto error_unreserve;
2760
2761         amdgpu_vm_bo_base_init(&vm->root.base, vm, root);
2762         amdgpu_bo_unreserve(vm->root.base.bo);
2763
2764         if (pasid) {
2765                 unsigned long flags;
2766
2767                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2768                 r = idr_alloc(&adev->vm_manager.pasid_idr, vm, pasid, pasid + 1,
2769                               GFP_ATOMIC);
2770                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2771                 if (r < 0)
2772                         goto error_free_root;
2773
2774                 vm->pasid = pasid;
2775         }
2776
2777         INIT_KFIFO(vm->faults);
2778         vm->fault_credit = 16;
2779
2780         return 0;
2781
2782 error_unreserve:
2783         amdgpu_bo_unreserve(vm->root.base.bo);
2784
2785 error_free_root:
2786         amdgpu_bo_unref(&vm->root.base.bo->shadow);
2787         amdgpu_bo_unref(&vm->root.base.bo);
2788         vm->root.base.bo = NULL;
2789
2790 error_free_sched_entity:
2791         drm_sched_entity_destroy(&vm->entity);
2792
2793         return r;
2794 }
2795
2796 /**
2797  * amdgpu_vm_make_compute - Turn a GFX VM into a compute VM
2798  *
2799  * @adev: amdgpu_device pointer
2800  * @vm: requested vm
2801  *
2802  * This only works on GFX VMs that don't have any BOs added and no
2803  * page tables allocated yet.
2804  *
2805  * Changes the following VM parameters:
2806  * - use_cpu_for_update
2807  * - pte_supports_ats
2808  * - pasid (old PASID is released, because compute manages its own PASIDs)
2809  *
2810  * Reinitializes the page directory to reflect the changed ATS
2811  * setting.
2812  *
2813  * Returns:
2814  * 0 for success, -errno for errors.
2815  */
2816 int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm, unsigned int pasid)
2817 {
2818         bool pte_support_ats = (adev->asic_type == CHIP_RAVEN);
2819         int r;
2820
2821         r = amdgpu_bo_reserve(vm->root.base.bo, true);
2822         if (r)
2823                 return r;
2824
2825         /* Sanity checks */
2826         if (!RB_EMPTY_ROOT(&vm->va.rb_root) || vm->root.entries) {
2827                 r = -EINVAL;
2828                 goto unreserve_bo;
2829         }
2830
2831         if (pasid) {
2832                 unsigned long flags;
2833
2834                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2835                 r = idr_alloc(&adev->vm_manager.pasid_idr, vm, pasid, pasid + 1,
2836                               GFP_ATOMIC);
2837                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2838
2839                 if (r == -ENOSPC)
2840                         goto unreserve_bo;
2841                 r = 0;
2842         }
2843
2844         /* Check if PD needs to be reinitialized and do it before
2845          * changing any other state, in case it fails.
2846          */
2847         if (pte_support_ats != vm->pte_support_ats) {
2848                 r = amdgpu_vm_clear_bo(adev, vm, vm->root.base.bo,
2849                                adev->vm_manager.root_level,
2850                                pte_support_ats);
2851                 if (r)
2852                         goto free_idr;
2853         }
2854
2855         /* Update VM state */
2856         vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2857                                     AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2858         vm->pte_support_ats = pte_support_ats;
2859         DRM_DEBUG_DRIVER("VM update mode is %s\n",
2860                          vm->use_cpu_for_update ? "CPU" : "SDMA");
2861         WARN_ONCE((vm->use_cpu_for_update & !amdgpu_gmc_vram_full_visible(&adev->gmc)),
2862                   "CPU update of VM recommended only for large BAR system\n");
2863
2864         if (vm->pasid) {
2865                 unsigned long flags;
2866
2867                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2868                 idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
2869                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2870
2871                 /* Free the original amdgpu allocated pasid
2872                  * Will be replaced with kfd allocated pasid
2873                  */
2874                 amdgpu_pasid_free(vm->pasid);
2875                 vm->pasid = 0;
2876         }
2877
2878         /* Free the shadow bo for compute VM */
2879         amdgpu_bo_unref(&vm->root.base.bo->shadow);
2880
2881         if (pasid)
2882                 vm->pasid = pasid;
2883
2884         goto unreserve_bo;
2885
2886 free_idr:
2887         if (pasid) {
2888                 unsigned long flags;
2889
2890                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2891                 idr_remove(&adev->vm_manager.pasid_idr, pasid);
2892                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2893         }
2894 unreserve_bo:
2895         amdgpu_bo_unreserve(vm->root.base.bo);
2896         return r;
2897 }
2898
2899 /**
2900  * amdgpu_vm_release_compute - release a compute vm
2901  * @adev: amdgpu_device pointer
2902  * @vm: a vm turned into compute vm by calling amdgpu_vm_make_compute
2903  *
2904  * This is a correspondant of amdgpu_vm_make_compute. It decouples compute
2905  * pasid from vm. Compute should stop use of vm after this call.
2906  */
2907 void amdgpu_vm_release_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2908 {
2909         if (vm->pasid) {
2910                 unsigned long flags;
2911
2912                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2913                 idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
2914                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2915         }
2916         vm->pasid = 0;
2917 }
2918
2919 /**
2920  * amdgpu_vm_free_levels - free PD/PT levels
2921  *
2922  * @adev: amdgpu device structure
2923  * @parent: PD/PT starting level to free
2924  * @level: level of parent structure
2925  *
2926  * Free the page directory or page table level and all sub levels.
2927  */
2928 static void amdgpu_vm_free_levels(struct amdgpu_device *adev,
2929                                   struct amdgpu_vm_pt *parent,
2930                                   unsigned level)
2931 {
2932         unsigned i, num_entries = amdgpu_vm_num_entries(adev, level);
2933
2934         if (parent->base.bo) {
2935                 list_del(&parent->base.bo_list);
2936                 list_del(&parent->base.vm_status);
2937                 amdgpu_bo_unref(&parent->base.bo->shadow);
2938                 amdgpu_bo_unref(&parent->base.bo);
2939         }
2940
2941         if (parent->entries)
2942                 for (i = 0; i < num_entries; i++)
2943                         amdgpu_vm_free_levels(adev, &parent->entries[i],
2944                                               level + 1);
2945
2946         kvfree(parent->entries);
2947 }
2948
2949 /**
2950  * amdgpu_vm_fini - tear down a vm instance
2951  *
2952  * @adev: amdgpu_device pointer
2953  * @vm: requested vm
2954  *
2955  * Tear down @vm.
2956  * Unbind the VM and remove all bos from the vm bo list
2957  */
2958 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2959 {
2960         struct amdgpu_bo_va_mapping *mapping, *tmp;
2961         bool prt_fini_needed = !!adev->gmc.gmc_funcs->set_prt;
2962         struct amdgpu_bo *root;
2963         u64 fault;
2964         int i, r;
2965
2966         amdgpu_amdkfd_gpuvm_destroy_cb(adev, vm);
2967
2968         /* Clear pending page faults from IH when the VM is destroyed */
2969         while (kfifo_get(&vm->faults, &fault))
2970                 amdgpu_ih_clear_fault(adev, fault);
2971
2972         if (vm->pasid) {
2973                 unsigned long flags;
2974
2975                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2976                 idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
2977                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2978         }
2979
2980         drm_sched_entity_destroy(&vm->entity);
2981
2982         if (!RB_EMPTY_ROOT(&vm->va.rb_root)) {
2983                 dev_err(adev->dev, "still active bo inside vm\n");
2984         }
2985         rbtree_postorder_for_each_entry_safe(mapping, tmp,
2986                                              &vm->va.rb_root, rb) {
2987                 list_del(&mapping->list);
2988                 amdgpu_vm_it_remove(mapping, &vm->va);
2989                 kfree(mapping);
2990         }
2991         list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
2992                 if (mapping->flags & AMDGPU_PTE_PRT && prt_fini_needed) {
2993                         amdgpu_vm_prt_fini(adev, vm);
2994                         prt_fini_needed = false;
2995                 }
2996
2997                 list_del(&mapping->list);
2998                 amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
2999         }
3000
3001         root = amdgpu_bo_ref(vm->root.base.bo);
3002         r = amdgpu_bo_reserve(root, true);
3003         if (r) {
3004                 dev_err(adev->dev, "Leaking page tables because BO reservation failed\n");
3005         } else {
3006                 amdgpu_vm_free_levels(adev, &vm->root,
3007                                       adev->vm_manager.root_level);
3008                 amdgpu_bo_unreserve(root);
3009         }
3010         amdgpu_bo_unref(&root);
3011         dma_fence_put(vm->last_update);
3012         for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
3013                 amdgpu_vmid_free_reserved(adev, vm, i);
3014 }
3015
3016 /**
3017  * amdgpu_vm_pasid_fault_credit - Check fault credit for given PASID
3018  *
3019  * @adev: amdgpu_device pointer
3020  * @pasid: PASID do identify the VM
3021  *
3022  * This function is expected to be called in interrupt context.
3023  *
3024  * Returns:
3025  * True if there was fault credit, false otherwise
3026  */
3027 bool amdgpu_vm_pasid_fault_credit(struct amdgpu_device *adev,
3028                                   unsigned int pasid)
3029 {
3030         struct amdgpu_vm *vm;
3031
3032         spin_lock(&adev->vm_manager.pasid_lock);
3033         vm = idr_find(&adev->vm_manager.pasid_idr, pasid);
3034         if (!vm) {
3035                 /* VM not found, can't track fault credit */
3036                 spin_unlock(&adev->vm_manager.pasid_lock);
3037                 return true;
3038         }
3039
3040         /* No lock needed. only accessed by IRQ handler */
3041         if (!vm->fault_credit) {
3042                 /* Too many faults in this VM */
3043                 spin_unlock(&adev->vm_manager.pasid_lock);
3044                 return false;
3045         }
3046
3047         vm->fault_credit--;
3048         spin_unlock(&adev->vm_manager.pasid_lock);
3049         return true;
3050 }
3051
3052 /**
3053  * amdgpu_vm_manager_init - init the VM manager
3054  *
3055  * @adev: amdgpu_device pointer
3056  *
3057  * Initialize the VM manager structures
3058  */
3059 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
3060 {
3061         unsigned i;
3062
3063         amdgpu_vmid_mgr_init(adev);
3064
3065         adev->vm_manager.fence_context =
3066                 dma_fence_context_alloc(AMDGPU_MAX_RINGS);
3067         for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
3068                 adev->vm_manager.seqno[i] = 0;
3069
3070         spin_lock_init(&adev->vm_manager.prt_lock);
3071         atomic_set(&adev->vm_manager.num_prt_users, 0);
3072
3073         /* If not overridden by the user, by default, only in large BAR systems
3074          * Compute VM tables will be updated by CPU
3075          */
3076 #ifdef CONFIG_X86_64
3077         if (amdgpu_vm_update_mode == -1) {
3078                 if (amdgpu_gmc_vram_full_visible(&adev->gmc))
3079                         adev->vm_manager.vm_update_mode =
3080                                 AMDGPU_VM_USE_CPU_FOR_COMPUTE;
3081                 else
3082                         adev->vm_manager.vm_update_mode = 0;
3083         } else
3084                 adev->vm_manager.vm_update_mode = amdgpu_vm_update_mode;
3085 #else
3086         adev->vm_manager.vm_update_mode = 0;
3087 #endif
3088
3089         idr_init(&adev->vm_manager.pasid_idr);
3090         spin_lock_init(&adev->vm_manager.pasid_lock);
3091 }
3092
3093 /**
3094  * amdgpu_vm_manager_fini - cleanup VM manager
3095  *
3096  * @adev: amdgpu_device pointer
3097  *
3098  * Cleanup the VM manager and free resources.
3099  */
3100 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
3101 {
3102         WARN_ON(!idr_is_empty(&adev->vm_manager.pasid_idr));
3103         idr_destroy(&adev->vm_manager.pasid_idr);
3104
3105         amdgpu_vmid_mgr_fini(adev);
3106 }
3107
3108 /**
3109  * amdgpu_vm_ioctl - Manages VMID reservation for vm hubs.
3110  *
3111  * @dev: drm device pointer
3112  * @data: drm_amdgpu_vm
3113  * @filp: drm file pointer
3114  *
3115  * Returns:
3116  * 0 for success, -errno for errors.
3117  */
3118 int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
3119 {
3120         union drm_amdgpu_vm *args = data;
3121         struct amdgpu_device *adev = dev->dev_private;
3122         struct amdgpu_fpriv *fpriv = filp->driver_priv;
3123         int r;
3124
3125         switch (args->in.op) {
3126         case AMDGPU_VM_OP_RESERVE_VMID:
3127                 /* current, we only have requirement to reserve vmid from gfxhub */
3128                 r = amdgpu_vmid_alloc_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB);
3129                 if (r)
3130                         return r;
3131                 break;
3132         case AMDGPU_VM_OP_UNRESERVE_VMID:
3133                 amdgpu_vmid_free_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB);
3134                 break;
3135         default:
3136                 return -EINVAL;
3137         }
3138
3139         return 0;
3140 }
3141
3142 /**
3143  * amdgpu_vm_get_task_info - Extracts task info for a PASID.
3144  *
3145  * @dev: drm device pointer
3146  * @pasid: PASID identifier for VM
3147  * @task_info: task_info to fill.
3148  */
3149 void amdgpu_vm_get_task_info(struct amdgpu_device *adev, unsigned int pasid,
3150                          struct amdgpu_task_info *task_info)
3151 {
3152         struct amdgpu_vm *vm;
3153
3154         spin_lock(&adev->vm_manager.pasid_lock);
3155
3156         vm = idr_find(&adev->vm_manager.pasid_idr, pasid);
3157         if (vm)
3158                 *task_info = vm->task_info;
3159
3160         spin_unlock(&adev->vm_manager.pasid_lock);
3161 }
3162
3163 /**
3164  * amdgpu_vm_set_task_info - Sets VMs task info.
3165  *
3166  * @vm: vm for which to set the info
3167  */
3168 void amdgpu_vm_set_task_info(struct amdgpu_vm *vm)
3169 {
3170         if (!vm->task_info.pid) {
3171                 vm->task_info.pid = current->pid;
3172                 get_task_comm(vm->task_info.task_name, current);
3173
3174                 if (current->group_leader->mm == current->mm) {
3175                         vm->task_info.tgid = current->group_leader->pid;
3176                         get_task_comm(vm->task_info.process_name, current->group_leader);
3177                 }
3178         }
3179 }