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