xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c (revision 5c458073553f0ef74f5c8db1bd459c87c722a299)
1 /*
2  * Copyright 2008 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors: Dave Airlie
25  *          Alex Deucher
26  *          Jerome Glisse
27  */
28 
29 #include <linux/dma-fence-array.h>
30 #include <linux/interval_tree_generic.h>
31 #include <linux/idr.h>
32 #include <linux/dma-buf.h>
33 
34 #include <drm/amdgpu_drm.h>
35 #include <drm/drm_drv.h>
36 #include <drm/ttm/ttm_tt.h>
37 #include <drm/drm_exec.h>
38 #include "amdgpu.h"
39 #include "amdgpu_vm.h"
40 #include "amdgpu_trace.h"
41 #include "amdgpu_amdkfd.h"
42 #include "amdgpu_gmc.h"
43 #include "amdgpu_xgmi.h"
44 #include "amdgpu_dma_buf.h"
45 #include "amdgpu_res_cursor.h"
46 #include "kfd_svm.h"
47 
48 /**
49  * DOC: GPUVM
50  *
51  * GPUVM is the MMU functionality provided on the GPU.
52  * GPUVM is similar to the legacy GART on older asics, however
53  * rather than there being a single global GART table
54  * for the entire GPU, there can be multiple GPUVM page tables active
55  * at any given time.  The GPUVM page tables can contain a mix
56  * VRAM pages and system pages (both memory and MMIO) and system pages
57  * can be mapped as snooped (cached system pages) or unsnooped
58  * (uncached system pages).
59  *
60  * Each active GPUVM has an ID associated with it and there is a page table
61  * linked with each VMID.  When executing a command buffer,
62  * the kernel tells the engine what VMID to use for that command
63  * buffer.  VMIDs are allocated dynamically as commands are submitted.
64  * The userspace drivers maintain their own address space and the kernel
65  * sets up their pages tables accordingly when they submit their
66  * command buffers and a VMID is assigned.
67  * The hardware supports up to 16 active GPUVMs at any given time.
68  *
69  * Each GPUVM is represented by a 1-2 or 1-5 level page table, depending
70  * on the ASIC family.  GPUVM supports RWX attributes on each page as well
71  * as other features such as encryption and caching attributes.
72  *
73  * VMID 0 is special.  It is the GPUVM used for the kernel driver.  In
74  * addition to an aperture managed by a page table, VMID 0 also has
75  * several other apertures.  There is an aperture for direct access to VRAM
76  * and there is a legacy AGP aperture which just forwards accesses directly
77  * to the matching system physical addresses (or IOVAs when an IOMMU is
78  * present).  These apertures provide direct access to these memories without
79  * incurring the overhead of a page table.  VMID 0 is used by the kernel
80  * driver for tasks like memory management.
81  *
82  * GPU clients (i.e., engines on the GPU) use GPUVM VMIDs to access memory.
83  * For user applications, each application can have their own unique GPUVM
84  * address space.  The application manages the address space and the kernel
85  * driver manages the GPUVM page tables for each process.  If an GPU client
86  * accesses an invalid page, it will generate a GPU page fault, similar to
87  * accessing an invalid page on a CPU.
88  */
89 
90 #define START(node) ((node)->start)
91 #define LAST(node) ((node)->last)
92 
93 INTERVAL_TREE_DEFINE(struct amdgpu_bo_va_mapping, rb, uint64_t, __subtree_last,
94 		     START, LAST, static, amdgpu_vm_it)
95 
96 #undef START
97 #undef LAST
98 
99 /**
100  * struct amdgpu_prt_cb - Helper to disable partial resident texture feature from a fence callback
101  */
102 struct amdgpu_prt_cb {
103 
104 	/**
105 	 * @adev: amdgpu device
106 	 */
107 	struct amdgpu_device *adev;
108 
109 	/**
110 	 * @cb: callback
111 	 */
112 	struct dma_fence_cb cb;
113 };
114 
115 /**
116  * struct amdgpu_vm_tlb_seq_struct - Helper to increment the TLB flush sequence
117  */
118 struct amdgpu_vm_tlb_seq_struct {
119 	/**
120 	 * @vm: pointer to the amdgpu_vm structure to set the fence sequence on
121 	 */
122 	struct amdgpu_vm *vm;
123 
124 	/**
125 	 * @cb: callback
126 	 */
127 	struct dma_fence_cb cb;
128 };
129 
130 /**
131  * amdgpu_vm_assert_locked - check if VM is correctly locked
132  * @vm: the VM which schould be tested
133  *
134  * Asserts that the VM root PD is locked.
135  */
136 static void amdgpu_vm_assert_locked(struct amdgpu_vm *vm)
137 {
138 	dma_resv_assert_held(vm->root.bo->tbo.base.resv);
139 }
140 
141 /* Initialize the amdgpu_vm_bo_status object */
142 static void amdgpu_vm_bo_status_init(struct amdgpu_vm_bo_status *lists)
143 {
144 	INIT_LIST_HEAD(&lists->evicted);
145 	INIT_LIST_HEAD(&lists->needs_update);
146 	INIT_LIST_HEAD(&lists->idle);
147 }
148 
149 /*
150  * Make sure we have the lock to modify the vm_bo status and return the object
151  * with the status lists.
152  */
153 static struct amdgpu_vm_bo_status *
154 amdgpu_vm_bo_lock_lists(struct amdgpu_vm_bo_base *vm_bo)
155 {
156 	struct amdgpu_vm *vm = vm_bo->vm;
157 	struct amdgpu_bo *bo = vm_bo->bo;
158 
159 	if (amdgpu_vm_is_bo_always_valid(vm, bo)) {
160 		/* No extra locking needed, protected by the root PD resv lock */
161 		amdgpu_vm_assert_locked(vm);
162 
163 		if (bo->tbo.type == ttm_bo_type_kernel)
164 			return &vm->kernel;
165 
166 		return &vm->always_valid;
167 	}
168 
169 	spin_lock(&vm_bo->vm->individual_lock);
170 	return &vm->individual;
171 }
172 
173 /* Eventually unlock the status list lock again */
174 static void amdgpu_vm_bo_unlock_lists(struct amdgpu_vm_bo_base *vm_bo)
175 {
176 	if (amdgpu_vm_is_bo_always_valid(vm_bo->vm, vm_bo->bo))
177 		amdgpu_vm_assert_locked(vm_bo->vm);
178 	else
179 		spin_unlock(&vm_bo->vm->individual_lock);
180 }
181 
182 /**
183  * amdgpu_vm_is_bo_always_valid - check if the BO is VM always valid
184  *
185  * @vm: VM to test against.
186  * @bo: BO to be tested.
187  *
188  * Returns true if the BO shares the dma_resv object with the root PD and is
189  * always guaranteed to be valid inside the VM.
190  */
191 bool amdgpu_vm_is_bo_always_valid(struct amdgpu_vm *vm, struct amdgpu_bo *bo)
192 {
193 	return bo && bo->tbo.base.resv == vm->root.bo->tbo.base.resv;
194 }
195 
196 /**
197  * amdgpu_vm_bo_evicted - vm_bo is evicted
198  *
199  * @vm_bo: vm_bo which is evicted
200  *
201  * State for vm_bo objects meaning the underlying BO was evicted and need to
202  * move in place again.
203  */
204 static void amdgpu_vm_bo_evicted(struct amdgpu_vm_bo_base *vm_bo)
205 {
206 	struct amdgpu_vm_bo_status *lists;
207 
208 	lists = amdgpu_vm_bo_lock_lists(vm_bo);
209 	vm_bo->moved = true;
210 	list_move(&vm_bo->vm_status, &lists->evicted);
211 	amdgpu_vm_bo_unlock_lists(vm_bo);
212 }
213 /**
214  * amdgpu_vm_bo_needs_update - vm_bo needs pagetable update
215  *
216  * @vm_bo: vm_bo which is out of date
217  *
218  * State for vm_bo objects meaning the underlying BO had mapping changes (move, PRT bind/unbind)
219  * but the new location is not yet reflected in the page tables.
220  */
221 static void amdgpu_vm_bo_needs_update(struct amdgpu_vm_bo_base *vm_bo)
222 {
223 	struct amdgpu_vm_bo_status *lists;
224 	struct amdgpu_bo *bo = vm_bo->bo;
225 
226 	/*
227 	 * The root PD doesn't have a parent PDE and goes directly into the
228 	 * idle state.
229 	 */
230 	lists = amdgpu_vm_bo_lock_lists(vm_bo);
231 	if (bo && bo->tbo.type == ttm_bo_type_kernel && !bo->parent) {
232 		vm_bo->moved = false;
233 		list_move(&vm_bo->vm_status, &lists->idle);
234 	} else {
235 		list_move(&vm_bo->vm_status, &lists->needs_update);
236 	}
237 	amdgpu_vm_bo_unlock_lists(vm_bo);
238 }
239 
240 /**
241  * amdgpu_vm_bo_idle - vm_bo is idle
242  *
243  * @vm_bo: vm_bo which is now idle
244  *
245  * State for vm_bo objects meaning we are done with the state machine and no
246  * further action is necessary.
247  */
248 static void amdgpu_vm_bo_idle(struct amdgpu_vm_bo_base *vm_bo)
249 {
250 	struct amdgpu_vm_bo_status *lists;
251 
252 	lists = amdgpu_vm_bo_lock_lists(vm_bo);
253 	if (!amdgpu_vm_is_bo_always_valid(vm_bo->vm, vm_bo->bo))
254 		vm_bo->moved = false;
255 	list_move(&vm_bo->vm_status, &lists->idle);
256 	amdgpu_vm_bo_unlock_lists(vm_bo);
257 }
258 
259 /**
260  * amdgpu_vm_bo_reset_state_machine - reset the vm_bo state machine
261  * @vm: the VM which state machine to reset
262  *
263  * Move all vm_bo object in the VM into a state where their location will be
264  * updated in the page tables again.
265  */
266 static void amdgpu_vm_bo_reset_state_machine(struct amdgpu_vm *vm)
267 {
268 	struct amdgpu_vm_bo_base *vm_bo, *tmp;
269 
270 	/*
271 	 * Don't use list splice here, we need the special handling for the root
272 	 * PD and set the moved flag appropriately.
273 	 */
274 	amdgpu_vm_assert_locked(vm);
275 	list_for_each_entry_safe(vm_bo, tmp, &vm->kernel.idle, vm_status)
276 		amdgpu_vm_bo_needs_update(vm_bo);
277 	list_for_each_entry_safe(vm_bo, tmp, &vm->always_valid.idle, vm_status)
278 		amdgpu_vm_bo_needs_update(vm_bo);
279 
280 	spin_lock(&vm->individual_lock);
281 	list_for_each_entry_safe(vm_bo, tmp, &vm->individual.idle, vm_status) {
282 		vm_bo->moved = true;
283 		list_move(&vm_bo->vm_status, &vm->individual.needs_update);
284 	}
285 	spin_unlock(&vm->individual_lock);
286 }
287 
288 /**
289  * amdgpu_vm_update_shared - helper to update shared memory stat
290  * @base: base structure for tracking BO usage in a VM
291  *
292  * Takes the vm stats_lock and updates the shared memory stat. If the basic
293  * stat changed (e.g. buffer was moved) amdgpu_vm_update_stats need to be called
294  * as well.
295  */
296 static void amdgpu_vm_update_shared(struct amdgpu_vm_bo_base *base)
297 {
298 	struct amdgpu_vm *vm = base->vm;
299 	struct amdgpu_bo *bo = base->bo;
300 	uint64_t size = amdgpu_bo_size(bo);
301 	uint32_t bo_memtype = amdgpu_bo_mem_stats_placement(bo);
302 	bool shared;
303 
304 	dma_resv_assert_held(bo->tbo.base.resv);
305 	spin_lock(&vm->stats_lock);
306 	shared = drm_gem_object_is_shared_for_memory_stats(&bo->tbo.base);
307 	if (base->shared != shared) {
308 		base->shared = shared;
309 		if (shared) {
310 			vm->stats[bo_memtype].drm.shared += size;
311 			vm->stats[bo_memtype].drm.private -= size;
312 		} else {
313 			vm->stats[bo_memtype].drm.shared -= size;
314 			vm->stats[bo_memtype].drm.private += size;
315 		}
316 	}
317 	spin_unlock(&vm->stats_lock);
318 }
319 
320 /**
321  * amdgpu_vm_bo_update_shared - callback when bo gets shared/unshared
322  * @bo: amdgpu buffer object
323  *
324  * Update the per VM stats for all the vm if needed from private to shared or
325  * vice versa.
326  */
327 void amdgpu_vm_bo_update_shared(struct amdgpu_bo *bo)
328 {
329 	struct amdgpu_vm_bo_base *base;
330 
331 	for (base = bo->vm_bo; base; base = base->next)
332 		amdgpu_vm_update_shared(base);
333 }
334 
335 /**
336  * amdgpu_vm_update_stats_locked - helper to update normal memory stat
337  * @base: base structure for tracking BO usage in a VM
338  * @res:  the ttm_resource to use for the purpose of accounting, may or may not
339  *        be bo->tbo.resource
340  * @sign: if we should add (+1) or subtract (-1) from the stat
341  *
342  * Caller need to have the vm stats_lock held. Useful for when multiple update
343  * need to happen at the same time.
344  */
345 static void amdgpu_vm_update_stats_locked(struct amdgpu_vm_bo_base *base,
346 					  struct ttm_resource *res, int sign)
347 {
348 	struct amdgpu_vm *vm = base->vm;
349 	struct amdgpu_bo *bo = base->bo;
350 	int64_t size = sign * amdgpu_bo_size(bo);
351 	uint32_t bo_memtype = amdgpu_bo_mem_stats_placement(bo);
352 
353 	/* For drm-total- and drm-shared-, BO are accounted by their preferred
354 	 * placement, see also amdgpu_bo_mem_stats_placement.
355 	 */
356 	if (base->shared)
357 		vm->stats[bo_memtype].drm.shared += size;
358 	else
359 		vm->stats[bo_memtype].drm.private += size;
360 
361 	if (res && res->mem_type < __AMDGPU_PL_NUM) {
362 		uint32_t res_memtype = res->mem_type;
363 
364 		vm->stats[res_memtype].drm.resident += size;
365 		/* BO only count as purgeable if it is resident,
366 		 * since otherwise there's nothing to purge.
367 		 */
368 		if (bo->flags & AMDGPU_GEM_CREATE_DISCARDABLE)
369 			vm->stats[res_memtype].drm.purgeable += size;
370 		if (!(bo->preferred_domains &
371 		      amdgpu_mem_type_to_domain(res_memtype)))
372 			vm->stats[bo_memtype].evicted += size;
373 	}
374 }
375 
376 /**
377  * amdgpu_vm_update_stats - helper to update normal memory stat
378  * @base: base structure for tracking BO usage in a VM
379  * @res:  the ttm_resource to use for the purpose of accounting, may or may not
380  *        be bo->tbo.resource
381  * @sign: if we should add (+1) or subtract (-1) from the stat
382  *
383  * Updates the basic memory stat when bo is added/deleted/moved.
384  */
385 void amdgpu_vm_update_stats(struct amdgpu_vm_bo_base *base,
386 			    struct ttm_resource *res, int sign)
387 {
388 	struct amdgpu_vm *vm = base->vm;
389 
390 	spin_lock(&vm->stats_lock);
391 	amdgpu_vm_update_stats_locked(base, res, sign);
392 	spin_unlock(&vm->stats_lock);
393 }
394 
395 /**
396  * amdgpu_vm_bo_base_init - Adds bo to the list of bos associated with the vm
397  *
398  * @base: base structure for tracking BO usage in a VM
399  * @vm: vm to which bo is to be added
400  * @bo: amdgpu buffer object
401  *
402  * Initialize a bo_va_base structure and add it to the appropriate lists
403  *
404  */
405 void amdgpu_vm_bo_base_init(struct amdgpu_vm_bo_base *base,
406 			    struct amdgpu_vm *vm, struct amdgpu_bo *bo)
407 {
408 	base->vm = vm;
409 	base->bo = bo;
410 	base->next = NULL;
411 	INIT_LIST_HEAD(&base->vm_status);
412 
413 	dma_resv_assert_held(vm->root.bo->tbo.base.resv);
414 	if (!bo)
415 		return;
416 
417 	base->next = bo->vm_bo;
418 	bo->vm_bo = base;
419 
420 	spin_lock(&vm->stats_lock);
421 	base->shared = drm_gem_object_is_shared_for_memory_stats(&bo->tbo.base);
422 	amdgpu_vm_update_stats_locked(base, bo->tbo.resource, +1);
423 	spin_unlock(&vm->stats_lock);
424 
425 	if (!amdgpu_vm_is_bo_always_valid(vm, bo)) {
426 		amdgpu_vm_bo_idle(base);
427 		return;
428 	}
429 
430 	ttm_bo_set_bulk_move(&bo->tbo, &vm->lru_bulk_move);
431 
432 	/*
433 	 * When a per VM isn't in the desired domain put it into the evicted
434 	 * state to make sure that it gets validated on the next best occasion.
435 	 */
436 	if (bo->preferred_domains &
437 	    amdgpu_mem_type_to_domain(bo->tbo.resource->mem_type))
438 		amdgpu_vm_bo_needs_update(base);
439 	else
440 		amdgpu_vm_bo_evicted(base);
441 }
442 
443 /**
444  * amdgpu_vm_lock_pd - lock PD in drm_exec
445  *
446  * @vm: vm providing the BOs
447  * @exec: drm execution context
448  * @num_fences: number of extra fences to reserve
449  *
450  * Lock the VM root PD in the DRM execution context.
451  */
452 int amdgpu_vm_lock_pd(struct amdgpu_vm *vm, struct drm_exec *exec,
453 		      unsigned int num_fences)
454 {
455 	/* We need at least two fences for the VM PD/PT updates */
456 	return drm_exec_prepare_obj(exec, &vm->root.bo->tbo.base,
457 				    2 + num_fences);
458 }
459 
460 /**
461  * amdgpu_vm_lock_individual - lock all BOs on the individual idle list
462  * @vm: vm providing the BOs
463  * @exec: drm execution context
464  * @num_fences: number of extra fences to reserve
465  *
466  * Lock the BOs on the individual idle list in the DRM execution context.
467  */
468 int amdgpu_vm_lock_individual(struct amdgpu_vm *vm, struct drm_exec *exec,
469 			      unsigned int num_fences)
470 {
471 	struct list_head *prev = &vm->individual.idle;
472 	struct amdgpu_bo_va *bo_va;
473 	struct amdgpu_bo *bo;
474 	int ret;
475 
476 	/* We can only trust prev->next while holding the lock */
477 	spin_lock(&vm->individual_lock);
478 	while (!list_is_head(prev->next, &vm->individual.idle)) {
479 		bo_va = list_entry(prev->next, typeof(*bo_va), base.vm_status);
480 
481 		bo = bo_va->base.bo;
482 		if (bo) {
483 			amdgpu_bo_ref(bo);
484 			spin_unlock(&vm->individual_lock);
485 
486 			ret = drm_exec_prepare_obj(exec, &bo->tbo.base, num_fences);
487 			amdgpu_bo_unref(&bo);
488 			if (unlikely(ret))
489 				return ret;
490 
491 			spin_lock(&vm->individual_lock);
492 		}
493 		prev = prev->next;
494 	}
495 	spin_unlock(&vm->individual_lock);
496 
497 	return 0;
498 }
499 
500 /**
501  * amdgpu_vm_move_to_lru_tail - move all BOs to the end of LRU
502  *
503  * @adev: amdgpu device pointer
504  * @vm: vm providing the BOs
505  *
506  * Move all BOs to the end of LRU and remember their positions to put them
507  * together.
508  */
509 void amdgpu_vm_move_to_lru_tail(struct amdgpu_device *adev,
510 				struct amdgpu_vm *vm)
511 {
512 	spin_lock(&adev->mman.bdev.lru_lock);
513 	ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
514 	spin_unlock(&adev->mman.bdev.lru_lock);
515 }
516 
517 /* Create scheduler entities for page table updates */
518 static int amdgpu_vm_init_entities(struct amdgpu_device *adev,
519 				   struct amdgpu_vm *vm)
520 {
521 	int r;
522 
523 	r = drm_sched_entity_init(&vm->immediate, DRM_SCHED_PRIORITY_NORMAL,
524 				  adev->vm_manager.vm_pte_scheds,
525 				  adev->vm_manager.vm_pte_num_scheds, NULL);
526 	if (r)
527 		goto error;
528 
529 	return drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL,
530 				     adev->vm_manager.vm_pte_scheds,
531 				     adev->vm_manager.vm_pte_num_scheds, NULL);
532 
533 error:
534 	drm_sched_entity_destroy(&vm->immediate);
535 	return r;
536 }
537 
538 /* Destroy the entities for page table updates again */
539 static void amdgpu_vm_fini_entities(struct amdgpu_vm *vm)
540 {
541 	drm_sched_entity_destroy(&vm->immediate);
542 	drm_sched_entity_destroy(&vm->delayed);
543 }
544 
545 /**
546  * amdgpu_vm_generation - return the page table re-generation counter
547  * @adev: the amdgpu_device
548  * @vm: optional VM to check, might be NULL
549  *
550  * Returns a page table re-generation token to allow checking if submissions
551  * are still valid to use this VM. The VM parameter might be NULL in which case
552  * just the VRAM lost counter will be used.
553  */
554 uint64_t amdgpu_vm_generation(struct amdgpu_device *adev, struct amdgpu_vm *vm)
555 {
556 	uint64_t result = (u64)atomic_read(&adev->vram_lost_counter) << 32;
557 
558 	if (!vm)
559 		return result;
560 
561 	result += lower_32_bits(vm->generation);
562 	/* Add one if the page tables will be re-generated on next CS */
563 	if (drm_sched_entity_error(&vm->delayed))
564 		++result;
565 
566 	return result;
567 }
568 
569 /**
570  * amdgpu_vm_validate - validate evicted BOs tracked in the VM
571  *
572  * @adev: amdgpu device pointer
573  * @vm: vm providing the BOs
574  * @ticket: optional reservation ticket used to reserve the VM
575  * @validate: callback to do the validation
576  * @param: parameter for the validation callback
577  *
578  * Validate the page table BOs and per-VM BOs on command submission if
579  * necessary. If a ticket is given, also try to validate evicted user queue
580  * BOs. They must already be reserved with the given ticket.
581  *
582  * Returns:
583  * Validation result.
584  */
585 int amdgpu_vm_validate(struct amdgpu_device *adev, struct amdgpu_vm *vm,
586 		       struct ww_acquire_ctx *ticket,
587 		       int (*validate)(void *p, struct amdgpu_bo *bo),
588 		       void *param)
589 {
590 	uint64_t new_vm_generation = amdgpu_vm_generation(adev, vm);
591 	struct amdgpu_vm_bo_base *bo_base, *tmp;
592 	int r;
593 
594 	dma_resv_assert_held(vm->root.bo->tbo.base.resv);
595 	if (vm->generation != new_vm_generation) {
596 		vm->generation = new_vm_generation;
597 		amdgpu_vm_bo_reset_state_machine(vm);
598 		amdgpu_vm_fini_entities(vm);
599 		r = amdgpu_vm_init_entities(adev, vm);
600 		if (r)
601 			return r;
602 	}
603 
604 	list_for_each_entry_safe(bo_base, tmp, &vm->kernel.evicted, vm_status) {
605 		r = validate(param, bo_base->bo);
606 		if (r)
607 			return r;
608 
609 		vm->update_funcs->map_table(to_amdgpu_bo_vm(bo_base->bo));
610 		bo_base->moved = true;
611 		amdgpu_vm_bo_needs_update(bo_base);
612 	}
613 
614 	/*
615 	 * As soon as all page tables are in place we can start updating them
616 	 * again.
617 	 */
618 	amdgpu_vm_eviction_lock(vm);
619 	vm->evicting = false;
620 	amdgpu_vm_eviction_unlock(vm);
621 
622 	list_for_each_entry_safe(bo_base, tmp, &vm->always_valid.evicted,
623 				 vm_status) {
624 		r = validate(param, bo_base->bo);
625 		if (r)
626 			return r;
627 
628 		bo_base->moved = true;
629 		amdgpu_vm_bo_needs_update(bo_base);
630 	}
631 
632 	if (!ticket)
633 		return 0;
634 
635 	spin_lock(&vm->individual_lock);
636 restart:
637 	list_for_each_entry(bo_base, &vm->individual.evicted, vm_status) {
638 		struct amdgpu_bo *bo = bo_base->bo;
639 
640 		if (dma_resv_locking_ctx(bo->tbo.base.resv) != ticket)
641 			continue;
642 
643 		spin_unlock(&vm->individual_lock);
644 
645 		r = validate(param, bo);
646 		if (r)
647 			return r;
648 
649 		bo_base->moved = true;
650 		amdgpu_vm_bo_needs_update(bo_base);
651 
652 		/* It's a bit inefficient to always jump back to the start, but
653 		 * we would need to re-structure the KFD for properly fixing
654 		 * that.
655 		 */
656 		spin_lock(&vm->individual_lock);
657 		goto restart;
658 	}
659 	spin_unlock(&vm->individual_lock);
660 
661 	return 0;
662 }
663 
664 /**
665  * amdgpu_vm_ready - check VM is ready for updates
666  *
667  * @vm: VM to check
668  *
669  * Check if all VM PDs/PTs are ready for updates
670  *
671  * Returns:
672  * True if VM is not evicting and all VM entities are not stopped
673  */
674 bool amdgpu_vm_ready(struct amdgpu_vm *vm)
675 {
676 	bool ret;
677 
678 	amdgpu_vm_assert_locked(vm);
679 
680 	amdgpu_vm_eviction_lock(vm);
681 	ret = !vm->evicting;
682 	amdgpu_vm_eviction_unlock(vm);
683 
684 	ret &= list_empty(&vm->kernel.evicted);
685 
686 	spin_lock(&vm->immediate.lock);
687 	ret &= !vm->immediate.stopped;
688 	spin_unlock(&vm->immediate.lock);
689 
690 	spin_lock(&vm->delayed.lock);
691 	ret &= !vm->delayed.stopped;
692 	spin_unlock(&vm->delayed.lock);
693 
694 	return ret;
695 }
696 
697 /**
698  * amdgpu_vm_check_compute_bug - check whether asic has compute vm bug
699  *
700  * @adev: amdgpu_device pointer
701  */
702 void amdgpu_vm_check_compute_bug(struct amdgpu_device *adev)
703 {
704 	const struct amdgpu_ip_block *ip_block;
705 	bool has_compute_vm_bug;
706 	struct amdgpu_ring *ring;
707 	int i;
708 
709 	has_compute_vm_bug = false;
710 
711 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
712 	if (ip_block) {
713 		/* Compute has a VM bug for GFX version < 7.
714 		   Compute has a VM bug for GFX 8 MEC firmware version < 673.*/
715 		if (ip_block->version->major <= 7)
716 			has_compute_vm_bug = true;
717 		else if (ip_block->version->major == 8)
718 			if (adev->gfx.mec_fw_version < 673)
719 				has_compute_vm_bug = true;
720 	}
721 
722 	for (i = 0; i < adev->num_rings; i++) {
723 		ring = adev->rings[i];
724 		if (ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE)
725 			/* only compute rings */
726 			ring->has_compute_vm_bug = has_compute_vm_bug;
727 		else
728 			ring->has_compute_vm_bug = false;
729 	}
730 }
731 
732 /**
733  * amdgpu_vm_need_pipeline_sync - Check if pipe sync is needed for job.
734  *
735  * @ring: ring on which the job will be submitted
736  * @job: job to submit
737  *
738  * Returns:
739  * True if sync is needed.
740  */
741 bool amdgpu_vm_need_pipeline_sync(struct amdgpu_ring *ring,
742 				  struct amdgpu_job *job)
743 {
744 	struct amdgpu_device *adev = ring->adev;
745 	unsigned vmhub = ring->vm_hub;
746 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
747 
748 	if (job->vmid == 0)
749 		return false;
750 
751 	if (job->vm_needs_flush || ring->has_compute_vm_bug)
752 		return true;
753 
754 	if (ring->funcs->emit_gds_switch && job->gds_switch_needed)
755 		return true;
756 
757 	if (amdgpu_vmid_had_gpu_reset(adev, &id_mgr->ids[job->vmid]))
758 		return true;
759 
760 	return false;
761 }
762 
763 /**
764  * amdgpu_vm_flush - hardware flush the vm
765  *
766  * @ring: ring to use for flush
767  * @job:  related job
768  * @need_pipe_sync: is pipe sync needed
769  *
770  * Emit a VM flush when it is necessary.
771  */
772 void amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job,
773 		     bool need_pipe_sync)
774 {
775 	struct amdgpu_device *adev = ring->adev;
776 	struct amdgpu_isolation *isolation = &adev->isolation[ring->xcp_id];
777 	unsigned vmhub = ring->vm_hub;
778 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
779 	struct amdgpu_vmid *id = &id_mgr->ids[job->vmid];
780 	bool spm_update_needed = job->spm_update_needed;
781 	bool gds_switch_needed = ring->funcs->emit_gds_switch &&
782 		job->gds_switch_needed;
783 	bool vm_flush_needed = job->vm_needs_flush;
784 	bool cleaner_shader_needed = false;
785 	bool pasid_mapping_needed = false;
786 	struct dma_fence *fence = NULL;
787 	unsigned int patch = 0;
788 
789 	if (amdgpu_vmid_had_gpu_reset(adev, id)) {
790 		gds_switch_needed = true;
791 		vm_flush_needed = true;
792 		pasid_mapping_needed = true;
793 		spm_update_needed = true;
794 	}
795 
796 	mutex_lock(&id_mgr->lock);
797 	if (id->pasid != job->pasid || !id->pasid_mapping ||
798 	    !dma_fence_is_signaled(id->pasid_mapping))
799 		pasid_mapping_needed = true;
800 	mutex_unlock(&id_mgr->lock);
801 
802 	gds_switch_needed &= !!ring->funcs->emit_gds_switch;
803 	vm_flush_needed &= !!ring->funcs->emit_vm_flush  &&
804 			job->vm_pd_addr != AMDGPU_BO_INVALID_OFFSET;
805 	pasid_mapping_needed &= adev->gmc.gmc_funcs->emit_pasid_mapping &&
806 		ring->funcs->emit_wreg;
807 
808 	cleaner_shader_needed = job->run_cleaner_shader &&
809 		adev->gfx.enable_cleaner_shader &&
810 		ring->funcs->emit_cleaner_shader && job->base.s_fence &&
811 		&job->base.s_fence->scheduled == isolation->spearhead;
812 
813 	if (!vm_flush_needed && !gds_switch_needed && !need_pipe_sync &&
814 	    !cleaner_shader_needed)
815 		return;
816 
817 	amdgpu_ring_ib_begin(ring);
818 
819 	/* There is no matching insert_end for this on purpose for the vm flush.
820 	 * The IB portion of the submission has both.  Having multiple
821 	 * insert_start sequences is ok, but you can only have one insert_end
822 	 * per submission based on the way VCN FW works.  For JPEG
823 	 * you can as many insert_start and insert_end sequences as you like as
824 	 * long as the rest of the packets come between start and end sequences.
825 	 */
826 	if (ring->funcs->insert_start)
827 		ring->funcs->insert_start(ring);
828 
829 	if (ring->funcs->init_cond_exec)
830 		patch = amdgpu_ring_init_cond_exec(ring,
831 						   ring->cond_exe_gpu_addr);
832 
833 	if (need_pipe_sync)
834 		amdgpu_ring_emit_pipeline_sync(ring);
835 
836 	if (cleaner_shader_needed)
837 		ring->funcs->emit_cleaner_shader(ring);
838 
839 	if (vm_flush_needed) {
840 		trace_amdgpu_vm_flush(ring, job->vmid, job->vm_pd_addr);
841 		amdgpu_ring_emit_vm_flush(ring, job->vmid, job->vm_pd_addr);
842 	}
843 
844 	if (pasid_mapping_needed)
845 		amdgpu_gmc_emit_pasid_mapping(ring, job->vmid, job->pasid);
846 
847 	if (spm_update_needed && adev->gfx.rlc.funcs->update_spm_vmid)
848 		adev->gfx.rlc.funcs->update_spm_vmid(adev, ring->xcc_id, ring, job->vmid);
849 
850 	if (ring->funcs->emit_gds_switch &&
851 	    gds_switch_needed) {
852 		amdgpu_ring_emit_gds_switch(ring, job->vmid, job->gds_base,
853 					    job->gds_size, job->gws_base,
854 					    job->gws_size, job->oa_base,
855 					    job->oa_size);
856 	}
857 
858 	amdgpu_fence_emit(ring, job->hw_vm_fence, 0);
859 	fence = &job->hw_vm_fence->base;
860 	/* get a ref for the job */
861 	dma_fence_get(fence);
862 
863 	if (vm_flush_needed) {
864 		mutex_lock(&id_mgr->lock);
865 		dma_fence_put(id->last_flush);
866 		id->last_flush = dma_fence_get(fence);
867 		id->current_gpu_reset_count =
868 			atomic_read(&adev->gpu_reset_counter);
869 		mutex_unlock(&id_mgr->lock);
870 	}
871 
872 	if (pasid_mapping_needed) {
873 		mutex_lock(&id_mgr->lock);
874 		id->pasid = job->pasid;
875 		dma_fence_put(id->pasid_mapping);
876 		id->pasid_mapping = dma_fence_get(fence);
877 		mutex_unlock(&id_mgr->lock);
878 	}
879 
880 	/*
881 	 * Make sure that all other submissions wait for the cleaner shader to
882 	 * finish before we push them to the HW.
883 	 */
884 	if (cleaner_shader_needed) {
885 		trace_amdgpu_cleaner_shader(ring, fence);
886 		mutex_lock(&adev->enforce_isolation_mutex);
887 		dma_fence_put(isolation->spearhead);
888 		isolation->spearhead = dma_fence_get(fence);
889 		mutex_unlock(&adev->enforce_isolation_mutex);
890 	}
891 	dma_fence_put(fence);
892 
893 	amdgpu_ring_patch_cond_exec(ring, patch);
894 
895 	/* the double SWITCH_BUFFER here *cannot* be skipped by COND_EXEC */
896 	if (ring->funcs->emit_switch_buffer) {
897 		amdgpu_ring_emit_switch_buffer(ring);
898 		amdgpu_ring_emit_switch_buffer(ring);
899 	}
900 
901 	amdgpu_ring_ib_end(ring);
902 }
903 
904 /**
905  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
906  *
907  * @vm: requested vm
908  * @bo: requested buffer object
909  *
910  * Find @bo inside the requested vm.
911  * Search inside the @bos vm list for the requested vm
912  * Returns the found bo_va or NULL if none is found
913  *
914  * Object has to be reserved!
915  *
916  * Returns:
917  * Found bo_va or NULL.
918  */
919 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
920 				       struct amdgpu_bo *bo)
921 {
922 	struct amdgpu_vm_bo_base *base;
923 
924 	for (base = bo->vm_bo; base; base = base->next) {
925 		if (base->vm != vm)
926 			continue;
927 
928 		return container_of(base, struct amdgpu_bo_va, base);
929 	}
930 	return NULL;
931 }
932 
933 /**
934  * amdgpu_vm_map_gart - Resolve gart mapping of addr
935  *
936  * @pages_addr: optional DMA address to use for lookup
937  * @addr: the unmapped addr
938  *
939  * Look up the physical address of the page that the pte resolves
940  * to.
941  *
942  * Returns:
943  * The pointer for the page table entry.
944  */
945 uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
946 {
947 	uint64_t result;
948 
949 	/* page table offset */
950 	result = pages_addr[addr >> PAGE_SHIFT];
951 
952 	/* in case cpu page size != gpu page size*/
953 	result |= addr & (~PAGE_MASK);
954 
955 	result &= 0xFFFFFFFFFFFFF000ULL;
956 
957 	return result;
958 }
959 
960 /**
961  * amdgpu_vm_update_pdes - make sure that all directories are valid
962  *
963  * @adev: amdgpu_device pointer
964  * @vm: requested vm
965  * @immediate: submit immediately to the paging queue
966  *
967  * Makes sure all directories are up to date.
968  *
969  * Returns:
970  * 0 for success, error for failure.
971  */
972 int amdgpu_vm_update_pdes(struct amdgpu_device *adev,
973 			  struct amdgpu_vm *vm, bool immediate)
974 {
975 	struct amdgpu_vm_update_params params;
976 	struct amdgpu_vm_bo_base *entry, *tmp;
977 	bool flush_tlb_needed = false;
978 	int r, idx;
979 
980 	amdgpu_vm_assert_locked(vm);
981 
982 	if (list_empty(&vm->kernel.needs_update))
983 		return 0;
984 
985 	if (!drm_dev_enter(adev_to_drm(adev), &idx))
986 		return -ENODEV;
987 
988 	memset(&params, 0, sizeof(params));
989 	params.adev = adev;
990 	params.vm = vm;
991 	params.immediate = immediate;
992 
993 	r = vm->update_funcs->prepare(&params, NULL,
994 				      AMDGPU_KERNEL_JOB_ID_VM_UPDATE_PDES);
995 	if (r)
996 		goto error;
997 
998 	list_for_each_entry(entry, &vm->kernel.needs_update, vm_status) {
999 		/* vm_flush_needed after updating moved PDEs */
1000 		flush_tlb_needed |= entry->moved;
1001 
1002 		r = amdgpu_vm_pde_update(&params, entry);
1003 		if (r)
1004 			goto error;
1005 	}
1006 
1007 	r = vm->update_funcs->commit(&params, &vm->last_update);
1008 	if (r)
1009 		goto error;
1010 
1011 	if (flush_tlb_needed)
1012 		atomic64_inc(&vm->tlb_seq);
1013 
1014 	list_for_each_entry_safe(entry, tmp, &vm->kernel.needs_update,
1015 				 vm_status)
1016 		amdgpu_vm_bo_idle(entry);
1017 
1018 error:
1019 	drm_dev_exit(idx);
1020 	return r;
1021 }
1022 
1023 /**
1024  * amdgpu_vm_tlb_seq_cb - make sure to increment tlb sequence
1025  * @fence: unused
1026  * @cb: the callback structure
1027  *
1028  * Increments the tlb sequence to make sure that future CS execute a VM flush.
1029  */
1030 static void amdgpu_vm_tlb_seq_cb(struct dma_fence *fence,
1031 				 struct dma_fence_cb *cb)
1032 {
1033 	struct amdgpu_vm_tlb_seq_struct *tlb_cb;
1034 
1035 	tlb_cb = container_of(cb, typeof(*tlb_cb), cb);
1036 	atomic64_inc(&tlb_cb->vm->tlb_seq);
1037 	kfree(tlb_cb);
1038 }
1039 
1040 /**
1041  * amdgpu_vm_tlb_flush - prepare TLB flush
1042  *
1043  * @params: parameters for update
1044  * @fence: input fence to sync TLB flush with
1045  * @tlb_cb: the callback structure
1046  *
1047  * Increments the tlb sequence to make sure that future CS execute a VM flush.
1048  */
1049 static void
1050 amdgpu_vm_tlb_flush(struct amdgpu_vm_update_params *params,
1051 		    struct dma_fence **fence,
1052 		    struct amdgpu_vm_tlb_seq_struct *tlb_cb)
1053 {
1054 	struct amdgpu_vm *vm = params->vm;
1055 
1056 	tlb_cb->vm = vm;
1057 	if (!fence || !*fence) {
1058 		amdgpu_vm_tlb_seq_cb(NULL, &tlb_cb->cb);
1059 		return;
1060 	}
1061 
1062 	if (!dma_fence_add_callback(*fence, &tlb_cb->cb,
1063 				    amdgpu_vm_tlb_seq_cb)) {
1064 		dma_fence_put(vm->last_tlb_flush);
1065 		vm->last_tlb_flush = dma_fence_get(*fence);
1066 	} else {
1067 		amdgpu_vm_tlb_seq_cb(NULL, &tlb_cb->cb);
1068 	}
1069 
1070 	/* Prepare a TLB flush fence to be attached to PTs */
1071 	/* The check for need_tlb_fence should be dropped once we
1072 	 * sort out the issues with KIQ/MES TLB invalidation timeouts.
1073 	 */
1074 	if (!params->unlocked && vm->need_tlb_fence) {
1075 		amdgpu_vm_tlb_fence_create(params->adev, vm, fence);
1076 
1077 		/* Makes sure no PD/PT is freed before the flush */
1078 		dma_resv_add_fence(vm->root.bo->tbo.base.resv, *fence,
1079 				   DMA_RESV_USAGE_BOOKKEEP);
1080 	}
1081 }
1082 
1083 /**
1084  * amdgpu_vm_update_range - update a range in the vm page table
1085  *
1086  * @adev: amdgpu_device pointer to use for commands
1087  * @vm: the VM to update the range
1088  * @immediate: immediate submission in a page fault
1089  * @unlocked: unlocked invalidation during MM callback
1090  * @flush_tlb: trigger tlb invalidation after update completed
1091  * @allow_override: change MTYPE for local NUMA nodes
1092  * @sync: fences we need to sync to
1093  * @start: start of mapped range
1094  * @last: last mapped entry
1095  * @flags: flags for the entries
1096  * @offset: offset into nodes and pages_addr
1097  * @vram_base: base for vram mappings
1098  * @res: ttm_resource to map
1099  * @pages_addr: DMA addresses to use for mapping
1100  * @fence: optional resulting fence
1101  *
1102  * Fill in the page table entries between @start and @last.
1103  *
1104  * Returns:
1105  * 0 for success, negative erro code for failure.
1106  */
1107 int amdgpu_vm_update_range(struct amdgpu_device *adev, struct amdgpu_vm *vm,
1108 			   bool immediate, bool unlocked, bool flush_tlb,
1109 			   bool allow_override, struct amdgpu_sync *sync,
1110 			   uint64_t start, uint64_t last, uint64_t flags,
1111 			   uint64_t offset, uint64_t vram_base,
1112 			   struct ttm_resource *res, dma_addr_t *pages_addr,
1113 			   struct dma_fence **fence)
1114 {
1115 	struct amdgpu_vm_tlb_seq_struct *tlb_cb;
1116 	struct amdgpu_vm_update_params params;
1117 	struct amdgpu_res_cursor cursor;
1118 	int r, idx;
1119 
1120 	if (!drm_dev_enter(adev_to_drm(adev), &idx))
1121 		return -ENODEV;
1122 
1123 	tlb_cb = kmalloc_obj(*tlb_cb);
1124 	if (!tlb_cb) {
1125 		drm_dev_exit(idx);
1126 		return -ENOMEM;
1127 	}
1128 
1129 	/* Vega20+XGMI where PTEs get inadvertently cached in L2 texture cache,
1130 	 * heavy-weight flush TLB unconditionally.
1131 	 */
1132 	flush_tlb |= adev->gmc.xgmi.num_physical_nodes &&
1133 		     amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 0);
1134 
1135 	/*
1136 	 * On GFX8 and older any 8 PTE block with a valid bit set enters the TLB
1137 	 */
1138 	flush_tlb |= amdgpu_ip_version(adev, GC_HWIP, 0) < IP_VERSION(9, 0, 0);
1139 
1140 	memset(&params, 0, sizeof(params));
1141 	params.adev = adev;
1142 	params.vm = vm;
1143 	params.immediate = immediate;
1144 	params.pages_addr = pages_addr;
1145 	params.unlocked = unlocked;
1146 	params.needs_flush = flush_tlb;
1147 	params.override_pte = allow_override && adev->gmc.override_pte;
1148 	INIT_LIST_HEAD(&params.tlb_flush_waitlist);
1149 
1150 	amdgpu_vm_eviction_lock(vm);
1151 	if (vm->evicting) {
1152 		r = -EBUSY;
1153 		goto error_free;
1154 	}
1155 
1156 	if (!unlocked && !dma_fence_is_signaled(vm->last_unlocked)) {
1157 		struct dma_fence *tmp = dma_fence_get_stub();
1158 
1159 		amdgpu_bo_fence(vm->root.bo, vm->last_unlocked, true);
1160 		swap(vm->last_unlocked, tmp);
1161 		dma_fence_put(tmp);
1162 	}
1163 
1164 	r = vm->update_funcs->prepare(&params, sync,
1165 				      AMDGPU_KERNEL_JOB_ID_VM_UPDATE_RANGE);
1166 	if (r)
1167 		goto error_free;
1168 
1169 	amdgpu_res_first(pages_addr ? NULL : res, offset,
1170 			 (last - start + 1) * AMDGPU_GPU_PAGE_SIZE, &cursor);
1171 	while (cursor.remaining) {
1172 		uint64_t tmp, num_entries, addr;
1173 
1174 		num_entries = cursor.size >> AMDGPU_GPU_PAGE_SHIFT;
1175 		if (pages_addr) {
1176 			bool contiguous = true;
1177 
1178 			if (num_entries > AMDGPU_GPU_PAGES_IN_CPU_PAGE) {
1179 				uint64_t pfn = cursor.start >> PAGE_SHIFT;
1180 				uint64_t count;
1181 
1182 				contiguous = pages_addr[pfn + 1] ==
1183 					pages_addr[pfn] + PAGE_SIZE;
1184 
1185 				tmp = num_entries /
1186 					AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1187 				for (count = 2; count < tmp; ++count) {
1188 					uint64_t idx = pfn + count;
1189 
1190 					if (contiguous != (pages_addr[idx] ==
1191 					    pages_addr[idx - 1] + PAGE_SIZE))
1192 						break;
1193 				}
1194 				if (!contiguous)
1195 					count--;
1196 				num_entries = count *
1197 					AMDGPU_GPU_PAGES_IN_CPU_PAGE;
1198 			}
1199 
1200 			if (!contiguous) {
1201 				addr = cursor.start;
1202 				params.pages_addr = pages_addr;
1203 			} else {
1204 				addr = pages_addr[cursor.start >> PAGE_SHIFT];
1205 				params.pages_addr = NULL;
1206 			}
1207 
1208 		} else if (flags & (AMDGPU_PTE_VALID | AMDGPU_PTE_PRT_FLAG(adev))) {
1209 			addr = vram_base + cursor.start;
1210 		} else {
1211 			addr = 0;
1212 		}
1213 
1214 		tmp = start + num_entries;
1215 		r = amdgpu_vm_ptes_update(&params, start, tmp, addr, flags);
1216 		if (r)
1217 			goto error_free;
1218 
1219 		amdgpu_res_next(&cursor, num_entries * AMDGPU_GPU_PAGE_SIZE);
1220 		start = tmp;
1221 	}
1222 
1223 	r = vm->update_funcs->commit(&params, fence);
1224 	if (r)
1225 		goto error_free;
1226 
1227 	if (params.needs_flush) {
1228 		amdgpu_vm_tlb_flush(&params, fence, tlb_cb);
1229 		tlb_cb = NULL;
1230 	}
1231 
1232 	amdgpu_vm_pt_free_list(adev, &params);
1233 
1234 error_free:
1235 	kfree(tlb_cb);
1236 	amdgpu_vm_eviction_unlock(vm);
1237 	drm_dev_exit(idx);
1238 	return r;
1239 }
1240 
1241 void amdgpu_vm_get_memory(struct amdgpu_vm *vm,
1242 			  struct amdgpu_mem_stats stats[__AMDGPU_PL_NUM])
1243 {
1244 	spin_lock(&vm->stats_lock);
1245 	memcpy(stats, vm->stats, sizeof(*stats) * __AMDGPU_PL_NUM);
1246 	spin_unlock(&vm->stats_lock);
1247 }
1248 
1249 /**
1250  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
1251  *
1252  * @adev: amdgpu_device pointer
1253  * @bo_va: requested BO and VM object
1254  * @clear: if true clear the entries
1255  *
1256  * Fill in the page table entries for @bo_va.
1257  *
1258  * Returns:
1259  * 0 for success, -EINVAL for failure.
1260  */
1261 int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va,
1262 			bool clear)
1263 {
1264 	struct amdgpu_bo *bo = bo_va->base.bo;
1265 	struct amdgpu_vm *vm = bo_va->base.vm;
1266 	struct amdgpu_bo_va_mapping *mapping;
1267 	struct dma_fence **last_update;
1268 	dma_addr_t *pages_addr = NULL;
1269 	struct ttm_resource *mem;
1270 	struct amdgpu_sync sync;
1271 	bool flush_tlb = clear;
1272 	uint64_t vram_base;
1273 	uint64_t flags;
1274 	bool uncached;
1275 	int r;
1276 
1277 	amdgpu_sync_create(&sync);
1278 	if (clear) {
1279 		mem = NULL;
1280 
1281 		/* Implicitly sync to command submissions in the same VM before
1282 		 * unmapping.
1283 		 */
1284 		r = amdgpu_sync_resv(adev, &sync, vm->root.bo->tbo.base.resv,
1285 				     AMDGPU_SYNC_EQ_OWNER, vm);
1286 		if (r)
1287 			goto error_free;
1288 		if (bo) {
1289 			r = amdgpu_sync_kfd(&sync, bo->tbo.base.resv);
1290 			if (r)
1291 				goto error_free;
1292 		}
1293 	} else if (!bo) {
1294 		mem = NULL;
1295 
1296 		/* PRT map operations don't need to sync to anything. */
1297 
1298 	} else {
1299 		struct drm_gem_object *obj = &bo->tbo.base;
1300 
1301 		if (drm_gem_is_imported(obj) && bo_va->is_xgmi) {
1302 			struct dma_buf *dma_buf = obj->import_attach->dmabuf;
1303 			struct drm_gem_object *gobj = dma_buf->priv;
1304 			struct amdgpu_bo *abo = gem_to_amdgpu_bo(gobj);
1305 
1306 			if (abo->tbo.resource &&
1307 			    abo->tbo.resource->mem_type == TTM_PL_VRAM)
1308 				bo = gem_to_amdgpu_bo(gobj);
1309 		}
1310 		mem = bo->tbo.resource;
1311 		if (mem && (mem->mem_type == TTM_PL_TT ||
1312 			    mem->mem_type == AMDGPU_PL_PREEMPT))
1313 			pages_addr = bo->tbo.ttm->dma_address;
1314 
1315 		/* Implicitly sync to moving fences before mapping anything */
1316 		r = amdgpu_sync_resv(adev, &sync, bo->tbo.base.resv,
1317 				     AMDGPU_SYNC_EXPLICIT, vm);
1318 		if (r)
1319 			goto error_free;
1320 	}
1321 
1322 	if (bo) {
1323 		struct amdgpu_device *bo_adev;
1324 
1325 		flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, mem);
1326 
1327 		if (amdgpu_bo_encrypted(bo))
1328 			flags |= AMDGPU_PTE_TMZ;
1329 
1330 		bo_adev = amdgpu_ttm_adev(bo->tbo.bdev);
1331 		vram_base = bo_adev->vm_manager.vram_base_offset;
1332 		uncached = (bo->flags & AMDGPU_GEM_CREATE_UNCACHED) != 0;
1333 	} else {
1334 		flags = 0x0;
1335 		vram_base = 0;
1336 		uncached = false;
1337 	}
1338 
1339 	if (clear || amdgpu_vm_is_bo_always_valid(vm, bo))
1340 		last_update = &vm->last_update;
1341 	else
1342 		last_update = &bo_va->last_pt_update;
1343 
1344 	if (!clear && bo_va->base.moved) {
1345 		flush_tlb = true;
1346 		list_splice_init(&bo_va->valids, &bo_va->invalids);
1347 
1348 	} else if (bo_va->cleared != clear) {
1349 		list_splice_init(&bo_va->valids, &bo_va->invalids);
1350 	}
1351 
1352 	list_for_each_entry(mapping, &bo_va->invalids, list) {
1353 		uint64_t update_flags = flags;
1354 
1355 		/* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1356 		 * but in case of something, we filter the flags in first place
1357 		 */
1358 		if (!(mapping->flags & AMDGPU_VM_PAGE_READABLE))
1359 			update_flags &= ~AMDGPU_PTE_READABLE;
1360 		if (!(mapping->flags & AMDGPU_VM_PAGE_WRITEABLE))
1361 			update_flags &= ~AMDGPU_PTE_WRITEABLE;
1362 
1363 		/* Apply ASIC specific mapping flags */
1364 		amdgpu_gmc_get_vm_pte(adev, vm, bo, mapping->flags,
1365 				      &update_flags);
1366 
1367 		trace_amdgpu_vm_bo_update(mapping);
1368 
1369 		r = amdgpu_vm_update_range(adev, vm, false, false, flush_tlb,
1370 					   !uncached, &sync, mapping->start,
1371 					   mapping->last, update_flags,
1372 					   mapping->offset, vram_base, mem,
1373 					   pages_addr, last_update);
1374 		if (r)
1375 			goto error_free;
1376 	}
1377 
1378 	/* If the BO is not in its preferred location add it back to
1379 	 * the evicted list so that it gets validated again on the
1380 	 * next command submission.
1381 	 */
1382 	if (amdgpu_vm_is_bo_always_valid(vm, bo)) {
1383 		if (bo->tbo.resource &&
1384 		    !(bo->preferred_domains &
1385 		      amdgpu_mem_type_to_domain(bo->tbo.resource->mem_type)))
1386 			amdgpu_vm_bo_evicted(&bo_va->base);
1387 		else
1388 			amdgpu_vm_bo_idle(&bo_va->base);
1389 	} else {
1390 		amdgpu_vm_bo_idle(&bo_va->base);
1391 	}
1392 
1393 	list_splice_init(&bo_va->invalids, &bo_va->valids);
1394 	bo_va->cleared = clear;
1395 	bo_va->base.moved = false;
1396 
1397 	if (trace_amdgpu_vm_bo_mapping_enabled()) {
1398 		list_for_each_entry(mapping, &bo_va->valids, list)
1399 			trace_amdgpu_vm_bo_mapping(mapping);
1400 	}
1401 
1402 error_free:
1403 	amdgpu_sync_free(&sync);
1404 	return r;
1405 }
1406 
1407 /**
1408  * amdgpu_vm_update_prt_state - update the global PRT state
1409  *
1410  * @adev: amdgpu_device pointer
1411  */
1412 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
1413 {
1414 	unsigned long flags;
1415 	bool enable;
1416 
1417 	spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
1418 	enable = !!atomic_read(&adev->vm_manager.num_prt_users);
1419 	adev->gmc.gmc_funcs->set_prt(adev, enable);
1420 	spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
1421 }
1422 
1423 /**
1424  * amdgpu_vm_prt_get - add a PRT user
1425  *
1426  * @adev: amdgpu_device pointer
1427  */
1428 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
1429 {
1430 	if (!adev->gmc.gmc_funcs->set_prt)
1431 		return;
1432 
1433 	if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
1434 		amdgpu_vm_update_prt_state(adev);
1435 }
1436 
1437 /**
1438  * amdgpu_vm_prt_put - drop a PRT user
1439  *
1440  * @adev: amdgpu_device pointer
1441  */
1442 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
1443 {
1444 	if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
1445 		amdgpu_vm_update_prt_state(adev);
1446 }
1447 
1448 /**
1449  * amdgpu_vm_prt_cb - callback for updating the PRT status
1450  *
1451  * @fence: fence for the callback
1452  * @_cb: the callback function
1453  */
1454 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
1455 {
1456 	struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
1457 
1458 	amdgpu_vm_prt_put(cb->adev);
1459 	kfree(cb);
1460 }
1461 
1462 /**
1463  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
1464  *
1465  * @adev: amdgpu_device pointer
1466  * @fence: fence for the callback
1467  */
1468 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
1469 				 struct dma_fence *fence)
1470 {
1471 	struct amdgpu_prt_cb *cb;
1472 
1473 	if (!adev->gmc.gmc_funcs->set_prt)
1474 		return;
1475 
1476 	cb = kmalloc_obj(struct amdgpu_prt_cb);
1477 	if (!cb) {
1478 		/* Last resort when we are OOM */
1479 		if (fence)
1480 			dma_fence_wait(fence, false);
1481 
1482 		amdgpu_vm_prt_put(adev);
1483 	} else {
1484 		cb->adev = adev;
1485 		if (!fence || dma_fence_add_callback(fence, &cb->cb,
1486 						     amdgpu_vm_prt_cb))
1487 			amdgpu_vm_prt_cb(fence, &cb->cb);
1488 	}
1489 }
1490 
1491 /**
1492  * amdgpu_vm_free_mapping - free a mapping
1493  *
1494  * @adev: amdgpu_device pointer
1495  * @vm: requested vm
1496  * @mapping: mapping to be freed
1497  * @fence: fence of the unmap operation
1498  *
1499  * Free a mapping and make sure we decrease the PRT usage count if applicable.
1500  */
1501 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
1502 				   struct amdgpu_vm *vm,
1503 				   struct amdgpu_bo_va_mapping *mapping,
1504 				   struct dma_fence *fence)
1505 {
1506 	if (mapping->flags & AMDGPU_VM_PAGE_PRT)
1507 		amdgpu_vm_add_prt_cb(adev, fence);
1508 	kfree(mapping);
1509 }
1510 
1511 /**
1512  * amdgpu_vm_prt_fini - finish all prt mappings
1513  *
1514  * @adev: amdgpu_device pointer
1515  * @vm: requested vm
1516  *
1517  * Register a cleanup callback to disable PRT support after VM dies.
1518  */
1519 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1520 {
1521 	struct dma_resv *resv = vm->root.bo->tbo.base.resv;
1522 	struct dma_resv_iter cursor;
1523 	struct dma_fence *fence;
1524 
1525 	dma_resv_for_each_fence(&cursor, resv, DMA_RESV_USAGE_BOOKKEEP, fence) {
1526 		/* Add a callback for each fence in the reservation object */
1527 		amdgpu_vm_prt_get(adev);
1528 		amdgpu_vm_add_prt_cb(adev, fence);
1529 	}
1530 }
1531 
1532 /**
1533  * amdgpu_vm_clear_freed - clear freed BOs in the PT
1534  *
1535  * @adev: amdgpu_device pointer
1536  * @vm: requested vm
1537  * @fence: optional resulting fence (unchanged if no work needed to be done
1538  * or if an error occurred)
1539  *
1540  * Make sure all freed BOs are cleared in the PT.
1541  * PTs have to be reserved and mutex must be locked!
1542  *
1543  * Returns:
1544  * 0 for success.
1545  *
1546  */
1547 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
1548 			  struct amdgpu_vm *vm,
1549 			  struct dma_fence **fence)
1550 {
1551 	struct amdgpu_bo_va_mapping *mapping;
1552 	struct dma_fence *f = NULL;
1553 	struct amdgpu_sync sync;
1554 	int r;
1555 
1556 
1557 	/*
1558 	 * Implicitly sync to command submissions in the same VM before
1559 	 * unmapping.
1560 	 */
1561 	amdgpu_sync_create(&sync);
1562 	r = amdgpu_sync_resv(adev, &sync, vm->root.bo->tbo.base.resv,
1563 			     AMDGPU_SYNC_EQ_OWNER, vm);
1564 	if (r)
1565 		goto error_free;
1566 
1567 	while (!list_empty(&vm->freed)) {
1568 		mapping = list_first_entry(&vm->freed,
1569 			struct amdgpu_bo_va_mapping, list);
1570 		list_del(&mapping->list);
1571 
1572 		r = amdgpu_vm_update_range(adev, vm, false, false, true, false,
1573 					   &sync, mapping->start, mapping->last,
1574 					   0, 0, 0, NULL, NULL, &f);
1575 		amdgpu_vm_free_mapping(adev, vm, mapping, f);
1576 		if (r) {
1577 			dma_fence_put(f);
1578 			goto error_free;
1579 		}
1580 	}
1581 
1582 	if (fence && f) {
1583 		dma_fence_put(*fence);
1584 		*fence = f;
1585 	} else {
1586 		dma_fence_put(f);
1587 	}
1588 
1589 error_free:
1590 	amdgpu_sync_free(&sync);
1591 	return r;
1592 
1593 }
1594 
1595 /**
1596  * amdgpu_vm_handle_moved - handle moved BOs in the PT
1597  *
1598  * @adev: amdgpu_device pointer
1599  * @vm: requested vm
1600  * @ticket: optional reservation ticket used to reserve the VM
1601  *
1602  * Make sure all BOs which are moved are updated in the PTs.
1603  *
1604  * Returns:
1605  * 0 for success.
1606  *
1607  * PTs have to be reserved!
1608  */
1609 int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
1610 			   struct amdgpu_vm *vm,
1611 			   struct ww_acquire_ctx *ticket)
1612 {
1613 	struct amdgpu_bo_va *bo_va, *tmp;
1614 	struct dma_resv *resv;
1615 	struct amdgpu_bo *bo;
1616 	bool clear, unlock;
1617 	int r;
1618 
1619 	list_for_each_entry_safe(bo_va, tmp, &vm->always_valid.needs_update,
1620 				 base.vm_status) {
1621 		/* Per VM BOs never need to bo cleared in the page tables */
1622 		r = amdgpu_vm_bo_update(adev, bo_va, false);
1623 		if (r)
1624 			return r;
1625 	}
1626 
1627 	spin_lock(&vm->individual_lock);
1628 	while (!list_empty(&vm->individual.needs_update)) {
1629 		bo_va = list_first_entry(&vm->individual.needs_update,
1630 					 typeof(*bo_va), base.vm_status);
1631 		bo = bo_va->base.bo;
1632 		resv = bo->tbo.base.resv;
1633 		spin_unlock(&vm->individual_lock);
1634 
1635 		/* Try to reserve the BO to avoid clearing its ptes */
1636 		if (!adev->debug_vm && !amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&
1637 		    dma_resv_trylock(resv)) {
1638 			clear = false;
1639 			unlock = true;
1640 		/* The caller is already holding the reservation lock */
1641 		} else if (ticket && dma_resv_locking_ctx(resv) == ticket) {
1642 			clear = false;
1643 			unlock = false;
1644 		/* Somebody else is using the BO right now */
1645 		} else {
1646 			clear = true;
1647 			unlock = false;
1648 		}
1649 
1650 		r = amdgpu_vm_bo_update(adev, bo_va, clear);
1651 
1652 		if (unlock)
1653 			dma_resv_unlock(resv);
1654 		if (r)
1655 			return r;
1656 
1657 		/* Remember evicted DMABuf imports in compute VMs for later
1658 		 * validation
1659 		 */
1660 		if (vm->is_compute_context &&
1661 		    drm_gem_is_imported(&bo_va->base.bo->tbo.base) &&
1662 		    (!bo_va->base.bo->tbo.resource ||
1663 		     bo_va->base.bo->tbo.resource->mem_type == TTM_PL_SYSTEM))
1664 			amdgpu_vm_bo_evicted(&bo_va->base);
1665 
1666 		spin_lock(&vm->individual_lock);
1667 	}
1668 	spin_unlock(&vm->individual_lock);
1669 
1670 	return 0;
1671 }
1672 
1673 /**
1674  * amdgpu_vm_flush_compute_tlb - Flush TLB on compute VM
1675  *
1676  * @adev: amdgpu_device pointer
1677  * @vm: requested vm
1678  * @flush_type: flush type
1679  * @xcc_mask: mask of XCCs that belong to the compute partition in need of a TLB flush.
1680  *
1681  * Flush TLB if needed for a compute VM.
1682  *
1683  * Returns:
1684  * 0 for success.
1685  */
1686 int amdgpu_vm_flush_compute_tlb(struct amdgpu_device *adev,
1687 				struct amdgpu_vm *vm,
1688 				uint32_t flush_type,
1689 				uint32_t xcc_mask)
1690 {
1691 	uint64_t tlb_seq = amdgpu_vm_tlb_seq(vm);
1692 	bool all_hub = false;
1693 	int xcc = 0, r = 0;
1694 
1695 	WARN_ON_ONCE(!vm->is_compute_context);
1696 
1697 	/*
1698 	 * It can be that we race and lose here, but that is extremely unlikely
1699 	 * and the worst thing which could happen is that we flush the changes
1700 	 * into the TLB once more which is harmless.
1701 	 */
1702 	if (atomic64_xchg(&vm->kfd_last_flushed_seq, tlb_seq) == tlb_seq)
1703 		return 0;
1704 
1705 	if (adev->family == AMDGPU_FAMILY_AI ||
1706 	    adev->family == AMDGPU_FAMILY_RV)
1707 		all_hub = true;
1708 
1709 	for_each_inst(xcc, xcc_mask) {
1710 		r = amdgpu_gmc_flush_gpu_tlb_pasid(adev, vm->pasid, flush_type,
1711 						   all_hub, xcc);
1712 		if (r)
1713 			break;
1714 	}
1715 	return r;
1716 }
1717 
1718 /**
1719  * amdgpu_vm_bo_add - add a bo to a specific vm
1720  *
1721  * @adev: amdgpu_device pointer
1722  * @vm: requested vm
1723  * @bo: amdgpu buffer object
1724  *
1725  * Add @bo into the requested vm.
1726  * Add @bo to the list of bos associated with the vm
1727  *
1728  * Returns:
1729  * Newly added bo_va or NULL for failure
1730  *
1731  * Object has to be reserved!
1732  */
1733 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
1734 				      struct amdgpu_vm *vm,
1735 				      struct amdgpu_bo *bo)
1736 {
1737 	struct amdgpu_bo_va *bo_va;
1738 
1739 	amdgpu_vm_assert_locked(vm);
1740 
1741 	bo_va = kzalloc_obj(struct amdgpu_bo_va);
1742 	if (bo_va == NULL) {
1743 		return NULL;
1744 	}
1745 	amdgpu_vm_bo_base_init(&bo_va->base, vm, bo);
1746 
1747 	bo_va->ref_count = 1;
1748 	bo_va->last_pt_update = dma_fence_get_stub();
1749 	INIT_LIST_HEAD(&bo_va->valids);
1750 	INIT_LIST_HEAD(&bo_va->invalids);
1751 
1752 	if (!bo)
1753 		return bo_va;
1754 
1755 	dma_resv_assert_held(bo->tbo.base.resv);
1756 	if (amdgpu_dmabuf_is_xgmi_accessible(adev, bo)) {
1757 		bo_va->is_xgmi = true;
1758 		/* Power up XGMI if it can be potentially used */
1759 		amdgpu_xgmi_set_pstate(adev, AMDGPU_XGMI_PSTATE_MAX_VEGA20);
1760 	}
1761 
1762 	return bo_va;
1763 }
1764 
1765 
1766 /**
1767  * amdgpu_vm_bo_insert_map - insert a new mapping
1768  *
1769  * @adev: amdgpu_device pointer
1770  * @bo_va: bo_va to store the address
1771  * @mapping: the mapping to insert
1772  *
1773  * Insert a new mapping into all structures.
1774  */
1775 static void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev,
1776 				    struct amdgpu_bo_va *bo_va,
1777 				    struct amdgpu_bo_va_mapping *mapping)
1778 {
1779 	struct amdgpu_vm *vm = bo_va->base.vm;
1780 	struct amdgpu_bo *bo = bo_va->base.bo;
1781 
1782 	mapping->bo_va = bo_va;
1783 	list_add(&mapping->list, &bo_va->invalids);
1784 	amdgpu_vm_it_insert(mapping, &vm->va);
1785 
1786 	if (mapping->flags & AMDGPU_VM_PAGE_PRT)
1787 		amdgpu_vm_prt_get(adev);
1788 
1789 	if (amdgpu_vm_is_bo_always_valid(vm, bo) && !bo_va->base.moved)
1790 		amdgpu_vm_bo_needs_update(&bo_va->base);
1791 
1792 	trace_amdgpu_vm_bo_map(bo_va, mapping);
1793 }
1794 
1795 /* Validate operation parameters to prevent potential abuse */
1796 static int amdgpu_vm_verify_parameters(struct amdgpu_device *adev,
1797 					  struct amdgpu_bo *bo,
1798 					  uint64_t saddr,
1799 					  uint64_t offset,
1800 					  uint64_t size)
1801 {
1802 	uint64_t tmp, lpfn;
1803 
1804 	if (saddr & AMDGPU_GPU_PAGE_MASK
1805 	    || offset & AMDGPU_GPU_PAGE_MASK
1806 	    || size & AMDGPU_GPU_PAGE_MASK)
1807 		return -EINVAL;
1808 
1809 	if (check_add_overflow(saddr, size, &tmp)
1810 	    || check_add_overflow(offset, size, &tmp)
1811 	    || size == 0 /* which also leads to end < begin */)
1812 		return -EINVAL;
1813 
1814 	/* make sure object fit at this offset */
1815 	if (bo && offset + size > amdgpu_bo_size(bo))
1816 		return -EINVAL;
1817 
1818 	/* Ensure last pfn not exceed max_pfn */
1819 	lpfn = (saddr + size - 1) >> AMDGPU_GPU_PAGE_SHIFT;
1820 	if (lpfn >= adev->vm_manager.max_pfn)
1821 		return -EINVAL;
1822 
1823 	return 0;
1824 }
1825 
1826 /**
1827  * amdgpu_vm_bo_map - map bo inside a vm
1828  *
1829  * @adev: amdgpu_device pointer
1830  * @bo_va: bo_va to store the address
1831  * @saddr: where to map the BO
1832  * @offset: requested offset in the BO
1833  * @size: BO size in bytes
1834  * @flags: attributes of pages (read/write/valid/etc.)
1835  *
1836  * Add a mapping of the BO at the specefied addr into the VM.
1837  *
1838  * Returns:
1839  * 0 for success, error for failure.
1840  *
1841  * Object has to be reserved and unreserved outside!
1842  */
1843 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
1844 		     struct amdgpu_bo_va *bo_va,
1845 		     uint64_t saddr, uint64_t offset,
1846 		     uint64_t size, uint32_t flags)
1847 {
1848 	struct amdgpu_bo_va_mapping *mapping, *tmp;
1849 	struct amdgpu_bo *bo = bo_va->base.bo;
1850 	struct amdgpu_vm *vm = bo_va->base.vm;
1851 	uint64_t eaddr;
1852 	int r;
1853 
1854 	r = amdgpu_vm_verify_parameters(adev, bo, saddr, offset, size);
1855 	if (r)
1856 		return r;
1857 
1858 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1859 	eaddr = saddr + (size - 1) / AMDGPU_GPU_PAGE_SIZE;
1860 
1861 	tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
1862 	if (tmp) {
1863 		/* bo and tmp overlap, invalid addr */
1864 		dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
1865 			"0x%010Lx-0x%010Lx\n", bo, saddr, eaddr,
1866 			tmp->start, tmp->last + 1);
1867 		return -EINVAL;
1868 	}
1869 
1870 	mapping = kmalloc_obj(*mapping);
1871 	if (!mapping)
1872 		return -ENOMEM;
1873 
1874 	mapping->start = saddr;
1875 	mapping->last = eaddr;
1876 	mapping->offset = offset;
1877 	mapping->flags = flags;
1878 
1879 	amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
1880 
1881 	return 0;
1882 }
1883 
1884 /**
1885  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
1886  *
1887  * @adev: amdgpu_device pointer
1888  * @bo_va: bo_va to store the address
1889  * @saddr: where to map the BO
1890  * @offset: requested offset in the BO
1891  * @size: BO size in bytes
1892  * @flags: attributes of pages (read/write/valid/etc.)
1893  *
1894  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
1895  * mappings as we do so.
1896  *
1897  * Returns:
1898  * 0 for success, error for failure.
1899  *
1900  * Object has to be reserved and unreserved outside!
1901  */
1902 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
1903 			     struct amdgpu_bo_va *bo_va,
1904 			     uint64_t saddr, uint64_t offset,
1905 			     uint64_t size, uint32_t flags)
1906 {
1907 	struct amdgpu_bo_va_mapping *mapping;
1908 	struct amdgpu_bo *bo = bo_va->base.bo;
1909 	uint64_t eaddr;
1910 	int r;
1911 
1912 	r = amdgpu_vm_verify_parameters(adev, bo, saddr, offset, size);
1913 	if (r)
1914 		return r;
1915 
1916 	/* Allocate all the needed memory */
1917 	mapping = kmalloc_obj(*mapping);
1918 	if (!mapping)
1919 		return -ENOMEM;
1920 
1921 	r = amdgpu_vm_bo_clear_mappings(adev, bo_va->base.vm, saddr, size);
1922 	if (r) {
1923 		kfree(mapping);
1924 		return r;
1925 	}
1926 
1927 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1928 	eaddr = saddr + (size - 1) / AMDGPU_GPU_PAGE_SIZE;
1929 
1930 	mapping->start = saddr;
1931 	mapping->last = eaddr;
1932 	mapping->offset = offset;
1933 	mapping->flags = flags;
1934 
1935 	amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
1936 
1937 	return 0;
1938 }
1939 
1940 /**
1941  * amdgpu_vm_bo_unmap - remove bo mapping from vm
1942  *
1943  * @adev: amdgpu_device pointer
1944  * @bo_va: bo_va to remove the address from
1945  * @saddr: where to the BO is mapped
1946  *
1947  * Remove a mapping of the BO at the specefied addr from the VM.
1948  *
1949  * Returns:
1950  * 0 for success, error for failure.
1951  *
1952  * Object has to be reserved and unreserved outside!
1953  */
1954 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
1955 		       struct amdgpu_bo_va *bo_va,
1956 		       uint64_t saddr)
1957 {
1958 	struct amdgpu_bo_va_mapping *mapping;
1959 	struct amdgpu_vm *vm = bo_va->base.vm;
1960 	bool valid = true;
1961 
1962 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1963 
1964 	list_for_each_entry(mapping, &bo_va->valids, list) {
1965 		if (mapping->start == saddr)
1966 			break;
1967 	}
1968 
1969 	if (&mapping->list == &bo_va->valids) {
1970 		valid = false;
1971 
1972 		list_for_each_entry(mapping, &bo_va->invalids, list) {
1973 			if (mapping->start == saddr)
1974 				break;
1975 		}
1976 
1977 		if (&mapping->list == &bo_va->invalids)
1978 			return -ENOENT;
1979 	}
1980 
1981 	/* It's unlikely to happen that the mapping userq hasn't been idled
1982 	 * during user requests GEM unmap IOCTL except for forcing the unmap
1983 	 * from user space.
1984 	 */
1985 	if (unlikely(bo_va->userq_va_mapped))
1986 		amdgpu_userq_gem_va_unmap_validate(adev, mapping);
1987 
1988 	list_del(&mapping->list);
1989 	amdgpu_vm_it_remove(mapping, &vm->va);
1990 	mapping->bo_va = NULL;
1991 	trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1992 
1993 	if (valid)
1994 		list_add(&mapping->list, &vm->freed);
1995 	else
1996 		amdgpu_vm_free_mapping(adev, vm, mapping,
1997 				       bo_va->last_pt_update);
1998 
1999 	return 0;
2000 }
2001 
2002 /**
2003  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
2004  *
2005  * @adev: amdgpu_device pointer
2006  * @vm: VM structure to use
2007  * @saddr: start of the range
2008  * @size: size of the range
2009  *
2010  * Remove all mappings in a range, split them as appropriate.
2011  *
2012  * Returns:
2013  * 0 for success, error for failure.
2014  */
2015 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
2016 				struct amdgpu_vm *vm,
2017 				uint64_t saddr, uint64_t size)
2018 {
2019 	struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
2020 	LIST_HEAD(removed);
2021 	uint64_t eaddr;
2022 	int r;
2023 
2024 	r = amdgpu_vm_verify_parameters(adev, NULL, saddr, 0, size);
2025 	if (r)
2026 		return r;
2027 
2028 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2029 	eaddr = saddr + (size - 1) / AMDGPU_GPU_PAGE_SIZE;
2030 
2031 	/* Allocate all the needed memory */
2032 	before = kzalloc_obj(*before);
2033 	if (!before)
2034 		return -ENOMEM;
2035 	INIT_LIST_HEAD(&before->list);
2036 
2037 	after = kzalloc_obj(*after);
2038 	if (!after) {
2039 		kfree(before);
2040 		return -ENOMEM;
2041 	}
2042 	INIT_LIST_HEAD(&after->list);
2043 
2044 	/* Now gather all removed mappings */
2045 	tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2046 	while (tmp) {
2047 		/* Remember mapping split at the start */
2048 		if (tmp->start < saddr) {
2049 			before->start = tmp->start;
2050 			before->last = saddr - 1;
2051 			before->offset = tmp->offset;
2052 			before->flags = tmp->flags;
2053 			before->bo_va = tmp->bo_va;
2054 			list_add(&before->list, &tmp->bo_va->invalids);
2055 		}
2056 
2057 		/* Remember mapping split at the end */
2058 		if (tmp->last > eaddr) {
2059 			after->start = eaddr + 1;
2060 			after->last = tmp->last;
2061 			after->offset = tmp->offset;
2062 			after->offset += (after->start - tmp->start) << PAGE_SHIFT;
2063 			after->flags = tmp->flags;
2064 			after->bo_va = tmp->bo_va;
2065 			list_add(&after->list, &tmp->bo_va->invalids);
2066 		}
2067 
2068 		list_del(&tmp->list);
2069 		list_add(&tmp->list, &removed);
2070 
2071 		tmp = amdgpu_vm_it_iter_next(tmp, saddr, eaddr);
2072 	}
2073 
2074 	/* And free them up */
2075 	list_for_each_entry_safe(tmp, next, &removed, list) {
2076 		amdgpu_vm_it_remove(tmp, &vm->va);
2077 		list_del(&tmp->list);
2078 
2079 		if (tmp->start < saddr)
2080 		    tmp->start = saddr;
2081 		if (tmp->last > eaddr)
2082 		    tmp->last = eaddr;
2083 
2084 		tmp->bo_va = NULL;
2085 		list_add(&tmp->list, &vm->freed);
2086 		trace_amdgpu_vm_bo_unmap(NULL, tmp);
2087 	}
2088 
2089 	/* Insert partial mapping before the range */
2090 	if (!list_empty(&before->list)) {
2091 		struct amdgpu_bo *bo = before->bo_va->base.bo;
2092 
2093 		amdgpu_vm_it_insert(before, &vm->va);
2094 		if (before->flags & AMDGPU_VM_PAGE_PRT)
2095 			amdgpu_vm_prt_get(adev);
2096 
2097 		if (amdgpu_vm_is_bo_always_valid(vm, bo) &&
2098 		    !before->bo_va->base.moved)
2099 			amdgpu_vm_bo_needs_update(&before->bo_va->base);
2100 	} else {
2101 		kfree(before);
2102 	}
2103 
2104 	/* Insert partial mapping after the range */
2105 	if (!list_empty(&after->list)) {
2106 		struct amdgpu_bo *bo = after->bo_va->base.bo;
2107 
2108 		amdgpu_vm_it_insert(after, &vm->va);
2109 		if (after->flags & AMDGPU_VM_PAGE_PRT)
2110 			amdgpu_vm_prt_get(adev);
2111 
2112 		if (amdgpu_vm_is_bo_always_valid(vm, bo) &&
2113 		    !after->bo_va->base.moved)
2114 			amdgpu_vm_bo_needs_update(&after->bo_va->base);
2115 	} else {
2116 		kfree(after);
2117 	}
2118 
2119 	return 0;
2120 }
2121 
2122 /**
2123  * amdgpu_vm_bo_lookup_mapping - find mapping by address
2124  *
2125  * @vm: the requested VM
2126  * @addr: the address
2127  *
2128  * Find a mapping by it's address.
2129  *
2130  * Returns:
2131  * The amdgpu_bo_va_mapping matching for addr or NULL
2132  *
2133  */
2134 struct amdgpu_bo_va_mapping *amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm,
2135 							 uint64_t addr)
2136 {
2137 	return amdgpu_vm_it_iter_first(&vm->va, addr, addr);
2138 }
2139 
2140 /**
2141  * amdgpu_vm_bo_trace_cs - trace all reserved mappings
2142  *
2143  * @vm: the requested vm
2144  * @ticket: CS ticket
2145  *
2146  * Trace all mappings of BOs reserved during a command submission.
2147  */
2148 void amdgpu_vm_bo_trace_cs(struct amdgpu_vm *vm, struct ww_acquire_ctx *ticket)
2149 {
2150 	struct amdgpu_bo_va_mapping *mapping;
2151 
2152 	if (!trace_amdgpu_vm_bo_cs_enabled())
2153 		return;
2154 
2155 	for (mapping = amdgpu_vm_it_iter_first(&vm->va, 0, U64_MAX); mapping;
2156 	     mapping = amdgpu_vm_it_iter_next(mapping, 0, U64_MAX)) {
2157 		if (mapping->bo_va && mapping->bo_va->base.bo) {
2158 			struct amdgpu_bo *bo;
2159 
2160 			bo = mapping->bo_va->base.bo;
2161 			if (dma_resv_locking_ctx(bo->tbo.base.resv) !=
2162 			    ticket)
2163 				continue;
2164 		}
2165 
2166 		trace_amdgpu_vm_bo_cs(mapping);
2167 	}
2168 }
2169 
2170 /**
2171  * amdgpu_vm_bo_del - remove a bo from a specific vm
2172  *
2173  * @adev: amdgpu_device pointer
2174  * @bo_va: requested bo_va
2175  *
2176  * Remove @bo_va->bo from the requested vm.
2177  *
2178  * Object have to be reserved!
2179  */
2180 void amdgpu_vm_bo_del(struct amdgpu_device *adev,
2181 		      struct amdgpu_bo_va *bo_va)
2182 {
2183 	struct amdgpu_bo_va_mapping *mapping, *next;
2184 	struct amdgpu_bo *bo = bo_va->base.bo;
2185 	struct amdgpu_vm *vm = bo_va->base.vm;
2186 	struct amdgpu_vm_bo_base **base;
2187 
2188 	dma_resv_assert_held(vm->root.bo->tbo.base.resv);
2189 
2190 	if (bo) {
2191 		dma_resv_assert_held(bo->tbo.base.resv);
2192 		if (amdgpu_vm_is_bo_always_valid(vm, bo))
2193 			ttm_bo_set_bulk_move(&bo->tbo, NULL);
2194 
2195 		for (base = &bo_va->base.bo->vm_bo; *base;
2196 		     base = &(*base)->next) {
2197 			if (*base != &bo_va->base)
2198 				continue;
2199 
2200 			amdgpu_vm_update_stats(*base, bo->tbo.resource, -1);
2201 			*base = bo_va->base.next;
2202 			break;
2203 		}
2204 	}
2205 
2206 	spin_lock(&vm->individual_lock);
2207 	list_del(&bo_va->base.vm_status);
2208 	spin_unlock(&vm->individual_lock);
2209 
2210 	list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
2211 		list_del(&mapping->list);
2212 		amdgpu_vm_it_remove(mapping, &vm->va);
2213 		mapping->bo_va = NULL;
2214 		trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2215 		list_add(&mapping->list, &vm->freed);
2216 	}
2217 	list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
2218 		list_del(&mapping->list);
2219 		amdgpu_vm_it_remove(mapping, &vm->va);
2220 		amdgpu_vm_free_mapping(adev, vm, mapping,
2221 				       bo_va->last_pt_update);
2222 	}
2223 
2224 	dma_fence_put(bo_va->last_pt_update);
2225 
2226 	if (bo && bo_va->is_xgmi)
2227 		amdgpu_xgmi_set_pstate(adev, AMDGPU_XGMI_PSTATE_MIN);
2228 
2229 	kfree(bo_va);
2230 }
2231 
2232 /**
2233  * amdgpu_vm_evictable - check if we can evict a VM
2234  *
2235  * @bo: A page table of the VM.
2236  *
2237  * Check if it is possible to evict a VM.
2238  */
2239 bool amdgpu_vm_evictable(struct amdgpu_bo *bo)
2240 {
2241 	struct amdgpu_vm_bo_base *bo_base = bo->vm_bo;
2242 
2243 	/* Page tables of a destroyed VM can go away immediately */
2244 	if (!bo_base || !bo_base->vm)
2245 		return true;
2246 
2247 	/* Don't evict VM page tables while they are busy */
2248 	if (!dma_resv_test_signaled(bo->tbo.base.resv, DMA_RESV_USAGE_BOOKKEEP))
2249 		return false;
2250 
2251 	/* Try to block ongoing updates */
2252 	if (!amdgpu_vm_eviction_trylock(bo_base->vm))
2253 		return false;
2254 
2255 	/* Don't evict VM page tables while they are updated */
2256 	if (!dma_fence_is_signaled(bo_base->vm->last_unlocked)) {
2257 		amdgpu_vm_eviction_unlock(bo_base->vm);
2258 		return false;
2259 	}
2260 
2261 	bo_base->vm->evicting = true;
2262 	amdgpu_vm_eviction_unlock(bo_base->vm);
2263 	return true;
2264 }
2265 
2266 /**
2267  * amdgpu_vm_bo_invalidate - mark the bo as invalid
2268  *
2269  * @bo: amdgpu buffer object
2270  * @evicted: is the BO evicted
2271  *
2272  * Mark @bo as invalid.
2273  */
2274 void amdgpu_vm_bo_invalidate(struct amdgpu_bo *bo, bool evicted)
2275 {
2276 	struct amdgpu_vm_bo_base *bo_base;
2277 
2278 	for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
2279 		struct amdgpu_vm *vm = bo_base->vm;
2280 
2281 		if (evicted && amdgpu_vm_is_bo_always_valid(vm, bo)) {
2282 			amdgpu_vm_bo_evicted(bo_base);
2283 			continue;
2284 		}
2285 
2286 		if (bo_base->moved)
2287 			continue;
2288 		bo_base->moved = true;
2289 		amdgpu_vm_bo_needs_update(bo_base);
2290 	}
2291 }
2292 
2293 /**
2294  * amdgpu_vm_bo_move - handle BO move
2295  *
2296  * @bo: amdgpu buffer object
2297  * @new_mem: the new placement of the BO move
2298  * @evicted: is the BO evicted
2299  *
2300  * Update the memory stats for the new placement and mark @bo as invalid.
2301  */
2302 void amdgpu_vm_bo_move(struct amdgpu_bo *bo, struct ttm_resource *new_mem,
2303 		       bool evicted)
2304 {
2305 	struct amdgpu_vm_bo_base *bo_base;
2306 
2307 	for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
2308 		struct amdgpu_vm *vm = bo_base->vm;
2309 
2310 		spin_lock(&vm->stats_lock);
2311 		amdgpu_vm_update_stats_locked(bo_base, bo->tbo.resource, -1);
2312 		amdgpu_vm_update_stats_locked(bo_base, new_mem, +1);
2313 		spin_unlock(&vm->stats_lock);
2314 	}
2315 
2316 	amdgpu_vm_bo_invalidate(bo, evicted);
2317 }
2318 
2319 /**
2320  * amdgpu_vm_get_block_size - calculate VM page table size as power of two
2321  *
2322  * @vm_size: VM size
2323  *
2324  * Returns:
2325  * VM page table as power of two
2326  */
2327 static uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
2328 {
2329 	/* Total bits covered by PD + PTs */
2330 	unsigned bits = ilog2(vm_size) + 18;
2331 
2332 	/* Make sure the PD is 4K in size up to 8GB address space.
2333 	   Above that split equal between PD and PTs */
2334 	if (vm_size <= 8)
2335 		return (bits - 9);
2336 	else
2337 		return ((bits + 3) / 2);
2338 }
2339 
2340 /**
2341  * amdgpu_vm_adjust_size - adjust vm size, block size and fragment size
2342  *
2343  * @adev: amdgpu_device pointer
2344  * @min_vm_size: the minimum vm size in GB if it's set auto
2345  * @fragment_size_default: Default PTE fragment size
2346  * @max_level: max VMPT level
2347  * @max_bits: max address space size in bits
2348  *
2349  */
2350 void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint32_t min_vm_size,
2351 			   uint32_t fragment_size_default, unsigned max_level,
2352 			   unsigned max_bits)
2353 {
2354 	unsigned int max_size = 1 << (max_bits - 30);
2355 	unsigned int vm_size;
2356 	uint64_t tmp;
2357 
2358 	/* adjust vm size first */
2359 	if (amdgpu_vm_size != -1) {
2360 		vm_size = amdgpu_vm_size;
2361 		if (vm_size > max_size) {
2362 			dev_warn(adev->dev, "VM size (%d) too large, max is %u GB\n",
2363 				 amdgpu_vm_size, max_size);
2364 			vm_size = max_size;
2365 		}
2366 	} else {
2367 		struct sysinfo si;
2368 		unsigned int phys_ram_gb;
2369 
2370 		/* Optimal VM size depends on the amount of physical
2371 		 * RAM available. Underlying requirements and
2372 		 * assumptions:
2373 		 *
2374 		 *  - Need to map system memory and VRAM from all GPUs
2375 		 *     - VRAM from other GPUs not known here
2376 		 *     - Assume VRAM <= system memory
2377 		 *  - On GFX8 and older, VM space can be segmented for
2378 		 *    different MTYPEs
2379 		 *  - Need to allow room for fragmentation, guard pages etc.
2380 		 *
2381 		 * This adds up to a rough guess of system memory x3.
2382 		 * Round up to power of two to maximize the available
2383 		 * VM size with the given page table size.
2384 		 */
2385 		si_meminfo(&si);
2386 		phys_ram_gb = ((uint64_t)si.totalram * si.mem_unit +
2387 			       (1 << 30) - 1) >> 30;
2388 		vm_size = roundup_pow_of_two(
2389 			clamp(phys_ram_gb * 3, min_vm_size, max_size));
2390 	}
2391 
2392 	adev->vm_manager.max_pfn = (uint64_t)vm_size << 18;
2393 	adev->vm_manager.max_level = max_level;
2394 
2395 	tmp = roundup_pow_of_two(adev->vm_manager.max_pfn);
2396 	if (amdgpu_vm_block_size != -1)
2397 		tmp >>= amdgpu_vm_block_size - 9;
2398 	tmp = DIV_ROUND_UP(fls64(tmp) - 1, 9) - 1;
2399 	adev->vm_manager.num_level = min_t(unsigned int, max_level, tmp);
2400 	switch (adev->vm_manager.num_level) {
2401 	case 4:
2402 		adev->vm_manager.root_level = AMDGPU_VM_PDB3;
2403 		break;
2404 	case 3:
2405 		adev->vm_manager.root_level = AMDGPU_VM_PDB2;
2406 		break;
2407 	case 2:
2408 		adev->vm_manager.root_level = AMDGPU_VM_PDB1;
2409 		break;
2410 	case 1:
2411 		adev->vm_manager.root_level = AMDGPU_VM_PDB0;
2412 		break;
2413 	default:
2414 		dev_err(adev->dev, "VMPT only supports 2~4+1 levels\n");
2415 	}
2416 	/* block size depends on vm size and hw setup*/
2417 	if (amdgpu_vm_block_size != -1)
2418 		adev->vm_manager.block_size =
2419 			min((unsigned)amdgpu_vm_block_size, max_bits
2420 			    - AMDGPU_GPU_PAGE_SHIFT
2421 			    - 9 * adev->vm_manager.num_level);
2422 	else if (adev->vm_manager.num_level > 1)
2423 		adev->vm_manager.block_size = 9;
2424 	else
2425 		adev->vm_manager.block_size = amdgpu_vm_get_block_size(tmp);
2426 
2427 	if (amdgpu_vm_fragment_size == -1)
2428 		adev->vm_manager.fragment_size = fragment_size_default;
2429 	else
2430 		adev->vm_manager.fragment_size = amdgpu_vm_fragment_size;
2431 
2432 	dev_info(
2433 		adev->dev,
2434 		"vm size is %u GB, %u levels, block size is %u-bit, fragment size is %u-bit\n",
2435 		vm_size, adev->vm_manager.num_level + 1,
2436 		adev->vm_manager.block_size, adev->vm_manager.fragment_size);
2437 }
2438 
2439 /**
2440  * amdgpu_vm_wait_idle - wait for the VM to become idle
2441  *
2442  * @vm: VM object to wait for
2443  * @timeout: timeout to wait for VM to become idle
2444  */
2445 long amdgpu_vm_wait_idle(struct amdgpu_vm *vm, long timeout)
2446 {
2447 	timeout = drm_sched_entity_flush(&vm->immediate, timeout);
2448 	if (timeout <= 0)
2449 		return timeout;
2450 
2451 	return drm_sched_entity_flush(&vm->delayed, timeout);
2452 }
2453 
2454 static void amdgpu_vm_destroy_task_info(struct kref *kref)
2455 {
2456 	struct amdgpu_task_info *ti = container_of(kref, struct amdgpu_task_info, refcount);
2457 
2458 	kfree(ti);
2459 }
2460 
2461 /**
2462  * amdgpu_vm_put_task_info - reference down the vm task_info ptr
2463  *
2464  * @task_info: task_info struct under discussion.
2465  *
2466  * frees the vm task_info ptr at the last put
2467  */
2468 void amdgpu_vm_put_task_info(struct amdgpu_task_info *task_info)
2469 {
2470 	if (task_info)
2471 		kref_put(&task_info->refcount, amdgpu_vm_destroy_task_info);
2472 }
2473 
2474 /**
2475  * amdgpu_vm_get_task_info_vm - Extracts task info for a vm.
2476  *
2477  * @vm: VM to get info from
2478  *
2479  * Returns the reference counted task_info structure, which must be
2480  * referenced down with amdgpu_vm_put_task_info.
2481  */
2482 struct amdgpu_task_info *
2483 amdgpu_vm_get_task_info_vm(struct amdgpu_vm *vm)
2484 {
2485 	struct amdgpu_task_info *ti = NULL;
2486 
2487 	if (vm) {
2488 		ti = vm->task_info;
2489 		kref_get(&vm->task_info->refcount);
2490 	}
2491 
2492 	return ti;
2493 }
2494 
2495 /**
2496  * amdgpu_vm_get_task_info_pasid - Extracts task info for a PASID.
2497  *
2498  * @adev: drm device pointer
2499  * @pasid: PASID identifier for VM
2500  *
2501  * Returns the reference counted task_info structure, which must be
2502  * referenced down with amdgpu_vm_put_task_info.
2503  */
2504 struct amdgpu_task_info *
2505 amdgpu_vm_get_task_info_pasid(struct amdgpu_device *adev, u32 pasid)
2506 {
2507 	struct amdgpu_task_info *ti;
2508 	struct amdgpu_vm *vm;
2509 	unsigned long flags;
2510 
2511 	xa_lock_irqsave(&adev->vm_manager.pasids, flags);
2512 	vm = xa_load(&adev->vm_manager.pasids, pasid);
2513 	ti = amdgpu_vm_get_task_info_vm(vm);
2514 	xa_unlock_irqrestore(&adev->vm_manager.pasids, flags);
2515 
2516 	return ti;
2517 }
2518 
2519 static int amdgpu_vm_create_task_info(struct amdgpu_vm *vm)
2520 {
2521 	vm->task_info = kzalloc_obj(struct amdgpu_task_info);
2522 	if (!vm->task_info)
2523 		return -ENOMEM;
2524 
2525 	kref_init(&vm->task_info->refcount);
2526 	return 0;
2527 }
2528 
2529 /**
2530  * amdgpu_vm_set_task_info - Sets VMs task info.
2531  *
2532  * @vm: vm for which to set the info
2533  */
2534 void amdgpu_vm_set_task_info(struct amdgpu_vm *vm)
2535 {
2536 	if (!vm->task_info)
2537 		return;
2538 
2539 	if (vm->task_info->task.pid == current->pid)
2540 		return;
2541 
2542 	vm->task_info->task.pid = current->pid;
2543 	get_task_comm(vm->task_info->task.comm, current);
2544 
2545 	vm->task_info->tgid = current->tgid;
2546 	get_task_comm(vm->task_info->process_name, current->group_leader);
2547 }
2548 
2549 /**
2550  * amdgpu_vm_init - initialize a vm instance
2551  *
2552  * @adev: amdgpu_device pointer
2553  * @vm: requested vm
2554  * @xcp_id: GPU partition selection id
2555  * @pasid: the pasid the VM is using on this GPU
2556  *
2557  * Init @vm fields.
2558  *
2559  * Returns:
2560  * 0 for success, error for failure.
2561  */
2562 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm,
2563 		   int32_t xcp_id, uint32_t pasid)
2564 {
2565 	struct amdgpu_bo *root_bo;
2566 	struct amdgpu_bo_vm *root;
2567 	int r, i;
2568 
2569 	vm->va = RB_ROOT_CACHED;
2570 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2571 		vm->reserved_vmid[i] = NULL;
2572 
2573 	amdgpu_vm_bo_status_init(&vm->kernel);
2574 	amdgpu_vm_bo_status_init(&vm->always_valid);
2575 	spin_lock_init(&vm->individual_lock);
2576 	amdgpu_vm_bo_status_init(&vm->individual);
2577 	INIT_LIST_HEAD(&vm->freed);
2578 	INIT_KFIFO(vm->faults);
2579 	spin_lock_init(&vm->stats_lock);
2580 
2581 	r = amdgpu_vm_init_entities(adev, vm);
2582 	if (r)
2583 		return r;
2584 
2585 	ttm_lru_bulk_move_init(&vm->lru_bulk_move);
2586 
2587 	vm->is_compute_context = false;
2588 	vm->need_tlb_fence = amdgpu_userq_enabled(&adev->ddev);
2589 
2590 	vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2591 				    AMDGPU_VM_USE_CPU_FOR_GFX);
2592 
2593 	dev_dbg(adev->dev, "VM update mode is %s\n",
2594 		vm->use_cpu_for_update ? "CPU" : "SDMA");
2595 	WARN_ONCE((vm->use_cpu_for_update &&
2596 		   !amdgpu_gmc_vram_full_visible(&adev->gmc)),
2597 		  "CPU update of VM recommended only for large BAR system\n");
2598 
2599 	if (vm->use_cpu_for_update)
2600 		vm->update_funcs = &amdgpu_vm_cpu_funcs;
2601 	else
2602 		vm->update_funcs = &amdgpu_vm_sdma_funcs;
2603 
2604 	vm->last_update = dma_fence_get_stub();
2605 	vm->last_unlocked = dma_fence_get_stub();
2606 	vm->last_tlb_flush = dma_fence_get_stub();
2607 	vm->generation = amdgpu_vm_generation(adev, NULL);
2608 
2609 	mutex_init(&vm->eviction_lock);
2610 	vm->evicting = false;
2611 	vm->tlb_fence_context = dma_fence_context_alloc(1);
2612 
2613 	r = amdgpu_vm_pt_create(adev, vm, adev->vm_manager.root_level,
2614 				false, &root, xcp_id);
2615 	if (r)
2616 		goto error_free_delayed;
2617 
2618 	root_bo = amdgpu_bo_ref(&root->bo);
2619 	r = amdgpu_bo_reserve(root_bo, true);
2620 	if (r) {
2621 		amdgpu_bo_unref(&root_bo);
2622 		goto error_free_delayed;
2623 	}
2624 
2625 	amdgpu_vm_bo_base_init(&vm->root, vm, root_bo);
2626 	r = dma_resv_reserve_fences(root_bo->tbo.base.resv, 1);
2627 	if (r)
2628 		goto error_free_root;
2629 
2630 	r = amdgpu_vm_pt_clear(adev, vm, root, false);
2631 	if (r)
2632 		goto error_free_root;
2633 
2634 	r = amdgpu_vm_create_task_info(vm);
2635 	if (r)
2636 		dev_dbg(adev->dev, "Failed to create task info for VM\n");
2637 
2638 	/* Store new PASID in XArray (if non-zero) */
2639 	if (pasid != 0) {
2640 		r = xa_err(xa_store_irq(&adev->vm_manager.pasids, pasid, vm, GFP_KERNEL));
2641 		if (r < 0)
2642 			goto error_free_root;
2643 
2644 		vm->pasid = pasid;
2645 	}
2646 
2647 	amdgpu_bo_unreserve(vm->root.bo);
2648 	amdgpu_bo_unref(&root_bo);
2649 
2650 	return 0;
2651 
2652 error_free_root:
2653 	/* If PASID was partially set, erase it from XArray before failing */
2654 	if (vm->pasid != 0) {
2655 		xa_erase_irq(&adev->vm_manager.pasids, vm->pasid);
2656 		vm->pasid = 0;
2657 	}
2658 	amdgpu_vm_pt_free_root(adev, vm);
2659 	amdgpu_bo_unreserve(vm->root.bo);
2660 	amdgpu_bo_unref(&root_bo);
2661 
2662 error_free_delayed:
2663 	dma_fence_put(vm->last_tlb_flush);
2664 	dma_fence_put(vm->last_unlocked);
2665 	ttm_lru_bulk_move_fini(&adev->mman.bdev, &vm->lru_bulk_move);
2666 	amdgpu_vm_fini_entities(vm);
2667 
2668 	return r;
2669 }
2670 
2671 /**
2672  * amdgpu_vm_make_compute - Turn a GFX VM into a compute VM
2673  *
2674  * @adev: amdgpu_device pointer
2675  * @vm: requested vm
2676  *
2677  * This only works on GFX VMs that don't have any BOs added and no
2678  * page tables allocated yet.
2679  *
2680  * Changes the following VM parameters:
2681  * - use_cpu_for_update
2682  * - pte_supports_ats
2683  *
2684  * Reinitializes the page directory to reflect the changed ATS
2685  * setting.
2686  *
2687  * Returns:
2688  * 0 for success, -errno for errors.
2689  */
2690 int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2691 {
2692 	int r;
2693 
2694 	r = amdgpu_bo_reserve(vm->root.bo, true);
2695 	if (r)
2696 		return r;
2697 
2698 	/* Update VM state */
2699 	vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2700 				    AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2701 	dev_dbg(adev->dev, "VM update mode is %s\n",
2702 		vm->use_cpu_for_update ? "CPU" : "SDMA");
2703 	WARN_ONCE((vm->use_cpu_for_update &&
2704 		   !amdgpu_gmc_vram_full_visible(&adev->gmc)),
2705 		  "CPU update of VM recommended only for large BAR system\n");
2706 
2707 	if (vm->use_cpu_for_update) {
2708 		/* Sync with last SDMA update/clear before switching to CPU */
2709 		r = amdgpu_bo_sync_wait(vm->root.bo,
2710 					AMDGPU_FENCE_OWNER_UNDEFINED, true);
2711 		if (r)
2712 			goto unreserve_bo;
2713 
2714 		vm->update_funcs = &amdgpu_vm_cpu_funcs;
2715 		r = amdgpu_vm_pt_map_tables(adev, vm);
2716 		if (r)
2717 			goto unreserve_bo;
2718 
2719 	} else {
2720 		vm->update_funcs = &amdgpu_vm_sdma_funcs;
2721 	}
2722 
2723 	dma_fence_put(vm->last_update);
2724 	vm->last_update = dma_fence_get_stub();
2725 	vm->is_compute_context = true;
2726 	vm->need_tlb_fence = true;
2727 
2728 unreserve_bo:
2729 	amdgpu_bo_unreserve(vm->root.bo);
2730 	return r;
2731 }
2732 
2733 static int amdgpu_vm_stats_is_zero(struct amdgpu_vm *vm)
2734 {
2735 	for (int i = 0; i < __AMDGPU_PL_NUM; ++i) {
2736 		if (!(drm_memory_stats_is_zero(&vm->stats[i].drm) &&
2737 		      vm->stats[i].evicted == 0))
2738 			return false;
2739 	}
2740 	return true;
2741 }
2742 
2743 /**
2744  * amdgpu_vm_fini - tear down a vm instance
2745  *
2746  * @adev: amdgpu_device pointer
2747  * @vm: requested vm
2748  *
2749  * Tear down @vm.
2750  * Unbind the VM and remove all bos from the vm bo list
2751  */
2752 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2753 {
2754 	struct amdgpu_bo_va_mapping *mapping, *tmp;
2755 	bool prt_fini_needed = !!adev->gmc.gmc_funcs->set_prt;
2756 	struct amdgpu_bo *root;
2757 	unsigned long flags;
2758 	int i;
2759 
2760 	amdgpu_amdkfd_gpuvm_destroy_cb(adev, vm);
2761 
2762 	root = amdgpu_bo_ref(vm->root.bo);
2763 	amdgpu_bo_reserve(root, true);
2764 	/* Remove PASID mapping before destroying VM */
2765 	if (vm->pasid != 0) {
2766 		xa_erase_irq(&adev->vm_manager.pasids, vm->pasid);
2767 		vm->pasid = 0;
2768 	}
2769 	dma_fence_wait(vm->last_unlocked, false);
2770 	dma_fence_put(vm->last_unlocked);
2771 	dma_fence_wait(vm->last_tlb_flush, false);
2772 	/* Make sure that all fence callbacks have completed */
2773 	dma_fence_lock_irqsave(vm->last_tlb_flush, flags);
2774 	dma_fence_unlock_irqrestore(vm->last_tlb_flush, flags);
2775 	dma_fence_put(vm->last_tlb_flush);
2776 
2777 	list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
2778 		if (mapping->flags & AMDGPU_VM_PAGE_PRT && prt_fini_needed) {
2779 			amdgpu_vm_prt_fini(adev, vm);
2780 			prt_fini_needed = false;
2781 		}
2782 
2783 		list_del(&mapping->list);
2784 		amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
2785 	}
2786 
2787 	amdgpu_vm_pt_free_root(adev, vm);
2788 	amdgpu_bo_unreserve(root);
2789 	amdgpu_bo_unref(&root);
2790 	WARN_ON(vm->root.bo);
2791 
2792 	amdgpu_vm_fini_entities(vm);
2793 
2794 	if (!RB_EMPTY_ROOT(&vm->va.rb_root)) {
2795 		dev_err(adev->dev, "still active bo inside vm\n");
2796 	}
2797 	rbtree_postorder_for_each_entry_safe(mapping, tmp,
2798 					     &vm->va.rb_root, rb) {
2799 		/* Don't remove the mapping here, we don't want to trigger a
2800 		 * rebalance and the tree is about to be destroyed anyway.
2801 		 */
2802 		list_del(&mapping->list);
2803 		kfree(mapping);
2804 	}
2805 
2806 	dma_fence_put(vm->last_update);
2807 
2808 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++) {
2809 		amdgpu_vmid_free_reserved(adev, vm, i);
2810 	}
2811 
2812 	ttm_lru_bulk_move_fini(&adev->mman.bdev, &vm->lru_bulk_move);
2813 
2814 	if (!amdgpu_vm_stats_is_zero(vm)) {
2815 		struct amdgpu_task_info *ti = vm->task_info;
2816 
2817 		dev_warn(adev->dev,
2818 			 "VM memory stats for proc %s(%d) task %s(%d) is non-zero when fini\n",
2819 			 ti->process_name, ti->task.pid, ti->task.comm, ti->tgid);
2820 	}
2821 
2822 	amdgpu_vm_put_task_info(vm->task_info);
2823 }
2824 
2825 /**
2826  * amdgpu_vm_manager_init - init the VM manager
2827  *
2828  * @adev: amdgpu_device pointer
2829  *
2830  * Initialize the VM manager structures
2831  */
2832 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
2833 {
2834 	/* Concurrent flushes are only possible starting with Vega10 and
2835 	 * are broken on Navi10 and Navi14.
2836 	 */
2837 	adev->vm_manager.concurrent_flush = !(adev->asic_type < CHIP_VEGA10 ||
2838 					      adev->asic_type == CHIP_NAVI10 ||
2839 					      adev->asic_type == CHIP_NAVI14);
2840 	amdgpu_vmid_mgr_init(adev);
2841 
2842 	spin_lock_init(&adev->vm_manager.prt_lock);
2843 	atomic_set(&adev->vm_manager.num_prt_users, 0);
2844 
2845 	/* If not overridden by the user, by default, only in large BAR systems
2846 	 * Compute VM tables will be updated by CPU
2847 	 */
2848 #ifdef CONFIG_X86_64
2849 	if (amdgpu_vm_update_mode == -1) {
2850 		/* For asic with VF MMIO access protection
2851 		 * avoid using CPU for VM table updates
2852 		 */
2853 		if (amdgpu_gmc_vram_full_visible(&adev->gmc) &&
2854 		    !amdgpu_sriov_vf_mmio_access_protection(adev))
2855 			adev->vm_manager.vm_update_mode =
2856 				AMDGPU_VM_USE_CPU_FOR_COMPUTE;
2857 		else
2858 			adev->vm_manager.vm_update_mode = 0;
2859 	} else
2860 		adev->vm_manager.vm_update_mode = amdgpu_vm_update_mode;
2861 #else
2862 	adev->vm_manager.vm_update_mode = 0;
2863 #endif
2864 
2865 	xa_init_flags(&adev->vm_manager.pasids, XA_FLAGS_LOCK_IRQ);
2866 }
2867 
2868 /**
2869  * amdgpu_vm_manager_fini - cleanup VM manager
2870  *
2871  * @adev: amdgpu_device pointer
2872  *
2873  * Cleanup the VM manager and free resources.
2874  */
2875 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
2876 {
2877 	WARN_ON(!xa_empty(&adev->vm_manager.pasids));
2878 	xa_destroy(&adev->vm_manager.pasids);
2879 
2880 	amdgpu_vmid_mgr_fini(adev);
2881 	amdgpu_pasid_mgr_cleanup();
2882 }
2883 
2884 /**
2885  * amdgpu_vm_ioctl - Manages VMID reservation for vm hubs.
2886  *
2887  * @dev: drm device pointer
2888  * @data: drm_amdgpu_vm
2889  * @filp: drm file pointer
2890  *
2891  * Returns:
2892  * 0 for success, -errno for errors.
2893  */
2894 int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
2895 {
2896 	union drm_amdgpu_vm *args = data;
2897 	struct amdgpu_device *adev = drm_to_adev(dev);
2898 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
2899 	struct amdgpu_vm *vm = &fpriv->vm;
2900 
2901 	/* No valid flags defined yet */
2902 	if (args->in.flags)
2903 		return -EINVAL;
2904 
2905 	switch (args->in.op) {
2906 	case AMDGPU_VM_OP_RESERVE_VMID:
2907 		/* We only have requirement to reserve vmid from gfxhub */
2908 		return amdgpu_vmid_alloc_reserved(adev, vm, AMDGPU_GFXHUB(0));
2909 	case AMDGPU_VM_OP_UNRESERVE_VMID:
2910 		amdgpu_vmid_free_reserved(adev, vm, AMDGPU_GFXHUB(0));
2911 		break;
2912 	default:
2913 		return -EINVAL;
2914 	}
2915 
2916 	return 0;
2917 }
2918 
2919 /**
2920  * amdgpu_vm_lock_by_pasid - look up a VM by PASID and lock its root PD
2921  * @adev: amdgpu device pointer
2922  * @pasid: PASID of the VM
2923  * @exec: drm_exec context to lock the root PD in
2924  *
2925  * Must be called from within a drm_exec_until_all_locked() loop; the caller
2926  * runs drm_exec_retry_on_contention() afterwards. The drm_exec context holds
2927  * a reference on the root BO until it is finalised.
2928  *
2929  * Return: the VM on success, or NULL if the PASID has no VM, the VM is being
2930  * torn down, or locking the root PD failed.
2931  */
2932 struct amdgpu_vm *amdgpu_vm_lock_by_pasid(struct amdgpu_device *adev,
2933 					  u32 pasid, struct drm_exec *exec)
2934 {
2935 	unsigned long irqflags;
2936 	struct amdgpu_bo *root;
2937 	struct amdgpu_vm *vm;
2938 	int r;
2939 
2940 	xa_lock_irqsave(&adev->vm_manager.pasids, irqflags);
2941 	vm = xa_load(&adev->vm_manager.pasids, pasid);
2942 	root = vm ? amdgpu_bo_ref(vm->root.bo) : NULL;
2943 	xa_unlock_irqrestore(&adev->vm_manager.pasids, irqflags);
2944 
2945 	if (!root)
2946 		return NULL;
2947 
2948 	r = drm_exec_lock_obj(exec, &root->tbo.base);
2949 	if (r) {
2950 		amdgpu_bo_unref(&root);
2951 		return NULL;
2952 	}
2953 
2954 	/* Double check that the VM still exists */
2955 	xa_lock_irqsave(&adev->vm_manager.pasids, irqflags);
2956 	vm = xa_load(&adev->vm_manager.pasids, pasid);
2957 	if (vm && vm->root.bo != root)
2958 		vm = NULL;
2959 	xa_unlock_irqrestore(&adev->vm_manager.pasids, irqflags);
2960 	if (!vm) {
2961 		drm_exec_unlock_obj(exec, &root->tbo.base);
2962 		amdgpu_bo_unref(&root);
2963 		return NULL;
2964 	}
2965 
2966 	/* The drm_exec context holds its own reference on the root BO. */
2967 	amdgpu_bo_unref(&root);
2968 
2969 	return vm;
2970 }
2971 
2972 /**
2973  * amdgpu_vm_handle_fault - graceful handling of VM faults.
2974  * @adev: amdgpu device pointer
2975  * @pasid: PASID of the VM
2976  * @ts: Timestamp of the fault
2977  * @vmid: VMID, only used for GFX 9.4.3.
2978  * @node_id: Node_id received in IH cookie. Only applicable for
2979  *           GFX 9.4.3.
2980  * @addr: Address of the fault
2981  * @write_fault: true is write fault, false is read fault
2982  *
2983  * Try to gracefully handle a VM fault. Return true if the fault was handled and
2984  * shouldn't be reported any more.
2985  */
2986 bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid,
2987 			    u32 vmid, u32 node_id, uint64_t addr,
2988 			    uint64_t ts, bool write_fault)
2989 {
2990 	bool is_compute_context = false;
2991 	struct drm_exec exec;
2992 	uint64_t value, flags;
2993 	struct amdgpu_vm *vm;
2994 	int r;
2995 
2996 	drm_exec_init(&exec, 0, 1);
2997 	drm_exec_until_all_locked(&exec) {
2998 		vm = amdgpu_vm_lock_by_pasid(adev, pasid, &exec);
2999 		drm_exec_retry_on_contention(&exec);
3000 		if (!vm)
3001 			break;
3002 	}
3003 	if (!vm) {
3004 		drm_exec_fini(&exec);
3005 		return false;
3006 	}
3007 
3008 	is_compute_context = vm->is_compute_context;
3009 
3010 	if (is_compute_context) {
3011 		__label__ drm_exec_retry;
3012 
3013 		/* Release the root PD lock since svm_range_restore_pages
3014 		 * might try to take it.
3015 		 * TODO: rework svm_range_restore_pages so that this isn't
3016 		 * necessary.
3017 		 */
3018 		drm_exec_fini(&exec);
3019 
3020 		if (!svm_range_restore_pages(adev, pasid, vmid,
3021 					     node_id, addr >> PAGE_SHIFT, ts, write_fault))
3022 			return true;
3023 
3024 		/* Re-acquire the VM lock, could be that the VM was freed in between. */
3025 		drm_exec_init(&exec, 0, 1);
3026 		drm_exec_until_all_locked(&exec) {
3027 			vm = amdgpu_vm_lock_by_pasid(adev, pasid, &exec);
3028 			drm_exec_retry_on_contention(&exec);
3029 			if (!vm)
3030 				break;
3031 		}
3032 		if (!vm) {
3033 			drm_exec_fini(&exec);
3034 			return false;
3035 		}
3036 	}
3037 
3038 	addr /= AMDGPU_GPU_PAGE_SIZE;
3039 	flags = AMDGPU_PTE_VALID | AMDGPU_PTE_SNOOPED |
3040 		AMDGPU_PTE_SYSTEM;
3041 
3042 	if (is_compute_context) {
3043 		/* Intentionally setting invalid PTE flag
3044 		 * combination to force a no-retry-fault
3045 		 */
3046 		flags = AMDGPU_VM_NORETRY_FLAGS;
3047 		value = 0;
3048 	} else if (amdgpu_vm_fault_stop == AMDGPU_VM_FAULT_STOP_NEVER) {
3049 		/* Redirect the access to the dummy page */
3050 		value = adev->dummy_page_addr;
3051 		flags |= AMDGPU_PTE_EXECUTABLE | AMDGPU_PTE_READABLE |
3052 			AMDGPU_PTE_WRITEABLE;
3053 
3054 	} else {
3055 		/* Let the hw retry silently on the PTE */
3056 		value = 0;
3057 	}
3058 
3059 	r = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, 1);
3060 	if (r) {
3061 		pr_debug("failed %d to reserve fence slot\n", r);
3062 		goto error_unlock;
3063 	}
3064 
3065 	r = amdgpu_vm_update_range(adev, vm, true, false, false, false,
3066 				   NULL, addr, addr, flags, value, 0, NULL, NULL, NULL);
3067 	if (r)
3068 		goto error_unlock;
3069 
3070 	r = amdgpu_vm_update_pdes(adev, vm, true);
3071 
3072 error_unlock:
3073 	drm_exec_fini(&exec);
3074 	if (r < 0)
3075 		dev_err(adev->dev, "Can't handle page fault (%d)\n", r);
3076 
3077 	return false;
3078 }
3079 
3080 #if defined(CONFIG_DEBUG_FS)
3081 
3082 /* print the debug info for a specific set of status lists */
3083 static void amdgpu_debugfs_vm_bo_status_info(struct seq_file *m,
3084 					     struct amdgpu_vm_bo_status *lists)
3085 {
3086 	struct amdgpu_vm_bo_base *base;
3087 	unsigned int id;
3088 
3089 	id = 0;
3090 	seq_puts(m, "\tEvicted BOs:\n");
3091 	list_for_each_entry(base, &lists->evicted, vm_status) {
3092 		if (!base->bo)
3093 			continue;
3094 
3095 		amdgpu_bo_print_info(id++, base->bo, m);
3096 	}
3097 
3098 	id = 0;
3099 	seq_puts(m, "\tMoved BOs:\n");
3100 	list_for_each_entry(base, &lists->needs_update, vm_status) {
3101 		if (!base->bo)
3102 			continue;
3103 
3104 		amdgpu_bo_print_info(id++, base->bo, m);
3105 	}
3106 
3107 	id = 0;
3108 	seq_puts(m, "\tIdle BOs:\n");
3109 	list_for_each_entry(base, &lists->needs_update, vm_status) {
3110 		if (!base->bo)
3111 			continue;
3112 
3113 		amdgpu_bo_print_info(id++, base->bo, m);
3114 	}
3115 }
3116 
3117 /**
3118  * amdgpu_debugfs_vm_bo_info  - print BO info for the VM
3119  *
3120  * @vm: Requested VM for printing BO info
3121  * @m: debugfs file
3122  *
3123  * Print BO information in debugfs file for the VM
3124  */
3125 void amdgpu_debugfs_vm_bo_info(struct amdgpu_vm *vm, struct seq_file *m)
3126 {
3127 	amdgpu_vm_assert_locked(vm);
3128 
3129 	seq_puts(m, "\tKernel PT/PDs:\n");
3130 	amdgpu_debugfs_vm_bo_status_info(m, &vm->kernel);
3131 
3132 	seq_puts(m, "\tPer VM BOs:\n");
3133 	amdgpu_debugfs_vm_bo_status_info(m, &vm->always_valid);
3134 
3135 	seq_puts(m, "\tIndividual BOs:\n");
3136 	spin_lock(&vm->individual_lock);
3137 	amdgpu_debugfs_vm_bo_status_info(m, &vm->individual);
3138 	spin_unlock(&vm->individual_lock);
3139 }
3140 #endif
3141 
3142 /**
3143  * amdgpu_vm_update_fault_cache - update cached fault into.
3144  * @adev: amdgpu device pointer
3145  * @pasid: PASID of the VM
3146  * @addr: Address of the fault
3147  * @status: GPUVM fault status register
3148  * @vmhub: which vmhub got the fault
3149  *
3150  * Cache the fault info for later use by userspace in debugging.
3151  */
3152 void amdgpu_vm_update_fault_cache(struct amdgpu_device *adev,
3153 				  unsigned int pasid,
3154 				  uint64_t addr,
3155 				  uint32_t status,
3156 				  unsigned int vmhub)
3157 {
3158 	struct amdgpu_vm *vm;
3159 	unsigned long flags;
3160 
3161 	xa_lock_irqsave(&adev->vm_manager.pasids, flags);
3162 
3163 	vm = xa_load(&adev->vm_manager.pasids, pasid);
3164 	/* Don't update the fault cache if status is 0.  In the multiple
3165 	 * fault case, subsequent faults will return a 0 status which is
3166 	 * useless for userspace and replaces the useful fault status, so
3167 	 * only update if status is non-0.
3168 	 */
3169 	if (vm && status) {
3170 		vm->fault_info.addr = addr;
3171 		vm->fault_info.status = status;
3172 		/*
3173 		 * Update the fault information globally for later usage
3174 		 * when vm could be stale or freed.
3175 		 */
3176 		adev->vm_manager.fault_info.addr = addr;
3177 		adev->vm_manager.fault_info.vmhub = vmhub;
3178 		adev->vm_manager.fault_info.status = status;
3179 
3180 		if (AMDGPU_IS_GFXHUB(vmhub)) {
3181 			vm->fault_info.vmhub = AMDGPU_VMHUB_TYPE_GFX;
3182 			vm->fault_info.vmhub |=
3183 				(vmhub - AMDGPU_GFXHUB_START) << AMDGPU_VMHUB_IDX_SHIFT;
3184 		} else if (AMDGPU_IS_MMHUB0(vmhub)) {
3185 			vm->fault_info.vmhub = AMDGPU_VMHUB_TYPE_MM0;
3186 			vm->fault_info.vmhub |=
3187 				(vmhub - AMDGPU_MMHUB0_START) << AMDGPU_VMHUB_IDX_SHIFT;
3188 		} else if (AMDGPU_IS_MMHUB1(vmhub)) {
3189 			vm->fault_info.vmhub = AMDGPU_VMHUB_TYPE_MM1;
3190 			vm->fault_info.vmhub |=
3191 				(vmhub - AMDGPU_MMHUB1_START) << AMDGPU_VMHUB_IDX_SHIFT;
3192 		} else {
3193 			WARN_ONCE(1, "Invalid vmhub %u\n", vmhub);
3194 		}
3195 	}
3196 	xa_unlock_irqrestore(&adev->vm_manager.pasids, flags);
3197 }
3198 
3199 void amdgpu_vm_print_task_info(struct amdgpu_device *adev,
3200 			       struct amdgpu_task_info *task_info)
3201 {
3202 	dev_err(adev->dev,
3203 		" Process %s pid %d thread %s pid %d\n",
3204 		task_info->process_name, task_info->tgid,
3205 		task_info->task.comm, task_info->task.pid);
3206 }
3207 
3208 void amdgpu_sdma_set_vm_pte_scheds(struct amdgpu_device *adev,
3209 				   const struct amdgpu_vm_pte_funcs *vm_pte_funcs)
3210 {
3211 	struct drm_gpu_scheduler *sched;
3212 	int i;
3213 
3214 	for (i = 0; i < adev->sdma.num_instances; i++) {
3215 		if (adev->sdma.has_page_queue)
3216 			sched = &adev->sdma.instance[i].page.sched;
3217 		else
3218 			sched = &adev->sdma.instance[i].ring.sched;
3219 		adev->vm_manager.vm_pte_scheds[i] = sched;
3220 	}
3221 	adev->vm_manager.vm_pte_num_scheds = adev->sdma.num_instances;
3222 	adev->vm_manager.vm_pte_funcs = vm_pte_funcs;
3223 }
3224