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