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