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