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