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