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