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 0
642 	if (vm->bulk_moveable) {
643 		spin_lock(&glob->lru_lock);
644 		ttm_bo_bulk_move_lru_tail(&vm->lru_bulk_move);
645 		spin_unlock(&glob->lru_lock);
646 		return;
647 	}
648 #endif
649 
650 	memset(&vm->lru_bulk_move, 0, sizeof(vm->lru_bulk_move));
651 
652 	spin_lock(&glob->lru_lock);
653 	list_for_each_entry(bo_base, &vm->idle, vm_status) {
654 		struct amdgpu_bo *bo = bo_base->bo;
655 
656 		if (!bo->parent)
657 			continue;
658 
659 		ttm_bo_move_to_lru_tail(&bo->tbo, &vm->lru_bulk_move);
660 		if (bo->shadow)
661 			ttm_bo_move_to_lru_tail(&bo->shadow->tbo,
662 						&vm->lru_bulk_move);
663 	}
664 	spin_unlock(&glob->lru_lock);
665 
666 	vm->bulk_moveable = true;
667 }
668 
669 /**
670  * amdgpu_vm_validate_pt_bos - validate the page table BOs
671  *
672  * @adev: amdgpu device pointer
673  * @vm: vm providing the BOs
674  * @validate: callback to do the validation
675  * @param: parameter for the validation callback
676  *
677  * Validate the page table BOs on command submission if neccessary.
678  *
679  * Returns:
680  * Validation result.
681  */
682 int amdgpu_vm_validate_pt_bos(struct amdgpu_device *adev, struct amdgpu_vm *vm,
683 			      int (*validate)(void *p, struct amdgpu_bo *bo),
684 			      void *param)
685 {
686 	struct amdgpu_vm_bo_base *bo_base, *tmp;
687 	int r = 0;
688 
689 	vm->bulk_moveable &= list_empty(&vm->evicted);
690 
691 	list_for_each_entry_safe(bo_base, tmp, &vm->evicted, vm_status) {
692 		struct amdgpu_bo *bo = bo_base->bo;
693 
694 		r = validate(param, bo);
695 		if (r)
696 			break;
697 
698 		if (bo->tbo.type != ttm_bo_type_kernel) {
699 			amdgpu_vm_bo_moved(bo_base);
700 		} else {
701 			if (vm->use_cpu_for_update)
702 				r = amdgpu_bo_kmap(bo, NULL);
703 			else
704 				r = amdgpu_ttm_alloc_gart(&bo->tbo);
705 			if (r)
706 				break;
707 			if (bo->shadow) {
708 				r = amdgpu_ttm_alloc_gart(&bo->shadow->tbo);
709 				if (r)
710 					break;
711 			}
712 			amdgpu_vm_bo_relocated(bo_base);
713 		}
714 	}
715 
716 	return r;
717 }
718 
719 /**
720  * amdgpu_vm_ready - check VM is ready for updates
721  *
722  * @vm: VM to check
723  *
724  * Check if all VM PDs/PTs are ready for updates
725  *
726  * Returns:
727  * True if eviction list is empty.
728  */
729 bool amdgpu_vm_ready(struct amdgpu_vm *vm)
730 {
731 	return list_empty(&vm->evicted);
732 }
733 
734 /**
735  * amdgpu_vm_clear_bo - initially clear the PDs/PTs
736  *
737  * @adev: amdgpu_device pointer
738  * @vm: VM to clear BO from
739  * @bo: BO to clear
740  * @level: level this BO is at
741  * @pte_support_ats: indicate ATS support from PTE
742  *
743  * Root PD needs to be reserved when calling this.
744  *
745  * Returns:
746  * 0 on success, errno otherwise.
747  */
748 static int amdgpu_vm_clear_bo(struct amdgpu_device *adev,
749 			      struct amdgpu_vm *vm, struct amdgpu_bo *bo,
750 			      unsigned level, bool pte_support_ats)
751 {
752 	struct ttm_operation_ctx ctx = { true, false };
753 	struct dma_fence *fence = NULL;
754 	unsigned entries, ats_entries;
755 	struct amdgpu_ring *ring;
756 	struct amdgpu_job *job;
757 	uint64_t addr;
758 	int r;
759 
760 	entries = amdgpu_bo_size(bo) / 8;
761 
762 	if (pte_support_ats) {
763 		if (level == adev->vm_manager.root_level) {
764 			ats_entries = amdgpu_vm_level_shift(adev, level);
765 			ats_entries += AMDGPU_GPU_PAGE_SHIFT;
766 			ats_entries = AMDGPU_GMC_HOLE_START >> ats_entries;
767 			ats_entries = min(ats_entries, entries);
768 			entries -= ats_entries;
769 		} else {
770 			ats_entries = entries;
771 			entries = 0;
772 		}
773 	} else {
774 		ats_entries = 0;
775 	}
776 
777 	ring = container_of(vm->entity.rq->sched, struct amdgpu_ring, sched);
778 
779 	r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
780 	if (r)
781 		goto error;
782 
783 	r = amdgpu_ttm_alloc_gart(&bo->tbo);
784 	if (r)
785 		return r;
786 
787 	r = amdgpu_job_alloc_with_ib(adev, 64, &job);
788 	if (r)
789 		goto error;
790 
791 	addr = amdgpu_bo_gpu_offset(bo);
792 	if (ats_entries) {
793 		uint64_t ats_value;
794 
795 		ats_value = AMDGPU_PTE_DEFAULT_ATC;
796 		if (level != AMDGPU_VM_PTB)
797 			ats_value |= AMDGPU_PDE_PTE;
798 
799 		amdgpu_vm_set_pte_pde(adev, &job->ibs[0], addr, 0,
800 				      ats_entries, 0, ats_value);
801 		addr += ats_entries * 8;
802 	}
803 
804 	if (entries)
805 		amdgpu_vm_set_pte_pde(adev, &job->ibs[0], addr, 0,
806 				      entries, 0, 0);
807 
808 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
809 
810 	WARN_ON(job->ibs[0].length_dw > 64);
811 	r = amdgpu_sync_resv(adev, &job->sync, bo->tbo.resv,
812 			     AMDGPU_FENCE_OWNER_UNDEFINED, false);
813 	if (r)
814 		goto error_free;
815 
816 	r = amdgpu_job_submit(job, &vm->entity, AMDGPU_FENCE_OWNER_UNDEFINED,
817 			      &fence);
818 	if (r)
819 		goto error_free;
820 
821 	amdgpu_bo_fence(bo, fence, true);
822 	dma_fence_put(fence);
823 
824 	if (bo->shadow)
825 		return amdgpu_vm_clear_bo(adev, vm, bo->shadow,
826 					  level, pte_support_ats);
827 
828 	return 0;
829 
830 error_free:
831 	amdgpu_job_free(job);
832 
833 error:
834 	return r;
835 }
836 
837 /**
838  * amdgpu_vm_bo_param - fill in parameters for PD/PT allocation
839  *
840  * @adev: amdgpu_device pointer
841  * @vm: requesting vm
842  * @bp: resulting BO allocation parameters
843  */
844 static void amdgpu_vm_bo_param(struct amdgpu_device *adev, struct amdgpu_vm *vm,
845 			       int level, struct amdgpu_bo_param *bp)
846 {
847 	memset(bp, 0, sizeof(*bp));
848 
849 	bp->size = amdgpu_vm_bo_size(adev, level);
850 	bp->byte_align = AMDGPU_GPU_PAGE_SIZE;
851 	bp->domain = AMDGPU_GEM_DOMAIN_VRAM;
852 	bp->domain = amdgpu_bo_get_preferred_pin_domain(adev, bp->domain);
853 	bp->flags = AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS |
854 		AMDGPU_GEM_CREATE_CPU_GTT_USWC;
855 	if (vm->use_cpu_for_update)
856 		bp->flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
857 	else if (!vm->root.base.bo || vm->root.base.bo->shadow)
858 		bp->flags |= AMDGPU_GEM_CREATE_SHADOW;
859 	bp->type = ttm_bo_type_kernel;
860 	if (vm->root.base.bo)
861 		bp->resv = vm->root.base.bo->tbo.resv;
862 }
863 
864 /**
865  * amdgpu_vm_alloc_pts - Allocate page tables.
866  *
867  * @adev: amdgpu_device pointer
868  * @vm: VM to allocate page tables for
869  * @saddr: Start address which needs to be allocated
870  * @size: Size from start address we need.
871  *
872  * Make sure the page directories and page tables are allocated
873  *
874  * Returns:
875  * 0 on success, errno otherwise.
876  */
877 int amdgpu_vm_alloc_pts(struct amdgpu_device *adev,
878 			struct amdgpu_vm *vm,
879 			uint64_t saddr, uint64_t size)
880 {
881 	struct amdgpu_vm_pt_cursor cursor;
882 	struct amdgpu_bo *pt;
883 	bool ats = false;
884 	uint64_t eaddr;
885 	int r;
886 
887 	/* validate the parameters */
888 	if (saddr & AMDGPU_GPU_PAGE_MASK || size & AMDGPU_GPU_PAGE_MASK)
889 		return -EINVAL;
890 
891 	eaddr = saddr + size - 1;
892 
893 	if (vm->pte_support_ats)
894 		ats = saddr < AMDGPU_GMC_HOLE_START;
895 
896 	saddr /= AMDGPU_GPU_PAGE_SIZE;
897 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
898 
899 	if (eaddr >= adev->vm_manager.max_pfn) {
900 		dev_err(adev->dev, "va above limit (0x%08llX >= 0x%08llX)\n",
901 			eaddr, adev->vm_manager.max_pfn);
902 		return -EINVAL;
903 	}
904 
905 	for_each_amdgpu_vm_pt_leaf(adev, vm, saddr, eaddr, cursor) {
906 		struct amdgpu_vm_pt *entry = cursor.entry;
907 		struct amdgpu_bo_param bp;
908 
909 		if (cursor.level < AMDGPU_VM_PTB) {
910 			unsigned num_entries;
911 
912 			num_entries = amdgpu_vm_num_entries(adev, cursor.level);
913 			entry->entries = kvmalloc_array(num_entries,
914 							sizeof(*entry->entries),
915 							GFP_KERNEL |
916 							__GFP_ZERO);
917 			if (!entry->entries)
918 				return -ENOMEM;
919 		}
920 
921 
922 		if (entry->base.bo)
923 			continue;
924 
925 		amdgpu_vm_bo_param(adev, vm, cursor.level, &bp);
926 
927 		r = amdgpu_bo_create(adev, &bp, &pt);
928 		if (r)
929 			return r;
930 
931 		r = amdgpu_vm_clear_bo(adev, vm, pt, cursor.level, ats);
932 		if (r)
933 			goto error_free_pt;
934 
935 		if (vm->use_cpu_for_update) {
936 			r = amdgpu_bo_kmap(pt, NULL);
937 			if (r)
938 				goto error_free_pt;
939 		}
940 
941 		/* Keep a reference to the root directory to avoid
942 		* freeing them up in the wrong order.
943 		*/
944 		pt->parent = amdgpu_bo_ref(cursor.parent->base.bo);
945 
946 		amdgpu_vm_bo_base_init(&entry->base, vm, pt);
947 	}
948 
949 	return 0;
950 
951 error_free_pt:
952 	amdgpu_bo_unref(&pt->shadow);
953 	amdgpu_bo_unref(&pt);
954 	return r;
955 }
956 
957 /**
958  * amdgpu_vm_free_pts - free PD/PT levels
959  *
960  * @adev: amdgpu device structure
961  * @vm: amdgpu vm structure
962  *
963  * Free the page directory or page table level and all sub levels.
964  */
965 static void amdgpu_vm_free_pts(struct amdgpu_device *adev,
966 			       struct amdgpu_vm *vm)
967 {
968 	struct amdgpu_vm_pt_cursor cursor;
969 	struct amdgpu_vm_pt *entry;
970 
971 	for_each_amdgpu_vm_pt_dfs_safe(adev, vm, cursor, entry) {
972 
973 		if (entry->base.bo) {
974 			entry->base.bo->vm_bo = NULL;
975 			list_del(&entry->base.vm_status);
976 			amdgpu_bo_unref(&entry->base.bo->shadow);
977 			amdgpu_bo_unref(&entry->base.bo);
978 		}
979 		kvfree(entry->entries);
980 	}
981 
982 	BUG_ON(vm->root.base.bo);
983 }
984 
985 /**
986  * amdgpu_vm_check_compute_bug - check whether asic has compute vm bug
987  *
988  * @adev: amdgpu_device pointer
989  */
990 void amdgpu_vm_check_compute_bug(struct amdgpu_device *adev)
991 {
992 	const struct amdgpu_ip_block *ip_block;
993 	bool has_compute_vm_bug;
994 	struct amdgpu_ring *ring;
995 	int i;
996 
997 	has_compute_vm_bug = false;
998 
999 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
1000 	if (ip_block) {
1001 		/* Compute has a VM bug for GFX version < 7.
1002 		   Compute has a VM bug for GFX 8 MEC firmware version < 673.*/
1003 		if (ip_block->version->major <= 7)
1004 			has_compute_vm_bug = true;
1005 		else if (ip_block->version->major == 8)
1006 			if (adev->gfx.mec_fw_version < 673)
1007 				has_compute_vm_bug = true;
1008 	}
1009 
1010 	for (i = 0; i < adev->num_rings; i++) {
1011 		ring = adev->rings[i];
1012 		if (ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE)
1013 			/* only compute rings */
1014 			ring->has_compute_vm_bug = has_compute_vm_bug;
1015 		else
1016 			ring->has_compute_vm_bug = false;
1017 	}
1018 }
1019 
1020 /**
1021  * amdgpu_vm_need_pipeline_sync - Check if pipe sync is needed for job.
1022  *
1023  * @ring: ring on which the job will be submitted
1024  * @job: job to submit
1025  *
1026  * Returns:
1027  * True if sync is needed.
1028  */
1029 bool amdgpu_vm_need_pipeline_sync(struct amdgpu_ring *ring,
1030 				  struct amdgpu_job *job)
1031 {
1032 	struct amdgpu_device *adev = ring->adev;
1033 	unsigned vmhub = ring->funcs->vmhub;
1034 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
1035 	struct amdgpu_vmid *id;
1036 	bool gds_switch_needed;
1037 	bool vm_flush_needed = job->vm_needs_flush || ring->has_compute_vm_bug;
1038 
1039 	if (job->vmid == 0)
1040 		return false;
1041 	id = &id_mgr->ids[job->vmid];
1042 	gds_switch_needed = ring->funcs->emit_gds_switch && (
1043 		id->gds_base != job->gds_base ||
1044 		id->gds_size != job->gds_size ||
1045 		id->gws_base != job->gws_base ||
1046 		id->gws_size != job->gws_size ||
1047 		id->oa_base != job->oa_base ||
1048 		id->oa_size != job->oa_size);
1049 
1050 	if (amdgpu_vmid_had_gpu_reset(adev, id))
1051 		return true;
1052 
1053 	return vm_flush_needed || gds_switch_needed;
1054 }
1055 
1056 /**
1057  * amdgpu_vm_flush - hardware flush the vm
1058  *
1059  * @ring: ring to use for flush
1060  * @job:  related job
1061  * @need_pipe_sync: is pipe sync needed
1062  *
1063  * Emit a VM flush when it is necessary.
1064  *
1065  * Returns:
1066  * 0 on success, errno otherwise.
1067  */
1068 int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job, bool need_pipe_sync)
1069 {
1070 	struct amdgpu_device *adev = ring->adev;
1071 	unsigned vmhub = ring->funcs->vmhub;
1072 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
1073 	struct amdgpu_vmid *id = &id_mgr->ids[job->vmid];
1074 	bool gds_switch_needed = ring->funcs->emit_gds_switch && (
1075 		id->gds_base != job->gds_base ||
1076 		id->gds_size != job->gds_size ||
1077 		id->gws_base != job->gws_base ||
1078 		id->gws_size != job->gws_size ||
1079 		id->oa_base != job->oa_base ||
1080 		id->oa_size != job->oa_size);
1081 	bool vm_flush_needed = job->vm_needs_flush;
1082 	bool pasid_mapping_needed = id->pasid != job->pasid ||
1083 		!id->pasid_mapping ||
1084 		!dma_fence_is_signaled(id->pasid_mapping);
1085 	struct dma_fence *fence = NULL;
1086 	unsigned patch_offset = 0;
1087 	int r;
1088 
1089 	if (amdgpu_vmid_had_gpu_reset(adev, id)) {
1090 		gds_switch_needed = true;
1091 		vm_flush_needed = true;
1092 		pasid_mapping_needed = true;
1093 	}
1094 
1095 	gds_switch_needed &= !!ring->funcs->emit_gds_switch;
1096 	vm_flush_needed &= !!ring->funcs->emit_vm_flush  &&
1097 			job->vm_pd_addr != AMDGPU_BO_INVALID_OFFSET;
1098 	pasid_mapping_needed &= adev->gmc.gmc_funcs->emit_pasid_mapping &&
1099 		ring->funcs->emit_wreg;
1100 
1101 	if (!vm_flush_needed && !gds_switch_needed && !need_pipe_sync)
1102 		return 0;
1103 
1104 	if (ring->funcs->init_cond_exec)
1105 		patch_offset = amdgpu_ring_init_cond_exec(ring);
1106 
1107 	if (need_pipe_sync)
1108 		amdgpu_ring_emit_pipeline_sync(ring);
1109 
1110 	if (vm_flush_needed) {
1111 		trace_amdgpu_vm_flush(ring, job->vmid, job->vm_pd_addr);
1112 		amdgpu_ring_emit_vm_flush(ring, job->vmid, job->vm_pd_addr);
1113 	}
1114 
1115 	if (pasid_mapping_needed)
1116 		amdgpu_gmc_emit_pasid_mapping(ring, job->vmid, job->pasid);
1117 
1118 	if (vm_flush_needed || pasid_mapping_needed) {
1119 		r = amdgpu_fence_emit(ring, &fence, 0);
1120 		if (r)
1121 			return r;
1122 	}
1123 
1124 	if (vm_flush_needed) {
1125 		mutex_lock(&id_mgr->lock);
1126 		dma_fence_put(id->last_flush);
1127 		id->last_flush = dma_fence_get(fence);
1128 		id->current_gpu_reset_count =
1129 			atomic_read(&adev->gpu_reset_counter);
1130 		mutex_unlock(&id_mgr->lock);
1131 	}
1132 
1133 	if (pasid_mapping_needed) {
1134 		id->pasid = job->pasid;
1135 		dma_fence_put(id->pasid_mapping);
1136 		id->pasid_mapping = dma_fence_get(fence);
1137 	}
1138 	dma_fence_put(fence);
1139 
1140 	if (ring->funcs->emit_gds_switch && gds_switch_needed) {
1141 		id->gds_base = job->gds_base;
1142 		id->gds_size = job->gds_size;
1143 		id->gws_base = job->gws_base;
1144 		id->gws_size = job->gws_size;
1145 		id->oa_base = job->oa_base;
1146 		id->oa_size = job->oa_size;
1147 		amdgpu_ring_emit_gds_switch(ring, job->vmid, job->gds_base,
1148 					    job->gds_size, job->gws_base,
1149 					    job->gws_size, job->oa_base,
1150 					    job->oa_size);
1151 	}
1152 
1153 	if (ring->funcs->patch_cond_exec)
1154 		amdgpu_ring_patch_cond_exec(ring, patch_offset);
1155 
1156 	/* the double SWITCH_BUFFER here *cannot* be skipped by COND_EXEC */
1157 	if (ring->funcs->emit_switch_buffer) {
1158 		amdgpu_ring_emit_switch_buffer(ring);
1159 		amdgpu_ring_emit_switch_buffer(ring);
1160 	}
1161 	return 0;
1162 }
1163 
1164 /**
1165  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
1166  *
1167  * @vm: requested vm
1168  * @bo: requested buffer object
1169  *
1170  * Find @bo inside the requested vm.
1171  * Search inside the @bos vm list for the requested vm
1172  * Returns the found bo_va or NULL if none is found
1173  *
1174  * Object has to be reserved!
1175  *
1176  * Returns:
1177  * Found bo_va or NULL.
1178  */
1179 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
1180 				       struct amdgpu_bo *bo)
1181 {
1182 	struct amdgpu_vm_bo_base *base;
1183 
1184 	for (base = bo->vm_bo; base; base = base->next) {
1185 		if (base->vm != vm)
1186 			continue;
1187 
1188 		return container_of(base, struct amdgpu_bo_va, base);
1189 	}
1190 	return NULL;
1191 }
1192 
1193 /**
1194  * amdgpu_vm_do_set_ptes - helper to call the right asic function
1195  *
1196  * @params: see amdgpu_pte_update_params definition
1197  * @bo: PD/PT to update
1198  * @pe: addr of the page entry
1199  * @addr: dst addr to write into pe
1200  * @count: number of page entries to update
1201  * @incr: increase next addr by incr bytes
1202  * @flags: hw access flags
1203  *
1204  * Traces the parameters and calls the right asic functions
1205  * to setup the page table using the DMA.
1206  */
1207 static void amdgpu_vm_do_set_ptes(struct amdgpu_pte_update_params *params,
1208 				  struct amdgpu_bo *bo,
1209 				  uint64_t pe, uint64_t addr,
1210 				  unsigned count, uint32_t incr,
1211 				  uint64_t flags)
1212 {
1213 	pe += amdgpu_bo_gpu_offset(bo);
1214 	trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
1215 
1216 	if (count < 3) {
1217 		amdgpu_vm_write_pte(params->adev, params->ib, pe,
1218 				    addr | flags, count, incr);
1219 
1220 	} else {
1221 		amdgpu_vm_set_pte_pde(params->adev, params->ib, pe, addr,
1222 				      count, incr, flags);
1223 	}
1224 }
1225 
1226 /**
1227  * amdgpu_vm_do_copy_ptes - copy the PTEs from the GART
1228  *
1229  * @params: see amdgpu_pte_update_params definition
1230  * @bo: PD/PT to update
1231  * @pe: addr of the page entry
1232  * @addr: dst addr to write into pe
1233  * @count: number of page entries to update
1234  * @incr: increase next addr by incr bytes
1235  * @flags: hw access flags
1236  *
1237  * Traces the parameters and calls the DMA function to copy the PTEs.
1238  */
1239 static void amdgpu_vm_do_copy_ptes(struct amdgpu_pte_update_params *params,
1240 				   struct amdgpu_bo *bo,
1241 				   uint64_t pe, uint64_t addr,
1242 				   unsigned count, uint32_t incr,
1243 				   uint64_t flags)
1244 {
1245 	uint64_t src = (params->src + (addr >> 12) * 8);
1246 
1247 	pe += amdgpu_bo_gpu_offset(bo);
1248 	trace_amdgpu_vm_copy_ptes(pe, src, count);
1249 
1250 	amdgpu_vm_copy_pte(params->adev, params->ib, pe, src, count);
1251 }
1252 
1253 /**
1254  * amdgpu_vm_map_gart - Resolve gart mapping of addr
1255  *
1256  * @pages_addr: optional DMA address to use for lookup
1257  * @addr: the unmapped addr
1258  *
1259  * Look up the physical address of the page that the pte resolves
1260  * to.
1261  *
1262  * Returns:
1263  * The pointer for the page table entry.
1264  */
1265 static uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
1266 {
1267 	uint64_t result;
1268 
1269 	/* page table offset */
1270 	result = pages_addr[addr >> PAGE_SHIFT];
1271 
1272 	/* in case cpu page size != gpu page size*/
1273 	result |= addr & (~PAGE_MASK);
1274 
1275 	result &= 0xFFFFFFFFFFFFF000ULL;
1276 
1277 	return result;
1278 }
1279 
1280 /**
1281  * amdgpu_vm_cpu_set_ptes - helper to update page tables via CPU
1282  *
1283  * @params: see amdgpu_pte_update_params definition
1284  * @bo: PD/PT to update
1285  * @pe: kmap addr of the page entry
1286  * @addr: dst addr to write into pe
1287  * @count: number of page entries to update
1288  * @incr: increase next addr by incr bytes
1289  * @flags: hw access flags
1290  *
1291  * Write count number of PT/PD entries directly.
1292  */
1293 static void amdgpu_vm_cpu_set_ptes(struct amdgpu_pte_update_params *params,
1294 				   struct amdgpu_bo *bo,
1295 				   uint64_t pe, uint64_t addr,
1296 				   unsigned count, uint32_t incr,
1297 				   uint64_t flags)
1298 {
1299 	unsigned int i;
1300 	uint64_t value;
1301 
1302 	pe += (unsigned long)amdgpu_bo_kptr(bo);
1303 
1304 	trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
1305 
1306 	for (i = 0; i < count; i++) {
1307 		value = params->pages_addr ?
1308 			amdgpu_vm_map_gart(params->pages_addr, addr) :
1309 			addr;
1310 		amdgpu_gmc_set_pte_pde(params->adev, (void *)(uintptr_t)pe,
1311 				       i, value, flags);
1312 		addr += incr;
1313 	}
1314 }
1315 
1316 
1317 /**
1318  * amdgpu_vm_wait_pd - Wait for PT BOs to be free.
1319  *
1320  * @adev: amdgpu_device pointer
1321  * @vm: related vm
1322  * @owner: fence owner
1323  *
1324  * Returns:
1325  * 0 on success, errno otherwise.
1326  */
1327 static int amdgpu_vm_wait_pd(struct amdgpu_device *adev, struct amdgpu_vm *vm,
1328 			     void *owner)
1329 {
1330 	struct amdgpu_sync sync;
1331 	int r;
1332 
1333 	amdgpu_sync_create(&sync);
1334 	amdgpu_sync_resv(adev, &sync, vm->root.base.bo->tbo.resv, owner, false);
1335 	r = amdgpu_sync_wait(&sync, true);
1336 	amdgpu_sync_free(&sync);
1337 
1338 	return r;
1339 }
1340 
1341 /**
1342  * amdgpu_vm_update_func - helper to call update function
1343  *
1344  * Calls the update function for both the given BO as well as its shadow.
1345  */
1346 static void amdgpu_vm_update_func(struct amdgpu_pte_update_params *params,
1347 				  struct amdgpu_bo *bo,
1348 				  uint64_t pe, uint64_t addr,
1349 				  unsigned count, uint32_t incr,
1350 				  uint64_t flags)
1351 {
1352 	if (bo->shadow)
1353 		params->func(params, bo->shadow, pe, addr, count, incr, flags);
1354 	params->func(params, bo, pe, addr, count, incr, flags);
1355 }
1356 
1357 /*
1358  * amdgpu_vm_update_pde - update a single level in the hierarchy
1359  *
1360  * @param: parameters for the update
1361  * @vm: requested vm
1362  * @parent: parent directory
1363  * @entry: entry to update
1364  *
1365  * Makes sure the requested entry in parent is up to date.
1366  */
1367 static void amdgpu_vm_update_pde(struct amdgpu_pte_update_params *params,
1368 				 struct amdgpu_vm *vm,
1369 				 struct amdgpu_vm_pt *parent,
1370 				 struct amdgpu_vm_pt *entry)
1371 {
1372 	struct amdgpu_bo *bo = parent->base.bo, *pbo;
1373 	uint64_t pde, pt, flags;
1374 	unsigned level;
1375 
1376 	/* Don't update huge pages here */
1377 	if (entry->huge)
1378 		return;
1379 
1380 	for (level = 0, pbo = bo->parent; pbo; ++level)
1381 		pbo = pbo->parent;
1382 
1383 	level += params->adev->vm_manager.root_level;
1384 	amdgpu_gmc_get_pde_for_bo(entry->base.bo, level, &pt, &flags);
1385 	pde = (entry - parent->entries) * 8;
1386 	amdgpu_vm_update_func(params, bo, pde, pt, 1, 0, flags);
1387 }
1388 
1389 /*
1390  * amdgpu_vm_invalidate_pds - mark all PDs as invalid
1391  *
1392  * @adev: amdgpu_device pointer
1393  * @vm: related vm
1394  *
1395  * Mark all PD level as invalid after an error.
1396  */
1397 static void amdgpu_vm_invalidate_pds(struct amdgpu_device *adev,
1398 				     struct amdgpu_vm *vm)
1399 {
1400 	struct amdgpu_vm_pt_cursor cursor;
1401 	struct amdgpu_vm_pt *entry;
1402 
1403 	for_each_amdgpu_vm_pt_dfs_safe(adev, vm, cursor, entry)
1404 		if (entry->base.bo && !entry->base.moved)
1405 			amdgpu_vm_bo_relocated(&entry->base);
1406 }
1407 
1408 /*
1409  * amdgpu_vm_update_directories - make sure that all directories are valid
1410  *
1411  * @adev: amdgpu_device pointer
1412  * @vm: requested vm
1413  *
1414  * Makes sure all directories are up to date.
1415  *
1416  * Returns:
1417  * 0 for success, error for failure.
1418  */
1419 int amdgpu_vm_update_directories(struct amdgpu_device *adev,
1420 				 struct amdgpu_vm *vm)
1421 {
1422 	struct amdgpu_pte_update_params params;
1423 	struct amdgpu_job *job;
1424 	unsigned ndw = 0;
1425 	int r = 0;
1426 
1427 	if (list_empty(&vm->relocated))
1428 		return 0;
1429 
1430 restart:
1431 	memset(&params, 0, sizeof(params));
1432 	params.adev = adev;
1433 
1434 	if (vm->use_cpu_for_update) {
1435 		r = amdgpu_vm_wait_pd(adev, vm, AMDGPU_FENCE_OWNER_VM);
1436 		if (unlikely(r))
1437 			return r;
1438 
1439 		params.func = amdgpu_vm_cpu_set_ptes;
1440 	} else {
1441 		ndw = 512 * 8;
1442 		r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1443 		if (r)
1444 			return r;
1445 
1446 		params.ib = &job->ibs[0];
1447 		params.func = amdgpu_vm_do_set_ptes;
1448 	}
1449 
1450 	while (!list_empty(&vm->relocated)) {
1451 		struct amdgpu_vm_pt *pt, *entry;
1452 
1453 		entry = list_first_entry(&vm->relocated, struct amdgpu_vm_pt,
1454 					 base.vm_status);
1455 		amdgpu_vm_bo_idle(&entry->base);
1456 
1457 		pt = amdgpu_vm_pt_parent(entry);
1458 		if (!pt)
1459 			continue;
1460 
1461 		amdgpu_vm_update_pde(&params, vm, pt, entry);
1462 
1463 		if (!vm->use_cpu_for_update &&
1464 		    (ndw - params.ib->length_dw) < 32)
1465 			break;
1466 	}
1467 
1468 	if (vm->use_cpu_for_update) {
1469 		/* Flush HDP */
1470 		mb();
1471 		amdgpu_asic_flush_hdp(adev, NULL);
1472 	} else if (params.ib->length_dw == 0) {
1473 		amdgpu_job_free(job);
1474 	} else {
1475 		struct amdgpu_bo *root = vm->root.base.bo;
1476 		struct amdgpu_ring *ring;
1477 		struct dma_fence *fence;
1478 
1479 		ring = container_of(vm->entity.rq->sched, struct amdgpu_ring,
1480 				    sched);
1481 
1482 		amdgpu_ring_pad_ib(ring, params.ib);
1483 		amdgpu_sync_resv(adev, &job->sync, root->tbo.resv,
1484 				 AMDGPU_FENCE_OWNER_VM, false);
1485 		WARN_ON(params.ib->length_dw > ndw);
1486 		r = amdgpu_job_submit(job, &vm->entity, AMDGPU_FENCE_OWNER_VM,
1487 				      &fence);
1488 		if (r)
1489 			goto error;
1490 
1491 		amdgpu_bo_fence(root, fence, true);
1492 		dma_fence_put(vm->last_update);
1493 		vm->last_update = fence;
1494 	}
1495 
1496 	if (!list_empty(&vm->relocated))
1497 		goto restart;
1498 
1499 	return 0;
1500 
1501 error:
1502 	amdgpu_vm_invalidate_pds(adev, vm);
1503 	amdgpu_job_free(job);
1504 	return r;
1505 }
1506 
1507 /**
1508  * amdgpu_vm_update_huge - figure out parameters for PTE updates
1509  *
1510  * Make sure to set the right flags for the PTEs at the desired level.
1511  */
1512 static void amdgpu_vm_update_huge(struct amdgpu_pte_update_params *params,
1513 				  struct amdgpu_bo *bo, unsigned level,
1514 				  uint64_t pe, uint64_t addr,
1515 				  unsigned count, uint32_t incr,
1516 				  uint64_t flags)
1517 
1518 {
1519 	if (level != AMDGPU_VM_PTB) {
1520 		flags |= AMDGPU_PDE_PTE;
1521 		amdgpu_gmc_get_vm_pde(params->adev, level, &addr, &flags);
1522 	}
1523 
1524 	amdgpu_vm_update_func(params, bo, pe, addr, count, incr, flags);
1525 }
1526 
1527 /**
1528  * amdgpu_vm_fragment - get fragment for PTEs
1529  *
1530  * @params: see amdgpu_pte_update_params definition
1531  * @start: first PTE to handle
1532  * @end: last PTE to handle
1533  * @flags: hw mapping flags
1534  * @frag: resulting fragment size
1535  * @frag_end: end of this fragment
1536  *
1537  * Returns the first possible fragment for the start and end address.
1538  */
1539 static void amdgpu_vm_fragment(struct amdgpu_pte_update_params *params,
1540 			       uint64_t start, uint64_t end, uint64_t flags,
1541 			       unsigned int *frag, uint64_t *frag_end)
1542 {
1543 	/**
1544 	 * The MC L1 TLB supports variable sized pages, based on a fragment
1545 	 * field in the PTE. When this field is set to a non-zero value, page
1546 	 * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
1547 	 * flags are considered valid for all PTEs within the fragment range
1548 	 * and corresponding mappings are assumed to be physically contiguous.
1549 	 *
1550 	 * The L1 TLB can store a single PTE for the whole fragment,
1551 	 * significantly increasing the space available for translation
1552 	 * caching. This leads to large improvements in throughput when the
1553 	 * TLB is under pressure.
1554 	 *
1555 	 * The L2 TLB distributes small and large fragments into two
1556 	 * asymmetric partitions. The large fragment cache is significantly
1557 	 * larger. Thus, we try to use large fragments wherever possible.
1558 	 * Userspace can support this by aligning virtual base address and
1559 	 * allocation size to the fragment size.
1560 	 *
1561 	 * Starting with Vega10 the fragment size only controls the L1. The L2
1562 	 * is now directly feed with small/huge/giant pages from the walker.
1563 	 */
1564 	unsigned max_frag;
1565 
1566 	if (params->adev->asic_type < CHIP_VEGA10)
1567 		max_frag = params->adev->vm_manager.fragment_size;
1568 	else
1569 		max_frag = 31;
1570 
1571 	/* system pages are non continuously */
1572 	if (params->src) {
1573 		*frag = 0;
1574 		*frag_end = end;
1575 		return;
1576 	}
1577 
1578 	/* This intentionally wraps around if no bit is set */
1579 	*frag = min((unsigned)ffs(start) - 1, (unsigned)fls64(end - start) - 1);
1580 	if (*frag >= max_frag) {
1581 		*frag = max_frag;
1582 		*frag_end = end & ~((1ULL << max_frag) - 1);
1583 	} else {
1584 		*frag_end = start + (1 << *frag);
1585 	}
1586 }
1587 
1588 /**
1589  * amdgpu_vm_update_ptes - make sure that page tables are valid
1590  *
1591  * @params: see amdgpu_pte_update_params definition
1592  * @start: start of GPU address range
1593  * @end: end of GPU address range
1594  * @dst: destination address to map to, the next dst inside the function
1595  * @flags: mapping flags
1596  *
1597  * Update the page tables in the range @start - @end.
1598  *
1599  * Returns:
1600  * 0 for success, -EINVAL for failure.
1601  */
1602 static int amdgpu_vm_update_ptes(struct amdgpu_pte_update_params *params,
1603 				 uint64_t start, uint64_t end,
1604 				 uint64_t dst, uint64_t flags)
1605 {
1606 	struct amdgpu_device *adev = params->adev;
1607 	struct amdgpu_vm_pt_cursor cursor;
1608 	uint64_t frag_start = start, frag_end;
1609 	unsigned int frag;
1610 
1611 	/* figure out the initial fragment */
1612 	amdgpu_vm_fragment(params, frag_start, end, flags, &frag, &frag_end);
1613 
1614 	/* walk over the address space and update the PTs */
1615 	amdgpu_vm_pt_start(adev, params->vm, start, &cursor);
1616 	while (cursor.pfn < end) {
1617 		struct amdgpu_bo *pt = cursor.entry->base.bo;
1618 		unsigned shift, parent_shift, mask;
1619 		uint64_t incr, entry_end, pe_start;
1620 
1621 		if (!pt)
1622 			return -ENOENT;
1623 
1624 		/* The root level can't be a huge page */
1625 		if (cursor.level == adev->vm_manager.root_level) {
1626 			if (!amdgpu_vm_pt_descendant(adev, &cursor))
1627 				return -ENOENT;
1628 			continue;
1629 		}
1630 
1631 		/* If it isn't already handled it can't be a huge page */
1632 		if (cursor.entry->huge) {
1633 			/* Add the entry to the relocated list to update it. */
1634 			cursor.entry->huge = false;
1635 			amdgpu_vm_bo_relocated(&cursor.entry->base);
1636 		}
1637 
1638 		shift = amdgpu_vm_level_shift(adev, cursor.level);
1639 		parent_shift = amdgpu_vm_level_shift(adev, cursor.level - 1);
1640 		if (adev->asic_type < CHIP_VEGA10) {
1641 			/* No huge page support before GMC v9 */
1642 			if (cursor.level != AMDGPU_VM_PTB) {
1643 				if (!amdgpu_vm_pt_descendant(adev, &cursor))
1644 					return -ENOENT;
1645 				continue;
1646 			}
1647 		} else if (frag < shift) {
1648 			/* We can't use this level when the fragment size is
1649 			 * smaller than the address shift. Go to the next
1650 			 * child entry and try again.
1651 			 */
1652 			if (!amdgpu_vm_pt_descendant(adev, &cursor))
1653 				return -ENOENT;
1654 			continue;
1655 		} else if (frag >= parent_shift &&
1656 			   cursor.level - 1 != adev->vm_manager.root_level) {
1657 			/* If the fragment size is even larger than the parent
1658 			 * shift we should go up one level and check it again
1659 			 * unless one level up is the root level.
1660 			 */
1661 			if (!amdgpu_vm_pt_ancestor(&cursor))
1662 				return -ENOENT;
1663 			continue;
1664 		}
1665 
1666 		/* Looks good so far, calculate parameters for the update */
1667 		incr = (uint64_t)AMDGPU_GPU_PAGE_SIZE << shift;
1668 		mask = amdgpu_vm_entries_mask(adev, cursor.level);
1669 		pe_start = ((cursor.pfn >> shift) & mask) * 8;
1670 		entry_end = (uint64_t)(mask + 1) << shift;
1671 		entry_end += cursor.pfn & ~(entry_end - 1);
1672 		entry_end = min(entry_end, end);
1673 
1674 		do {
1675 			uint64_t upd_end = min(entry_end, frag_end);
1676 			unsigned nptes = (upd_end - frag_start) >> shift;
1677 
1678 			amdgpu_vm_update_huge(params, pt, cursor.level,
1679 					      pe_start, dst, nptes, incr,
1680 					      flags | AMDGPU_PTE_FRAG(frag));
1681 
1682 			pe_start += nptes * 8;
1683 			dst += (uint64_t)nptes * AMDGPU_GPU_PAGE_SIZE << shift;
1684 
1685 			frag_start = upd_end;
1686 			if (frag_start >= frag_end) {
1687 				/* figure out the next fragment */
1688 				amdgpu_vm_fragment(params, frag_start, end,
1689 						   flags, &frag, &frag_end);
1690 				if (frag < shift)
1691 					break;
1692 			}
1693 		} while (frag_start < entry_end);
1694 
1695 		if (amdgpu_vm_pt_descendant(adev, &cursor)) {
1696 			/* Mark all child entries as huge */
1697 			while (cursor.pfn < frag_start) {
1698 				cursor.entry->huge = true;
1699 				amdgpu_vm_pt_next(adev, &cursor);
1700 			}
1701 
1702 		} else if (frag >= shift) {
1703 			/* or just move on to the next on the same level. */
1704 			amdgpu_vm_pt_next(adev, &cursor);
1705 		}
1706 	}
1707 
1708 	return 0;
1709 }
1710 
1711 /**
1712  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
1713  *
1714  * @adev: amdgpu_device pointer
1715  * @exclusive: fence we need to sync to
1716  * @pages_addr: DMA addresses to use for mapping
1717  * @vm: requested vm
1718  * @start: start of mapped range
1719  * @last: last mapped entry
1720  * @flags: flags for the entries
1721  * @addr: addr to set the area to
1722  * @fence: optional resulting fence
1723  *
1724  * Fill in the page table entries between @start and @last.
1725  *
1726  * Returns:
1727  * 0 for success, -EINVAL for failure.
1728  */
1729 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
1730 				       struct dma_fence *exclusive,
1731 				       dma_addr_t *pages_addr,
1732 				       struct amdgpu_vm *vm,
1733 				       uint64_t start, uint64_t last,
1734 				       uint64_t flags, uint64_t addr,
1735 				       struct dma_fence **fence)
1736 {
1737 	struct amdgpu_ring *ring;
1738 	void *owner = AMDGPU_FENCE_OWNER_VM;
1739 	unsigned nptes, ncmds, ndw;
1740 	struct amdgpu_job *job;
1741 	struct amdgpu_pte_update_params params;
1742 	struct dma_fence *f = NULL;
1743 	int r;
1744 
1745 	memset(&params, 0, sizeof(params));
1746 	params.adev = adev;
1747 	params.vm = vm;
1748 
1749 	/* sync to everything on unmapping */
1750 	if (!(flags & AMDGPU_PTE_VALID))
1751 		owner = AMDGPU_FENCE_OWNER_UNDEFINED;
1752 
1753 	if (vm->use_cpu_for_update) {
1754 		/* params.src is used as flag to indicate system Memory */
1755 		if (pages_addr)
1756 			params.src = ~0;
1757 
1758 		/* Wait for PT BOs to be free. PTs share the same resv. object
1759 		 * as the root PD BO
1760 		 */
1761 		r = amdgpu_vm_wait_pd(adev, vm, owner);
1762 		if (unlikely(r))
1763 			return r;
1764 
1765 		params.func = amdgpu_vm_cpu_set_ptes;
1766 		params.pages_addr = pages_addr;
1767 		return amdgpu_vm_update_ptes(&params, start, last + 1,
1768 					     addr, flags);
1769 	}
1770 
1771 	ring = container_of(vm->entity.rq->sched, struct amdgpu_ring, sched);
1772 
1773 	nptes = last - start + 1;
1774 
1775 	/*
1776 	 * reserve space for two commands every (1 << BLOCK_SIZE)
1777 	 *  entries or 2k dwords (whatever is smaller)
1778          *
1779          * The second command is for the shadow pagetables.
1780 	 */
1781 	if (vm->root.base.bo->shadow)
1782 		ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1) * 2;
1783 	else
1784 		ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1);
1785 
1786 	/* padding, etc. */
1787 	ndw = 64;
1788 
1789 	if (pages_addr) {
1790 		/* copy commands needed */
1791 		ndw += ncmds * adev->vm_manager.vm_pte_funcs->copy_pte_num_dw;
1792 
1793 		/* and also PTEs */
1794 		ndw += nptes * 2;
1795 
1796 		params.func = amdgpu_vm_do_copy_ptes;
1797 
1798 	} else {
1799 		/* set page commands needed */
1800 		ndw += ncmds * 10;
1801 
1802 		/* extra commands for begin/end fragments */
1803 		if (vm->root.base.bo->shadow)
1804 		        ndw += 2 * 10 * adev->vm_manager.fragment_size * 2;
1805 		else
1806 		        ndw += 2 * 10 * adev->vm_manager.fragment_size;
1807 
1808 		params.func = amdgpu_vm_do_set_ptes;
1809 	}
1810 
1811 	r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1812 	if (r)
1813 		return r;
1814 
1815 	params.ib = &job->ibs[0];
1816 
1817 	if (pages_addr) {
1818 		uint64_t *pte;
1819 		unsigned i;
1820 
1821 		/* Put the PTEs at the end of the IB. */
1822 		i = ndw - nptes * 2;
1823 		pte= (uint64_t *)&(job->ibs->ptr[i]);
1824 		params.src = job->ibs->gpu_addr + i * 4;
1825 
1826 		for (i = 0; i < nptes; ++i) {
1827 			pte[i] = amdgpu_vm_map_gart(pages_addr, addr + i *
1828 						    AMDGPU_GPU_PAGE_SIZE);
1829 			pte[i] |= flags;
1830 		}
1831 		addr = 0;
1832 	}
1833 
1834 	r = amdgpu_sync_fence(adev, &job->sync, exclusive, false);
1835 	if (r)
1836 		goto error_free;
1837 
1838 	r = amdgpu_sync_resv(adev, &job->sync, vm->root.base.bo->tbo.resv,
1839 			     owner, false);
1840 	if (r)
1841 		goto error_free;
1842 
1843 	r = amdgpu_vm_update_ptes(&params, start, last + 1, addr, flags);
1844 	if (r)
1845 		goto error_free;
1846 
1847 	amdgpu_ring_pad_ib(ring, params.ib);
1848 	WARN_ON(params.ib->length_dw > ndw);
1849 	r = amdgpu_job_submit(job, &vm->entity, AMDGPU_FENCE_OWNER_VM, &f);
1850 	if (r)
1851 		goto error_free;
1852 
1853 	amdgpu_bo_fence(vm->root.base.bo, f, true);
1854 	dma_fence_put(*fence);
1855 	*fence = f;
1856 	return 0;
1857 
1858 error_free:
1859 	amdgpu_job_free(job);
1860 	return r;
1861 }
1862 
1863 /**
1864  * amdgpu_vm_bo_split_mapping - split a mapping into smaller chunks
1865  *
1866  * @adev: amdgpu_device pointer
1867  * @exclusive: fence we need to sync to
1868  * @pages_addr: DMA addresses to use for mapping
1869  * @vm: requested vm
1870  * @mapping: mapped range and flags to use for the update
1871  * @flags: HW flags for the mapping
1872  * @nodes: array of drm_mm_nodes with the MC addresses
1873  * @fence: optional resulting fence
1874  *
1875  * Split the mapping into smaller chunks so that each update fits
1876  * into a SDMA IB.
1877  *
1878  * Returns:
1879  * 0 for success, -EINVAL for failure.
1880  */
1881 static int amdgpu_vm_bo_split_mapping(struct amdgpu_device *adev,
1882 				      struct dma_fence *exclusive,
1883 				      dma_addr_t *pages_addr,
1884 				      struct amdgpu_vm *vm,
1885 				      struct amdgpu_bo_va_mapping *mapping,
1886 				      uint64_t flags,
1887 				      struct drm_mm_node *nodes,
1888 				      struct dma_fence **fence)
1889 {
1890 	unsigned min_linear_pages = 1 << adev->vm_manager.fragment_size;
1891 	uint64_t pfn, start = mapping->start;
1892 	int r;
1893 
1894 	/* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1895 	 * but in case of something, we filter the flags in first place
1896 	 */
1897 	if (!(mapping->flags & AMDGPU_PTE_READABLE))
1898 		flags &= ~AMDGPU_PTE_READABLE;
1899 	if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1900 		flags &= ~AMDGPU_PTE_WRITEABLE;
1901 
1902 	flags &= ~AMDGPU_PTE_EXECUTABLE;
1903 	flags |= mapping->flags & AMDGPU_PTE_EXECUTABLE;
1904 
1905 	flags &= ~AMDGPU_PTE_MTYPE_MASK;
1906 	flags |= (mapping->flags & AMDGPU_PTE_MTYPE_MASK);
1907 
1908 	if ((mapping->flags & AMDGPU_PTE_PRT) &&
1909 	    (adev->asic_type >= CHIP_VEGA10)) {
1910 		flags |= AMDGPU_PTE_PRT;
1911 		flags &= ~AMDGPU_PTE_VALID;
1912 	}
1913 
1914 	trace_amdgpu_vm_bo_update(mapping);
1915 
1916 	pfn = mapping->offset >> PAGE_SHIFT;
1917 	if (nodes) {
1918 		while (pfn >= nodes->size) {
1919 			pfn -= nodes->size;
1920 			++nodes;
1921 		}
1922 	}
1923 
1924 	do {
1925 		dma_addr_t *dma_addr = NULL;
1926 		uint64_t max_entries;
1927 		uint64_t addr, last;
1928 
1929 		if (nodes) {
1930 			addr = nodes->start << PAGE_SHIFT;
1931 			max_entries = (nodes->size - pfn) *
1932 				AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1933 		} else {
1934 			addr = 0;
1935 			max_entries = S64_MAX;
1936 		}
1937 
1938 		if (pages_addr) {
1939 			uint64_t count;
1940 
1941 			max_entries = min(max_entries, 16ull * 1024ull);
1942 			for (count = 1;
1943 			     count < max_entries / AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1944 			     ++count) {
1945 				uint64_t idx = pfn + count;
1946 
1947 				if (pages_addr[idx] !=
1948 				    (pages_addr[idx - 1] + PAGE_SIZE))
1949 					break;
1950 			}
1951 
1952 			if (count < min_linear_pages) {
1953 				addr = pfn << PAGE_SHIFT;
1954 				dma_addr = pages_addr;
1955 			} else {
1956 				addr = pages_addr[pfn];
1957 				max_entries = count * AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1958 			}
1959 
1960 		} else if (flags & AMDGPU_PTE_VALID) {
1961 			addr += adev->vm_manager.vram_base_offset;
1962 			addr += pfn << PAGE_SHIFT;
1963 		}
1964 
1965 		last = min((uint64_t)mapping->last, start + max_entries - 1);
1966 		r = amdgpu_vm_bo_update_mapping(adev, exclusive, dma_addr, vm,
1967 						start, last, flags, addr,
1968 						fence);
1969 		if (r)
1970 			return r;
1971 
1972 		pfn += (last - start + 1) / AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1973 		if (nodes && nodes->size == pfn) {
1974 			pfn = 0;
1975 			++nodes;
1976 		}
1977 		start = last + 1;
1978 
1979 	} while (unlikely(start != mapping->last + 1));
1980 
1981 	return 0;
1982 }
1983 
1984 /**
1985  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
1986  *
1987  * @adev: amdgpu_device pointer
1988  * @bo_va: requested BO and VM object
1989  * @clear: if true clear the entries
1990  *
1991  * Fill in the page table entries for @bo_va.
1992  *
1993  * Returns:
1994  * 0 for success, -EINVAL for failure.
1995  */
1996 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
1997 			struct amdgpu_bo_va *bo_va,
1998 			bool clear)
1999 {
2000 	struct amdgpu_bo *bo = bo_va->base.bo;
2001 	struct amdgpu_vm *vm = bo_va->base.vm;
2002 	struct amdgpu_bo_va_mapping *mapping;
2003 	dma_addr_t *pages_addr = NULL;
2004 	struct ttm_mem_reg *mem;
2005 	struct drm_mm_node *nodes;
2006 	struct dma_fence *exclusive, **last_update;
2007 	uint64_t flags;
2008 	int r;
2009 
2010 	if (clear || !bo) {
2011 		mem = NULL;
2012 		nodes = NULL;
2013 		exclusive = NULL;
2014 	} else {
2015 		struct ttm_dma_tt *ttm;
2016 
2017 		mem = &bo->tbo.mem;
2018 		nodes = mem->mm_node;
2019 		if (mem->mem_type == TTM_PL_TT) {
2020 			ttm = container_of(bo->tbo.ttm, struct ttm_dma_tt, ttm);
2021 			pages_addr = ttm->dma_address;
2022 		}
2023 		exclusive = reservation_object_get_excl(bo->tbo.resv);
2024 	}
2025 
2026 	if (bo)
2027 		flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, mem);
2028 	else
2029 		flags = 0x0;
2030 
2031 	if (clear || (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv))
2032 		last_update = &vm->last_update;
2033 	else
2034 		last_update = &bo_va->last_pt_update;
2035 
2036 	if (!clear && bo_va->base.moved) {
2037 		bo_va->base.moved = false;
2038 		list_splice_init(&bo_va->valids, &bo_va->invalids);
2039 
2040 	} else if (bo_va->cleared != clear) {
2041 		list_splice_init(&bo_va->valids, &bo_va->invalids);
2042 	}
2043 
2044 	list_for_each_entry(mapping, &bo_va->invalids, list) {
2045 		r = amdgpu_vm_bo_split_mapping(adev, exclusive, pages_addr, vm,
2046 					       mapping, flags, nodes,
2047 					       last_update);
2048 		if (r)
2049 			return r;
2050 	}
2051 
2052 	if (vm->use_cpu_for_update) {
2053 		/* Flush HDP */
2054 		mb();
2055 		amdgpu_asic_flush_hdp(adev, NULL);
2056 	}
2057 
2058 	/* If the BO is not in its preferred location add it back to
2059 	 * the evicted list so that it gets validated again on the
2060 	 * next command submission.
2061 	 */
2062 	if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
2063 		uint32_t mem_type = bo->tbo.mem.mem_type;
2064 
2065 		if (!(bo->preferred_domains & amdgpu_mem_type_to_domain(mem_type)))
2066 			amdgpu_vm_bo_evicted(&bo_va->base);
2067 		else
2068 			amdgpu_vm_bo_idle(&bo_va->base);
2069 	} else {
2070 		amdgpu_vm_bo_done(&bo_va->base);
2071 	}
2072 
2073 	list_splice_init(&bo_va->invalids, &bo_va->valids);
2074 	bo_va->cleared = clear;
2075 
2076 	if (trace_amdgpu_vm_bo_mapping_enabled()) {
2077 		list_for_each_entry(mapping, &bo_va->valids, list)
2078 			trace_amdgpu_vm_bo_mapping(mapping);
2079 	}
2080 
2081 	return 0;
2082 }
2083 
2084 /**
2085  * amdgpu_vm_update_prt_state - update the global PRT state
2086  *
2087  * @adev: amdgpu_device pointer
2088  */
2089 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
2090 {
2091 	unsigned long flags;
2092 	bool enable;
2093 
2094 	spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
2095 	enable = !!atomic_read(&adev->vm_manager.num_prt_users);
2096 	adev->gmc.gmc_funcs->set_prt(adev, enable);
2097 	spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
2098 }
2099 
2100 /**
2101  * amdgpu_vm_prt_get - add a PRT user
2102  *
2103  * @adev: amdgpu_device pointer
2104  */
2105 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
2106 {
2107 	if (!adev->gmc.gmc_funcs->set_prt)
2108 		return;
2109 
2110 	if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
2111 		amdgpu_vm_update_prt_state(adev);
2112 }
2113 
2114 /**
2115  * amdgpu_vm_prt_put - drop a PRT user
2116  *
2117  * @adev: amdgpu_device pointer
2118  */
2119 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
2120 {
2121 	if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
2122 		amdgpu_vm_update_prt_state(adev);
2123 }
2124 
2125 /**
2126  * amdgpu_vm_prt_cb - callback for updating the PRT status
2127  *
2128  * @fence: fence for the callback
2129  * @_cb: the callback function
2130  */
2131 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
2132 {
2133 	struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
2134 
2135 	amdgpu_vm_prt_put(cb->adev);
2136 	kfree(cb);
2137 }
2138 
2139 /**
2140  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
2141  *
2142  * @adev: amdgpu_device pointer
2143  * @fence: fence for the callback
2144  */
2145 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
2146 				 struct dma_fence *fence)
2147 {
2148 	struct amdgpu_prt_cb *cb;
2149 
2150 	if (!adev->gmc.gmc_funcs->set_prt)
2151 		return;
2152 
2153 	cb = kmalloc(sizeof(struct amdgpu_prt_cb), GFP_KERNEL);
2154 	if (!cb) {
2155 		/* Last resort when we are OOM */
2156 		if (fence)
2157 			dma_fence_wait(fence, false);
2158 
2159 		amdgpu_vm_prt_put(adev);
2160 	} else {
2161 		cb->adev = adev;
2162 		if (!fence || dma_fence_add_callback(fence, &cb->cb,
2163 						     amdgpu_vm_prt_cb))
2164 			amdgpu_vm_prt_cb(fence, &cb->cb);
2165 	}
2166 }
2167 
2168 /**
2169  * amdgpu_vm_free_mapping - free a mapping
2170  *
2171  * @adev: amdgpu_device pointer
2172  * @vm: requested vm
2173  * @mapping: mapping to be freed
2174  * @fence: fence of the unmap operation
2175  *
2176  * Free a mapping and make sure we decrease the PRT usage count if applicable.
2177  */
2178 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
2179 				   struct amdgpu_vm *vm,
2180 				   struct amdgpu_bo_va_mapping *mapping,
2181 				   struct dma_fence *fence)
2182 {
2183 	if (mapping->flags & AMDGPU_PTE_PRT)
2184 		amdgpu_vm_add_prt_cb(adev, fence);
2185 	kfree(mapping);
2186 }
2187 
2188 /**
2189  * amdgpu_vm_prt_fini - finish all prt mappings
2190  *
2191  * @adev: amdgpu_device pointer
2192  * @vm: requested vm
2193  *
2194  * Register a cleanup callback to disable PRT support after VM dies.
2195  */
2196 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2197 {
2198 	struct reservation_object *resv = vm->root.base.bo->tbo.resv;
2199 	struct dma_fence *excl, **shared;
2200 	unsigned i, shared_count;
2201 	int r;
2202 
2203 	r = reservation_object_get_fences_rcu(resv, &excl,
2204 					      &shared_count, &shared);
2205 	if (r) {
2206 		/* Not enough memory to grab the fence list, as last resort
2207 		 * block for all the fences to complete.
2208 		 */
2209 		reservation_object_wait_timeout_rcu(resv, true, false,
2210 						    MAX_SCHEDULE_TIMEOUT);
2211 		return;
2212 	}
2213 
2214 	/* Add a callback for each fence in the reservation object */
2215 	amdgpu_vm_prt_get(adev);
2216 	amdgpu_vm_add_prt_cb(adev, excl);
2217 
2218 	for (i = 0; i < shared_count; ++i) {
2219 		amdgpu_vm_prt_get(adev);
2220 		amdgpu_vm_add_prt_cb(adev, shared[i]);
2221 	}
2222 
2223 	kfree(shared);
2224 }
2225 
2226 /**
2227  * amdgpu_vm_clear_freed - clear freed BOs in the PT
2228  *
2229  * @adev: amdgpu_device pointer
2230  * @vm: requested vm
2231  * @fence: optional resulting fence (unchanged if no work needed to be done
2232  * or if an error occurred)
2233  *
2234  * Make sure all freed BOs are cleared in the PT.
2235  * PTs have to be reserved and mutex must be locked!
2236  *
2237  * Returns:
2238  * 0 for success.
2239  *
2240  */
2241 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
2242 			  struct amdgpu_vm *vm,
2243 			  struct dma_fence **fence)
2244 {
2245 	struct amdgpu_bo_va_mapping *mapping;
2246 	uint64_t init_pte_value = 0;
2247 	struct dma_fence *f = NULL;
2248 	int r;
2249 
2250 	while (!list_empty(&vm->freed)) {
2251 		mapping = list_first_entry(&vm->freed,
2252 			struct amdgpu_bo_va_mapping, list);
2253 		list_del(&mapping->list);
2254 
2255 		if (vm->pte_support_ats &&
2256 		    mapping->start < AMDGPU_GMC_HOLE_START)
2257 			init_pte_value = AMDGPU_PTE_DEFAULT_ATC;
2258 
2259 		r = amdgpu_vm_bo_update_mapping(adev, NULL, NULL, vm,
2260 						mapping->start, mapping->last,
2261 						init_pte_value, 0, &f);
2262 		amdgpu_vm_free_mapping(adev, vm, mapping, f);
2263 		if (r) {
2264 			dma_fence_put(f);
2265 			return r;
2266 		}
2267 	}
2268 
2269 	if (fence && f) {
2270 		dma_fence_put(*fence);
2271 		*fence = f;
2272 	} else {
2273 		dma_fence_put(f);
2274 	}
2275 
2276 	return 0;
2277 
2278 }
2279 
2280 /**
2281  * amdgpu_vm_handle_moved - handle moved BOs in the PT
2282  *
2283  * @adev: amdgpu_device pointer
2284  * @vm: requested vm
2285  *
2286  * Make sure all BOs which are moved are updated in the PTs.
2287  *
2288  * Returns:
2289  * 0 for success.
2290  *
2291  * PTs have to be reserved!
2292  */
2293 int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
2294 			   struct amdgpu_vm *vm)
2295 {
2296 	struct amdgpu_bo_va *bo_va, *tmp;
2297 	struct reservation_object *resv;
2298 	bool clear;
2299 	int r;
2300 
2301 	list_for_each_entry_safe(bo_va, tmp, &vm->moved, base.vm_status) {
2302 		/* Per VM BOs never need to bo cleared in the page tables */
2303 		r = amdgpu_vm_bo_update(adev, bo_va, false);
2304 		if (r)
2305 			return r;
2306 	}
2307 
2308 	spin_lock(&vm->invalidated_lock);
2309 	while (!list_empty(&vm->invalidated)) {
2310 		bo_va = list_first_entry(&vm->invalidated, struct amdgpu_bo_va,
2311 					 base.vm_status);
2312 		resv = bo_va->base.bo->tbo.resv;
2313 		spin_unlock(&vm->invalidated_lock);
2314 
2315 		/* Try to reserve the BO to avoid clearing its ptes */
2316 		if (!amdgpu_vm_debug && reservation_object_trylock(resv))
2317 			clear = false;
2318 		/* Somebody else is using the BO right now */
2319 		else
2320 			clear = true;
2321 
2322 		r = amdgpu_vm_bo_update(adev, bo_va, clear);
2323 		if (r)
2324 			return r;
2325 
2326 		if (!clear)
2327 			reservation_object_unlock(resv);
2328 		spin_lock(&vm->invalidated_lock);
2329 	}
2330 	spin_unlock(&vm->invalidated_lock);
2331 
2332 	return 0;
2333 }
2334 
2335 /**
2336  * amdgpu_vm_bo_add - add a bo to a specific vm
2337  *
2338  * @adev: amdgpu_device pointer
2339  * @vm: requested vm
2340  * @bo: amdgpu buffer object
2341  *
2342  * Add @bo into the requested vm.
2343  * Add @bo to the list of bos associated with the vm
2344  *
2345  * Returns:
2346  * Newly added bo_va or NULL for failure
2347  *
2348  * Object has to be reserved!
2349  */
2350 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
2351 				      struct amdgpu_vm *vm,
2352 				      struct amdgpu_bo *bo)
2353 {
2354 	struct amdgpu_bo_va *bo_va;
2355 
2356 	bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
2357 	if (bo_va == NULL) {
2358 		return NULL;
2359 	}
2360 	amdgpu_vm_bo_base_init(&bo_va->base, vm, bo);
2361 
2362 	bo_va->ref_count = 1;
2363 	INIT_LIST_HEAD(&bo_va->valids);
2364 	INIT_LIST_HEAD(&bo_va->invalids);
2365 
2366 	return bo_va;
2367 }
2368 
2369 
2370 /**
2371  * amdgpu_vm_bo_insert_mapping - insert a new mapping
2372  *
2373  * @adev: amdgpu_device pointer
2374  * @bo_va: bo_va to store the address
2375  * @mapping: the mapping to insert
2376  *
2377  * Insert a new mapping into all structures.
2378  */
2379 static void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev,
2380 				    struct amdgpu_bo_va *bo_va,
2381 				    struct amdgpu_bo_va_mapping *mapping)
2382 {
2383 	struct amdgpu_vm *vm = bo_va->base.vm;
2384 	struct amdgpu_bo *bo = bo_va->base.bo;
2385 
2386 	mapping->bo_va = bo_va;
2387 	list_add(&mapping->list, &bo_va->invalids);
2388 	amdgpu_vm_it_insert(mapping, &vm->va);
2389 
2390 	if (mapping->flags & AMDGPU_PTE_PRT)
2391 		amdgpu_vm_prt_get(adev);
2392 
2393 	if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv &&
2394 	    !bo_va->base.moved) {
2395 		list_move(&bo_va->base.vm_status, &vm->moved);
2396 	}
2397 	trace_amdgpu_vm_bo_map(bo_va, mapping);
2398 }
2399 
2400 /**
2401  * amdgpu_vm_bo_map - map bo inside a vm
2402  *
2403  * @adev: amdgpu_device pointer
2404  * @bo_va: bo_va to store the address
2405  * @saddr: where to map the BO
2406  * @offset: requested offset in the BO
2407  * @size: BO size in bytes
2408  * @flags: attributes of pages (read/write/valid/etc.)
2409  *
2410  * Add a mapping of the BO at the specefied addr into the VM.
2411  *
2412  * Returns:
2413  * 0 for success, error for failure.
2414  *
2415  * Object has to be reserved and unreserved outside!
2416  */
2417 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
2418 		     struct amdgpu_bo_va *bo_va,
2419 		     uint64_t saddr, uint64_t offset,
2420 		     uint64_t size, uint64_t flags)
2421 {
2422 	struct amdgpu_bo_va_mapping *mapping, *tmp;
2423 	struct amdgpu_bo *bo = bo_va->base.bo;
2424 	struct amdgpu_vm *vm = bo_va->base.vm;
2425 	uint64_t eaddr;
2426 
2427 	/* validate the parameters */
2428 	if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
2429 	    size == 0 || size & AMDGPU_GPU_PAGE_MASK)
2430 		return -EINVAL;
2431 
2432 	/* make sure object fit at this offset */
2433 	eaddr = saddr + size - 1;
2434 	if (saddr >= eaddr ||
2435 	    (bo && offset + size > amdgpu_bo_size(bo)))
2436 		return -EINVAL;
2437 
2438 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2439 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
2440 
2441 	tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2442 	if (tmp) {
2443 		/* bo and tmp overlap, invalid addr */
2444 		dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
2445 			"0x%010Lx-0x%010Lx\n", bo, saddr, eaddr,
2446 			tmp->start, tmp->last + 1);
2447 		return -EINVAL;
2448 	}
2449 
2450 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2451 	if (!mapping)
2452 		return -ENOMEM;
2453 
2454 	mapping->start = saddr;
2455 	mapping->last = eaddr;
2456 	mapping->offset = offset;
2457 	mapping->flags = flags;
2458 
2459 	amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
2460 
2461 	return 0;
2462 }
2463 
2464 /**
2465  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
2466  *
2467  * @adev: amdgpu_device pointer
2468  * @bo_va: bo_va to store the address
2469  * @saddr: where to map the BO
2470  * @offset: requested offset in the BO
2471  * @size: BO size in bytes
2472  * @flags: attributes of pages (read/write/valid/etc.)
2473  *
2474  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
2475  * mappings as we do so.
2476  *
2477  * Returns:
2478  * 0 for success, error for failure.
2479  *
2480  * Object has to be reserved and unreserved outside!
2481  */
2482 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
2483 			     struct amdgpu_bo_va *bo_va,
2484 			     uint64_t saddr, uint64_t offset,
2485 			     uint64_t size, uint64_t flags)
2486 {
2487 	struct amdgpu_bo_va_mapping *mapping;
2488 	struct amdgpu_bo *bo = bo_va->base.bo;
2489 	uint64_t eaddr;
2490 	int r;
2491 
2492 	/* validate the parameters */
2493 	if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
2494 	    size == 0 || size & AMDGPU_GPU_PAGE_MASK)
2495 		return -EINVAL;
2496 
2497 	/* make sure object fit at this offset */
2498 	eaddr = saddr + size - 1;
2499 	if (saddr >= eaddr ||
2500 	    (bo && offset + size > amdgpu_bo_size(bo)))
2501 		return -EINVAL;
2502 
2503 	/* Allocate all the needed memory */
2504 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2505 	if (!mapping)
2506 		return -ENOMEM;
2507 
2508 	r = amdgpu_vm_bo_clear_mappings(adev, bo_va->base.vm, saddr, size);
2509 	if (r) {
2510 		kfree(mapping);
2511 		return r;
2512 	}
2513 
2514 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2515 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
2516 
2517 	mapping->start = saddr;
2518 	mapping->last = eaddr;
2519 	mapping->offset = offset;
2520 	mapping->flags = flags;
2521 
2522 	amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
2523 
2524 	return 0;
2525 }
2526 
2527 /**
2528  * amdgpu_vm_bo_unmap - remove bo mapping from vm
2529  *
2530  * @adev: amdgpu_device pointer
2531  * @bo_va: bo_va to remove the address from
2532  * @saddr: where to the BO is mapped
2533  *
2534  * Remove a mapping of the BO at the specefied addr from the VM.
2535  *
2536  * Returns:
2537  * 0 for success, error for failure.
2538  *
2539  * Object has to be reserved and unreserved outside!
2540  */
2541 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
2542 		       struct amdgpu_bo_va *bo_va,
2543 		       uint64_t saddr)
2544 {
2545 	struct amdgpu_bo_va_mapping *mapping;
2546 	struct amdgpu_vm *vm = bo_va->base.vm;
2547 	bool valid = true;
2548 
2549 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2550 
2551 	list_for_each_entry(mapping, &bo_va->valids, list) {
2552 		if (mapping->start == saddr)
2553 			break;
2554 	}
2555 
2556 	if (&mapping->list == &bo_va->valids) {
2557 		valid = false;
2558 
2559 		list_for_each_entry(mapping, &bo_va->invalids, list) {
2560 			if (mapping->start == saddr)
2561 				break;
2562 		}
2563 
2564 		if (&mapping->list == &bo_va->invalids)
2565 			return -ENOENT;
2566 	}
2567 
2568 	list_del(&mapping->list);
2569 	amdgpu_vm_it_remove(mapping, &vm->va);
2570 	mapping->bo_va = NULL;
2571 	trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2572 
2573 	if (valid)
2574 		list_add(&mapping->list, &vm->freed);
2575 	else
2576 		amdgpu_vm_free_mapping(adev, vm, mapping,
2577 				       bo_va->last_pt_update);
2578 
2579 	return 0;
2580 }
2581 
2582 /**
2583  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
2584  *
2585  * @adev: amdgpu_device pointer
2586  * @vm: VM structure to use
2587  * @saddr: start of the range
2588  * @size: size of the range
2589  *
2590  * Remove all mappings in a range, split them as appropriate.
2591  *
2592  * Returns:
2593  * 0 for success, error for failure.
2594  */
2595 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
2596 				struct amdgpu_vm *vm,
2597 				uint64_t saddr, uint64_t size)
2598 {
2599 	struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
2600 	LIST_HEAD(removed);
2601 	uint64_t eaddr;
2602 
2603 	eaddr = saddr + size - 1;
2604 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2605 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
2606 
2607 	/* Allocate all the needed memory */
2608 	before = kzalloc(sizeof(*before), GFP_KERNEL);
2609 	if (!before)
2610 		return -ENOMEM;
2611 	INIT_LIST_HEAD(&before->list);
2612 
2613 	after = kzalloc(sizeof(*after), GFP_KERNEL);
2614 	if (!after) {
2615 		kfree(before);
2616 		return -ENOMEM;
2617 	}
2618 	INIT_LIST_HEAD(&after->list);
2619 
2620 	/* Now gather all removed mappings */
2621 	tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2622 	while (tmp) {
2623 		/* Remember mapping split at the start */
2624 		if (tmp->start < saddr) {
2625 			before->start = tmp->start;
2626 			before->last = saddr - 1;
2627 			before->offset = tmp->offset;
2628 			before->flags = tmp->flags;
2629 			before->bo_va = tmp->bo_va;
2630 			list_add(&before->list, &tmp->bo_va->invalids);
2631 		}
2632 
2633 		/* Remember mapping split at the end */
2634 		if (tmp->last > eaddr) {
2635 			after->start = eaddr + 1;
2636 			after->last = tmp->last;
2637 			after->offset = tmp->offset;
2638 			after->offset += after->start - tmp->start;
2639 			after->flags = tmp->flags;
2640 			after->bo_va = tmp->bo_va;
2641 			list_add(&after->list, &tmp->bo_va->invalids);
2642 		}
2643 
2644 		list_del(&tmp->list);
2645 		list_add(&tmp->list, &removed);
2646 
2647 		tmp = amdgpu_vm_it_iter_next(tmp, saddr, eaddr);
2648 	}
2649 
2650 	/* And free them up */
2651 	list_for_each_entry_safe(tmp, next, &removed, list) {
2652 		amdgpu_vm_it_remove(tmp, &vm->va);
2653 		list_del(&tmp->list);
2654 
2655 		if (tmp->start < saddr)
2656 		    tmp->start = saddr;
2657 		if (tmp->last > eaddr)
2658 		    tmp->last = eaddr;
2659 
2660 		tmp->bo_va = NULL;
2661 		list_add(&tmp->list, &vm->freed);
2662 		trace_amdgpu_vm_bo_unmap(NULL, tmp);
2663 	}
2664 
2665 	/* Insert partial mapping before the range */
2666 	if (!list_empty(&before->list)) {
2667 		amdgpu_vm_it_insert(before, &vm->va);
2668 		if (before->flags & AMDGPU_PTE_PRT)
2669 			amdgpu_vm_prt_get(adev);
2670 	} else {
2671 		kfree(before);
2672 	}
2673 
2674 	/* Insert partial mapping after the range */
2675 	if (!list_empty(&after->list)) {
2676 		amdgpu_vm_it_insert(after, &vm->va);
2677 		if (after->flags & AMDGPU_PTE_PRT)
2678 			amdgpu_vm_prt_get(adev);
2679 	} else {
2680 		kfree(after);
2681 	}
2682 
2683 	return 0;
2684 }
2685 
2686 /**
2687  * amdgpu_vm_bo_lookup_mapping - find mapping by address
2688  *
2689  * @vm: the requested VM
2690  * @addr: the address
2691  *
2692  * Find a mapping by it's address.
2693  *
2694  * Returns:
2695  * The amdgpu_bo_va_mapping matching for addr or NULL
2696  *
2697  */
2698 struct amdgpu_bo_va_mapping *amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm,
2699 							 uint64_t addr)
2700 {
2701 	return amdgpu_vm_it_iter_first(&vm->va, addr, addr);
2702 }
2703 
2704 /**
2705  * amdgpu_vm_bo_trace_cs - trace all reserved mappings
2706  *
2707  * @vm: the requested vm
2708  * @ticket: CS ticket
2709  *
2710  * Trace all mappings of BOs reserved during a command submission.
2711  */
2712 void amdgpu_vm_bo_trace_cs(struct amdgpu_vm *vm, struct ww_acquire_ctx *ticket)
2713 {
2714 	struct amdgpu_bo_va_mapping *mapping;
2715 
2716 	if (!trace_amdgpu_vm_bo_cs_enabled())
2717 		return;
2718 
2719 	for (mapping = amdgpu_vm_it_iter_first(&vm->va, 0, U64_MAX); mapping;
2720 	     mapping = amdgpu_vm_it_iter_next(mapping, 0, U64_MAX)) {
2721 		if (mapping->bo_va && mapping->bo_va->base.bo) {
2722 			struct amdgpu_bo *bo;
2723 
2724 			bo = mapping->bo_va->base.bo;
2725 			if (READ_ONCE(bo->tbo.resv->lock.ctx) != ticket)
2726 				continue;
2727 		}
2728 
2729 		trace_amdgpu_vm_bo_cs(mapping);
2730 	}
2731 }
2732 
2733 /**
2734  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
2735  *
2736  * @adev: amdgpu_device pointer
2737  * @bo_va: requested bo_va
2738  *
2739  * Remove @bo_va->bo from the requested vm.
2740  *
2741  * Object have to be reserved!
2742  */
2743 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
2744 		      struct amdgpu_bo_va *bo_va)
2745 {
2746 	struct amdgpu_bo_va_mapping *mapping, *next;
2747 	struct amdgpu_bo *bo = bo_va->base.bo;
2748 	struct amdgpu_vm *vm = bo_va->base.vm;
2749 	struct amdgpu_vm_bo_base **base;
2750 
2751 	if (bo) {
2752 		if (bo->tbo.resv == vm->root.base.bo->tbo.resv)
2753 			vm->bulk_moveable = false;
2754 
2755 		for (base = &bo_va->base.bo->vm_bo; *base;
2756 		     base = &(*base)->next) {
2757 			if (*base != &bo_va->base)
2758 				continue;
2759 
2760 			*base = bo_va->base.next;
2761 			break;
2762 		}
2763 	}
2764 
2765 	spin_lock(&vm->invalidated_lock);
2766 	list_del(&bo_va->base.vm_status);
2767 	spin_unlock(&vm->invalidated_lock);
2768 
2769 	list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
2770 		list_del(&mapping->list);
2771 		amdgpu_vm_it_remove(mapping, &vm->va);
2772 		mapping->bo_va = NULL;
2773 		trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2774 		list_add(&mapping->list, &vm->freed);
2775 	}
2776 	list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
2777 		list_del(&mapping->list);
2778 		amdgpu_vm_it_remove(mapping, &vm->va);
2779 		amdgpu_vm_free_mapping(adev, vm, mapping,
2780 				       bo_va->last_pt_update);
2781 	}
2782 
2783 	dma_fence_put(bo_va->last_pt_update);
2784 	kfree(bo_va);
2785 }
2786 
2787 /**
2788  * amdgpu_vm_bo_invalidate - mark the bo as invalid
2789  *
2790  * @adev: amdgpu_device pointer
2791  * @bo: amdgpu buffer object
2792  * @evicted: is the BO evicted
2793  *
2794  * Mark @bo as invalid.
2795  */
2796 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
2797 			     struct amdgpu_bo *bo, bool evicted)
2798 {
2799 	struct amdgpu_vm_bo_base *bo_base;
2800 
2801 	/* shadow bo doesn't have bo base, its validation needs its parent */
2802 	if (bo->parent && bo->parent->shadow == bo)
2803 		bo = bo->parent;
2804 
2805 	for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
2806 		struct amdgpu_vm *vm = bo_base->vm;
2807 
2808 		if (evicted && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
2809 			amdgpu_vm_bo_evicted(bo_base);
2810 			continue;
2811 		}
2812 
2813 		if (bo_base->moved)
2814 			continue;
2815 		bo_base->moved = true;
2816 
2817 		if (bo->tbo.type == ttm_bo_type_kernel)
2818 			amdgpu_vm_bo_relocated(bo_base);
2819 		else if (bo->tbo.resv == vm->root.base.bo->tbo.resv)
2820 			amdgpu_vm_bo_moved(bo_base);
2821 		else
2822 			amdgpu_vm_bo_invalidated(bo_base);
2823 	}
2824 }
2825 
2826 /**
2827  * amdgpu_vm_get_block_size - calculate VM page table size as power of two
2828  *
2829  * @vm_size: VM size
2830  *
2831  * Returns:
2832  * VM page table as power of two
2833  */
2834 static uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
2835 {
2836 	/* Total bits covered by PD + PTs */
2837 	unsigned bits = ilog2(vm_size) + 18;
2838 
2839 	/* Make sure the PD is 4K in size up to 8GB address space.
2840 	   Above that split equal between PD and PTs */
2841 	if (vm_size <= 8)
2842 		return (bits - 9);
2843 	else
2844 		return ((bits + 3) / 2);
2845 }
2846 
2847 /**
2848  * amdgpu_vm_adjust_size - adjust vm size, block size and fragment size
2849  *
2850  * @adev: amdgpu_device pointer
2851  * @min_vm_size: the minimum vm size in GB if it's set auto
2852  * @fragment_size_default: Default PTE fragment size
2853  * @max_level: max VMPT level
2854  * @max_bits: max address space size in bits
2855  *
2856  */
2857 void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint32_t min_vm_size,
2858 			   uint32_t fragment_size_default, unsigned max_level,
2859 			   unsigned max_bits)
2860 {
2861 	unsigned int max_size = 1 << (max_bits - 30);
2862 	unsigned int vm_size;
2863 	uint64_t tmp;
2864 
2865 	/* adjust vm size first */
2866 	if (amdgpu_vm_size != -1) {
2867 		vm_size = amdgpu_vm_size;
2868 		if (vm_size > max_size) {
2869 			dev_warn(adev->dev, "VM size (%d) too large, max is %u GB\n",
2870 				 amdgpu_vm_size, max_size);
2871 			vm_size = max_size;
2872 		}
2873 	} else {
2874 		struct sysinfo si;
2875 		unsigned int phys_ram_gb;
2876 
2877 		/* Optimal VM size depends on the amount of physical
2878 		 * RAM available. Underlying requirements and
2879 		 * assumptions:
2880 		 *
2881 		 *  - Need to map system memory and VRAM from all GPUs
2882 		 *     - VRAM from other GPUs not known here
2883 		 *     - Assume VRAM <= system memory
2884 		 *  - On GFX8 and older, VM space can be segmented for
2885 		 *    different MTYPEs
2886 		 *  - Need to allow room for fragmentation, guard pages etc.
2887 		 *
2888 		 * This adds up to a rough guess of system memory x3.
2889 		 * Round up to power of two to maximize the available
2890 		 * VM size with the given page table size.
2891 		 */
2892 		si_meminfo(&si);
2893 		phys_ram_gb = ((uint64_t)si.totalram * si.mem_unit +
2894 			       (1 << 30) - 1) >> 30;
2895 		vm_size = roundup_pow_of_two(
2896 			min(max(phys_ram_gb * 3, min_vm_size), max_size));
2897 	}
2898 
2899 	adev->vm_manager.max_pfn = (uint64_t)vm_size << 18;
2900 
2901 	tmp = roundup_pow_of_two(adev->vm_manager.max_pfn);
2902 	if (amdgpu_vm_block_size != -1)
2903 		tmp >>= amdgpu_vm_block_size - 9;
2904 	tmp = DIV_ROUND_UP(fls64(tmp) - 1, 9) - 1;
2905 	adev->vm_manager.num_level = min(max_level, (unsigned)tmp);
2906 	switch (adev->vm_manager.num_level) {
2907 	case 3:
2908 		adev->vm_manager.root_level = AMDGPU_VM_PDB2;
2909 		break;
2910 	case 2:
2911 		adev->vm_manager.root_level = AMDGPU_VM_PDB1;
2912 		break;
2913 	case 1:
2914 		adev->vm_manager.root_level = AMDGPU_VM_PDB0;
2915 		break;
2916 	default:
2917 		dev_err(adev->dev, "VMPT only supports 2~4+1 levels\n");
2918 	}
2919 	/* block size depends on vm size and hw setup*/
2920 	if (amdgpu_vm_block_size != -1)
2921 		adev->vm_manager.block_size =
2922 			min((unsigned)amdgpu_vm_block_size, max_bits
2923 			    - AMDGPU_GPU_PAGE_SHIFT
2924 			    - 9 * adev->vm_manager.num_level);
2925 	else if (adev->vm_manager.num_level > 1)
2926 		adev->vm_manager.block_size = 9;
2927 	else
2928 		adev->vm_manager.block_size = amdgpu_vm_get_block_size(tmp);
2929 
2930 	if (amdgpu_vm_fragment_size == -1)
2931 		adev->vm_manager.fragment_size = fragment_size_default;
2932 	else
2933 		adev->vm_manager.fragment_size = amdgpu_vm_fragment_size;
2934 
2935 	DRM_INFO("vm size is %u GB, %u levels, block size is %u-bit, fragment size is %u-bit\n",
2936 		 vm_size, adev->vm_manager.num_level + 1,
2937 		 adev->vm_manager.block_size,
2938 		 adev->vm_manager.fragment_size);
2939 }
2940 
2941 static struct amdgpu_retryfault_hashtable *init_fault_hash(void)
2942 {
2943 	struct amdgpu_retryfault_hashtable *fault_hash;
2944 
2945 	fault_hash = kmalloc(sizeof(*fault_hash), GFP_KERNEL);
2946 	if (!fault_hash)
2947 		return fault_hash;
2948 
2949 	INIT_CHASH_TABLE(fault_hash->hash,
2950 			AMDGPU_PAGEFAULT_HASH_BITS, 8, 0);
2951 	spin_lock_init(&fault_hash->lock);
2952 	fault_hash->count = 0;
2953 
2954 	return fault_hash;
2955 }
2956 
2957 /**
2958  * amdgpu_vm_init - initialize a vm instance
2959  *
2960  * @adev: amdgpu_device pointer
2961  * @vm: requested vm
2962  * @vm_context: Indicates if it GFX or Compute context
2963  * @pasid: Process address space identifier
2964  *
2965  * Init @vm fields.
2966  *
2967  * Returns:
2968  * 0 for success, error for failure.
2969  */
2970 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm,
2971 		   int vm_context, unsigned int pasid)
2972 {
2973 	struct amdgpu_bo_param bp;
2974 	struct amdgpu_bo *root;
2975 	int r, i;
2976 
2977 	vm->va = RB_ROOT_CACHED;
2978 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2979 		vm->reserved_vmid[i] = NULL;
2980 	INIT_LIST_HEAD(&vm->evicted);
2981 	INIT_LIST_HEAD(&vm->relocated);
2982 	INIT_LIST_HEAD(&vm->moved);
2983 	INIT_LIST_HEAD(&vm->idle);
2984 	INIT_LIST_HEAD(&vm->invalidated);
2985 	spin_lock_init(&vm->invalidated_lock);
2986 	INIT_LIST_HEAD(&vm->freed);
2987 
2988 	/* create scheduler entity for page table updates */
2989 	r = drm_sched_entity_init(&vm->entity, adev->vm_manager.vm_pte_rqs,
2990 				  adev->vm_manager.vm_pte_num_rqs, NULL);
2991 	if (r)
2992 		return r;
2993 
2994 	vm->pte_support_ats = false;
2995 
2996 	if (vm_context == AMDGPU_VM_CONTEXT_COMPUTE) {
2997 		vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2998 						AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2999 
3000 		if (adev->asic_type == CHIP_RAVEN)
3001 			vm->pte_support_ats = true;
3002 	} else {
3003 		vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
3004 						AMDGPU_VM_USE_CPU_FOR_GFX);
3005 	}
3006 	DRM_DEBUG_DRIVER("VM update mode is %s\n",
3007 			 vm->use_cpu_for_update ? "CPU" : "SDMA");
3008 	WARN_ONCE((vm->use_cpu_for_update & !amdgpu_gmc_vram_full_visible(&adev->gmc)),
3009 		  "CPU update of VM recommended only for large BAR system\n");
3010 	vm->last_update = NULL;
3011 
3012 	amdgpu_vm_bo_param(adev, vm, adev->vm_manager.root_level, &bp);
3013 	if (vm_context == AMDGPU_VM_CONTEXT_COMPUTE)
3014 		bp.flags &= ~AMDGPU_GEM_CREATE_SHADOW;
3015 	r = amdgpu_bo_create(adev, &bp, &root);
3016 	if (r)
3017 		goto error_free_sched_entity;
3018 
3019 	r = amdgpu_bo_reserve(root, true);
3020 	if (r)
3021 		goto error_free_root;
3022 
3023 	r = reservation_object_reserve_shared(root->tbo.resv, 1);
3024 	if (r)
3025 		goto error_unreserve;
3026 
3027 	r = amdgpu_vm_clear_bo(adev, vm, root,
3028 			       adev->vm_manager.root_level,
3029 			       vm->pte_support_ats);
3030 	if (r)
3031 		goto error_unreserve;
3032 
3033 	amdgpu_vm_bo_base_init(&vm->root.base, vm, root);
3034 	amdgpu_bo_unreserve(vm->root.base.bo);
3035 
3036 	if (pasid) {
3037 		unsigned long flags;
3038 
3039 		spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
3040 		r = idr_alloc(&adev->vm_manager.pasid_idr, vm, pasid, pasid + 1,
3041 			      GFP_ATOMIC);
3042 		spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
3043 		if (r < 0)
3044 			goto error_free_root;
3045 
3046 		vm->pasid = pasid;
3047 	}
3048 
3049 	vm->fault_hash = init_fault_hash();
3050 	if (!vm->fault_hash) {
3051 		r = -ENOMEM;
3052 		goto error_free_root;
3053 	}
3054 
3055 	INIT_KFIFO(vm->faults);
3056 
3057 	return 0;
3058 
3059 error_unreserve:
3060 	amdgpu_bo_unreserve(vm->root.base.bo);
3061 
3062 error_free_root:
3063 	amdgpu_bo_unref(&vm->root.base.bo->shadow);
3064 	amdgpu_bo_unref(&vm->root.base.bo);
3065 	vm->root.base.bo = NULL;
3066 
3067 error_free_sched_entity:
3068 	drm_sched_entity_destroy(&vm->entity);
3069 
3070 	return r;
3071 }
3072 
3073 /**
3074  * amdgpu_vm_make_compute - Turn a GFX VM into a compute VM
3075  *
3076  * @adev: amdgpu_device pointer
3077  * @vm: requested vm
3078  *
3079  * This only works on GFX VMs that don't have any BOs added and no
3080  * page tables allocated yet.
3081  *
3082  * Changes the following VM parameters:
3083  * - use_cpu_for_update
3084  * - pte_supports_ats
3085  * - pasid (old PASID is released, because compute manages its own PASIDs)
3086  *
3087  * Reinitializes the page directory to reflect the changed ATS
3088  * setting.
3089  *
3090  * Returns:
3091  * 0 for success, -errno for errors.
3092  */
3093 int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm, unsigned int pasid)
3094 {
3095 	bool pte_support_ats = (adev->asic_type == CHIP_RAVEN);
3096 	int r;
3097 
3098 	r = amdgpu_bo_reserve(vm->root.base.bo, true);
3099 	if (r)
3100 		return r;
3101 
3102 	/* Sanity checks */
3103 	if (!RB_EMPTY_ROOT(&vm->va.rb_root) || vm->root.entries) {
3104 		r = -EINVAL;
3105 		goto unreserve_bo;
3106 	}
3107 
3108 	if (pasid) {
3109 		unsigned long flags;
3110 
3111 		spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
3112 		r = idr_alloc(&adev->vm_manager.pasid_idr, vm, pasid, pasid + 1,
3113 			      GFP_ATOMIC);
3114 		spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
3115 
3116 		if (r == -ENOSPC)
3117 			goto unreserve_bo;
3118 		r = 0;
3119 	}
3120 
3121 	/* Check if PD needs to be reinitialized and do it before
3122 	 * changing any other state, in case it fails.
3123 	 */
3124 	if (pte_support_ats != vm->pte_support_ats) {
3125 		r = amdgpu_vm_clear_bo(adev, vm, vm->root.base.bo,
3126 			       adev->vm_manager.root_level,
3127 			       pte_support_ats);
3128 		if (r)
3129 			goto free_idr;
3130 	}
3131 
3132 	/* Update VM state */
3133 	vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
3134 				    AMDGPU_VM_USE_CPU_FOR_COMPUTE);
3135 	vm->pte_support_ats = pte_support_ats;
3136 	DRM_DEBUG_DRIVER("VM update mode is %s\n",
3137 			 vm->use_cpu_for_update ? "CPU" : "SDMA");
3138 	WARN_ONCE((vm->use_cpu_for_update & !amdgpu_gmc_vram_full_visible(&adev->gmc)),
3139 		  "CPU update of VM recommended only for large BAR system\n");
3140 
3141 	if (vm->pasid) {
3142 		unsigned long flags;
3143 
3144 		spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
3145 		idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
3146 		spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
3147 
3148 		/* Free the original amdgpu allocated pasid
3149 		 * Will be replaced with kfd allocated pasid
3150 		 */
3151 		amdgpu_pasid_free(vm->pasid);
3152 		vm->pasid = 0;
3153 	}
3154 
3155 	/* Free the shadow bo for compute VM */
3156 	amdgpu_bo_unref(&vm->root.base.bo->shadow);
3157 
3158 	if (pasid)
3159 		vm->pasid = pasid;
3160 
3161 	goto unreserve_bo;
3162 
3163 free_idr:
3164 	if (pasid) {
3165 		unsigned long flags;
3166 
3167 		spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
3168 		idr_remove(&adev->vm_manager.pasid_idr, pasid);
3169 		spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
3170 	}
3171 unreserve_bo:
3172 	amdgpu_bo_unreserve(vm->root.base.bo);
3173 	return r;
3174 }
3175 
3176 /**
3177  * amdgpu_vm_release_compute - release a compute vm
3178  * @adev: amdgpu_device pointer
3179  * @vm: a vm turned into compute vm by calling amdgpu_vm_make_compute
3180  *
3181  * This is a correspondant of amdgpu_vm_make_compute. It decouples compute
3182  * pasid from vm. Compute should stop use of vm after this call.
3183  */
3184 void amdgpu_vm_release_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
3185 {
3186 	if (vm->pasid) {
3187 		unsigned long flags;
3188 
3189 		spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
3190 		idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
3191 		spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
3192 	}
3193 	vm->pasid = 0;
3194 }
3195 
3196 /**
3197  * amdgpu_vm_fini - tear down a vm instance
3198  *
3199  * @adev: amdgpu_device pointer
3200  * @vm: requested vm
3201  *
3202  * Tear down @vm.
3203  * Unbind the VM and remove all bos from the vm bo list
3204  */
3205 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
3206 {
3207 	struct amdgpu_bo_va_mapping *mapping, *tmp;
3208 	bool prt_fini_needed = !!adev->gmc.gmc_funcs->set_prt;
3209 	struct amdgpu_bo *root;
3210 	u64 fault;
3211 	int i, r;
3212 
3213 	amdgpu_amdkfd_gpuvm_destroy_cb(adev, vm);
3214 
3215 	/* Clear pending page faults from IH when the VM is destroyed */
3216 	while (kfifo_get(&vm->faults, &fault))
3217 		amdgpu_vm_clear_fault(vm->fault_hash, fault);
3218 
3219 	if (vm->pasid) {
3220 		unsigned long flags;
3221 
3222 		spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
3223 		idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
3224 		spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
3225 	}
3226 
3227 	kfree(vm->fault_hash);
3228 	vm->fault_hash = NULL;
3229 
3230 	drm_sched_entity_destroy(&vm->entity);
3231 
3232 	if (!RB_EMPTY_ROOT(&vm->va.rb_root)) {
3233 		dev_err(adev->dev, "still active bo inside vm\n");
3234 	}
3235 	rbtree_postorder_for_each_entry_safe(mapping, tmp,
3236 					     &vm->va.rb_root, rb) {
3237 		/* Don't remove the mapping here, we don't want to trigger a
3238 		 * rebalance and the tree is about to be destroyed anyway.
3239 		 */
3240 		list_del(&mapping->list);
3241 		kfree(mapping);
3242 	}
3243 	list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
3244 		if (mapping->flags & AMDGPU_PTE_PRT && prt_fini_needed) {
3245 			amdgpu_vm_prt_fini(adev, vm);
3246 			prt_fini_needed = false;
3247 		}
3248 
3249 		list_del(&mapping->list);
3250 		amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
3251 	}
3252 
3253 	root = amdgpu_bo_ref(vm->root.base.bo);
3254 	r = amdgpu_bo_reserve(root, true);
3255 	if (r) {
3256 		dev_err(adev->dev, "Leaking page tables because BO reservation failed\n");
3257 	} else {
3258 		amdgpu_vm_free_pts(adev, vm);
3259 		amdgpu_bo_unreserve(root);
3260 	}
3261 	amdgpu_bo_unref(&root);
3262 	dma_fence_put(vm->last_update);
3263 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
3264 		amdgpu_vmid_free_reserved(adev, vm, i);
3265 }
3266 
3267 /**
3268  * amdgpu_vm_manager_init - init the VM manager
3269  *
3270  * @adev: amdgpu_device pointer
3271  *
3272  * Initialize the VM manager structures
3273  */
3274 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
3275 {
3276 	unsigned i;
3277 
3278 	amdgpu_vmid_mgr_init(adev);
3279 
3280 	adev->vm_manager.fence_context =
3281 		dma_fence_context_alloc(AMDGPU_MAX_RINGS);
3282 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
3283 		adev->vm_manager.seqno[i] = 0;
3284 
3285 	spin_lock_init(&adev->vm_manager.prt_lock);
3286 	atomic_set(&adev->vm_manager.num_prt_users, 0);
3287 
3288 	/* If not overridden by the user, by default, only in large BAR systems
3289 	 * Compute VM tables will be updated by CPU
3290 	 */
3291 #ifdef CONFIG_X86_64
3292 	if (amdgpu_vm_update_mode == -1) {
3293 		if (amdgpu_gmc_vram_full_visible(&adev->gmc))
3294 			adev->vm_manager.vm_update_mode =
3295 				AMDGPU_VM_USE_CPU_FOR_COMPUTE;
3296 		else
3297 			adev->vm_manager.vm_update_mode = 0;
3298 	} else
3299 		adev->vm_manager.vm_update_mode = amdgpu_vm_update_mode;
3300 #else
3301 	adev->vm_manager.vm_update_mode = 0;
3302 #endif
3303 
3304 	idr_init(&adev->vm_manager.pasid_idr);
3305 	spin_lock_init(&adev->vm_manager.pasid_lock);
3306 }
3307 
3308 /**
3309  * amdgpu_vm_manager_fini - cleanup VM manager
3310  *
3311  * @adev: amdgpu_device pointer
3312  *
3313  * Cleanup the VM manager and free resources.
3314  */
3315 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
3316 {
3317 	WARN_ON(!idr_is_empty(&adev->vm_manager.pasid_idr));
3318 	idr_destroy(&adev->vm_manager.pasid_idr);
3319 
3320 	amdgpu_vmid_mgr_fini(adev);
3321 }
3322 
3323 /**
3324  * amdgpu_vm_ioctl - Manages VMID reservation for vm hubs.
3325  *
3326  * @dev: drm device pointer
3327  * @data: drm_amdgpu_vm
3328  * @filp: drm file pointer
3329  *
3330  * Returns:
3331  * 0 for success, -errno for errors.
3332  */
3333 int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
3334 {
3335 	union drm_amdgpu_vm *args = data;
3336 	struct amdgpu_device *adev = dev->dev_private;
3337 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
3338 	int r;
3339 
3340 	switch (args->in.op) {
3341 	case AMDGPU_VM_OP_RESERVE_VMID:
3342 		/* current, we only have requirement to reserve vmid from gfxhub */
3343 		r = amdgpu_vmid_alloc_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB);
3344 		if (r)
3345 			return r;
3346 		break;
3347 	case AMDGPU_VM_OP_UNRESERVE_VMID:
3348 		amdgpu_vmid_free_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB);
3349 		break;
3350 	default:
3351 		return -EINVAL;
3352 	}
3353 
3354 	return 0;
3355 }
3356 
3357 /**
3358  * amdgpu_vm_get_task_info - Extracts task info for a PASID.
3359  *
3360  * @adev: drm device pointer
3361  * @pasid: PASID identifier for VM
3362  * @task_info: task_info to fill.
3363  */
3364 void amdgpu_vm_get_task_info(struct amdgpu_device *adev, unsigned int pasid,
3365 			 struct amdgpu_task_info *task_info)
3366 {
3367 	struct amdgpu_vm *vm;
3368 	unsigned long flags;
3369 
3370 	spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
3371 
3372 	vm = idr_find(&adev->vm_manager.pasid_idr, pasid);
3373 	if (vm)
3374 		*task_info = vm->task_info;
3375 
3376 	spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
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