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