OSDN Git Service

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