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