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