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