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