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