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