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