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