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