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