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