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