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 "amdgpu.h"
38 #include "amdgpu_trace.h"
39 #include "amdgpu_amdkfd.h"
40 #include "amdgpu_gmc.h"
41 #include "amdgpu_xgmi.h"
42 #include "amdgpu_dma_buf.h"
43 #include "amdgpu_res_cursor.h"
44 #include "kfd_svm.h"
45 
46 /**
47  * DOC: GPUVM
48  *
49  * GPUVM is similar to the legacy gart on older asics, however
50  * rather than there being a single global gart table
51  * for the entire GPU, there are multiple VM page tables active
52  * at any given time.  The VM page tables can contain a mix
53  * vram pages and system memory pages and system memory pages
54  * can be mapped as snooped (cached system pages) or unsnooped
55  * (uncached system pages).
56  * Each VM has an ID associated with it and there is a page table
57  * associated with each VMID.  When executing a command buffer,
58  * the kernel tells the ring what VMID to use for that command
59  * buffer.  VMIDs are allocated dynamically as commands are submitted.
60  * The userspace drivers maintain their own address space and the kernel
61  * sets up their pages tables accordingly when they submit their
62  * command buffers and a VMID is assigned.
63  * Cayman/Trinity support up to 8 active VMs at any given time;
64  * SI supports 16.
65  */
66 
67 #define START(node) ((node)->start)
68 #define LAST(node) ((node)->last)
69 
70 INTERVAL_TREE_DEFINE(struct amdgpu_bo_va_mapping, rb, uint64_t, __subtree_last,
71 		     START, LAST, static, amdgpu_vm_it)
72 
73 #undef START
74 #undef LAST
75 
76 /**
77  * struct amdgpu_prt_cb - Helper to disable partial resident texture feature from a fence callback
78  */
79 struct amdgpu_prt_cb {
80 
81 	/**
82 	 * @adev: amdgpu device
83 	 */
84 	struct amdgpu_device *adev;
85 
86 	/**
87 	 * @cb: callback
88 	 */
89 	struct dma_fence_cb cb;
90 };
91 
92 /**
93  * struct amdgpu_vm_tlb_seq_cb - Helper to increment the TLB flush sequence
94  */
95 struct amdgpu_vm_tlb_seq_cb {
96 	/**
97 	 * @vm: pointer to the amdgpu_vm structure to set the fence sequence on
98 	 */
99 	struct amdgpu_vm *vm;
100 
101 	/**
102 	 * @cb: callback
103 	 */
104 	struct dma_fence_cb cb;
105 };
106 
107 /**
108  * amdgpu_vm_set_pasid - manage pasid and vm ptr mapping
109  *
110  * @adev: amdgpu_device pointer
111  * @vm: amdgpu_vm pointer
112  * @pasid: the pasid the VM is using on this GPU
113  *
114  * Set the pasid this VM is using on this GPU, can also be used to remove the
115  * pasid by passing in zero.
116  *
117  */
118 int amdgpu_vm_set_pasid(struct amdgpu_device *adev, struct amdgpu_vm *vm,
119 			u32 pasid)
120 {
121 	int r;
122 
123 	if (vm->pasid == pasid)
124 		return 0;
125 
126 	if (vm->pasid) {
127 		r = xa_err(xa_erase_irq(&adev->vm_manager.pasids, vm->pasid));
128 		if (r < 0)
129 			return r;
130 
131 		vm->pasid = 0;
132 	}
133 
134 	if (pasid) {
135 		r = xa_err(xa_store_irq(&adev->vm_manager.pasids, pasid, vm,
136 					GFP_KERNEL));
137 		if (r < 0)
138 			return r;
139 
140 		vm->pasid = pasid;
141 	}
142 
143 
144 	return 0;
145 }
146 
147 /**
148  * amdgpu_vm_bo_evicted - vm_bo is evicted
149  *
150  * @vm_bo: vm_bo which is evicted
151  *
152  * State for PDs/PTs and per VM BOs which are not at the location they should
153  * be.
154  */
155 static void amdgpu_vm_bo_evicted(struct amdgpu_vm_bo_base *vm_bo)
156 {
157 	struct amdgpu_vm *vm = vm_bo->vm;
158 	struct amdgpu_bo *bo = vm_bo->bo;
159 
160 	vm_bo->moved = true;
161 	spin_lock(&vm_bo->vm->status_lock);
162 	if (bo->tbo.type == ttm_bo_type_kernel)
163 		list_move(&vm_bo->vm_status, &vm->evicted);
164 	else
165 		list_move_tail(&vm_bo->vm_status, &vm->evicted);
166 	spin_unlock(&vm_bo->vm->status_lock);
167 }
168 /**
169  * amdgpu_vm_bo_moved - vm_bo is moved
170  *
171  * @vm_bo: vm_bo which is moved
172  *
173  * State for per VM BOs which are moved, but that change is not yet reflected
174  * in the page tables.
175  */
176 static void amdgpu_vm_bo_moved(struct amdgpu_vm_bo_base *vm_bo)
177 {
178 	spin_lock(&vm_bo->vm->status_lock);
179 	list_move(&vm_bo->vm_status, &vm_bo->vm->moved);
180 	spin_unlock(&vm_bo->vm->status_lock);
181 }
182 
183 /**
184  * amdgpu_vm_bo_idle - vm_bo is idle
185  *
186  * @vm_bo: vm_bo which is now idle
187  *
188  * State for PDs/PTs and per VM BOs which have gone through the state machine
189  * and are now idle.
190  */
191 static void amdgpu_vm_bo_idle(struct amdgpu_vm_bo_base *vm_bo)
192 {
193 	spin_lock(&vm_bo->vm->status_lock);
194 	list_move(&vm_bo->vm_status, &vm_bo->vm->idle);
195 	spin_unlock(&vm_bo->vm->status_lock);
196 	vm_bo->moved = false;
197 }
198 
199 /**
200  * amdgpu_vm_bo_invalidated - vm_bo is invalidated
201  *
202  * @vm_bo: vm_bo which is now invalidated
203  *
204  * State for normal BOs which are invalidated and that change not yet reflected
205  * in the PTs.
206  */
207 static void amdgpu_vm_bo_invalidated(struct amdgpu_vm_bo_base *vm_bo)
208 {
209 	spin_lock(&vm_bo->vm->status_lock);
210 	list_move(&vm_bo->vm_status, &vm_bo->vm->invalidated);
211 	spin_unlock(&vm_bo->vm->status_lock);
212 }
213 
214 /**
215  * amdgpu_vm_bo_relocated - vm_bo is reloacted
216  *
217  * @vm_bo: vm_bo which is relocated
218  *
219  * State for PDs/PTs which needs to update their parent PD.
220  * For the root PD, just move to idle state.
221  */
222 static void amdgpu_vm_bo_relocated(struct amdgpu_vm_bo_base *vm_bo)
223 {
224 	if (vm_bo->bo->parent) {
225 		spin_lock(&vm_bo->vm->status_lock);
226 		list_move(&vm_bo->vm_status, &vm_bo->vm->relocated);
227 		spin_unlock(&vm_bo->vm->status_lock);
228 	} else {
229 		amdgpu_vm_bo_idle(vm_bo);
230 	}
231 }
232 
233 /**
234  * amdgpu_vm_bo_done - vm_bo is done
235  *
236  * @vm_bo: vm_bo which is now done
237  *
238  * State for normal BOs which are invalidated and that change has been updated
239  * in the PTs.
240  */
241 static void amdgpu_vm_bo_done(struct amdgpu_vm_bo_base *vm_bo)
242 {
243 	spin_lock(&vm_bo->vm->status_lock);
244 	list_move(&vm_bo->vm_status, &vm_bo->vm->done);
245 	spin_unlock(&vm_bo->vm->status_lock);
246 }
247 
248 /**
249  * amdgpu_vm_bo_base_init - Adds bo to the list of bos associated with the vm
250  *
251  * @base: base structure for tracking BO usage in a VM
252  * @vm: vm to which bo is to be added
253  * @bo: amdgpu buffer object
254  *
255  * Initialize a bo_va_base structure and add it to the appropriate lists
256  *
257  */
258 void amdgpu_vm_bo_base_init(struct amdgpu_vm_bo_base *base,
259 			    struct amdgpu_vm *vm, struct amdgpu_bo *bo)
260 {
261 	base->vm = vm;
262 	base->bo = bo;
263 	base->next = NULL;
264 	INIT_LIST_HEAD(&base->vm_status);
265 
266 	if (!bo)
267 		return;
268 	base->next = bo->vm_bo;
269 	bo->vm_bo = base;
270 
271 	if (bo->tbo.base.resv != vm->root.bo->tbo.base.resv)
272 		return;
273 
274 	dma_resv_assert_held(vm->root.bo->tbo.base.resv);
275 
276 	ttm_bo_set_bulk_move(&bo->tbo, &vm->lru_bulk_move);
277 	if (bo->tbo.type == ttm_bo_type_kernel && bo->parent)
278 		amdgpu_vm_bo_relocated(base);
279 	else
280 		amdgpu_vm_bo_idle(base);
281 
282 	if (bo->preferred_domains &
283 	    amdgpu_mem_type_to_domain(bo->tbo.resource->mem_type))
284 		return;
285 
286 	/*
287 	 * we checked all the prerequisites, but it looks like this per vm bo
288 	 * is currently evicted. add the bo to the evicted list to make sure it
289 	 * is validated on next vm use to avoid fault.
290 	 * */
291 	amdgpu_vm_bo_evicted(base);
292 }
293 
294 /**
295  * amdgpu_vm_get_pd_bo - add the VM PD to a validation list
296  *
297  * @vm: vm providing the BOs
298  * @validated: head of validation list
299  * @entry: entry to add
300  *
301  * Add the page directory to the list of BOs to
302  * validate for command submission.
303  */
304 void amdgpu_vm_get_pd_bo(struct amdgpu_vm *vm,
305 			 struct list_head *validated,
306 			 struct amdgpu_bo_list_entry *entry)
307 {
308 	entry->priority = 0;
309 	entry->tv.bo = &vm->root.bo->tbo;
310 	/* Two for VM updates, one for TTM and one for the CS job */
311 	entry->tv.num_shared = 4;
312 	entry->user_pages = NULL;
313 	list_add(&entry->tv.head, validated);
314 }
315 
316 /**
317  * amdgpu_vm_move_to_lru_tail - move all BOs to the end of LRU
318  *
319  * @adev: amdgpu device pointer
320  * @vm: vm providing the BOs
321  *
322  * Move all BOs to the end of LRU and remember their positions to put them
323  * together.
324  */
325 void amdgpu_vm_move_to_lru_tail(struct amdgpu_device *adev,
326 				struct amdgpu_vm *vm)
327 {
328 	spin_lock(&adev->mman.bdev.lru_lock);
329 	ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
330 	spin_unlock(&adev->mman.bdev.lru_lock);
331 }
332 
333 /**
334  * amdgpu_vm_validate_pt_bos - validate the page table BOs
335  *
336  * @adev: amdgpu device pointer
337  * @vm: vm providing the BOs
338  * @validate: callback to do the validation
339  * @param: parameter for the validation callback
340  *
341  * Validate the page table BOs on command submission if neccessary.
342  *
343  * Returns:
344  * Validation result.
345  */
346 int amdgpu_vm_validate_pt_bos(struct amdgpu_device *adev, struct amdgpu_vm *vm,
347 			      int (*validate)(void *p, struct amdgpu_bo *bo),
348 			      void *param)
349 {
350 	struct amdgpu_vm_bo_base *bo_base;
351 	struct amdgpu_bo *shadow;
352 	struct amdgpu_bo *bo;
353 	int r;
354 
355 	spin_lock(&vm->status_lock);
356 	while (!list_empty(&vm->evicted)) {
357 		bo_base = list_first_entry(&vm->evicted,
358 					   struct amdgpu_vm_bo_base,
359 					   vm_status);
360 		spin_unlock(&vm->status_lock);
361 
362 		bo = bo_base->bo;
363 		shadow = amdgpu_bo_shadowed(bo);
364 
365 		r = validate(param, bo);
366 		if (r)
367 			return r;
368 		if (shadow) {
369 			r = validate(param, shadow);
370 			if (r)
371 				return r;
372 		}
373 
374 		if (bo->tbo.type != ttm_bo_type_kernel) {
375 			amdgpu_vm_bo_moved(bo_base);
376 		} else {
377 			vm->update_funcs->map_table(to_amdgpu_bo_vm(bo));
378 			amdgpu_vm_bo_relocated(bo_base);
379 		}
380 		spin_lock(&vm->status_lock);
381 	}
382 	spin_unlock(&vm->status_lock);
383 
384 	amdgpu_vm_eviction_lock(vm);
385 	vm->evicting = false;
386 	amdgpu_vm_eviction_unlock(vm);
387 
388 	return 0;
389 }
390 
391 /**
392  * amdgpu_vm_ready - check VM is ready for updates
393  *
394  * @vm: VM to check
395  *
396  * Check if all VM PDs/PTs are ready for updates
397  *
398  * Returns:
399  * True if VM is not evicting.
400  */
401 bool amdgpu_vm_ready(struct amdgpu_vm *vm)
402 {
403 	bool empty;
404 	bool ret;
405 
406 	amdgpu_vm_eviction_lock(vm);
407 	ret = !vm->evicting;
408 	amdgpu_vm_eviction_unlock(vm);
409 
410 	spin_lock(&vm->status_lock);
411 	empty = list_empty(&vm->evicted);
412 	spin_unlock(&vm->status_lock);
413 
414 	return ret && empty;
415 }
416 
417 /**
418  * amdgpu_vm_check_compute_bug - check whether asic has compute vm bug
419  *
420  * @adev: amdgpu_device pointer
421  */
422 void amdgpu_vm_check_compute_bug(struct amdgpu_device *adev)
423 {
424 	const struct amdgpu_ip_block *ip_block;
425 	bool has_compute_vm_bug;
426 	struct amdgpu_ring *ring;
427 	int i;
428 
429 	has_compute_vm_bug = false;
430 
431 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
432 	if (ip_block) {
433 		/* Compute has a VM bug for GFX version < 7.
434 		   Compute has a VM bug for GFX 8 MEC firmware version < 673.*/
435 		if (ip_block->version->major <= 7)
436 			has_compute_vm_bug = true;
437 		else if (ip_block->version->major == 8)
438 			if (adev->gfx.mec_fw_version < 673)
439 				has_compute_vm_bug = true;
440 	}
441 
442 	for (i = 0; i < adev->num_rings; i++) {
443 		ring = adev->rings[i];
444 		if (ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE)
445 			/* only compute rings */
446 			ring->has_compute_vm_bug = has_compute_vm_bug;
447 		else
448 			ring->has_compute_vm_bug = false;
449 	}
450 }
451 
452 /**
453  * amdgpu_vm_need_pipeline_sync - Check if pipe sync is needed for job.
454  *
455  * @ring: ring on which the job will be submitted
456  * @job: job to submit
457  *
458  * Returns:
459  * True if sync is needed.
460  */
461 bool amdgpu_vm_need_pipeline_sync(struct amdgpu_ring *ring,
462 				  struct amdgpu_job *job)
463 {
464 	struct amdgpu_device *adev = ring->adev;
465 	unsigned vmhub = ring->funcs->vmhub;
466 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
467 	struct amdgpu_vmid *id;
468 	bool gds_switch_needed;
469 	bool vm_flush_needed = job->vm_needs_flush || ring->has_compute_vm_bug;
470 
471 	if (job->vmid == 0)
472 		return false;
473 	id = &id_mgr->ids[job->vmid];
474 	gds_switch_needed = ring->funcs->emit_gds_switch && (
475 		id->gds_base != job->gds_base ||
476 		id->gds_size != job->gds_size ||
477 		id->gws_base != job->gws_base ||
478 		id->gws_size != job->gws_size ||
479 		id->oa_base != job->oa_base ||
480 		id->oa_size != job->oa_size);
481 
482 	if (amdgpu_vmid_had_gpu_reset(adev, id))
483 		return true;
484 
485 	return vm_flush_needed || gds_switch_needed;
486 }
487 
488 /**
489  * amdgpu_vm_flush - hardware flush the vm
490  *
491  * @ring: ring to use for flush
492  * @job:  related job
493  * @need_pipe_sync: is pipe sync needed
494  *
495  * Emit a VM flush when it is necessary.
496  *
497  * Returns:
498  * 0 on success, errno otherwise.
499  */
500 int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job,
501 		    bool need_pipe_sync)
502 {
503 	struct amdgpu_device *adev = ring->adev;
504 	unsigned vmhub = ring->funcs->vmhub;
505 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
506 	struct amdgpu_vmid *id = &id_mgr->ids[job->vmid];
507 	bool gds_switch_needed = ring->funcs->emit_gds_switch && (
508 		id->gds_base != job->gds_base ||
509 		id->gds_size != job->gds_size ||
510 		id->gws_base != job->gws_base ||
511 		id->gws_size != job->gws_size ||
512 		id->oa_base != job->oa_base ||
513 		id->oa_size != job->oa_size);
514 	bool vm_flush_needed = job->vm_needs_flush;
515 	struct dma_fence *fence = NULL;
516 	bool pasid_mapping_needed = false;
517 	unsigned patch_offset = 0;
518 	bool update_spm_vmid_needed = (job->vm && (job->vm->reserved_vmid[vmhub] != NULL));
519 	int r;
520 
521 	if (update_spm_vmid_needed && adev->gfx.rlc.funcs->update_spm_vmid)
522 		adev->gfx.rlc.funcs->update_spm_vmid(adev, job->vmid);
523 
524 	if (amdgpu_vmid_had_gpu_reset(adev, id)) {
525 		gds_switch_needed = true;
526 		vm_flush_needed = true;
527 		pasid_mapping_needed = true;
528 	}
529 
530 	mutex_lock(&id_mgr->lock);
531 	if (id->pasid != job->pasid || !id->pasid_mapping ||
532 	    !dma_fence_is_signaled(id->pasid_mapping))
533 		pasid_mapping_needed = true;
534 	mutex_unlock(&id_mgr->lock);
535 
536 	gds_switch_needed &= !!ring->funcs->emit_gds_switch;
537 	vm_flush_needed &= !!ring->funcs->emit_vm_flush  &&
538 			job->vm_pd_addr != AMDGPU_BO_INVALID_OFFSET;
539 	pasid_mapping_needed &= adev->gmc.gmc_funcs->emit_pasid_mapping &&
540 		ring->funcs->emit_wreg;
541 
542 	if (!vm_flush_needed && !gds_switch_needed && !need_pipe_sync)
543 		return 0;
544 
545 	if (ring->funcs->init_cond_exec)
546 		patch_offset = amdgpu_ring_init_cond_exec(ring);
547 
548 	if (need_pipe_sync)
549 		amdgpu_ring_emit_pipeline_sync(ring);
550 
551 	if (vm_flush_needed) {
552 		trace_amdgpu_vm_flush(ring, job->vmid, job->vm_pd_addr);
553 		amdgpu_ring_emit_vm_flush(ring, job->vmid, job->vm_pd_addr);
554 	}
555 
556 	if (pasid_mapping_needed)
557 		amdgpu_gmc_emit_pasid_mapping(ring, job->vmid, job->pasid);
558 
559 	if (vm_flush_needed || pasid_mapping_needed) {
560 		r = amdgpu_fence_emit(ring, &fence, NULL, 0);
561 		if (r)
562 			return r;
563 	}
564 
565 	if (vm_flush_needed) {
566 		mutex_lock(&id_mgr->lock);
567 		dma_fence_put(id->last_flush);
568 		id->last_flush = dma_fence_get(fence);
569 		id->current_gpu_reset_count =
570 			atomic_read(&adev->gpu_reset_counter);
571 		mutex_unlock(&id_mgr->lock);
572 	}
573 
574 	if (pasid_mapping_needed) {
575 		mutex_lock(&id_mgr->lock);
576 		id->pasid = job->pasid;
577 		dma_fence_put(id->pasid_mapping);
578 		id->pasid_mapping = dma_fence_get(fence);
579 		mutex_unlock(&id_mgr->lock);
580 	}
581 	dma_fence_put(fence);
582 
583 	if (!ring->is_mes_queue && ring->funcs->emit_gds_switch &&
584 	    gds_switch_needed) {
585 		id->gds_base = job->gds_base;
586 		id->gds_size = job->gds_size;
587 		id->gws_base = job->gws_base;
588 		id->gws_size = job->gws_size;
589 		id->oa_base = job->oa_base;
590 		id->oa_size = job->oa_size;
591 		amdgpu_ring_emit_gds_switch(ring, job->vmid, job->gds_base,
592 					    job->gds_size, job->gws_base,
593 					    job->gws_size, job->oa_base,
594 					    job->oa_size);
595 	}
596 
597 	if (ring->funcs->patch_cond_exec)
598 		amdgpu_ring_patch_cond_exec(ring, patch_offset);
599 
600 	/* the double SWITCH_BUFFER here *cannot* be skipped by COND_EXEC */
601 	if (ring->funcs->emit_switch_buffer) {
602 		amdgpu_ring_emit_switch_buffer(ring);
603 		amdgpu_ring_emit_switch_buffer(ring);
604 	}
605 	return 0;
606 }
607 
608 /**
609  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
610  *
611  * @vm: requested vm
612  * @bo: requested buffer object
613  *
614  * Find @bo inside the requested vm.
615  * Search inside the @bos vm list for the requested vm
616  * Returns the found bo_va or NULL if none is found
617  *
618  * Object has to be reserved!
619  *
620  * Returns:
621  * Found bo_va or NULL.
622  */
623 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
624 				       struct amdgpu_bo *bo)
625 {
626 	struct amdgpu_vm_bo_base *base;
627 
628 	for (base = bo->vm_bo; base; base = base->next) {
629 		if (base->vm != vm)
630 			continue;
631 
632 		return container_of(base, struct amdgpu_bo_va, base);
633 	}
634 	return NULL;
635 }
636 
637 /**
638  * amdgpu_vm_map_gart - Resolve gart mapping of addr
639  *
640  * @pages_addr: optional DMA address to use for lookup
641  * @addr: the unmapped addr
642  *
643  * Look up the physical address of the page that the pte resolves
644  * to.
645  *
646  * Returns:
647  * The pointer for the page table entry.
648  */
649 uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
650 {
651 	uint64_t result;
652 
653 	/* page table offset */
654 	result = pages_addr[addr >> PAGE_SHIFT];
655 
656 	/* in case cpu page size != gpu page size*/
657 	result |= addr & (~PAGE_MASK);
658 
659 	result &= 0xFFFFFFFFFFFFF000ULL;
660 
661 	return result;
662 }
663 
664 /**
665  * amdgpu_vm_update_pdes - make sure that all directories are valid
666  *
667  * @adev: amdgpu_device pointer
668  * @vm: requested vm
669  * @immediate: submit immediately to the paging queue
670  *
671  * Makes sure all directories are up to date.
672  *
673  * Returns:
674  * 0 for success, error for failure.
675  */
676 int amdgpu_vm_update_pdes(struct amdgpu_device *adev,
677 			  struct amdgpu_vm *vm, bool immediate)
678 {
679 	struct amdgpu_vm_update_params params;
680 	struct amdgpu_vm_bo_base *entry;
681 	bool flush_tlb_needed = false;
682 	LIST_HEAD(relocated);
683 	int r, idx;
684 
685 	spin_lock(&vm->status_lock);
686 	list_splice_init(&vm->relocated, &relocated);
687 	spin_unlock(&vm->status_lock);
688 
689 	if (list_empty(&relocated))
690 		return 0;
691 
692 	if (!drm_dev_enter(adev_to_drm(adev), &idx))
693 		return -ENODEV;
694 
695 	memset(&params, 0, sizeof(params));
696 	params.adev = adev;
697 	params.vm = vm;
698 	params.immediate = immediate;
699 
700 	r = vm->update_funcs->prepare(&params, NULL, AMDGPU_SYNC_EXPLICIT);
701 	if (r)
702 		goto error;
703 
704 	list_for_each_entry(entry, &relocated, vm_status) {
705 		/* vm_flush_needed after updating moved PDEs */
706 		flush_tlb_needed |= entry->moved;
707 
708 		r = amdgpu_vm_pde_update(&params, entry);
709 		if (r)
710 			goto error;
711 	}
712 
713 	r = vm->update_funcs->commit(&params, &vm->last_update);
714 	if (r)
715 		goto error;
716 
717 	if (flush_tlb_needed)
718 		atomic64_inc(&vm->tlb_seq);
719 
720 	while (!list_empty(&relocated)) {
721 		entry = list_first_entry(&relocated, struct amdgpu_vm_bo_base,
722 					 vm_status);
723 		amdgpu_vm_bo_idle(entry);
724 	}
725 
726 error:
727 	drm_dev_exit(idx);
728 	return r;
729 }
730 
731 /**
732  * amdgpu_vm_tlb_seq_cb - make sure to increment tlb sequence
733  * @fence: unused
734  * @cb: the callback structure
735  *
736  * Increments the tlb sequence to make sure that future CS execute a VM flush.
737  */
738 static void amdgpu_vm_tlb_seq_cb(struct dma_fence *fence,
739 				 struct dma_fence_cb *cb)
740 {
741 	struct amdgpu_vm_tlb_seq_cb *tlb_cb;
742 
743 	tlb_cb = container_of(cb, typeof(*tlb_cb), cb);
744 	atomic64_inc(&tlb_cb->vm->tlb_seq);
745 	kfree(tlb_cb);
746 }
747 
748 /**
749  * amdgpu_vm_update_range - update a range in the vm page table
750  *
751  * @adev: amdgpu_device pointer to use for commands
752  * @vm: the VM to update the range
753  * @immediate: immediate submission in a page fault
754  * @unlocked: unlocked invalidation during MM callback
755  * @flush_tlb: trigger tlb invalidation after update completed
756  * @resv: fences we need to sync to
757  * @start: start of mapped range
758  * @last: last mapped entry
759  * @flags: flags for the entries
760  * @offset: offset into nodes and pages_addr
761  * @vram_base: base for vram mappings
762  * @res: ttm_resource to map
763  * @pages_addr: DMA addresses to use for mapping
764  * @fence: optional resulting fence
765  *
766  * Fill in the page table entries between @start and @last.
767  *
768  * Returns:
769  * 0 for success, negative erro code for failure.
770  */
771 int amdgpu_vm_update_range(struct amdgpu_device *adev, struct amdgpu_vm *vm,
772 			   bool immediate, bool unlocked, bool flush_tlb,
773 			   struct dma_resv *resv, uint64_t start, uint64_t last,
774 			   uint64_t flags, uint64_t offset, uint64_t vram_base,
775 			   struct ttm_resource *res, dma_addr_t *pages_addr,
776 			   struct dma_fence **fence)
777 {
778 	struct amdgpu_vm_update_params params;
779 	struct amdgpu_vm_tlb_seq_cb *tlb_cb;
780 	struct amdgpu_res_cursor cursor;
781 	enum amdgpu_sync_mode sync_mode;
782 	int r, idx;
783 
784 	if (!drm_dev_enter(adev_to_drm(adev), &idx))
785 		return -ENODEV;
786 
787 	tlb_cb = kmalloc(sizeof(*tlb_cb), GFP_KERNEL);
788 	if (!tlb_cb) {
789 		r = -ENOMEM;
790 		goto error_unlock;
791 	}
792 
793 	/* Vega20+XGMI where PTEs get inadvertently cached in L2 texture cache,
794 	 * heavy-weight flush TLB unconditionally.
795 	 */
796 	flush_tlb |= adev->gmc.xgmi.num_physical_nodes &&
797 		     adev->ip_versions[GC_HWIP][0] == IP_VERSION(9, 4, 0);
798 
799 	/*
800 	 * On GFX8 and older any 8 PTE block with a valid bit set enters the TLB
801 	 */
802 	flush_tlb |= adev->ip_versions[GC_HWIP][0] < IP_VERSION(9, 0, 0);
803 
804 	memset(&params, 0, sizeof(params));
805 	params.adev = adev;
806 	params.vm = vm;
807 	params.immediate = immediate;
808 	params.pages_addr = pages_addr;
809 	params.unlocked = unlocked;
810 
811 	/* Implicitly sync to command submissions in the same VM before
812 	 * unmapping. Sync to moving fences before mapping.
813 	 */
814 	if (!(flags & AMDGPU_PTE_VALID))
815 		sync_mode = AMDGPU_SYNC_EQ_OWNER;
816 	else
817 		sync_mode = AMDGPU_SYNC_EXPLICIT;
818 
819 	amdgpu_vm_eviction_lock(vm);
820 	if (vm->evicting) {
821 		r = -EBUSY;
822 		goto error_free;
823 	}
824 
825 	if (!unlocked && !dma_fence_is_signaled(vm->last_unlocked)) {
826 		struct dma_fence *tmp = dma_fence_get_stub();
827 
828 		amdgpu_bo_fence(vm->root.bo, vm->last_unlocked, true);
829 		swap(vm->last_unlocked, tmp);
830 		dma_fence_put(tmp);
831 	}
832 
833 	r = vm->update_funcs->prepare(&params, resv, sync_mode);
834 	if (r)
835 		goto error_free;
836 
837 	amdgpu_res_first(pages_addr ? NULL : res, offset,
838 			 (last - start + 1) * AMDGPU_GPU_PAGE_SIZE, &cursor);
839 	while (cursor.remaining) {
840 		uint64_t tmp, num_entries, addr;
841 
842 		num_entries = cursor.size >> AMDGPU_GPU_PAGE_SHIFT;
843 		if (pages_addr) {
844 			bool contiguous = true;
845 
846 			if (num_entries > AMDGPU_GPU_PAGES_IN_CPU_PAGE) {
847 				uint64_t pfn = cursor.start >> PAGE_SHIFT;
848 				uint64_t count;
849 
850 				contiguous = pages_addr[pfn + 1] ==
851 					pages_addr[pfn] + PAGE_SIZE;
852 
853 				tmp = num_entries /
854 					AMDGPU_GPU_PAGES_IN_CPU_PAGE;
855 				for (count = 2; count < tmp; ++count) {
856 					uint64_t idx = pfn + count;
857 
858 					if (contiguous != (pages_addr[idx] ==
859 					    pages_addr[idx - 1] + PAGE_SIZE))
860 						break;
861 				}
862 				num_entries = count *
863 					AMDGPU_GPU_PAGES_IN_CPU_PAGE;
864 			}
865 
866 			if (!contiguous) {
867 				addr = cursor.start;
868 				params.pages_addr = pages_addr;
869 			} else {
870 				addr = pages_addr[cursor.start >> PAGE_SHIFT];
871 				params.pages_addr = NULL;
872 			}
873 
874 		} else if (flags & (AMDGPU_PTE_VALID | AMDGPU_PTE_PRT)) {
875 			addr = vram_base + cursor.start;
876 		} else {
877 			addr = 0;
878 		}
879 
880 		tmp = start + num_entries;
881 		r = amdgpu_vm_ptes_update(&params, start, tmp, addr, flags);
882 		if (r)
883 			goto error_free;
884 
885 		amdgpu_res_next(&cursor, num_entries * AMDGPU_GPU_PAGE_SIZE);
886 		start = tmp;
887 	}
888 
889 	r = vm->update_funcs->commit(&params, fence);
890 
891 	if (flush_tlb || params.table_freed) {
892 		tlb_cb->vm = vm;
893 		if (fence && *fence &&
894 		    !dma_fence_add_callback(*fence, &tlb_cb->cb,
895 					   amdgpu_vm_tlb_seq_cb)) {
896 			dma_fence_put(vm->last_tlb_flush);
897 			vm->last_tlb_flush = dma_fence_get(*fence);
898 		} else {
899 			amdgpu_vm_tlb_seq_cb(NULL, &tlb_cb->cb);
900 		}
901 		tlb_cb = NULL;
902 	}
903 
904 error_free:
905 	kfree(tlb_cb);
906 
907 error_unlock:
908 	amdgpu_vm_eviction_unlock(vm);
909 	drm_dev_exit(idx);
910 	return r;
911 }
912 
913 void amdgpu_vm_get_memory(struct amdgpu_vm *vm, uint64_t *vram_mem,
914 				uint64_t *gtt_mem, uint64_t *cpu_mem)
915 {
916 	struct amdgpu_bo_va *bo_va, *tmp;
917 
918 	spin_lock(&vm->status_lock);
919 	list_for_each_entry_safe(bo_va, tmp, &vm->idle, base.vm_status) {
920 		if (!bo_va->base.bo)
921 			continue;
922 		amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
923 				gtt_mem, cpu_mem);
924 	}
925 	list_for_each_entry_safe(bo_va, tmp, &vm->evicted, base.vm_status) {
926 		if (!bo_va->base.bo)
927 			continue;
928 		amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
929 				gtt_mem, cpu_mem);
930 	}
931 	list_for_each_entry_safe(bo_va, tmp, &vm->relocated, base.vm_status) {
932 		if (!bo_va->base.bo)
933 			continue;
934 		amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
935 				gtt_mem, cpu_mem);
936 	}
937 	list_for_each_entry_safe(bo_va, tmp, &vm->moved, base.vm_status) {
938 		if (!bo_va->base.bo)
939 			continue;
940 		amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
941 				gtt_mem, cpu_mem);
942 	}
943 	list_for_each_entry_safe(bo_va, tmp, &vm->invalidated, base.vm_status) {
944 		if (!bo_va->base.bo)
945 			continue;
946 		amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
947 				gtt_mem, cpu_mem);
948 	}
949 	list_for_each_entry_safe(bo_va, tmp, &vm->done, base.vm_status) {
950 		if (!bo_va->base.bo)
951 			continue;
952 		amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
953 				gtt_mem, cpu_mem);
954 	}
955 	spin_unlock(&vm->status_lock);
956 }
957 /**
958  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
959  *
960  * @adev: amdgpu_device pointer
961  * @bo_va: requested BO and VM object
962  * @clear: if true clear the entries
963  *
964  * Fill in the page table entries for @bo_va.
965  *
966  * Returns:
967  * 0 for success, -EINVAL for failure.
968  */
969 int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va,
970 			bool clear)
971 {
972 	struct amdgpu_bo *bo = bo_va->base.bo;
973 	struct amdgpu_vm *vm = bo_va->base.vm;
974 	struct amdgpu_bo_va_mapping *mapping;
975 	dma_addr_t *pages_addr = NULL;
976 	struct ttm_resource *mem;
977 	struct dma_fence **last_update;
978 	bool flush_tlb = clear;
979 	struct dma_resv *resv;
980 	uint64_t vram_base;
981 	uint64_t flags;
982 	int r;
983 
984 	if (clear || !bo) {
985 		mem = NULL;
986 		resv = vm->root.bo->tbo.base.resv;
987 	} else {
988 		struct drm_gem_object *obj = &bo->tbo.base;
989 
990 		resv = bo->tbo.base.resv;
991 		if (obj->import_attach && bo_va->is_xgmi) {
992 			struct dma_buf *dma_buf = obj->import_attach->dmabuf;
993 			struct drm_gem_object *gobj = dma_buf->priv;
994 			struct amdgpu_bo *abo = gem_to_amdgpu_bo(gobj);
995 
996 			if (abo->tbo.resource->mem_type == TTM_PL_VRAM)
997 				bo = gem_to_amdgpu_bo(gobj);
998 		}
999 		mem = bo->tbo.resource;
1000 		if (mem->mem_type == TTM_PL_TT ||
1001 		    mem->mem_type == AMDGPU_PL_PREEMPT)
1002 			pages_addr = bo->tbo.ttm->dma_address;
1003 	}
1004 
1005 	if (bo) {
1006 		struct amdgpu_device *bo_adev;
1007 
1008 		flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, mem);
1009 
1010 		if (amdgpu_bo_encrypted(bo))
1011 			flags |= AMDGPU_PTE_TMZ;
1012 
1013 		bo_adev = amdgpu_ttm_adev(bo->tbo.bdev);
1014 		vram_base = bo_adev->vm_manager.vram_base_offset;
1015 	} else {
1016 		flags = 0x0;
1017 		vram_base = 0;
1018 	}
1019 
1020 	if (clear || (bo && bo->tbo.base.resv ==
1021 		      vm->root.bo->tbo.base.resv))
1022 		last_update = &vm->last_update;
1023 	else
1024 		last_update = &bo_va->last_pt_update;
1025 
1026 	if (!clear && bo_va->base.moved) {
1027 		flush_tlb = true;
1028 		list_splice_init(&bo_va->valids, &bo_va->invalids);
1029 
1030 	} else if (bo_va->cleared != clear) {
1031 		list_splice_init(&bo_va->valids, &bo_va->invalids);
1032 	}
1033 
1034 	list_for_each_entry(mapping, &bo_va->invalids, list) {
1035 		uint64_t update_flags = flags;
1036 
1037 		/* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1038 		 * but in case of something, we filter the flags in first place
1039 		 */
1040 		if (!(mapping->flags & AMDGPU_PTE_READABLE))
1041 			update_flags &= ~AMDGPU_PTE_READABLE;
1042 		if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1043 			update_flags &= ~AMDGPU_PTE_WRITEABLE;
1044 
1045 		/* Apply ASIC specific mapping flags */
1046 		amdgpu_gmc_get_vm_pte(adev, mapping, &update_flags);
1047 
1048 		trace_amdgpu_vm_bo_update(mapping);
1049 
1050 		r = amdgpu_vm_update_range(adev, vm, false, false, flush_tlb,
1051 					   resv, mapping->start, mapping->last,
1052 					   update_flags, mapping->offset,
1053 					   vram_base, mem, pages_addr,
1054 					   last_update);
1055 		if (r)
1056 			return r;
1057 	}
1058 
1059 	/* If the BO is not in its preferred location add it back to
1060 	 * the evicted list so that it gets validated again on the
1061 	 * next command submission.
1062 	 */
1063 	if (bo && bo->tbo.base.resv == vm->root.bo->tbo.base.resv) {
1064 		uint32_t mem_type = bo->tbo.resource->mem_type;
1065 
1066 		if (!(bo->preferred_domains &
1067 		      amdgpu_mem_type_to_domain(mem_type)))
1068 			amdgpu_vm_bo_evicted(&bo_va->base);
1069 		else
1070 			amdgpu_vm_bo_idle(&bo_va->base);
1071 	} else {
1072 		amdgpu_vm_bo_done(&bo_va->base);
1073 	}
1074 
1075 	list_splice_init(&bo_va->invalids, &bo_va->valids);
1076 	bo_va->cleared = clear;
1077 	bo_va->base.moved = false;
1078 
1079 	if (trace_amdgpu_vm_bo_mapping_enabled()) {
1080 		list_for_each_entry(mapping, &bo_va->valids, list)
1081 			trace_amdgpu_vm_bo_mapping(mapping);
1082 	}
1083 
1084 	return 0;
1085 }
1086 
1087 /**
1088  * amdgpu_vm_update_prt_state - update the global PRT state
1089  *
1090  * @adev: amdgpu_device pointer
1091  */
1092 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
1093 {
1094 	unsigned long flags;
1095 	bool enable;
1096 
1097 	spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
1098 	enable = !!atomic_read(&adev->vm_manager.num_prt_users);
1099 	adev->gmc.gmc_funcs->set_prt(adev, enable);
1100 	spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
1101 }
1102 
1103 /**
1104  * amdgpu_vm_prt_get - add a PRT user
1105  *
1106  * @adev: amdgpu_device pointer
1107  */
1108 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
1109 {
1110 	if (!adev->gmc.gmc_funcs->set_prt)
1111 		return;
1112 
1113 	if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
1114 		amdgpu_vm_update_prt_state(adev);
1115 }
1116 
1117 /**
1118  * amdgpu_vm_prt_put - drop a PRT user
1119  *
1120  * @adev: amdgpu_device pointer
1121  */
1122 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
1123 {
1124 	if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
1125 		amdgpu_vm_update_prt_state(adev);
1126 }
1127 
1128 /**
1129  * amdgpu_vm_prt_cb - callback for updating the PRT status
1130  *
1131  * @fence: fence for the callback
1132  * @_cb: the callback function
1133  */
1134 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
1135 {
1136 	struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
1137 
1138 	amdgpu_vm_prt_put(cb->adev);
1139 	kfree(cb);
1140 }
1141 
1142 /**
1143  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
1144  *
1145  * @adev: amdgpu_device pointer
1146  * @fence: fence for the callback
1147  */
1148 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
1149 				 struct dma_fence *fence)
1150 {
1151 	struct amdgpu_prt_cb *cb;
1152 
1153 	if (!adev->gmc.gmc_funcs->set_prt)
1154 		return;
1155 
1156 	cb = kmalloc(sizeof(struct amdgpu_prt_cb), GFP_KERNEL);
1157 	if (!cb) {
1158 		/* Last resort when we are OOM */
1159 		if (fence)
1160 			dma_fence_wait(fence, false);
1161 
1162 		amdgpu_vm_prt_put(adev);
1163 	} else {
1164 		cb->adev = adev;
1165 		if (!fence || dma_fence_add_callback(fence, &cb->cb,
1166 						     amdgpu_vm_prt_cb))
1167 			amdgpu_vm_prt_cb(fence, &cb->cb);
1168 	}
1169 }
1170 
1171 /**
1172  * amdgpu_vm_free_mapping - free a mapping
1173  *
1174  * @adev: amdgpu_device pointer
1175  * @vm: requested vm
1176  * @mapping: mapping to be freed
1177  * @fence: fence of the unmap operation
1178  *
1179  * Free a mapping and make sure we decrease the PRT usage count if applicable.
1180  */
1181 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
1182 				   struct amdgpu_vm *vm,
1183 				   struct amdgpu_bo_va_mapping *mapping,
1184 				   struct dma_fence *fence)
1185 {
1186 	if (mapping->flags & AMDGPU_PTE_PRT)
1187 		amdgpu_vm_add_prt_cb(adev, fence);
1188 	kfree(mapping);
1189 }
1190 
1191 /**
1192  * amdgpu_vm_prt_fini - finish all prt mappings
1193  *
1194  * @adev: amdgpu_device pointer
1195  * @vm: requested vm
1196  *
1197  * Register a cleanup callback to disable PRT support after VM dies.
1198  */
1199 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1200 {
1201 	struct dma_resv *resv = vm->root.bo->tbo.base.resv;
1202 	struct dma_resv_iter cursor;
1203 	struct dma_fence *fence;
1204 
1205 	dma_resv_for_each_fence(&cursor, resv, DMA_RESV_USAGE_BOOKKEEP, fence) {
1206 		/* Add a callback for each fence in the reservation object */
1207 		amdgpu_vm_prt_get(adev);
1208 		amdgpu_vm_add_prt_cb(adev, fence);
1209 	}
1210 }
1211 
1212 /**
1213  * amdgpu_vm_clear_freed - clear freed BOs in the PT
1214  *
1215  * @adev: amdgpu_device pointer
1216  * @vm: requested vm
1217  * @fence: optional resulting fence (unchanged if no work needed to be done
1218  * or if an error occurred)
1219  *
1220  * Make sure all freed BOs are cleared in the PT.
1221  * PTs have to be reserved and mutex must be locked!
1222  *
1223  * Returns:
1224  * 0 for success.
1225  *
1226  */
1227 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
1228 			  struct amdgpu_vm *vm,
1229 			  struct dma_fence **fence)
1230 {
1231 	struct dma_resv *resv = vm->root.bo->tbo.base.resv;
1232 	struct amdgpu_bo_va_mapping *mapping;
1233 	uint64_t init_pte_value = 0;
1234 	struct dma_fence *f = NULL;
1235 	int r;
1236 
1237 	while (!list_empty(&vm->freed)) {
1238 		mapping = list_first_entry(&vm->freed,
1239 			struct amdgpu_bo_va_mapping, list);
1240 		list_del(&mapping->list);
1241 
1242 		if (vm->pte_support_ats &&
1243 		    mapping->start < AMDGPU_GMC_HOLE_START)
1244 			init_pte_value = AMDGPU_PTE_DEFAULT_ATC;
1245 
1246 		r = amdgpu_vm_update_range(adev, vm, false, false, true, resv,
1247 					   mapping->start, mapping->last,
1248 					   init_pte_value, 0, 0, NULL, NULL,
1249 					   &f);
1250 		amdgpu_vm_free_mapping(adev, vm, mapping, f);
1251 		if (r) {
1252 			dma_fence_put(f);
1253 			return r;
1254 		}
1255 	}
1256 
1257 	if (fence && f) {
1258 		dma_fence_put(*fence);
1259 		*fence = f;
1260 	} else {
1261 		dma_fence_put(f);
1262 	}
1263 
1264 	return 0;
1265 
1266 }
1267 
1268 /**
1269  * amdgpu_vm_handle_moved - handle moved BOs in the PT
1270  *
1271  * @adev: amdgpu_device pointer
1272  * @vm: requested vm
1273  *
1274  * Make sure all BOs which are moved are updated in the PTs.
1275  *
1276  * Returns:
1277  * 0 for success.
1278  *
1279  * PTs have to be reserved!
1280  */
1281 int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
1282 			   struct amdgpu_vm *vm)
1283 {
1284 	struct amdgpu_bo_va *bo_va;
1285 	struct dma_resv *resv;
1286 	bool clear;
1287 	int r;
1288 
1289 	spin_lock(&vm->status_lock);
1290 	while (!list_empty(&vm->moved)) {
1291 		bo_va = list_first_entry(&vm->moved, struct amdgpu_bo_va,
1292 					 base.vm_status);
1293 		spin_unlock(&vm->status_lock);
1294 
1295 		/* Per VM BOs never need to bo cleared in the page tables */
1296 		r = amdgpu_vm_bo_update(adev, bo_va, false);
1297 		if (r)
1298 			return r;
1299 		spin_lock(&vm->status_lock);
1300 	}
1301 
1302 	while (!list_empty(&vm->invalidated)) {
1303 		bo_va = list_first_entry(&vm->invalidated, struct amdgpu_bo_va,
1304 					 base.vm_status);
1305 		resv = bo_va->base.bo->tbo.base.resv;
1306 		spin_unlock(&vm->status_lock);
1307 
1308 		/* Try to reserve the BO to avoid clearing its ptes */
1309 		if (!amdgpu_vm_debug && dma_resv_trylock(resv))
1310 			clear = false;
1311 		/* Somebody else is using the BO right now */
1312 		else
1313 			clear = true;
1314 
1315 		r = amdgpu_vm_bo_update(adev, bo_va, clear);
1316 		if (r)
1317 			return r;
1318 
1319 		if (!clear)
1320 			dma_resv_unlock(resv);
1321 		spin_lock(&vm->status_lock);
1322 	}
1323 	spin_unlock(&vm->status_lock);
1324 
1325 	return 0;
1326 }
1327 
1328 /**
1329  * amdgpu_vm_bo_add - add a bo to a specific vm
1330  *
1331  * @adev: amdgpu_device pointer
1332  * @vm: requested vm
1333  * @bo: amdgpu buffer object
1334  *
1335  * Add @bo into the requested vm.
1336  * Add @bo to the list of bos associated with the vm
1337  *
1338  * Returns:
1339  * Newly added bo_va or NULL for failure
1340  *
1341  * Object has to be reserved!
1342  */
1343 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
1344 				      struct amdgpu_vm *vm,
1345 				      struct amdgpu_bo *bo)
1346 {
1347 	struct amdgpu_bo_va *bo_va;
1348 
1349 	bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
1350 	if (bo_va == NULL) {
1351 		return NULL;
1352 	}
1353 	amdgpu_vm_bo_base_init(&bo_va->base, vm, bo);
1354 
1355 	bo_va->ref_count = 1;
1356 	INIT_LIST_HEAD(&bo_va->valids);
1357 	INIT_LIST_HEAD(&bo_va->invalids);
1358 
1359 	if (!bo)
1360 		return bo_va;
1361 
1362 	dma_resv_assert_held(bo->tbo.base.resv);
1363 	if (amdgpu_dmabuf_is_xgmi_accessible(adev, bo)) {
1364 		bo_va->is_xgmi = true;
1365 		/* Power up XGMI if it can be potentially used */
1366 		amdgpu_xgmi_set_pstate(adev, AMDGPU_XGMI_PSTATE_MAX_VEGA20);
1367 	}
1368 
1369 	return bo_va;
1370 }
1371 
1372 
1373 /**
1374  * amdgpu_vm_bo_insert_map - insert a new mapping
1375  *
1376  * @adev: amdgpu_device pointer
1377  * @bo_va: bo_va to store the address
1378  * @mapping: the mapping to insert
1379  *
1380  * Insert a new mapping into all structures.
1381  */
1382 static void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev,
1383 				    struct amdgpu_bo_va *bo_va,
1384 				    struct amdgpu_bo_va_mapping *mapping)
1385 {
1386 	struct amdgpu_vm *vm = bo_va->base.vm;
1387 	struct amdgpu_bo *bo = bo_va->base.bo;
1388 
1389 	mapping->bo_va = bo_va;
1390 	list_add(&mapping->list, &bo_va->invalids);
1391 	amdgpu_vm_it_insert(mapping, &vm->va);
1392 
1393 	if (mapping->flags & AMDGPU_PTE_PRT)
1394 		amdgpu_vm_prt_get(adev);
1395 
1396 	if (bo && bo->tbo.base.resv == vm->root.bo->tbo.base.resv &&
1397 	    !bo_va->base.moved) {
1398 		amdgpu_vm_bo_moved(&bo_va->base);
1399 	}
1400 	trace_amdgpu_vm_bo_map(bo_va, mapping);
1401 }
1402 
1403 /**
1404  * amdgpu_vm_bo_map - map bo inside a vm
1405  *
1406  * @adev: amdgpu_device pointer
1407  * @bo_va: bo_va to store the address
1408  * @saddr: where to map the BO
1409  * @offset: requested offset in the BO
1410  * @size: BO size in bytes
1411  * @flags: attributes of pages (read/write/valid/etc.)
1412  *
1413  * Add a mapping of the BO at the specefied addr into the VM.
1414  *
1415  * Returns:
1416  * 0 for success, error for failure.
1417  *
1418  * Object has to be reserved and unreserved outside!
1419  */
1420 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
1421 		     struct amdgpu_bo_va *bo_va,
1422 		     uint64_t saddr, uint64_t offset,
1423 		     uint64_t size, uint64_t flags)
1424 {
1425 	struct amdgpu_bo_va_mapping *mapping, *tmp;
1426 	struct amdgpu_bo *bo = bo_va->base.bo;
1427 	struct amdgpu_vm *vm = bo_va->base.vm;
1428 	uint64_t eaddr;
1429 
1430 	/* validate the parameters */
1431 	if (saddr & ~PAGE_MASK || offset & ~PAGE_MASK ||
1432 	    size == 0 || size & ~PAGE_MASK)
1433 		return -EINVAL;
1434 
1435 	/* make sure object fit at this offset */
1436 	eaddr = saddr + size - 1;
1437 	if (saddr >= eaddr ||
1438 	    (bo && offset + size > amdgpu_bo_size(bo)) ||
1439 	    (eaddr >= adev->vm_manager.max_pfn << AMDGPU_GPU_PAGE_SHIFT))
1440 		return -EINVAL;
1441 
1442 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1443 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
1444 
1445 	tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
1446 	if (tmp) {
1447 		/* bo and tmp overlap, invalid addr */
1448 		dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
1449 			"0x%010Lx-0x%010Lx\n", bo, saddr, eaddr,
1450 			tmp->start, tmp->last + 1);
1451 		return -EINVAL;
1452 	}
1453 
1454 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1455 	if (!mapping)
1456 		return -ENOMEM;
1457 
1458 	mapping->start = saddr;
1459 	mapping->last = eaddr;
1460 	mapping->offset = offset;
1461 	mapping->flags = flags;
1462 
1463 	amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
1464 
1465 	return 0;
1466 }
1467 
1468 /**
1469  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
1470  *
1471  * @adev: amdgpu_device pointer
1472  * @bo_va: bo_va to store the address
1473  * @saddr: where to map the BO
1474  * @offset: requested offset in the BO
1475  * @size: BO size in bytes
1476  * @flags: attributes of pages (read/write/valid/etc.)
1477  *
1478  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
1479  * mappings as we do so.
1480  *
1481  * Returns:
1482  * 0 for success, error for failure.
1483  *
1484  * Object has to be reserved and unreserved outside!
1485  */
1486 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
1487 			     struct amdgpu_bo_va *bo_va,
1488 			     uint64_t saddr, uint64_t offset,
1489 			     uint64_t size, uint64_t flags)
1490 {
1491 	struct amdgpu_bo_va_mapping *mapping;
1492 	struct amdgpu_bo *bo = bo_va->base.bo;
1493 	uint64_t eaddr;
1494 	int r;
1495 
1496 	/* validate the parameters */
1497 	if (saddr & ~PAGE_MASK || offset & ~PAGE_MASK ||
1498 	    size == 0 || size & ~PAGE_MASK)
1499 		return -EINVAL;
1500 
1501 	/* make sure object fit at this offset */
1502 	eaddr = saddr + size - 1;
1503 	if (saddr >= eaddr ||
1504 	    (bo && offset + size > amdgpu_bo_size(bo)) ||
1505 	    (eaddr >= adev->vm_manager.max_pfn << AMDGPU_GPU_PAGE_SHIFT))
1506 		return -EINVAL;
1507 
1508 	/* Allocate all the needed memory */
1509 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1510 	if (!mapping)
1511 		return -ENOMEM;
1512 
1513 	r = amdgpu_vm_bo_clear_mappings(adev, bo_va->base.vm, saddr, size);
1514 	if (r) {
1515 		kfree(mapping);
1516 		return r;
1517 	}
1518 
1519 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1520 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
1521 
1522 	mapping->start = saddr;
1523 	mapping->last = eaddr;
1524 	mapping->offset = offset;
1525 	mapping->flags = flags;
1526 
1527 	amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
1528 
1529 	return 0;
1530 }
1531 
1532 /**
1533  * amdgpu_vm_bo_unmap - remove bo mapping from vm
1534  *
1535  * @adev: amdgpu_device pointer
1536  * @bo_va: bo_va to remove the address from
1537  * @saddr: where to the BO is mapped
1538  *
1539  * Remove a mapping of the BO at the specefied addr from the VM.
1540  *
1541  * Returns:
1542  * 0 for success, error for failure.
1543  *
1544  * Object has to be reserved and unreserved outside!
1545  */
1546 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
1547 		       struct amdgpu_bo_va *bo_va,
1548 		       uint64_t saddr)
1549 {
1550 	struct amdgpu_bo_va_mapping *mapping;
1551 	struct amdgpu_vm *vm = bo_va->base.vm;
1552 	bool valid = true;
1553 
1554 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1555 
1556 	list_for_each_entry(mapping, &bo_va->valids, list) {
1557 		if (mapping->start == saddr)
1558 			break;
1559 	}
1560 
1561 	if (&mapping->list == &bo_va->valids) {
1562 		valid = false;
1563 
1564 		list_for_each_entry(mapping, &bo_va->invalids, list) {
1565 			if (mapping->start == saddr)
1566 				break;
1567 		}
1568 
1569 		if (&mapping->list == &bo_va->invalids)
1570 			return -ENOENT;
1571 	}
1572 
1573 	list_del(&mapping->list);
1574 	amdgpu_vm_it_remove(mapping, &vm->va);
1575 	mapping->bo_va = NULL;
1576 	trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1577 
1578 	if (valid)
1579 		list_add(&mapping->list, &vm->freed);
1580 	else
1581 		amdgpu_vm_free_mapping(adev, vm, mapping,
1582 				       bo_va->last_pt_update);
1583 
1584 	return 0;
1585 }
1586 
1587 /**
1588  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
1589  *
1590  * @adev: amdgpu_device pointer
1591  * @vm: VM structure to use
1592  * @saddr: start of the range
1593  * @size: size of the range
1594  *
1595  * Remove all mappings in a range, split them as appropriate.
1596  *
1597  * Returns:
1598  * 0 for success, error for failure.
1599  */
1600 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
1601 				struct amdgpu_vm *vm,
1602 				uint64_t saddr, uint64_t size)
1603 {
1604 	struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
1605 	LIST_HEAD(removed);
1606 	uint64_t eaddr;
1607 
1608 	eaddr = saddr + size - 1;
1609 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1610 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
1611 
1612 	/* Allocate all the needed memory */
1613 	before = kzalloc(sizeof(*before), GFP_KERNEL);
1614 	if (!before)
1615 		return -ENOMEM;
1616 	INIT_LIST_HEAD(&before->list);
1617 
1618 	after = kzalloc(sizeof(*after), GFP_KERNEL);
1619 	if (!after) {
1620 		kfree(before);
1621 		return -ENOMEM;
1622 	}
1623 	INIT_LIST_HEAD(&after->list);
1624 
1625 	/* Now gather all removed mappings */
1626 	tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
1627 	while (tmp) {
1628 		/* Remember mapping split at the start */
1629 		if (tmp->start < saddr) {
1630 			before->start = tmp->start;
1631 			before->last = saddr - 1;
1632 			before->offset = tmp->offset;
1633 			before->flags = tmp->flags;
1634 			before->bo_va = tmp->bo_va;
1635 			list_add(&before->list, &tmp->bo_va->invalids);
1636 		}
1637 
1638 		/* Remember mapping split at the end */
1639 		if (tmp->last > eaddr) {
1640 			after->start = eaddr + 1;
1641 			after->last = tmp->last;
1642 			after->offset = tmp->offset;
1643 			after->offset += (after->start - tmp->start) << PAGE_SHIFT;
1644 			after->flags = tmp->flags;
1645 			after->bo_va = tmp->bo_va;
1646 			list_add(&after->list, &tmp->bo_va->invalids);
1647 		}
1648 
1649 		list_del(&tmp->list);
1650 		list_add(&tmp->list, &removed);
1651 
1652 		tmp = amdgpu_vm_it_iter_next(tmp, saddr, eaddr);
1653 	}
1654 
1655 	/* And free them up */
1656 	list_for_each_entry_safe(tmp, next, &removed, list) {
1657 		amdgpu_vm_it_remove(tmp, &vm->va);
1658 		list_del(&tmp->list);
1659 
1660 		if (tmp->start < saddr)
1661 		    tmp->start = saddr;
1662 		if (tmp->last > eaddr)
1663 		    tmp->last = eaddr;
1664 
1665 		tmp->bo_va = NULL;
1666 		list_add(&tmp->list, &vm->freed);
1667 		trace_amdgpu_vm_bo_unmap(NULL, tmp);
1668 	}
1669 
1670 	/* Insert partial mapping before the range */
1671 	if (!list_empty(&before->list)) {
1672 		amdgpu_vm_it_insert(before, &vm->va);
1673 		if (before->flags & AMDGPU_PTE_PRT)
1674 			amdgpu_vm_prt_get(adev);
1675 	} else {
1676 		kfree(before);
1677 	}
1678 
1679 	/* Insert partial mapping after the range */
1680 	if (!list_empty(&after->list)) {
1681 		amdgpu_vm_it_insert(after, &vm->va);
1682 		if (after->flags & AMDGPU_PTE_PRT)
1683 			amdgpu_vm_prt_get(adev);
1684 	} else {
1685 		kfree(after);
1686 	}
1687 
1688 	return 0;
1689 }
1690 
1691 /**
1692  * amdgpu_vm_bo_lookup_mapping - find mapping by address
1693  *
1694  * @vm: the requested VM
1695  * @addr: the address
1696  *
1697  * Find a mapping by it's address.
1698  *
1699  * Returns:
1700  * The amdgpu_bo_va_mapping matching for addr or NULL
1701  *
1702  */
1703 struct amdgpu_bo_va_mapping *amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm,
1704 							 uint64_t addr)
1705 {
1706 	return amdgpu_vm_it_iter_first(&vm->va, addr, addr);
1707 }
1708 
1709 /**
1710  * amdgpu_vm_bo_trace_cs - trace all reserved mappings
1711  *
1712  * @vm: the requested vm
1713  * @ticket: CS ticket
1714  *
1715  * Trace all mappings of BOs reserved during a command submission.
1716  */
1717 void amdgpu_vm_bo_trace_cs(struct amdgpu_vm *vm, struct ww_acquire_ctx *ticket)
1718 {
1719 	struct amdgpu_bo_va_mapping *mapping;
1720 
1721 	if (!trace_amdgpu_vm_bo_cs_enabled())
1722 		return;
1723 
1724 	for (mapping = amdgpu_vm_it_iter_first(&vm->va, 0, U64_MAX); mapping;
1725 	     mapping = amdgpu_vm_it_iter_next(mapping, 0, U64_MAX)) {
1726 		if (mapping->bo_va && mapping->bo_va->base.bo) {
1727 			struct amdgpu_bo *bo;
1728 
1729 			bo = mapping->bo_va->base.bo;
1730 			if (dma_resv_locking_ctx(bo->tbo.base.resv) !=
1731 			    ticket)
1732 				continue;
1733 		}
1734 
1735 		trace_amdgpu_vm_bo_cs(mapping);
1736 	}
1737 }
1738 
1739 /**
1740  * amdgpu_vm_bo_del - remove a bo from a specific vm
1741  *
1742  * @adev: amdgpu_device pointer
1743  * @bo_va: requested bo_va
1744  *
1745  * Remove @bo_va->bo from the requested vm.
1746  *
1747  * Object have to be reserved!
1748  */
1749 void amdgpu_vm_bo_del(struct amdgpu_device *adev,
1750 		      struct amdgpu_bo_va *bo_va)
1751 {
1752 	struct amdgpu_bo_va_mapping *mapping, *next;
1753 	struct amdgpu_bo *bo = bo_va->base.bo;
1754 	struct amdgpu_vm *vm = bo_va->base.vm;
1755 	struct amdgpu_vm_bo_base **base;
1756 
1757 	dma_resv_assert_held(vm->root.bo->tbo.base.resv);
1758 
1759 	if (bo) {
1760 		dma_resv_assert_held(bo->tbo.base.resv);
1761 		if (bo->tbo.base.resv == vm->root.bo->tbo.base.resv)
1762 			ttm_bo_set_bulk_move(&bo->tbo, NULL);
1763 
1764 		for (base = &bo_va->base.bo->vm_bo; *base;
1765 		     base = &(*base)->next) {
1766 			if (*base != &bo_va->base)
1767 				continue;
1768 
1769 			*base = bo_va->base.next;
1770 			break;
1771 		}
1772 	}
1773 
1774 	spin_lock(&vm->status_lock);
1775 	list_del(&bo_va->base.vm_status);
1776 	spin_unlock(&vm->status_lock);
1777 
1778 	list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
1779 		list_del(&mapping->list);
1780 		amdgpu_vm_it_remove(mapping, &vm->va);
1781 		mapping->bo_va = NULL;
1782 		trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1783 		list_add(&mapping->list, &vm->freed);
1784 	}
1785 	list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
1786 		list_del(&mapping->list);
1787 		amdgpu_vm_it_remove(mapping, &vm->va);
1788 		amdgpu_vm_free_mapping(adev, vm, mapping,
1789 				       bo_va->last_pt_update);
1790 	}
1791 
1792 	dma_fence_put(bo_va->last_pt_update);
1793 
1794 	if (bo && bo_va->is_xgmi)
1795 		amdgpu_xgmi_set_pstate(adev, AMDGPU_XGMI_PSTATE_MIN);
1796 
1797 	kfree(bo_va);
1798 }
1799 
1800 /**
1801  * amdgpu_vm_evictable - check if we can evict a VM
1802  *
1803  * @bo: A page table of the VM.
1804  *
1805  * Check if it is possible to evict a VM.
1806  */
1807 bool amdgpu_vm_evictable(struct amdgpu_bo *bo)
1808 {
1809 	struct amdgpu_vm_bo_base *bo_base = bo->vm_bo;
1810 
1811 	/* Page tables of a destroyed VM can go away immediately */
1812 	if (!bo_base || !bo_base->vm)
1813 		return true;
1814 
1815 	/* Don't evict VM page tables while they are busy */
1816 	if (!dma_resv_test_signaled(bo->tbo.base.resv, DMA_RESV_USAGE_BOOKKEEP))
1817 		return false;
1818 
1819 	/* Try to block ongoing updates */
1820 	if (!amdgpu_vm_eviction_trylock(bo_base->vm))
1821 		return false;
1822 
1823 	/* Don't evict VM page tables while they are updated */
1824 	if (!dma_fence_is_signaled(bo_base->vm->last_unlocked)) {
1825 		amdgpu_vm_eviction_unlock(bo_base->vm);
1826 		return false;
1827 	}
1828 
1829 	bo_base->vm->evicting = true;
1830 	amdgpu_vm_eviction_unlock(bo_base->vm);
1831 	return true;
1832 }
1833 
1834 /**
1835  * amdgpu_vm_bo_invalidate - mark the bo as invalid
1836  *
1837  * @adev: amdgpu_device pointer
1838  * @bo: amdgpu buffer object
1839  * @evicted: is the BO evicted
1840  *
1841  * Mark @bo as invalid.
1842  */
1843 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
1844 			     struct amdgpu_bo *bo, bool evicted)
1845 {
1846 	struct amdgpu_vm_bo_base *bo_base;
1847 
1848 	/* shadow bo doesn't have bo base, its validation needs its parent */
1849 	if (bo->parent && (amdgpu_bo_shadowed(bo->parent) == bo))
1850 		bo = bo->parent;
1851 
1852 	for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
1853 		struct amdgpu_vm *vm = bo_base->vm;
1854 
1855 		if (evicted && bo->tbo.base.resv == vm->root.bo->tbo.base.resv) {
1856 			amdgpu_vm_bo_evicted(bo_base);
1857 			continue;
1858 		}
1859 
1860 		if (bo_base->moved)
1861 			continue;
1862 		bo_base->moved = true;
1863 
1864 		if (bo->tbo.type == ttm_bo_type_kernel)
1865 			amdgpu_vm_bo_relocated(bo_base);
1866 		else if (bo->tbo.base.resv == vm->root.bo->tbo.base.resv)
1867 			amdgpu_vm_bo_moved(bo_base);
1868 		else
1869 			amdgpu_vm_bo_invalidated(bo_base);
1870 	}
1871 }
1872 
1873 /**
1874  * amdgpu_vm_get_block_size - calculate VM page table size as power of two
1875  *
1876  * @vm_size: VM size
1877  *
1878  * Returns:
1879  * VM page table as power of two
1880  */
1881 static uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
1882 {
1883 	/* Total bits covered by PD + PTs */
1884 	unsigned bits = ilog2(vm_size) + 18;
1885 
1886 	/* Make sure the PD is 4K in size up to 8GB address space.
1887 	   Above that split equal between PD and PTs */
1888 	if (vm_size <= 8)
1889 		return (bits - 9);
1890 	else
1891 		return ((bits + 3) / 2);
1892 }
1893 
1894 /**
1895  * amdgpu_vm_adjust_size - adjust vm size, block size and fragment size
1896  *
1897  * @adev: amdgpu_device pointer
1898  * @min_vm_size: the minimum vm size in GB if it's set auto
1899  * @fragment_size_default: Default PTE fragment size
1900  * @max_level: max VMPT level
1901  * @max_bits: max address space size in bits
1902  *
1903  */
1904 void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint32_t min_vm_size,
1905 			   uint32_t fragment_size_default, unsigned max_level,
1906 			   unsigned max_bits)
1907 {
1908 	unsigned int max_size = 1 << (max_bits - 30);
1909 	unsigned int vm_size;
1910 	uint64_t tmp;
1911 
1912 	/* adjust vm size first */
1913 	if (amdgpu_vm_size != -1) {
1914 		vm_size = amdgpu_vm_size;
1915 		if (vm_size > max_size) {
1916 			dev_warn(adev->dev, "VM size (%d) too large, max is %u GB\n",
1917 				 amdgpu_vm_size, max_size);
1918 			vm_size = max_size;
1919 		}
1920 	} else {
1921 		struct sysinfo si;
1922 		unsigned int phys_ram_gb;
1923 
1924 		/* Optimal VM size depends on the amount of physical
1925 		 * RAM available. Underlying requirements and
1926 		 * assumptions:
1927 		 *
1928 		 *  - Need to map system memory and VRAM from all GPUs
1929 		 *     - VRAM from other GPUs not known here
1930 		 *     - Assume VRAM <= system memory
1931 		 *  - On GFX8 and older, VM space can be segmented for
1932 		 *    different MTYPEs
1933 		 *  - Need to allow room for fragmentation, guard pages etc.
1934 		 *
1935 		 * This adds up to a rough guess of system memory x3.
1936 		 * Round up to power of two to maximize the available
1937 		 * VM size with the given page table size.
1938 		 */
1939 		si_meminfo(&si);
1940 		phys_ram_gb = ((uint64_t)si.totalram * si.mem_unit +
1941 			       (1 << 30) - 1) >> 30;
1942 		vm_size = roundup_pow_of_two(
1943 			min(max(phys_ram_gb * 3, min_vm_size), max_size));
1944 	}
1945 
1946 	adev->vm_manager.max_pfn = (uint64_t)vm_size << 18;
1947 
1948 	tmp = roundup_pow_of_two(adev->vm_manager.max_pfn);
1949 	if (amdgpu_vm_block_size != -1)
1950 		tmp >>= amdgpu_vm_block_size - 9;
1951 	tmp = DIV_ROUND_UP(fls64(tmp) - 1, 9) - 1;
1952 	adev->vm_manager.num_level = min(max_level, (unsigned)tmp);
1953 	switch (adev->vm_manager.num_level) {
1954 	case 3:
1955 		adev->vm_manager.root_level = AMDGPU_VM_PDB2;
1956 		break;
1957 	case 2:
1958 		adev->vm_manager.root_level = AMDGPU_VM_PDB1;
1959 		break;
1960 	case 1:
1961 		adev->vm_manager.root_level = AMDGPU_VM_PDB0;
1962 		break;
1963 	default:
1964 		dev_err(adev->dev, "VMPT only supports 2~4+1 levels\n");
1965 	}
1966 	/* block size depends on vm size and hw setup*/
1967 	if (amdgpu_vm_block_size != -1)
1968 		adev->vm_manager.block_size =
1969 			min((unsigned)amdgpu_vm_block_size, max_bits
1970 			    - AMDGPU_GPU_PAGE_SHIFT
1971 			    - 9 * adev->vm_manager.num_level);
1972 	else if (adev->vm_manager.num_level > 1)
1973 		adev->vm_manager.block_size = 9;
1974 	else
1975 		adev->vm_manager.block_size = amdgpu_vm_get_block_size(tmp);
1976 
1977 	if (amdgpu_vm_fragment_size == -1)
1978 		adev->vm_manager.fragment_size = fragment_size_default;
1979 	else
1980 		adev->vm_manager.fragment_size = amdgpu_vm_fragment_size;
1981 
1982 	DRM_INFO("vm size is %u GB, %u levels, block size is %u-bit, fragment size is %u-bit\n",
1983 		 vm_size, adev->vm_manager.num_level + 1,
1984 		 adev->vm_manager.block_size,
1985 		 adev->vm_manager.fragment_size);
1986 }
1987 
1988 /**
1989  * amdgpu_vm_wait_idle - wait for the VM to become idle
1990  *
1991  * @vm: VM object to wait for
1992  * @timeout: timeout to wait for VM to become idle
1993  */
1994 long amdgpu_vm_wait_idle(struct amdgpu_vm *vm, long timeout)
1995 {
1996 	timeout = dma_resv_wait_timeout(vm->root.bo->tbo.base.resv,
1997 					DMA_RESV_USAGE_BOOKKEEP,
1998 					true, timeout);
1999 	if (timeout <= 0)
2000 		return timeout;
2001 
2002 	return dma_fence_wait_timeout(vm->last_unlocked, true, timeout);
2003 }
2004 
2005 /**
2006  * amdgpu_vm_init - initialize a vm instance
2007  *
2008  * @adev: amdgpu_device pointer
2009  * @vm: requested vm
2010  *
2011  * Init @vm fields.
2012  *
2013  * Returns:
2014  * 0 for success, error for failure.
2015  */
2016 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2017 {
2018 	struct amdgpu_bo *root_bo;
2019 	struct amdgpu_bo_vm *root;
2020 	int r, i;
2021 
2022 	vm->va = RB_ROOT_CACHED;
2023 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2024 		vm->reserved_vmid[i] = NULL;
2025 	INIT_LIST_HEAD(&vm->evicted);
2026 	INIT_LIST_HEAD(&vm->relocated);
2027 	INIT_LIST_HEAD(&vm->moved);
2028 	INIT_LIST_HEAD(&vm->idle);
2029 	INIT_LIST_HEAD(&vm->invalidated);
2030 	spin_lock_init(&vm->status_lock);
2031 	INIT_LIST_HEAD(&vm->freed);
2032 	INIT_LIST_HEAD(&vm->done);
2033 	INIT_LIST_HEAD(&vm->pt_freed);
2034 	INIT_WORK(&vm->pt_free_work, amdgpu_vm_pt_free_work);
2035 
2036 	/* create scheduler entities for page table updates */
2037 	r = drm_sched_entity_init(&vm->immediate, DRM_SCHED_PRIORITY_NORMAL,
2038 				  adev->vm_manager.vm_pte_scheds,
2039 				  adev->vm_manager.vm_pte_num_scheds, NULL);
2040 	if (r)
2041 		return r;
2042 
2043 	r = drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL,
2044 				  adev->vm_manager.vm_pte_scheds,
2045 				  adev->vm_manager.vm_pte_num_scheds, NULL);
2046 	if (r)
2047 		goto error_free_immediate;
2048 
2049 	vm->pte_support_ats = false;
2050 	vm->is_compute_context = false;
2051 
2052 	vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2053 				    AMDGPU_VM_USE_CPU_FOR_GFX);
2054 
2055 	DRM_DEBUG_DRIVER("VM update mode is %s\n",
2056 			 vm->use_cpu_for_update ? "CPU" : "SDMA");
2057 	WARN_ONCE((vm->use_cpu_for_update &&
2058 		   !amdgpu_gmc_vram_full_visible(&adev->gmc)),
2059 		  "CPU update of VM recommended only for large BAR system\n");
2060 
2061 	if (vm->use_cpu_for_update)
2062 		vm->update_funcs = &amdgpu_vm_cpu_funcs;
2063 	else
2064 		vm->update_funcs = &amdgpu_vm_sdma_funcs;
2065 	vm->last_update = NULL;
2066 	vm->last_unlocked = dma_fence_get_stub();
2067 	vm->last_tlb_flush = dma_fence_get_stub();
2068 
2069 	mutex_init(&vm->eviction_lock);
2070 	vm->evicting = false;
2071 
2072 	r = amdgpu_vm_pt_create(adev, vm, adev->vm_manager.root_level,
2073 				false, &root);
2074 	if (r)
2075 		goto error_free_delayed;
2076 	root_bo = &root->bo;
2077 	r = amdgpu_bo_reserve(root_bo, true);
2078 	if (r)
2079 		goto error_free_root;
2080 
2081 	r = dma_resv_reserve_fences(root_bo->tbo.base.resv, 1);
2082 	if (r)
2083 		goto error_unreserve;
2084 
2085 	amdgpu_vm_bo_base_init(&vm->root, vm, root_bo);
2086 
2087 	r = amdgpu_vm_pt_clear(adev, vm, root, false);
2088 	if (r)
2089 		goto error_unreserve;
2090 
2091 	amdgpu_bo_unreserve(vm->root.bo);
2092 
2093 	INIT_KFIFO(vm->faults);
2094 
2095 	return 0;
2096 
2097 error_unreserve:
2098 	amdgpu_bo_unreserve(vm->root.bo);
2099 
2100 error_free_root:
2101 	amdgpu_bo_unref(&root->shadow);
2102 	amdgpu_bo_unref(&root_bo);
2103 	vm->root.bo = NULL;
2104 
2105 error_free_delayed:
2106 	dma_fence_put(vm->last_tlb_flush);
2107 	dma_fence_put(vm->last_unlocked);
2108 	drm_sched_entity_destroy(&vm->delayed);
2109 
2110 error_free_immediate:
2111 	drm_sched_entity_destroy(&vm->immediate);
2112 
2113 	return r;
2114 }
2115 
2116 /**
2117  * amdgpu_vm_make_compute - Turn a GFX VM into a compute VM
2118  *
2119  * @adev: amdgpu_device pointer
2120  * @vm: requested vm
2121  *
2122  * This only works on GFX VMs that don't have any BOs added and no
2123  * page tables allocated yet.
2124  *
2125  * Changes the following VM parameters:
2126  * - use_cpu_for_update
2127  * - pte_supports_ats
2128  *
2129  * Reinitializes the page directory to reflect the changed ATS
2130  * setting.
2131  *
2132  * Returns:
2133  * 0 for success, -errno for errors.
2134  */
2135 int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2136 {
2137 	bool pte_support_ats = (adev->asic_type == CHIP_RAVEN);
2138 	int r;
2139 
2140 	r = amdgpu_bo_reserve(vm->root.bo, true);
2141 	if (r)
2142 		return r;
2143 
2144 	/* Sanity checks */
2145 	if (!amdgpu_vm_pt_is_root_clean(adev, vm)) {
2146 		r = -EINVAL;
2147 		goto unreserve_bo;
2148 	}
2149 
2150 	/* Check if PD needs to be reinitialized and do it before
2151 	 * changing any other state, in case it fails.
2152 	 */
2153 	if (pte_support_ats != vm->pte_support_ats) {
2154 		vm->pte_support_ats = pte_support_ats;
2155 		r = amdgpu_vm_pt_clear(adev, vm, to_amdgpu_bo_vm(vm->root.bo),
2156 				       false);
2157 		if (r)
2158 			goto unreserve_bo;
2159 	}
2160 
2161 	/* Update VM state */
2162 	vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2163 				    AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2164 	DRM_DEBUG_DRIVER("VM update mode is %s\n",
2165 			 vm->use_cpu_for_update ? "CPU" : "SDMA");
2166 	WARN_ONCE((vm->use_cpu_for_update &&
2167 		   !amdgpu_gmc_vram_full_visible(&adev->gmc)),
2168 		  "CPU update of VM recommended only for large BAR system\n");
2169 
2170 	if (vm->use_cpu_for_update) {
2171 		/* Sync with last SDMA update/clear before switching to CPU */
2172 		r = amdgpu_bo_sync_wait(vm->root.bo,
2173 					AMDGPU_FENCE_OWNER_UNDEFINED, true);
2174 		if (r)
2175 			goto unreserve_bo;
2176 
2177 		vm->update_funcs = &amdgpu_vm_cpu_funcs;
2178 	} else {
2179 		vm->update_funcs = &amdgpu_vm_sdma_funcs;
2180 	}
2181 	/*
2182 	 * Make sure root PD gets mapped. As vm_update_mode could be changed
2183 	 * when turning a GFX VM into a compute VM.
2184 	 */
2185 	r = vm->update_funcs->map_table(to_amdgpu_bo_vm(vm->root.bo));
2186 	if (r)
2187 		goto unreserve_bo;
2188 
2189 	dma_fence_put(vm->last_update);
2190 	vm->last_update = NULL;
2191 	vm->is_compute_context = true;
2192 
2193 	/* Free the shadow bo for compute VM */
2194 	amdgpu_bo_unref(&to_amdgpu_bo_vm(vm->root.bo)->shadow);
2195 
2196 	goto unreserve_bo;
2197 
2198 unreserve_bo:
2199 	amdgpu_bo_unreserve(vm->root.bo);
2200 	return r;
2201 }
2202 
2203 /**
2204  * amdgpu_vm_release_compute - release a compute vm
2205  * @adev: amdgpu_device pointer
2206  * @vm: a vm turned into compute vm by calling amdgpu_vm_make_compute
2207  *
2208  * This is a correspondant of amdgpu_vm_make_compute. It decouples compute
2209  * pasid from vm. Compute should stop use of vm after this call.
2210  */
2211 void amdgpu_vm_release_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2212 {
2213 	amdgpu_vm_set_pasid(adev, vm, 0);
2214 	vm->is_compute_context = false;
2215 }
2216 
2217 /**
2218  * amdgpu_vm_fini - tear down a vm instance
2219  *
2220  * @adev: amdgpu_device pointer
2221  * @vm: requested vm
2222  *
2223  * Tear down @vm.
2224  * Unbind the VM and remove all bos from the vm bo list
2225  */
2226 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2227 {
2228 	struct amdgpu_bo_va_mapping *mapping, *tmp;
2229 	bool prt_fini_needed = !!adev->gmc.gmc_funcs->set_prt;
2230 	struct amdgpu_bo *root;
2231 	unsigned long flags;
2232 	int i;
2233 
2234 	amdgpu_amdkfd_gpuvm_destroy_cb(adev, vm);
2235 
2236 	flush_work(&vm->pt_free_work);
2237 
2238 	root = amdgpu_bo_ref(vm->root.bo);
2239 	amdgpu_bo_reserve(root, true);
2240 	amdgpu_vm_set_pasid(adev, vm, 0);
2241 	dma_fence_wait(vm->last_unlocked, false);
2242 	dma_fence_put(vm->last_unlocked);
2243 	dma_fence_wait(vm->last_tlb_flush, false);
2244 	/* Make sure that all fence callbacks have completed */
2245 	spin_lock_irqsave(vm->last_tlb_flush->lock, flags);
2246 	spin_unlock_irqrestore(vm->last_tlb_flush->lock, flags);
2247 	dma_fence_put(vm->last_tlb_flush);
2248 
2249 	list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
2250 		if (mapping->flags & AMDGPU_PTE_PRT && prt_fini_needed) {
2251 			amdgpu_vm_prt_fini(adev, vm);
2252 			prt_fini_needed = false;
2253 		}
2254 
2255 		list_del(&mapping->list);
2256 		amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
2257 	}
2258 
2259 	amdgpu_vm_pt_free_root(adev, vm);
2260 	amdgpu_bo_unreserve(root);
2261 	amdgpu_bo_unref(&root);
2262 	WARN_ON(vm->root.bo);
2263 
2264 	drm_sched_entity_destroy(&vm->immediate);
2265 	drm_sched_entity_destroy(&vm->delayed);
2266 
2267 	if (!RB_EMPTY_ROOT(&vm->va.rb_root)) {
2268 		dev_err(adev->dev, "still active bo inside vm\n");
2269 	}
2270 	rbtree_postorder_for_each_entry_safe(mapping, tmp,
2271 					     &vm->va.rb_root, rb) {
2272 		/* Don't remove the mapping here, we don't want to trigger a
2273 		 * rebalance and the tree is about to be destroyed anyway.
2274 		 */
2275 		list_del(&mapping->list);
2276 		kfree(mapping);
2277 	}
2278 
2279 	dma_fence_put(vm->last_update);
2280 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2281 		amdgpu_vmid_free_reserved(adev, vm, i);
2282 }
2283 
2284 /**
2285  * amdgpu_vm_manager_init - init the VM manager
2286  *
2287  * @adev: amdgpu_device pointer
2288  *
2289  * Initialize the VM manager structures
2290  */
2291 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
2292 {
2293 	unsigned i;
2294 
2295 	/* Concurrent flushes are only possible starting with Vega10 and
2296 	 * are broken on Navi10 and Navi14.
2297 	 */
2298 	adev->vm_manager.concurrent_flush = !(adev->asic_type < CHIP_VEGA10 ||
2299 					      adev->asic_type == CHIP_NAVI10 ||
2300 					      adev->asic_type == CHIP_NAVI14);
2301 	amdgpu_vmid_mgr_init(adev);
2302 
2303 	adev->vm_manager.fence_context =
2304 		dma_fence_context_alloc(AMDGPU_MAX_RINGS);
2305 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
2306 		adev->vm_manager.seqno[i] = 0;
2307 
2308 	spin_lock_init(&adev->vm_manager.prt_lock);
2309 	atomic_set(&adev->vm_manager.num_prt_users, 0);
2310 
2311 	/* If not overridden by the user, by default, only in large BAR systems
2312 	 * Compute VM tables will be updated by CPU
2313 	 */
2314 #ifdef CONFIG_X86_64
2315 	if (amdgpu_vm_update_mode == -1) {
2316 		/* For asic with VF MMIO access protection
2317 		 * avoid using CPU for VM table updates
2318 		 */
2319 		if (amdgpu_gmc_vram_full_visible(&adev->gmc) &&
2320 		    !amdgpu_sriov_vf_mmio_access_protection(adev))
2321 			adev->vm_manager.vm_update_mode =
2322 				AMDGPU_VM_USE_CPU_FOR_COMPUTE;
2323 		else
2324 			adev->vm_manager.vm_update_mode = 0;
2325 	} else
2326 		adev->vm_manager.vm_update_mode = amdgpu_vm_update_mode;
2327 #else
2328 	adev->vm_manager.vm_update_mode = 0;
2329 #endif
2330 
2331 	xa_init_flags(&adev->vm_manager.pasids, XA_FLAGS_LOCK_IRQ);
2332 }
2333 
2334 /**
2335  * amdgpu_vm_manager_fini - cleanup VM manager
2336  *
2337  * @adev: amdgpu_device pointer
2338  *
2339  * Cleanup the VM manager and free resources.
2340  */
2341 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
2342 {
2343 	WARN_ON(!xa_empty(&adev->vm_manager.pasids));
2344 	xa_destroy(&adev->vm_manager.pasids);
2345 
2346 	amdgpu_vmid_mgr_fini(adev);
2347 }
2348 
2349 /**
2350  * amdgpu_vm_ioctl - Manages VMID reservation for vm hubs.
2351  *
2352  * @dev: drm device pointer
2353  * @data: drm_amdgpu_vm
2354  * @filp: drm file pointer
2355  *
2356  * Returns:
2357  * 0 for success, -errno for errors.
2358  */
2359 int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
2360 {
2361 	union drm_amdgpu_vm *args = data;
2362 	struct amdgpu_device *adev = drm_to_adev(dev);
2363 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
2364 	long timeout = msecs_to_jiffies(2000);
2365 	int r;
2366 
2367 	switch (args->in.op) {
2368 	case AMDGPU_VM_OP_RESERVE_VMID:
2369 		/* We only have requirement to reserve vmid from gfxhub */
2370 		r = amdgpu_vmid_alloc_reserved(adev, &fpriv->vm,
2371 					       AMDGPU_GFXHUB_0);
2372 		if (r)
2373 			return r;
2374 		break;
2375 	case AMDGPU_VM_OP_UNRESERVE_VMID:
2376 		if (amdgpu_sriov_runtime(adev))
2377 			timeout = 8 * timeout;
2378 
2379 		/* Wait vm idle to make sure the vmid set in SPM_VMID is
2380 		 * not referenced anymore.
2381 		 */
2382 		r = amdgpu_bo_reserve(fpriv->vm.root.bo, true);
2383 		if (r)
2384 			return r;
2385 
2386 		r = amdgpu_vm_wait_idle(&fpriv->vm, timeout);
2387 		if (r < 0)
2388 			return r;
2389 
2390 		amdgpu_bo_unreserve(fpriv->vm.root.bo);
2391 		amdgpu_vmid_free_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB_0);
2392 		break;
2393 	default:
2394 		return -EINVAL;
2395 	}
2396 
2397 	return 0;
2398 }
2399 
2400 /**
2401  * amdgpu_vm_get_task_info - Extracts task info for a PASID.
2402  *
2403  * @adev: drm device pointer
2404  * @pasid: PASID identifier for VM
2405  * @task_info: task_info to fill.
2406  */
2407 void amdgpu_vm_get_task_info(struct amdgpu_device *adev, u32 pasid,
2408 			 struct amdgpu_task_info *task_info)
2409 {
2410 	struct amdgpu_vm *vm;
2411 	unsigned long flags;
2412 
2413 	xa_lock_irqsave(&adev->vm_manager.pasids, flags);
2414 
2415 	vm = xa_load(&adev->vm_manager.pasids, pasid);
2416 	if (vm)
2417 		*task_info = vm->task_info;
2418 
2419 	xa_unlock_irqrestore(&adev->vm_manager.pasids, flags);
2420 }
2421 
2422 /**
2423  * amdgpu_vm_set_task_info - Sets VMs task info.
2424  *
2425  * @vm: vm for which to set the info
2426  */
2427 void amdgpu_vm_set_task_info(struct amdgpu_vm *vm)
2428 {
2429 	if (vm->task_info.pid)
2430 		return;
2431 
2432 	vm->task_info.pid = current->pid;
2433 	get_task_comm(vm->task_info.task_name, current);
2434 
2435 	if (current->group_leader->mm != current->mm)
2436 		return;
2437 
2438 	vm->task_info.tgid = current->group_leader->pid;
2439 	get_task_comm(vm->task_info.process_name, current->group_leader);
2440 }
2441 
2442 /**
2443  * amdgpu_vm_handle_fault - graceful handling of VM faults.
2444  * @adev: amdgpu device pointer
2445  * @pasid: PASID of the VM
2446  * @addr: Address of the fault
2447  * @write_fault: true is write fault, false is read fault
2448  *
2449  * Try to gracefully handle a VM fault. Return true if the fault was handled and
2450  * shouldn't be reported any more.
2451  */
2452 bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid,
2453 			    uint64_t addr, bool write_fault)
2454 {
2455 	bool is_compute_context = false;
2456 	struct amdgpu_bo *root;
2457 	unsigned long irqflags;
2458 	uint64_t value, flags;
2459 	struct amdgpu_vm *vm;
2460 	int r;
2461 
2462 	xa_lock_irqsave(&adev->vm_manager.pasids, irqflags);
2463 	vm = xa_load(&adev->vm_manager.pasids, pasid);
2464 	if (vm) {
2465 		root = amdgpu_bo_ref(vm->root.bo);
2466 		is_compute_context = vm->is_compute_context;
2467 	} else {
2468 		root = NULL;
2469 	}
2470 	xa_unlock_irqrestore(&adev->vm_manager.pasids, irqflags);
2471 
2472 	if (!root)
2473 		return false;
2474 
2475 	addr /= AMDGPU_GPU_PAGE_SIZE;
2476 
2477 	if (is_compute_context &&
2478 	    !svm_range_restore_pages(adev, pasid, addr, write_fault)) {
2479 		amdgpu_bo_unref(&root);
2480 		return true;
2481 	}
2482 
2483 	r = amdgpu_bo_reserve(root, true);
2484 	if (r)
2485 		goto error_unref;
2486 
2487 	/* Double check that the VM still exists */
2488 	xa_lock_irqsave(&adev->vm_manager.pasids, irqflags);
2489 	vm = xa_load(&adev->vm_manager.pasids, pasid);
2490 	if (vm && vm->root.bo != root)
2491 		vm = NULL;
2492 	xa_unlock_irqrestore(&adev->vm_manager.pasids, irqflags);
2493 	if (!vm)
2494 		goto error_unlock;
2495 
2496 	flags = AMDGPU_PTE_VALID | AMDGPU_PTE_SNOOPED |
2497 		AMDGPU_PTE_SYSTEM;
2498 
2499 	if (is_compute_context) {
2500 		/* Intentionally setting invalid PTE flag
2501 		 * combination to force a no-retry-fault
2502 		 */
2503 		flags = AMDGPU_PTE_SNOOPED | AMDGPU_PTE_PRT;
2504 		value = 0;
2505 	} else if (amdgpu_vm_fault_stop == AMDGPU_VM_FAULT_STOP_NEVER) {
2506 		/* Redirect the access to the dummy page */
2507 		value = adev->dummy_page_addr;
2508 		flags |= AMDGPU_PTE_EXECUTABLE | AMDGPU_PTE_READABLE |
2509 			AMDGPU_PTE_WRITEABLE;
2510 
2511 	} else {
2512 		/* Let the hw retry silently on the PTE */
2513 		value = 0;
2514 	}
2515 
2516 	r = dma_resv_reserve_fences(root->tbo.base.resv, 1);
2517 	if (r) {
2518 		pr_debug("failed %d to reserve fence slot\n", r);
2519 		goto error_unlock;
2520 	}
2521 
2522 	r = amdgpu_vm_update_range(adev, vm, true, false, false, NULL, addr,
2523 				   addr, flags, value, 0, NULL, NULL, NULL);
2524 	if (r)
2525 		goto error_unlock;
2526 
2527 	r = amdgpu_vm_update_pdes(adev, vm, true);
2528 
2529 error_unlock:
2530 	amdgpu_bo_unreserve(root);
2531 	if (r < 0)
2532 		DRM_ERROR("Can't handle page fault (%d)\n", r);
2533 
2534 error_unref:
2535 	amdgpu_bo_unref(&root);
2536 
2537 	return false;
2538 }
2539 
2540 #if defined(CONFIG_DEBUG_FS)
2541 /**
2542  * amdgpu_debugfs_vm_bo_info  - print BO info for the VM
2543  *
2544  * @vm: Requested VM for printing BO info
2545  * @m: debugfs file
2546  *
2547  * Print BO information in debugfs file for the VM
2548  */
2549 void amdgpu_debugfs_vm_bo_info(struct amdgpu_vm *vm, struct seq_file *m)
2550 {
2551 	struct amdgpu_bo_va *bo_va, *tmp;
2552 	u64 total_idle = 0;
2553 	u64 total_evicted = 0;
2554 	u64 total_relocated = 0;
2555 	u64 total_moved = 0;
2556 	u64 total_invalidated = 0;
2557 	u64 total_done = 0;
2558 	unsigned int total_idle_objs = 0;
2559 	unsigned int total_evicted_objs = 0;
2560 	unsigned int total_relocated_objs = 0;
2561 	unsigned int total_moved_objs = 0;
2562 	unsigned int total_invalidated_objs = 0;
2563 	unsigned int total_done_objs = 0;
2564 	unsigned int id = 0;
2565 
2566 	spin_lock(&vm->status_lock);
2567 	seq_puts(m, "\tIdle BOs:\n");
2568 	list_for_each_entry_safe(bo_va, tmp, &vm->idle, base.vm_status) {
2569 		if (!bo_va->base.bo)
2570 			continue;
2571 		total_idle += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2572 	}
2573 	total_idle_objs = id;
2574 	id = 0;
2575 
2576 	seq_puts(m, "\tEvicted BOs:\n");
2577 	list_for_each_entry_safe(bo_va, tmp, &vm->evicted, base.vm_status) {
2578 		if (!bo_va->base.bo)
2579 			continue;
2580 		total_evicted += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2581 	}
2582 	total_evicted_objs = id;
2583 	id = 0;
2584 
2585 	seq_puts(m, "\tRelocated BOs:\n");
2586 	list_for_each_entry_safe(bo_va, tmp, &vm->relocated, base.vm_status) {
2587 		if (!bo_va->base.bo)
2588 			continue;
2589 		total_relocated += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2590 	}
2591 	total_relocated_objs = id;
2592 	id = 0;
2593 
2594 	seq_puts(m, "\tMoved BOs:\n");
2595 	list_for_each_entry_safe(bo_va, tmp, &vm->moved, base.vm_status) {
2596 		if (!bo_va->base.bo)
2597 			continue;
2598 		total_moved += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2599 	}
2600 	total_moved_objs = id;
2601 	id = 0;
2602 
2603 	seq_puts(m, "\tInvalidated BOs:\n");
2604 	list_for_each_entry_safe(bo_va, tmp, &vm->invalidated, base.vm_status) {
2605 		if (!bo_va->base.bo)
2606 			continue;
2607 		total_invalidated += amdgpu_bo_print_info(id++,	bo_va->base.bo, m);
2608 	}
2609 	total_invalidated_objs = id;
2610 	id = 0;
2611 
2612 	seq_puts(m, "\tDone BOs:\n");
2613 	list_for_each_entry_safe(bo_va, tmp, &vm->done, base.vm_status) {
2614 		if (!bo_va->base.bo)
2615 			continue;
2616 		total_done += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2617 	}
2618 	spin_unlock(&vm->status_lock);
2619 	total_done_objs = id;
2620 
2621 	seq_printf(m, "\tTotal idle size:        %12lld\tobjs:\t%d\n", total_idle,
2622 		   total_idle_objs);
2623 	seq_printf(m, "\tTotal evicted size:     %12lld\tobjs:\t%d\n", total_evicted,
2624 		   total_evicted_objs);
2625 	seq_printf(m, "\tTotal relocated size:   %12lld\tobjs:\t%d\n", total_relocated,
2626 		   total_relocated_objs);
2627 	seq_printf(m, "\tTotal moved size:       %12lld\tobjs:\t%d\n", total_moved,
2628 		   total_moved_objs);
2629 	seq_printf(m, "\tTotal invalidated size: %12lld\tobjs:\t%d\n", total_invalidated,
2630 		   total_invalidated_objs);
2631 	seq_printf(m, "\tTotal done size:        %12lld\tobjs:\t%d\n", total_done,
2632 		   total_done_objs);
2633 }
2634 #endif
2635