xref: /linux/drivers/gpu/drm/xe/xe_vm.c (revision 0d2d3dce0f529d8cee77f3e098bdf7712c5f6a0d)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2021 Intel Corporation
4  */
5 
6 #include "xe_vm.h"
7 
8 #include <linux/dma-fence-array.h>
9 #include <linux/error-injection.h>
10 #include <linux/nospec.h>
11 
12 #include <drm/drm_drv.h>
13 #include <drm/drm_exec.h>
14 #include <drm/drm_print.h>
15 #include <drm/ttm/ttm_tt.h>
16 #include <uapi/drm/xe_drm.h>
17 #include <linux/ascii85.h>
18 #include <linux/delay.h>
19 #include <linux/kthread.h>
20 #include <linux/mm.h>
21 #include <linux/swap.h>
22 
23 #include <generated/xe_wa_oob.h>
24 
25 #include "regs/xe_gtt_defs.h"
26 #include "xe_assert.h"
27 #include "xe_bo.h"
28 #include "xe_cpu_bind.h"
29 #include "xe_device.h"
30 #include "xe_drm_client.h"
31 #include "xe_exec_queue.h"
32 #include "xe_gt.h"
33 #include "xe_migrate.h"
34 #include "xe_pagefault.h"
35 #include "xe_pat.h"
36 #include "xe_pm.h"
37 #include "xe_preempt_fence.h"
38 #include "xe_pt.h"
39 #include "xe_pxp.h"
40 #include "xe_sriov_vf.h"
41 #include "xe_svm.h"
42 #include "xe_sync.h"
43 #include "xe_tile.h"
44 #include "xe_tlb_inval.h"
45 #include "xe_trace_bo.h"
46 #include "xe_vm_madvise.h"
47 #include "xe_wa.h"
48 
49 static struct drm_gem_object *xe_vm_obj(struct xe_vm *vm)
50 {
51 	return vm->gpuvm.r_obj;
52 }
53 
54 /**
55  * xe_vm_drm_exec_lock() - Lock the vm's resv with a drm_exec transaction
56  * @vm: The vm whose resv is to be locked.
57  * @exec: The drm_exec transaction.
58  *
59  * Helper to lock the vm's resv as part of a drm_exec transaction.
60  *
61  * Return: %0 on success. See drm_exec_lock_obj() for error codes.
62  */
63 int xe_vm_drm_exec_lock(struct xe_vm *vm, struct drm_exec *exec)
64 {
65 	return drm_exec_lock_obj(exec, xe_vm_obj(vm));
66 }
67 
68 static bool preempt_fences_waiting(struct xe_vm *vm)
69 {
70 	struct xe_exec_queue *q;
71 
72 	lockdep_assert_held(&vm->lock);
73 	xe_vm_assert_held(vm);
74 
75 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
76 		if (!q->lr.pfence ||
77 		    test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
78 			     &q->lr.pfence->flags)) {
79 			return true;
80 		}
81 	}
82 
83 	return false;
84 }
85 
86 static void free_preempt_fences(struct list_head *list)
87 {
88 	struct list_head *link, *next;
89 
90 	list_for_each_safe(link, next, list)
91 		xe_preempt_fence_free(to_preempt_fence_from_link(link));
92 }
93 
94 static int alloc_preempt_fences(struct xe_vm *vm, struct list_head *list,
95 				unsigned int *count)
96 {
97 	lockdep_assert_held(&vm->lock);
98 	xe_vm_assert_held(vm);
99 
100 	if (*count >= vm->preempt.num_exec_queues)
101 		return 0;
102 
103 	for (; *count < vm->preempt.num_exec_queues; ++(*count)) {
104 		struct xe_preempt_fence *pfence = xe_preempt_fence_alloc();
105 
106 		if (IS_ERR(pfence))
107 			return PTR_ERR(pfence);
108 
109 		list_move_tail(xe_preempt_fence_link(pfence), list);
110 	}
111 
112 	return 0;
113 }
114 
115 static int wait_for_existing_preempt_fences(struct xe_vm *vm)
116 {
117 	struct xe_exec_queue *q;
118 	bool vf_migration = IS_SRIOV_VF(vm->xe) &&
119 		xe_sriov_vf_migration_supported(vm->xe);
120 	signed long wait_time = vf_migration ? HZ / 5 : MAX_SCHEDULE_TIMEOUT;
121 
122 	xe_vm_assert_held(vm);
123 
124 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
125 		if (q->lr.pfence) {
126 			long timeout;
127 
128 			timeout = dma_fence_wait_timeout(q->lr.pfence, false,
129 							 wait_time);
130 			if (!timeout) {
131 				xe_assert(vm->xe, vf_migration);
132 				return -EAGAIN;
133 			}
134 
135 			/* Only -ETIME on fence indicates VM needs to be killed */
136 			if (timeout < 0 || q->lr.pfence->error == -ETIME)
137 				return -ETIME;
138 
139 			dma_fence_put(q->lr.pfence);
140 			q->lr.pfence = NULL;
141 		}
142 	}
143 
144 	return 0;
145 }
146 
147 static bool xe_vm_is_idle(struct xe_vm *vm)
148 {
149 	struct xe_exec_queue *q;
150 
151 	xe_vm_assert_held(vm);
152 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
153 		if (!xe_exec_queue_is_idle(q, 0))
154 			return false;
155 	}
156 
157 	return true;
158 }
159 
160 static void arm_preempt_fences(struct xe_vm *vm, struct list_head *list)
161 {
162 	struct list_head *link;
163 	struct xe_exec_queue *q;
164 
165 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
166 		struct dma_fence *fence;
167 
168 		link = list->next;
169 		xe_assert(vm->xe, link != list);
170 
171 		fence = xe_preempt_fence_arm(to_preempt_fence_from_link(link),
172 					     q, q->lr.context,
173 					     ++q->lr.seqno);
174 		dma_fence_put(q->lr.pfence);
175 		q->lr.pfence = fence;
176 	}
177 }
178 
179 static int add_preempt_fences(struct xe_vm *vm, struct xe_bo *bo)
180 {
181 	struct xe_exec_queue *q;
182 	int err;
183 
184 	xe_bo_assert_held(bo);
185 
186 	if (!vm->preempt.num_exec_queues)
187 		return 0;
188 
189 	err = dma_resv_reserve_fences(bo->ttm.base.resv, vm->preempt.num_exec_queues);
190 	if (err)
191 		return err;
192 
193 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link)
194 		if (q->lr.pfence) {
195 			dma_resv_add_fence(bo->ttm.base.resv,
196 					   q->lr.pfence,
197 					   DMA_RESV_USAGE_BOOKKEEP);
198 		}
199 
200 	return 0;
201 }
202 
203 static void resume_and_reinstall_preempt_fences(struct xe_vm *vm,
204 						struct drm_exec *exec)
205 {
206 	struct xe_exec_queue *q;
207 
208 	lockdep_assert_held(&vm->lock);
209 	xe_vm_assert_held(vm);
210 
211 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
212 		/*
213 		 * Only resume queues whose suspend() actually succeeded. A
214 		 * failed suspend() (e.g. killed/banned/wedged) leaves the queue
215 		 * un-suspended, so it must not be resumed.
216 		 *
217 		 * Also skip queues that have since been reset/killed/banned/
218 		 * wedged: their suspend may not have completed (suspend_pending
219 		 * can still be set, e.g. a preempt fence signalled with -ENOENT
220 		 * without waiting), so resuming would trip the !suspend_pending
221 		 * assert in the backend. Such queues are being torn down anyway,
222 		 * so leave them marked suspended and let teardown resolve their
223 		 * state.
224 		 */
225 		if (READ_ONCE(q->lr.suspended) && !q->ops->reset_status(q)) {
226 			WRITE_ONCE(q->lr.suspended, false);
227 			q->ops->resume(q);
228 		}
229 
230 		drm_gpuvm_resv_add_fence(&vm->gpuvm, exec, q->lr.pfence,
231 					 DMA_RESV_USAGE_BOOKKEEP, DMA_RESV_USAGE_BOOKKEEP);
232 	}
233 }
234 
235 int xe_vm_add_compute_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q)
236 {
237 	struct drm_gpuvm_exec vm_exec = {
238 		.vm = &vm->gpuvm,
239 		.flags = DRM_EXEC_INTERRUPTIBLE_WAIT,
240 		.num_fences = 1,
241 	};
242 	struct drm_exec *exec = &vm_exec.exec;
243 	struct xe_validation_ctx ctx;
244 	struct dma_fence *pfence;
245 	int err;
246 	bool wait;
247 
248 	xe_assert(vm->xe, xe_vm_in_preempt_fence_mode(vm));
249 
250 	down_write(&vm->lock);
251 	err = xe_validation_exec_lock(&ctx, &vm_exec, &vm->xe->val);
252 	if (err)
253 		goto out_up_write;
254 
255 	pfence = xe_preempt_fence_create(q, q->lr.context,
256 					 ++q->lr.seqno);
257 	if (IS_ERR(pfence)) {
258 		err = PTR_ERR(pfence);
259 		goto out_fini;
260 	}
261 
262 	list_add(&q->lr.link, &vm->preempt.exec_queues);
263 	++vm->preempt.num_exec_queues;
264 	q->lr.pfence = pfence;
265 
266 	xe_svm_notifier_lock(vm);
267 
268 	drm_gpuvm_resv_add_fence(&vm->gpuvm, exec, pfence,
269 				 DMA_RESV_USAGE_BOOKKEEP, DMA_RESV_USAGE_BOOKKEEP);
270 
271 	/*
272 	 * Check to see if a preemption on VM is in flight or userptr
273 	 * invalidation, if so trigger this preempt fence to sync state with
274 	 * other preempt fences on the VM.
275 	 *
276 	 * Also trigger it if eviction or rebinding is pending. BOs evicted
277 	 * before the first exec queue was added had no preempt fence to
278 	 * trigger. Suspend this queue until the rebind worker restores
279 	 * the mappings.
280 	 */
281 	wait = __xe_vm_userptr_needs_repin(vm) || preempt_fences_waiting(vm) ||
282 		!list_empty(&vm->gpuvm.evict.list) ||
283 		!list_empty(&vm->rebind_list);
284 	if (wait)
285 		dma_fence_enable_signaling(pfence);
286 
287 	xe_svm_notifier_unlock(vm);
288 
289 out_fini:
290 	xe_validation_ctx_fini(&ctx);
291 out_up_write:
292 	up_write(&vm->lock);
293 
294 	return err;
295 }
296 ALLOW_ERROR_INJECTION(xe_vm_add_compute_exec_queue, ERRNO);
297 
298 /**
299  * xe_vm_remove_compute_exec_queue() - Remove compute exec queue from VM
300  * @vm: The VM.
301  * @q: The exec_queue
302  *
303  * Note that this function might be called multiple times on the same queue.
304  */
305 void xe_vm_remove_compute_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q)
306 {
307 	if (!xe_vm_in_preempt_fence_mode(vm))
308 		return;
309 
310 	down_write(&vm->lock);
311 	if (!list_empty(&q->lr.link)) {
312 		list_del_init(&q->lr.link);
313 		--vm->preempt.num_exec_queues;
314 	}
315 	if (q->lr.pfence) {
316 		dma_fence_enable_signaling(q->lr.pfence);
317 		dma_fence_put(q->lr.pfence);
318 		q->lr.pfence = NULL;
319 	}
320 	up_write(&vm->lock);
321 }
322 
323 #define XE_VM_REBIND_RETRY_TIMEOUT_MS 1000
324 
325 /**
326  * xe_vm_kill() - VM Kill
327  * @vm: The VM.
328  * @unlocked: Flag indicates the VM's dma-resv is not held
329  *
330  * Kill the VM by setting banned flag indicated VM is no longer available for
331  * use. If in preempt fence mode, also kill all exec queue attached to the VM.
332  */
333 void xe_vm_kill(struct xe_vm *vm, bool unlocked)
334 {
335 	struct xe_exec_queue *q;
336 
337 	lockdep_assert_held(&vm->lock);
338 
339 	if (unlocked)
340 		xe_vm_lock(vm, false);
341 
342 	vm->flags |= XE_VM_FLAG_BANNED;
343 	trace_xe_vm_kill(vm);
344 
345 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link)
346 		q->ops->kill(q);
347 
348 	if (unlocked)
349 		xe_vm_unlock(vm);
350 
351 	/* TODO: Inform user the VM is banned */
352 }
353 
354 static int xe_gpuvm_validate(struct drm_gpuvm_bo *vm_bo, struct drm_exec *exec)
355 {
356 	struct xe_vm *vm = gpuvm_to_vm(vm_bo->vm);
357 	struct xe_bo *bo = gem_to_xe_bo(vm_bo->obj);
358 	struct drm_gpuva *gpuva;
359 	int ret;
360 
361 	lockdep_assert_held(&vm->lock);
362 	drm_gpuvm_bo_for_each_va(gpuva, vm_bo)
363 		list_move_tail(&gpuva_to_vma(gpuva)->combined_links.rebind,
364 			       &vm->rebind_list);
365 
366 	/* Skip re-populating purged BOs, rebind maps scratch pages. */
367 	if (xe_bo_is_purged(bo)) {
368 		vm_bo->evicted = false;
369 		return 0;
370 	}
371 
372 	if (!try_wait_for_completion(&vm->xe->pm_block))
373 		return -EAGAIN;
374 
375 	ret = xe_bo_validate(bo, vm, false, exec);
376 	if (ret)
377 		return ret;
378 
379 	vm_bo->evicted = false;
380 	return 0;
381 }
382 
383 /**
384  * xe_vm_validate_rebind() - Validate buffer objects and rebind vmas
385  * @vm: The vm for which we are rebinding.
386  * @exec: The struct drm_exec with the locked GEM objects.
387  * @num_fences: The number of fences to reserve for the operation, not
388  * including rebinds and validations.
389  *
390  * Validates all evicted gem objects and rebinds their vmas. Note that
391  * rebindings may cause evictions and hence the validation-rebind
392  * sequence is rerun until there are no more objects to validate.
393  *
394  * Return: 0 on success, negative error code on error. In particular,
395  * may return -EINTR or -ERESTARTSYS if interrupted, and -EDEADLK if
396  * the drm_exec transaction needs to be restarted.
397  */
398 int xe_vm_validate_rebind(struct xe_vm *vm, struct drm_exec *exec,
399 			  unsigned int num_fences)
400 {
401 	struct drm_gem_object *obj;
402 	int ret;
403 
404 	do {
405 		ret = drm_gpuvm_validate(&vm->gpuvm, exec);
406 		if (ret)
407 			return ret;
408 
409 		ret = xe_vm_rebind(vm, false);
410 		if (ret)
411 			return ret;
412 	} while (!list_empty(&vm->gpuvm.evict.list));
413 
414 	drm_exec_for_each_locked_object(exec, obj) {
415 		ret = dma_resv_reserve_fences(obj->resv, num_fences);
416 		if (ret)
417 			return ret;
418 	}
419 
420 	return 0;
421 }
422 
423 /**
424  * xe_vm_bump_lru() - Bump the LRU position of BOs used by a submission
425  * @vm: The vm for which we are bumping LRUs.
426  * @exec: The struct drm_exec with the locked GEM objects.
427  *
428  * Move the VM's private BOs, and all external objects locked by @exec,
429  * to the LRU tail. Private BOs are moved in bulk using @vm's
430  * &xe_vm.lru_bulk_move. External objects, which may be shared with other
431  * VMs, are not part of that bulk move and are bumped individually.
432  */
433 void xe_vm_bump_lru(struct xe_vm *vm, struct drm_exec *exec)
434 {
435 	spinlock_t *lru_lock = &vm->xe->ttm.lru_lock;
436 	struct drm_gem_object *obj;
437 
438 	spin_lock(lru_lock);
439 	ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
440 	drm_exec_for_each_locked_object(exec, obj) {
441 		if (!drm_gpuvm_is_extobj(&vm->gpuvm, obj))
442 			continue;
443 
444 		ttm_bo_move_to_lru_tail(&gem_to_xe_bo(obj)->ttm);
445 		cond_resched_lock(lru_lock);
446 	}
447 	spin_unlock(lru_lock);
448 }
449 
450 static int xe_preempt_work_begin(struct drm_exec *exec, struct xe_vm *vm,
451 				 bool *done)
452 {
453 	int err;
454 
455 	err = drm_gpuvm_prepare_vm(&vm->gpuvm, exec, 0);
456 	if (err)
457 		return err;
458 
459 	if (xe_vm_is_idle(vm)) {
460 		vm->preempt.rebind_deactivated = true;
461 		*done = true;
462 		return 0;
463 	}
464 
465 	if (!preempt_fences_waiting(vm)) {
466 		*done = true;
467 		return 0;
468 	}
469 
470 	err = drm_gpuvm_prepare_objects(&vm->gpuvm, exec, 0);
471 	if (err)
472 		return err;
473 
474 	err = wait_for_existing_preempt_fences(vm);
475 	if (err)
476 		return err;
477 
478 	/*
479 	 * Add validation and rebinding to the locking loop since both can
480 	 * cause evictions which may require blocing dma_resv locks.
481 	 * The fence reservation here is intended for the new preempt fences
482 	 * we attach at the end of the rebind work.
483 	 */
484 	return xe_vm_validate_rebind(vm, exec, vm->preempt.num_exec_queues);
485 }
486 
487 static bool vm_suspend_rebind_worker(struct xe_vm *vm)
488 {
489 	struct xe_device *xe = vm->xe;
490 	bool ret = false;
491 
492 	mutex_lock(&xe->rebind_resume_lock);
493 	if (!try_wait_for_completion(&vm->xe->pm_block)) {
494 		ret = true;
495 		list_move_tail(&vm->preempt.pm_activate_link, &xe->rebind_resume_list);
496 	}
497 	mutex_unlock(&xe->rebind_resume_lock);
498 
499 	return ret;
500 }
501 
502 /**
503  * xe_vm_resume_rebind_worker() - Resume the rebind worker.
504  * @vm: The vm whose preempt worker to resume.
505  *
506  * Resume a preempt worker that was previously suspended by
507  * vm_suspend_rebind_worker().
508  */
509 void xe_vm_resume_rebind_worker(struct xe_vm *vm)
510 {
511 	queue_work(vm->xe->ordered_wq, &vm->preempt.rebind_work);
512 }
513 
514 static void preempt_rebind_work_func(struct work_struct *w)
515 {
516 	struct xe_vm *vm = container_of(w, struct xe_vm, preempt.rebind_work);
517 	struct xe_validation_ctx ctx;
518 	struct drm_exec exec;
519 	unsigned int fence_count = 0;
520 	LIST_HEAD(preempt_fences);
521 	int err = 0;
522 	long wait;
523 	int __maybe_unused tries = 0;
524 
525 	xe_assert(vm->xe, xe_vm_in_preempt_fence_mode(vm));
526 	trace_xe_vm_rebind_worker_enter(vm);
527 
528 	down_write(&vm->lock);
529 
530 	if (xe_vm_is_closed_or_banned(vm)) {
531 		up_write(&vm->lock);
532 		trace_xe_vm_rebind_worker_exit(vm);
533 		return;
534 	}
535 
536 retry:
537 	if (!try_wait_for_completion(&vm->xe->pm_block) && vm_suspend_rebind_worker(vm)) {
538 		up_write(&vm->lock);
539 		/* We don't actually block but don't make progress. */
540 		xe_pm_might_block_on_suspend();
541 		return;
542 	}
543 
544 	if (xe_vm_userptr_check_repin(vm)) {
545 		err = xe_vm_userptr_pin(vm);
546 		if (err)
547 			goto out_unlock_outer;
548 	}
549 
550 	err = xe_validation_ctx_init(&ctx, &vm->xe->val, &exec,
551 				     (struct xe_val_flags) {.interruptible = true});
552 	if (err)
553 		goto out_unlock_outer;
554 
555 	drm_exec_until_all_locked(&exec) {
556 		bool done = false;
557 
558 		err = xe_preempt_work_begin(&exec, vm, &done);
559 		drm_exec_retry_on_contention(&exec);
560 		xe_validation_retry_on_oom(&ctx, &err);
561 		if (err || done) {
562 			xe_validation_ctx_fini(&ctx);
563 			goto out_unlock_outer;
564 		}
565 	}
566 
567 	err = alloc_preempt_fences(vm, &preempt_fences, &fence_count);
568 	if (err)
569 		goto out_unlock;
570 
571 	xe_vm_set_validation_exec(vm, &exec);
572 	err = xe_vm_rebind(vm, true);
573 	xe_vm_set_validation_exec(vm, NULL);
574 	if (err)
575 		goto out_unlock;
576 
577 	/* Wait on rebinds and munmap style VM unbinds */
578 	wait = dma_resv_wait_timeout(xe_vm_resv(vm),
579 				     DMA_RESV_USAGE_KERNEL,
580 				     false, MAX_SCHEDULE_TIMEOUT);
581 	if (wait <= 0) {
582 		err = -ETIME;
583 		goto out_unlock;
584 	}
585 
586 #define retry_required(__tries, __vm) \
587 	(IS_ENABLED(CONFIG_DRM_XE_USERPTR_INVAL_INJECT) ? \
588 	(!(__tries)++ || __xe_vm_userptr_needs_repin(__vm)) : \
589 	__xe_vm_userptr_needs_repin(__vm))
590 
591 	xe_svm_notifier_lock(vm);
592 	if (retry_required(tries, vm)) {
593 		xe_svm_notifier_unlock(vm);
594 		err = -EAGAIN;
595 		goto out_unlock;
596 	}
597 
598 #undef retry_required
599 
600 	xe_vm_bump_lru(vm, &exec);
601 
602 	/* Point of no return. */
603 	arm_preempt_fences(vm, &preempt_fences);
604 	resume_and_reinstall_preempt_fences(vm, &exec);
605 	xe_svm_notifier_unlock(vm);
606 
607 out_unlock:
608 	xe_validation_ctx_fini(&ctx);
609 out_unlock_outer:
610 	if (err == -EAGAIN) {
611 		trace_xe_vm_rebind_worker_retry(vm);
612 
613 		/*
614 		 * We can't block in workers on a VF which supports migration
615 		 * given this can block the VF post-migration workers from
616 		 * getting scheduled.
617 		 */
618 		if (IS_SRIOV_VF(vm->xe) &&
619 		    xe_sriov_vf_migration_supported(vm->xe)) {
620 			up_write(&vm->lock);
621 			xe_vm_queue_rebind_worker(vm);
622 			return;
623 		}
624 
625 		goto retry;
626 	}
627 
628 	if (err) {
629 		drm_warn(&vm->xe->drm, "VM worker error: %d\n", err);
630 		xe_vm_kill(vm, true);
631 	}
632 	up_write(&vm->lock);
633 
634 	free_preempt_fences(&preempt_fences);
635 
636 	trace_xe_vm_rebind_worker_exit(vm);
637 }
638 
639 /**
640  * xe_vm_add_fault_entry_pf() - Add pagefault to vm fault list
641  * @vm: The VM.
642  * @pf: The pagefault.
643  *
644  * This function takes the data from the pagefault @pf and saves it to @vm->faults.list.
645  *
646  * The function exits silently if the list is full, and reports a warning if the pagefault
647  * could not be saved to the list.
648  */
649 void xe_vm_add_fault_entry_pf(struct xe_vm *vm, struct xe_pagefault *pf)
650 {
651 	struct xe_vm_fault_entry *e;
652 	struct xe_hw_engine *hwe;
653 	u8 engine_class = FIELD_GET(XE_PAGEFAULT_ENGINE_CLASS_MASK,
654 				    pf->consumer.engine_class_instance);
655 	u8 engine_instance = FIELD_GET(XE_PAGEFAULT_ENGINE_INSTANCE_MASK,
656 				       pf->consumer.engine_class_instance);
657 
658 	/* Do not report faults on reserved engines */
659 	hwe = xe_gt_hw_engine(pf->gt, engine_class, engine_instance, false);
660 	if (!hwe || xe_hw_engine_is_reserved(hwe))
661 		return;
662 
663 	e = kzalloc_obj(*e);
664 	if (!e) {
665 		drm_warn(&vm->xe->drm,
666 			 "Could not allocate memory for fault!\n");
667 		return;
668 	}
669 
670 	guard(spinlock)(&vm->faults.lock);
671 
672 	/*
673 	 * Limit the number of faults in the fault list to prevent
674 	 * memory overuse.
675 	 */
676 	if (vm->faults.len >= MAX_FAULTS_SAVED_PER_VM) {
677 		kfree(e);
678 		return;
679 	}
680 
681 	e->address = xe_pagefault_addr(pf);
682 	/*
683 	 * TODO:
684 	 * Address precision is currently always SZ_4K, but this may change
685 	 * in the future.
686 	 */
687 	e->address_precision = SZ_4K;
688 	e->access_type = pf->consumer.access_type;
689 	e->fault_type = FIELD_GET(XE_PAGEFAULT_TYPE_MASK,
690 				  pf->consumer.fault_type_level);
691 	e->fault_level = FIELD_GET(XE_PAGEFAULT_LEVEL_MASK,
692 				   pf->consumer.fault_type_level);
693 	e->srcid = FIELD_GET(XE_PAGEFAULT_SRCID_MASK, pf->consumer.id);
694 
695 	list_add_tail(&e->list, &vm->faults.list);
696 	vm->faults.len++;
697 }
698 
699 static void xe_vm_clear_fault_entries(struct xe_vm *vm)
700 {
701 	struct xe_vm_fault_entry *e, *tmp;
702 
703 	guard(spinlock)(&vm->faults.lock);
704 	list_for_each_entry_safe(e, tmp, &vm->faults.list, list) {
705 		list_del(&e->list);
706 		kfree(e);
707 	}
708 	vm->faults.len = 0;
709 }
710 
711 static noinline int xe_vma_ops_alloc(struct xe_vma_ops *vops, bool array_of_binds)
712 {
713 	int i;
714 
715 	for (i = 0; i < XE_MAX_TILES_PER_DEVICE; ++i) {
716 		if (!vops->pt_update_ops[i].num_ops)
717 			continue;
718 
719 		vops->pt_update_ops[i].pt_job_ops =
720 			xe_pt_job_ops_alloc(vops->pt_update_ops[i].num_ops);
721 		if (!vops->pt_update_ops[i].pt_job_ops)
722 			return array_of_binds ? -ENOBUFS : -ENOMEM;
723 	}
724 
725 	return 0;
726 }
727 ALLOW_ERROR_INJECTION(xe_vma_ops_alloc, ERRNO);
728 
729 static void xe_vma_svm_prefetch_ranges_fini(struct xe_vma_op *op)
730 {
731 	struct xe_svm_range *svm_range;
732 	unsigned long i;
733 
734 	xa_for_each(&op->prefetch_range.range, i, svm_range)
735 		xe_svm_range_put(svm_range);
736 
737 	xa_destroy(&op->prefetch_range.range);
738 }
739 
740 static void xe_vma_svm_prefetch_op_fini(struct xe_vma_op *op)
741 {
742 	struct xe_vma *vma;
743 
744 	vma = gpuva_to_vma(op->base.prefetch.va);
745 
746 	if (op->base.op == DRM_GPUVA_OP_PREFETCH && xe_vma_is_cpu_addr_mirror(vma))
747 		xe_vma_svm_prefetch_ranges_fini(op);
748 }
749 
750 static void xe_vma_svm_prefetch_ops_fini(struct xe_vma_ops *vops)
751 {
752 	struct xe_vma_op *op;
753 
754 	if (!(vops->flags & XE_VMA_OPS_FLAG_HAS_SVM_PREFETCH))
755 		return;
756 
757 	list_for_each_entry(op, &vops->list, link)
758 		xe_vma_svm_prefetch_op_fini(op);
759 }
760 
761 static void xe_vma_ops_fini(struct xe_vma_ops *vops)
762 {
763 	int i;
764 
765 	xe_vma_svm_prefetch_ops_fini(vops);
766 
767 	for (i = 0; i < XE_MAX_TILES_PER_DEVICE; ++i)
768 		xe_pt_job_ops_put(vops->pt_update_ops[i].pt_job_ops);
769 }
770 
771 static void xe_vma_ops_incr_pt_update_ops(struct xe_vma_ops *vops, u8 tile_mask, int inc_val)
772 {
773 	int i;
774 
775 	if (!inc_val)
776 		return;
777 
778 	for (i = 0; i < XE_MAX_TILES_PER_DEVICE; ++i)
779 		if (BIT(i) & tile_mask)
780 			vops->pt_update_ops[i].num_ops += inc_val;
781 }
782 
783 #define XE_VMA_CREATE_MASK (		    \
784 	XE_VMA_READ_ONLY |		    \
785 	XE_VMA_DUMPABLE |		    \
786 	XE_VMA_SYSTEM_ALLOCATOR |           \
787 	DRM_GPUVA_SPARSE |		    \
788 	XE_VMA_MADV_AUTORESET)
789 
790 static void xe_vm_populate_rebind(struct xe_vma_op *op, struct xe_vma *vma,
791 				  u8 tile_mask)
792 {
793 	INIT_LIST_HEAD(&op->link);
794 	op->tile_mask = tile_mask;
795 	op->base.op = DRM_GPUVA_OP_MAP;
796 	op->base.map.va.addr = vma->gpuva.va.addr;
797 	op->base.map.va.range = vma->gpuva.va.range;
798 	op->base.map.gem.obj = vma->gpuva.gem.obj;
799 	op->base.map.gem.offset = vma->gpuva.gem.offset;
800 	op->map.vma = vma;
801 	op->map.immediate = true;
802 	op->map.vma_flags = vma->gpuva.flags & XE_VMA_CREATE_MASK;
803 }
804 
805 static int xe_vm_ops_add_rebind(struct xe_vma_ops *vops, struct xe_vma *vma,
806 				u8 tile_mask)
807 {
808 	struct xe_vma_op *op;
809 
810 	op = kzalloc_obj(*op);
811 	if (!op)
812 		return -ENOMEM;
813 
814 	xe_vm_populate_rebind(op, vma, tile_mask);
815 	list_add_tail(&op->link, &vops->list);
816 	xe_vma_ops_incr_pt_update_ops(vops, tile_mask, 1);
817 
818 	return 0;
819 }
820 
821 static struct dma_fence *ops_execute(struct xe_vm *vm,
822 				     struct xe_vma_ops *vops);
823 static void xe_vma_ops_init(struct xe_vma_ops *vops, struct xe_vm *vm,
824 			    struct xe_exec_queue *q,
825 			    struct xe_sync_entry *syncs, u32 num_syncs);
826 
827 int xe_vm_rebind(struct xe_vm *vm, bool rebind_worker)
828 {
829 	struct dma_fence *fence;
830 	struct xe_vma *vma, *next;
831 	struct xe_vma_ops vops;
832 	struct xe_vma_op *op, *next_op;
833 	int err;
834 
835 	lockdep_assert_held(&vm->lock);
836 	if ((xe_vm_in_lr_mode(vm) && !rebind_worker) ||
837 	    list_empty(&vm->rebind_list))
838 		return 0;
839 
840 	xe_vma_ops_init(&vops, vm, xe_cpu_bind_queue(vm->xe->cpu_bind),
841 			NULL, 0);
842 	vops.flags |= XE_VMA_OPS_FLAG_WAIT_VM_BOOKKEEP;
843 
844 	xe_vm_assert_held(vm);
845 	list_for_each_entry(vma, &vm->rebind_list, combined_links.rebind) {
846 		xe_assert(vm->xe, vma->tile_present);
847 
848 		if (rebind_worker)
849 			trace_xe_vma_rebind_worker(vma);
850 		else
851 			trace_xe_vma_rebind_exec(vma);
852 
853 		err = xe_vm_ops_add_rebind(&vops, vma,
854 					   vma->tile_present);
855 		if (err)
856 			goto free_ops;
857 	}
858 
859 	err = xe_vma_ops_alloc(&vops, false);
860 	if (err)
861 		goto free_ops;
862 
863 	fence = ops_execute(vm, &vops);
864 	if (IS_ERR(fence)) {
865 		err = PTR_ERR(fence);
866 	} else {
867 		dma_fence_put(fence);
868 		list_for_each_entry_safe(vma, next, &vm->rebind_list,
869 					 combined_links.rebind)
870 			list_del_init(&vma->combined_links.rebind);
871 	}
872 free_ops:
873 	list_for_each_entry_safe(op, next_op, &vops.list, link) {
874 		list_del(&op->link);
875 		kfree(op);
876 	}
877 	xe_vma_ops_fini(&vops);
878 
879 	return err;
880 }
881 
882 static u8 adjust_rebind_tile_mask(struct xe_vm *vm, u8 tile_mask)
883 {
884 	if (vm->xe->info.has_pt_mirror)
885 		return tile_mask;
886 
887 	return (0x1 << vm->xe->info.tile_count) - 1;
888 }
889 
890 struct dma_fence *xe_vma_rebind(struct xe_vm *vm, struct xe_vma *vma, u8 tile_mask)
891 {
892 	struct dma_fence *fence = NULL;
893 	struct xe_vma_ops vops;
894 	struct xe_vma_op *op, *next_op;
895 	int err;
896 
897 	lockdep_assert_held(&vm->lock);
898 	xe_vm_assert_held(vm);
899 	xe_assert(vm->xe, xe_vm_in_fault_mode(vm));
900 
901 	xe_vma_ops_init(&vops, vm, xe_cpu_bind_queue(vm->xe->cpu_bind),
902 			NULL, 0);
903 	vops.flags |= XE_VMA_OPS_FLAG_SKIP_TLB_WAIT |
904 		XE_VMA_OPS_FLAG_WAIT_VM_BOOKKEEP;
905 
906 	err = xe_vm_ops_add_rebind(&vops, vma,
907 				   adjust_rebind_tile_mask(vm, tile_mask));
908 	if (err)
909 		return ERR_PTR(err);
910 
911 	err = xe_vma_ops_alloc(&vops, false);
912 	if (err) {
913 		fence = ERR_PTR(err);
914 		goto free_ops;
915 	}
916 
917 	fence = ops_execute(vm, &vops);
918 
919 free_ops:
920 	list_for_each_entry_safe(op, next_op, &vops.list, link) {
921 		list_del(&op->link);
922 		kfree(op);
923 	}
924 	xe_vma_ops_fini(&vops);
925 
926 	return fence;
927 }
928 
929 static void xe_vm_populate_range_rebind(struct xe_vma_op *op,
930 					struct xe_vma *vma,
931 					struct xe_svm_range *range,
932 					u8 tile_mask)
933 {
934 	INIT_LIST_HEAD(&op->link);
935 	op->tile_mask = tile_mask;
936 	op->base.op = DRM_GPUVA_OP_DRIVER;
937 	op->subop = XE_VMA_SUBOP_MAP_RANGE;
938 	op->map_range.vma = vma;
939 	op->map_range.range = range;
940 }
941 
942 static int
943 xe_vm_ops_add_range_rebind(struct xe_vma_ops *vops,
944 			   struct xe_vma *vma,
945 			   struct xe_svm_range *range,
946 			   u8 tile_mask)
947 {
948 	struct xe_vma_op *op;
949 
950 	op = kzalloc_obj(*op);
951 	if (!op)
952 		return -ENOMEM;
953 
954 	xe_vm_populate_range_rebind(op, vma, range, tile_mask);
955 	list_add_tail(&op->link, &vops->list);
956 	xe_vma_ops_incr_pt_update_ops(vops, tile_mask, 1);
957 
958 	return 0;
959 }
960 
961 /**
962  * xe_vm_range_rebind() - VM range (re)bind
963  * @vm: The VM which the range belongs to.
964  * @vma: The VMA which the range belongs to.
965  * @range: SVM range to rebind.
966  * @tile_mask: Tile mask to bind the range to.
967  *
968  * (re)bind SVM range setting up GPU page tables for the range.
969  *
970  * Return: dma fence for rebind to signal completion on success, ERR_PTR on
971  * failure
972  */
973 struct dma_fence *xe_vm_range_rebind(struct xe_vm *vm,
974 				     struct xe_vma *vma,
975 				     struct xe_svm_range *range,
976 				     u8 tile_mask)
977 {
978 	struct dma_fence *fence = NULL;
979 	struct xe_vma_ops vops;
980 	struct xe_vma_op *op, *next_op;
981 	int err;
982 
983 	lockdep_assert_held(&range->lock);
984 	lockdep_assert_held(&vm->lock);
985 	xe_vm_assert_held(vm);
986 	xe_assert(vm->xe, xe_vm_in_fault_mode(vm));
987 	xe_assert(vm->xe, xe_vma_is_cpu_addr_mirror(vma));
988 
989 	xe_vma_ops_init(&vops, vm, xe_cpu_bind_queue(vm->xe->cpu_bind),
990 			NULL, 0);
991 	vops.flags |= XE_VMA_OPS_FLAG_SKIP_TLB_WAIT |
992 		XE_VMA_OPS_FLAG_WAIT_VM_BOOKKEEP;
993 
994 	err = xe_vm_ops_add_range_rebind(&vops, vma, range,
995 					 adjust_rebind_tile_mask(vm, tile_mask));
996 	if (err)
997 		return ERR_PTR(err);
998 
999 	err = xe_vma_ops_alloc(&vops, false);
1000 	if (err) {
1001 		fence = ERR_PTR(err);
1002 		goto free_ops;
1003 	}
1004 
1005 	fence = ops_execute(vm, &vops);
1006 
1007 free_ops:
1008 	list_for_each_entry_safe(op, next_op, &vops.list, link) {
1009 		list_del(&op->link);
1010 		kfree(op);
1011 	}
1012 	xe_vma_ops_fini(&vops);
1013 
1014 	return fence;
1015 }
1016 
1017 static void xe_vm_populate_range_unbind(struct xe_vma_op *op,
1018 					struct xe_svm_range *range)
1019 {
1020 	INIT_LIST_HEAD(&op->link);
1021 	op->tile_mask = range->tile_present;
1022 	op->base.op = DRM_GPUVA_OP_DRIVER;
1023 	op->subop = XE_VMA_SUBOP_UNMAP_RANGE;
1024 	op->unmap_range.range = range;
1025 }
1026 
1027 static int
1028 xe_vm_ops_add_range_unbind(struct xe_vma_ops *vops,
1029 			   struct xe_svm_range *range)
1030 {
1031 	struct xe_vma_op *op;
1032 
1033 	op = kzalloc_obj(*op);
1034 	if (!op)
1035 		return -ENOMEM;
1036 
1037 	xe_vm_populate_range_unbind(op, range);
1038 	list_add_tail(&op->link, &vops->list);
1039 	xe_vma_ops_incr_pt_update_ops(vops, range->tile_present, 1);
1040 
1041 	return 0;
1042 }
1043 
1044 /**
1045  * xe_vm_range_unbind() - VM range unbind
1046  * @vm: The VM which the range belongs to.
1047  * @range: SVM range to rebind.
1048  *
1049  * Unbind SVM range removing the GPU page tables for the range.
1050  *
1051  * Return: dma fence for unbind to signal completion on success, ERR_PTR on
1052  * failure
1053  */
1054 struct dma_fence *xe_vm_range_unbind(struct xe_vm *vm,
1055 				     struct xe_svm_range *range)
1056 {
1057 	struct dma_fence *fence = NULL;
1058 	struct xe_vma_ops vops;
1059 	struct xe_vma_op *op, *next_op;
1060 	int err;
1061 
1062 	lockdep_assert_held(&range->lock);
1063 	lockdep_assert_held(&vm->lock);
1064 	xe_vm_assert_held(vm);
1065 	xe_assert(vm->xe, xe_vm_in_fault_mode(vm));
1066 
1067 	if (!range->tile_present)
1068 		return dma_fence_get_stub();
1069 
1070 	xe_vma_ops_init(&vops, vm, xe_cpu_bind_queue(vm->xe->cpu_bind),
1071 			NULL, 0);
1072 	vops.flags |= XE_VMA_OPS_FLAG_WAIT_VM_BOOKKEEP;
1073 
1074 	err = xe_vm_ops_add_range_unbind(&vops, range);
1075 	if (err)
1076 		return ERR_PTR(err);
1077 
1078 	err = xe_vma_ops_alloc(&vops, false);
1079 	if (err) {
1080 		fence = ERR_PTR(err);
1081 		goto free_ops;
1082 	}
1083 
1084 	fence = ops_execute(vm, &vops);
1085 
1086 free_ops:
1087 	list_for_each_entry_safe(op, next_op, &vops.list, link) {
1088 		list_del(&op->link);
1089 		kfree(op);
1090 	}
1091 	xe_vma_ops_fini(&vops);
1092 
1093 	return fence;
1094 }
1095 
1096 static void xe_vma_mem_attr_fini(struct xe_vma_mem_attr *attr)
1097 {
1098 	drm_pagemap_put(attr->preferred_loc.dpagemap);
1099 }
1100 
1101 static void xe_vma_free(struct xe_vma *vma)
1102 {
1103 	xe_vma_mem_attr_fini(&vma->attr);
1104 
1105 	if (xe_vma_is_userptr(vma))
1106 		kfree(to_userptr_vma(vma));
1107 	else
1108 		kfree(vma);
1109 }
1110 
1111 /**
1112  * xe_vma_mem_attr_copy() - copy an xe_vma_mem_attr structure.
1113  * @to: Destination.
1114  * @from: Source.
1115  *
1116  * Copies an xe_vma_mem_attr structure taking care to get reference
1117  * counting of individual members right.
1118  */
1119 void xe_vma_mem_attr_copy(struct xe_vma_mem_attr *to, struct xe_vma_mem_attr *from)
1120 {
1121 	xe_vma_mem_attr_fini(to);
1122 	*to = *from;
1123 	if (to->preferred_loc.dpagemap)
1124 		drm_pagemap_get(to->preferred_loc.dpagemap);
1125 }
1126 
1127 static struct xe_vma *xe_vma_create(struct xe_vm *vm,
1128 				    struct xe_bo *bo,
1129 				    u64 bo_offset_or_userptr,
1130 				    u64 start, u64 end,
1131 				    struct xe_vma_mem_attr *attr,
1132 				    unsigned int flags)
1133 {
1134 	struct xe_vma *vma;
1135 	struct xe_tile *tile;
1136 	u8 id;
1137 	bool is_null = (flags & DRM_GPUVA_SPARSE);
1138 	bool is_cpu_addr_mirror = (flags & XE_VMA_SYSTEM_ALLOCATOR);
1139 
1140 	xe_assert(vm->xe, start < end);
1141 	xe_assert(vm->xe, end < vm->size);
1142 
1143 	/*
1144 	 * Allocate and ensure that the xe_vma_is_userptr() return
1145 	 * matches what was allocated.
1146 	 */
1147 	if (!bo && !is_null && !is_cpu_addr_mirror) {
1148 		struct xe_userptr_vma *uvma = kzalloc_obj(*uvma);
1149 
1150 		if (!uvma)
1151 			return ERR_PTR(-ENOMEM);
1152 
1153 		vma = &uvma->vma;
1154 	} else {
1155 		vma = kzalloc_obj(*vma);
1156 		if (!vma)
1157 			return ERR_PTR(-ENOMEM);
1158 
1159 		if (bo)
1160 			vma->gpuva.gem.obj = &bo->ttm.base;
1161 	}
1162 
1163 	INIT_LIST_HEAD(&vma->combined_links.rebind);
1164 
1165 	INIT_LIST_HEAD(&vma->gpuva.gem.entry);
1166 	vma->gpuva.vm = &vm->gpuvm;
1167 	vma->gpuva.va.addr = start;
1168 	vma->gpuva.va.range = end - start + 1;
1169 	vma->gpuva.flags = flags;
1170 
1171 	for_each_tile(tile, vm->xe, id)
1172 		vma->tile_mask |= 0x1 << id;
1173 
1174 	if (vm->xe->info.has_atomic_enable_pte_bit)
1175 		vma->gpuva.flags |= XE_VMA_ATOMIC_PTE_BIT;
1176 
1177 	xe_vma_mem_attr_copy(&vma->attr, attr);
1178 	if (bo) {
1179 		struct drm_gpuvm_bo *vm_bo;
1180 
1181 		xe_bo_assert_held(bo);
1182 
1183 		/*
1184 		 * Reject only WILLNEED mappings on DONTNEED/PURGED BOs. This
1185 		 * gates new vm_bind ioctls (user supplies WILLNEED) while
1186 		 * still allowing partial-unbind / remap splits whose new VMAs
1187 		 * inherit the parent's DONTNEED attr. It must also run before
1188 		 * xe_bo_willneed_get_locked() below so a 0->1 holder bump
1189 		 * cannot silently promote DONTNEED back to WILLNEED.
1190 		 */
1191 		if (vma->attr.purgeable_state == XE_MADV_PURGEABLE_WILLNEED) {
1192 			if (xe_bo_madv_is_dontneed(bo)) {
1193 				xe_vma_free(vma);
1194 				return ERR_PTR(-EBUSY);
1195 			}
1196 			if (xe_bo_is_purged(bo)) {
1197 				xe_vma_free(vma);
1198 				return ERR_PTR(-EINVAL);
1199 			}
1200 		}
1201 
1202 		vm_bo = drm_gpuvm_bo_obtain_locked(vma->gpuva.vm, &bo->ttm.base);
1203 		if (IS_ERR(vm_bo)) {
1204 			xe_vma_free(vma);
1205 			return ERR_CAST(vm_bo);
1206 		}
1207 
1208 		drm_gpuvm_bo_extobj_add(vm_bo);
1209 		drm_gem_object_get(&bo->ttm.base);
1210 		vma->gpuva.gem.offset = bo_offset_or_userptr;
1211 		drm_gpuva_link(&vma->gpuva, vm_bo);
1212 		drm_gpuvm_bo_put(vm_bo);
1213 
1214 		xe_bo_vma_count_inc_locked(bo);
1215 		if (vma->attr.purgeable_state == XE_MADV_PURGEABLE_WILLNEED)
1216 			xe_bo_willneed_get_locked(bo);
1217 	} else /* userptr or null */ {
1218 		if (!is_null && !is_cpu_addr_mirror) {
1219 			struct xe_userptr_vma *uvma = to_userptr_vma(vma);
1220 			u64 size = end - start + 1;
1221 			int err;
1222 
1223 			vma->gpuva.gem.offset = bo_offset_or_userptr;
1224 
1225 			err = xe_userptr_setup(uvma, xe_vma_userptr(vma), size);
1226 			if (err) {
1227 				xe_vma_free(vma);
1228 				return ERR_PTR(err);
1229 			}
1230 		}
1231 
1232 		xe_vm_get(vm);
1233 	}
1234 
1235 	mutex_init(&vma->fault_lock);
1236 
1237 	return vma;
1238 }
1239 
1240 static void xe_vma_destroy_late(struct xe_vma *vma)
1241 {
1242 	struct xe_vm *vm = xe_vma_vm(vma);
1243 	struct xe_bo *bo = xe_vma_bo(vma);
1244 
1245 	if (vma->ufence) {
1246 		xe_sync_ufence_put(vma->ufence);
1247 		vma->ufence = NULL;
1248 	}
1249 
1250 	if (xe_vma_is_userptr(vma)) {
1251 		struct xe_userptr_vma *uvma = to_userptr_vma(vma);
1252 
1253 		xe_userptr_remove(uvma);
1254 		xe_vm_put(vm);
1255 	} else if (xe_vma_is_null(vma) || xe_vma_is_cpu_addr_mirror(vma)) {
1256 		xe_vm_put(vm);
1257 	} else {
1258 		xe_bo_put(bo);
1259 	}
1260 
1261 	mutex_destroy(&vma->fault_lock);
1262 	xe_vma_free(vma);
1263 }
1264 
1265 static void vma_destroy_work_func(struct work_struct *w)
1266 {
1267 	struct xe_vma *vma =
1268 		container_of(w, struct xe_vma, destroy_work);
1269 
1270 	xe_vma_destroy_late(vma);
1271 }
1272 
1273 static void vma_destroy_cb(struct dma_fence *fence,
1274 			   struct dma_fence_cb *cb)
1275 {
1276 	struct xe_vma *vma = container_of(cb, struct xe_vma, destroy_cb);
1277 
1278 	INIT_WORK(&vma->destroy_work, vma_destroy_work_func);
1279 	queue_work(system_dfl_wq, &vma->destroy_work);
1280 }
1281 
1282 static void xe_vm_assert_write_mode_or_garbage_collector(struct xe_vm *vm)
1283 {
1284 	lockdep_assert(lockdep_is_held_type(&vm->lock, 0) ||
1285 		       (lockdep_is_held_type(&vm->lock, 1) &&
1286 			lockdep_is_held_type(&vm->svm.garbage_collector.lock, 0)));
1287 }
1288 
1289 static void xe_vma_destroy(struct xe_vma *vma, struct dma_fence *fence)
1290 {
1291 	struct xe_vm *vm = xe_vma_vm(vma);
1292 	struct xe_bo *bo = xe_vma_bo(vma);
1293 
1294 	xe_vm_assert_write_mode_or_garbage_collector(vm);
1295 	xe_assert(vm->xe, list_empty(&vma->combined_links.destroy));
1296 
1297 	if (xe_vma_is_userptr(vma)) {
1298 		xe_assert(vm->xe, vma->gpuva.flags & XE_VMA_DESTROYED);
1299 		xe_userptr_destroy(to_userptr_vma(vma));
1300 	} else if (!xe_vma_is_null(vma) && !xe_vma_is_cpu_addr_mirror(vma)) {
1301 		xe_bo_assert_held(bo);
1302 
1303 		drm_gpuva_unlink(&vma->gpuva);
1304 
1305 		xe_bo_vma_count_dec_locked(bo);
1306 		if (vma->attr.purgeable_state == XE_MADV_PURGEABLE_WILLNEED)
1307 			xe_bo_willneed_put_locked(bo);
1308 	}
1309 
1310 	xe_vm_assert_held(vm);
1311 	if (fence) {
1312 		int ret = dma_fence_add_callback(fence, &vma->destroy_cb,
1313 						 vma_destroy_cb);
1314 
1315 		if (ret) {
1316 			XE_WARN_ON(ret != -ENOENT);
1317 			xe_vma_destroy_late(vma);
1318 		}
1319 	} else {
1320 		xe_vma_destroy_late(vma);
1321 	}
1322 }
1323 
1324 /**
1325  * xe_vm_lock_vma() - drm_exec utility to lock a vma
1326  * @exec: The drm_exec object we're currently locking for.
1327  * @vma: The vma for witch we want to lock the vm resv and any attached
1328  * object's resv.
1329  *
1330  * Return: 0 on success, negative error code on error. In particular
1331  * may return -EDEADLK on WW transaction contention and -EINTR if
1332  * an interruptible wait is terminated by a signal.
1333  */
1334 int xe_vm_lock_vma(struct drm_exec *exec, struct xe_vma *vma)
1335 {
1336 	struct xe_vm *vm = xe_vma_vm(vma);
1337 	struct xe_bo *bo = xe_vma_bo(vma);
1338 	int err;
1339 
1340 	XE_WARN_ON(!vm);
1341 
1342 	err = drm_exec_lock_obj(exec, xe_vm_obj(vm));
1343 	if (!err && bo && !bo->vm)
1344 		err = drm_exec_lock_obj(exec, &bo->ttm.base);
1345 
1346 	return err;
1347 }
1348 
1349 static void xe_vma_destroy_unlocked(struct xe_vma *vma)
1350 {
1351 	struct xe_device *xe = xe_vma_vm(vma)->xe;
1352 	struct xe_validation_ctx ctx;
1353 	struct drm_exec exec;
1354 	int err = 0;
1355 
1356 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {}, err) {
1357 		err = xe_vm_lock_vma(&exec, vma);
1358 		drm_exec_retry_on_contention(&exec);
1359 		if (XE_WARN_ON(err))
1360 			break;
1361 		xe_vma_destroy(vma, NULL);
1362 	}
1363 	xe_assert(xe, !err);
1364 }
1365 
1366 struct xe_vma *
1367 xe_vm_find_overlapping_vma(struct xe_vm *vm, u64 start, u64 range)
1368 {
1369 	struct drm_gpuva *gpuva;
1370 
1371 	lockdep_assert_held(&vm->lock);
1372 
1373 	if (xe_vm_is_closed_or_banned(vm))
1374 		return NULL;
1375 
1376 	xe_assert(vm->xe, start + range <= vm->size);
1377 
1378 	mutex_lock(&vm->snap_mutex);
1379 	gpuva = drm_gpuva_find_first(&vm->gpuvm, start, range);
1380 	mutex_unlock(&vm->snap_mutex);
1381 
1382 	return gpuva ? gpuva_to_vma(gpuva) : NULL;
1383 }
1384 
1385 static int xe_vm_insert_vma(struct xe_vm *vm, struct xe_vma *vma)
1386 {
1387 	int err;
1388 
1389 	xe_assert(vm->xe, xe_vma_vm(vma) == vm);
1390 	xe_vm_assert_write_mode_or_garbage_collector(vm);
1391 
1392 	mutex_lock(&vm->snap_mutex);
1393 	err = drm_gpuva_insert(&vm->gpuvm, &vma->gpuva);
1394 	mutex_unlock(&vm->snap_mutex);
1395 	XE_WARN_ON(err);	/* Shouldn't be possible */
1396 
1397 	return err;
1398 }
1399 
1400 static void xe_vm_remove_vma(struct xe_vm *vm, struct xe_vma *vma)
1401 {
1402 	xe_assert(vm->xe, xe_vma_vm(vma) == vm);
1403 	xe_vm_assert_write_mode_or_garbage_collector(vm);
1404 
1405 	mutex_lock(&vm->snap_mutex);
1406 	drm_gpuva_remove(&vma->gpuva);
1407 	mutex_unlock(&vm->snap_mutex);
1408 }
1409 
1410 static struct drm_gpuva_op *xe_vm_op_alloc(void)
1411 {
1412 	struct xe_vma_op *op;
1413 
1414 	op = kzalloc_obj(*op);
1415 
1416 	if (unlikely(!op))
1417 		return NULL;
1418 
1419 	return &op->base;
1420 }
1421 
1422 static void xe_vm_free(struct drm_gpuvm *gpuvm);
1423 
1424 static const struct drm_gpuvm_ops gpuvm_ops = {
1425 	.op_alloc = xe_vm_op_alloc,
1426 	.vm_bo_validate = xe_gpuvm_validate,
1427 	.vm_free = xe_vm_free,
1428 };
1429 
1430 static u64 pde_encode_pat_index(u16 pat_index)
1431 {
1432 	u64 pte = 0;
1433 
1434 	if (pat_index & BIT(0))
1435 		pte |= XE_PPGTT_PTE_PAT0;
1436 
1437 	if (pat_index & BIT(1))
1438 		pte |= XE_PPGTT_PTE_PAT1;
1439 
1440 	return pte;
1441 }
1442 
1443 static u64 pte_encode_pat_index(u16 pat_index, u32 pt_level)
1444 {
1445 	u64 pte = 0;
1446 
1447 	if (pat_index & BIT(0))
1448 		pte |= XE_PPGTT_PTE_PAT0;
1449 
1450 	if (pat_index & BIT(1))
1451 		pte |= XE_PPGTT_PTE_PAT1;
1452 
1453 	if (pat_index & BIT(2)) {
1454 		if (pt_level)
1455 			pte |= XE_PPGTT_PDE_PDPE_PAT2;
1456 		else
1457 			pte |= XE_PPGTT_PTE_PAT2;
1458 	}
1459 
1460 	if (pat_index & BIT(3))
1461 		pte |= XELPG_PPGTT_PTE_PAT3;
1462 
1463 	if (pat_index & (BIT(4)))
1464 		pte |= XE2_PPGTT_PTE_PAT4;
1465 
1466 	return pte;
1467 }
1468 
1469 static u64 pte_encode_ps(u32 pt_level)
1470 {
1471 	XE_WARN_ON(pt_level > MAX_HUGEPTE_LEVEL);
1472 
1473 	if (pt_level == 1)
1474 		return XE_PDE_PS_2M;
1475 	else if (pt_level == 2)
1476 		return XE_PDPE_PS_1G;
1477 
1478 	return 0;
1479 }
1480 
1481 static u16 pde_pat_index(struct xe_bo *bo)
1482 {
1483 	struct xe_device *xe = xe_bo_device(bo);
1484 	u16 pat_index;
1485 
1486 	/*
1487 	 * We only have two bits to encode the PAT index in non-leaf nodes, but
1488 	 * these only point to other paging structures so we only need a minimal
1489 	 * selection of options. The user PAT index is only for encoding leaf
1490 	 * nodes, where we have use of more bits to do the encoding. The
1491 	 * non-leaf nodes are instead under driver control so the chosen index
1492 	 * here should be distinct from the user PAT index. Also the
1493 	 * corresponding coherency of the PAT index should be tied to the
1494 	 * allocation type of the page table (or at least we should pick
1495 	 * something which is always safe).
1496 	 */
1497 	if (!xe_bo_is_vram(bo) && bo->ttm.ttm->caching == ttm_cached)
1498 		pat_index = xe_cache_pat_idx(xe, XE_CACHE_WB);
1499 	else
1500 		pat_index = xe_cache_pat_idx(xe, XE_CACHE_NONE);
1501 
1502 	xe_assert(xe, pat_index <= 3);
1503 
1504 	return pat_index;
1505 }
1506 
1507 static u64 xelp_pde_encode_bo(struct xe_bo *bo, u64 bo_offset)
1508 {
1509 	u64 pde;
1510 
1511 	pde = xe_bo_addr(bo, bo_offset, XE_PAGE_SIZE);
1512 	pde |= XE_PAGE_PRESENT | XE_PAGE_RW;
1513 	pde |= pde_encode_pat_index(pde_pat_index(bo));
1514 
1515 	return pde;
1516 }
1517 
1518 static u64 xelp_pte_encode_bo(struct xe_bo *bo, u64 bo_offset,
1519 			      u16 pat_index, u32 pt_level)
1520 {
1521 	u64 pte;
1522 
1523 	pte = xe_bo_addr(bo, bo_offset, XE_PAGE_SIZE);
1524 	pte |= XE_PAGE_PRESENT | XE_PAGE_RW;
1525 	pte |= pte_encode_pat_index(pat_index, pt_level);
1526 	pte |= pte_encode_ps(pt_level);
1527 
1528 	if (xe_bo_is_vram(bo) || xe_bo_is_stolen_devmem(bo))
1529 		pte |= XE_PPGTT_PTE_DM;
1530 
1531 	return pte;
1532 }
1533 
1534 static u64 xelp_pte_encode_vma(u64 pte, struct xe_vma *vma,
1535 			       u16 pat_index, u32 pt_level)
1536 {
1537 	struct xe_bo *bo = xe_vma_bo(vma);
1538 	struct xe_vm *vm = xe_vma_vm(vma);
1539 
1540 	pte |= XE_PAGE_PRESENT;
1541 
1542 	if (likely(!xe_vma_read_only(vma)))
1543 		pte |= XE_PAGE_RW;
1544 
1545 	pte |= pte_encode_pat_index(pat_index, pt_level);
1546 	pte |= pte_encode_ps(pt_level);
1547 
1548 	/*
1549 	 * NULL PTEs redirect to scratch page (return zeros on read).
1550 	 * Set for: 1) explicit null VMAs, 2) purged BOs on scratch VMs.
1551 	 * Never set NULL flag without scratch page - causes undefined behavior.
1552 	 */
1553 	if (unlikely(xe_vma_is_null(vma) ||
1554 		     (bo && xe_bo_is_purged(bo) && xe_vm_has_scratch(vm))))
1555 		pte |= XE_PTE_NULL;
1556 
1557 	return pte;
1558 }
1559 
1560 static u64 xelp_pte_encode_addr(struct xe_device *xe, u64 addr,
1561 				u16 pat_index,
1562 				u32 pt_level, bool devmem, u64 flags)
1563 {
1564 	u64 pte;
1565 
1566 	/* Avoid passing random bits directly as flags */
1567 	xe_assert(xe, !(flags & ~XE_PTE_PS64));
1568 
1569 	pte = addr;
1570 	pte |= XE_PAGE_PRESENT | XE_PAGE_RW;
1571 	pte |= pte_encode_pat_index(pat_index, pt_level);
1572 	pte |= pte_encode_ps(pt_level);
1573 
1574 	if (devmem)
1575 		pte |= XE_PPGTT_PTE_DM;
1576 
1577 	pte |= flags;
1578 
1579 	return pte;
1580 }
1581 
1582 static const struct xe_pt_ops xelp_pt_ops = {
1583 	.pte_encode_bo = xelp_pte_encode_bo,
1584 	.pte_encode_vma = xelp_pte_encode_vma,
1585 	.pte_encode_addr = xelp_pte_encode_addr,
1586 	.pde_encode_bo = xelp_pde_encode_bo,
1587 };
1588 
1589 static void vm_destroy_work_func(struct work_struct *w);
1590 
1591 /**
1592  * xe_vm_create_scratch() - Setup a scratch memory pagetable tree for the
1593  * given tile and vm.
1594  * @xe: xe device.
1595  * @tile: tile to set up for.
1596  * @vm: vm to set up for.
1597  * @exec: The struct drm_exec object used to lock the vm resv.
1598  *
1599  * Sets up a pagetable tree with one page-table per level and a single
1600  * leaf PTE. All pagetable entries point to the single page-table or,
1601  * for MAX_HUGEPTE_LEVEL, a NULL huge PTE returning 0 on read and
1602  * writes become NOPs.
1603  *
1604  * Return: 0 on success, negative error code on error.
1605  */
1606 static int xe_vm_create_scratch(struct xe_device *xe, struct xe_tile *tile,
1607 				struct xe_vm *vm, struct drm_exec *exec)
1608 {
1609 	u8 id = tile->id;
1610 	int i;
1611 
1612 	for (i = MAX_HUGEPTE_LEVEL; i < vm->pt_root[id]->level; i++) {
1613 		vm->scratch_pt[id][i] = xe_pt_create(vm, tile, i, exec);
1614 		if (IS_ERR(vm->scratch_pt[id][i])) {
1615 			int err = PTR_ERR(vm->scratch_pt[id][i]);
1616 
1617 			vm->scratch_pt[id][i] = NULL;
1618 			return err;
1619 		}
1620 		xe_pt_populate_empty(tile, vm, vm->scratch_pt[id][i]);
1621 	}
1622 
1623 	return 0;
1624 }
1625 ALLOW_ERROR_INJECTION(xe_vm_create_scratch, ERRNO);
1626 
1627 static void xe_vm_free_scratch(struct xe_vm *vm)
1628 {
1629 	struct xe_tile *tile;
1630 	u8 id;
1631 
1632 	if (!xe_vm_has_scratch(vm))
1633 		return;
1634 
1635 	for_each_tile(tile, vm->xe, id) {
1636 		u32 i;
1637 
1638 		if (!vm->pt_root[id])
1639 			continue;
1640 
1641 		for (i = MAX_HUGEPTE_LEVEL; i < vm->pt_root[id]->level; ++i)
1642 			if (vm->scratch_pt[id][i])
1643 				xe_pt_destroy(vm->scratch_pt[id][i], vm->flags, NULL);
1644 	}
1645 }
1646 
1647 static void xe_vm_pt_destroy(struct xe_vm *vm)
1648 {
1649 	struct xe_tile *tile;
1650 	u8 id;
1651 
1652 	xe_vm_assert_held(vm);
1653 
1654 	for_each_tile(tile, vm->xe, id) {
1655 		if (vm->pt_root[id]) {
1656 			xe_pt_destroy(vm->pt_root[id], vm->flags, NULL);
1657 			vm->pt_root[id] = NULL;
1658 		}
1659 	}
1660 }
1661 
1662 static void xe_vm_init_prove_locking(struct xe_device *xe, struct xe_vm *vm)
1663 {
1664 	if (!IS_ENABLED(CONFIG_PROVE_LOCKING))
1665 		return;
1666 
1667 	fs_reclaim_acquire(GFP_KERNEL);
1668 	might_lock(&vm->exec_queues.lock);
1669 	fs_reclaim_release(GFP_KERNEL);
1670 
1671 	down_read(&vm->exec_queues.lock);
1672 	might_lock(&xe_root_mmio_gt(xe)->uc.guc.ct.lock);
1673 	up_read(&vm->exec_queues.lock);
1674 }
1675 
1676 struct xe_vm *xe_vm_create(struct xe_device *xe, u32 flags, struct xe_file *xef)
1677 {
1678 	struct drm_gem_object *vm_resv_obj;
1679 	struct xe_validation_ctx ctx;
1680 	struct drm_exec exec;
1681 	struct xe_vm *vm;
1682 	int err;
1683 	struct xe_tile *tile;
1684 	u8 id;
1685 
1686 	/*
1687 	 * Since the GSCCS is not user-accessible, we don't expect a GSC VM to
1688 	 * ever be in faulting mode.
1689 	 */
1690 	xe_assert(xe, !((flags & XE_VM_FLAG_GSC) && (flags & XE_VM_FLAG_FAULT_MODE)));
1691 
1692 	vm = kzalloc_obj(*vm);
1693 	if (!vm)
1694 		return ERR_PTR(-ENOMEM);
1695 
1696 	vm->xe = xe;
1697 
1698 	vm->size = 1ull << xe->info.va_bits;
1699 	vm->flags = flags;
1700 
1701 	if (xef)
1702 		vm->xef = xe_file_get(xef);
1703 	/*
1704 	 * GSC VMs are kernel-owned, only used for PXP ops and can sometimes be
1705 	 * manipulated under the PXP mutex. However, the PXP mutex can be taken
1706 	 * under a user-VM lock when the PXP session is started at exec_queue
1707 	 * creation time. Those are different VMs and therefore there is no risk
1708 	 * of deadlock, but we need to tell lockdep that this is the case or it
1709 	 * will print a warning.
1710 	 */
1711 	if (flags & XE_VM_FLAG_GSC) {
1712 		static struct lock_class_key gsc_vm_key;
1713 
1714 		__init_rwsem(&vm->lock, "gsc_vm", &gsc_vm_key);
1715 	} else {
1716 		init_rwsem(&vm->lock);
1717 	}
1718 	mutex_init(&vm->snap_mutex);
1719 
1720 	INIT_LIST_HEAD(&vm->rebind_list);
1721 
1722 	INIT_LIST_HEAD(&vm->userptr.repin_list);
1723 	INIT_LIST_HEAD(&vm->userptr.invalidated);
1724 	spin_lock_init(&vm->userptr.invalidated_lock);
1725 
1726 	INIT_LIST_HEAD(&vm->faults.list);
1727 	spin_lock_init(&vm->faults.lock);
1728 
1729 	ttm_lru_bulk_move_init(&vm->lru_bulk_move);
1730 
1731 	INIT_WORK(&vm->destroy_work, vm_destroy_work_func);
1732 
1733 	INIT_LIST_HEAD(&vm->preempt.exec_queues);
1734 	for (id = 0; id < XE_MAX_TILES_PER_DEVICE * XE_MAX_GT_PER_TILE; ++id)
1735 		INIT_LIST_HEAD(&vm->exec_queues.list[id]);
1736 	if (flags & XE_VM_FLAG_FAULT_MODE)
1737 		vm->preempt.min_run_period_ms = xe->min_run_period_pf_ms;
1738 	else
1739 		vm->preempt.min_run_period_ms = xe->min_run_period_lr_ms;
1740 
1741 	init_rwsem(&vm->exec_queues.lock);
1742 	xe_vm_init_prove_locking(xe, vm);
1743 	xe_range_fence_tree_init(&vm->rftree);
1744 
1745 	vm->pt_ops = &xelp_pt_ops;
1746 
1747 	/*
1748 	 * Long-running workloads are not protected by the scheduler references.
1749 	 * By design, run_job for long-running workloads returns NULL and the
1750 	 * scheduler drops all the references of it, hence protecting the VM
1751 	 * for this case is necessary.
1752 	 */
1753 	if (flags & XE_VM_FLAG_LR_MODE) {
1754 		INIT_WORK(&vm->preempt.rebind_work, preempt_rebind_work_func);
1755 		xe_pm_runtime_get_noresume(xe);
1756 		INIT_LIST_HEAD(&vm->preempt.pm_activate_link);
1757 	}
1758 
1759 	err = xe_svm_init(vm);
1760 	if (err)
1761 		goto err_no_resv;
1762 
1763 	vm_resv_obj = drm_gpuvm_resv_object_alloc(&xe->drm);
1764 	if (!vm_resv_obj) {
1765 		err = -ENOMEM;
1766 		goto err_svm_fini;
1767 	}
1768 
1769 	drm_gpuvm_init(&vm->gpuvm, "Xe VM", DRM_GPUVM_RESV_PROTECTED, &xe->drm,
1770 		       vm_resv_obj, 0, vm->size, 0, 0, &gpuvm_ops);
1771 
1772 	drm_gem_object_put(vm_resv_obj);
1773 
1774 	err = 0;
1775 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = true},
1776 			    err) {
1777 		err = xe_vm_drm_exec_lock(vm, &exec);
1778 		drm_exec_retry_on_contention(&exec);
1779 
1780 		if (IS_DGFX(xe) && xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K)
1781 			vm->flags |= XE_VM_FLAG_64K;
1782 
1783 		for_each_tile(tile, xe, id) {
1784 			if (flags & XE_VM_FLAG_MIGRATION &&
1785 			    tile->id != XE_VM_FLAG_TILE_ID(flags) &&
1786 			    (vm->xe->info.has_pt_mirror || id))
1787 				continue;
1788 
1789 			vm->pt_root[id] = xe_pt_create(vm, tile, xe->info.vm_max_level,
1790 						       &exec);
1791 			if (IS_ERR(vm->pt_root[id])) {
1792 				err = PTR_ERR(vm->pt_root[id]);
1793 				vm->pt_root[id] = NULL;
1794 				xe_vm_pt_destroy(vm);
1795 				drm_exec_retry_on_contention(&exec);
1796 				xe_validation_retry_on_oom(&ctx, &err);
1797 				break;
1798 			}
1799 		}
1800 		if (err)
1801 			break;
1802 
1803 		if (xe_vm_has_scratch(vm)) {
1804 			for_each_tile(tile, xe, id) {
1805 				if (!vm->pt_root[id])
1806 					continue;
1807 
1808 				err = xe_vm_create_scratch(xe, tile, vm, &exec);
1809 				if (err) {
1810 					xe_vm_free_scratch(vm);
1811 					xe_vm_pt_destroy(vm);
1812 					drm_exec_retry_on_contention(&exec);
1813 					xe_validation_retry_on_oom(&ctx, &err);
1814 					break;
1815 				}
1816 			}
1817 			if (err)
1818 				break;
1819 			vm->batch_invalidate_tlb = true;
1820 		}
1821 
1822 		if (vm->flags & XE_VM_FLAG_LR_MODE)
1823 			vm->batch_invalidate_tlb = false;
1824 
1825 		/* Fill pt_root after allocating scratch tables */
1826 		for_each_tile(tile, xe, id) {
1827 			if (!vm->pt_root[id])
1828 				continue;
1829 
1830 			xe_pt_populate_empty(tile, vm, vm->pt_root[id]);
1831 		}
1832 	}
1833 	if (err)
1834 		goto err_close;
1835 
1836 	/* Kernel migration VM shouldn't have a circular loop.. */
1837 	if (!(flags & XE_VM_FLAG_MIGRATION)) {
1838 		for_each_tile(tile, xe, id) {
1839 			struct xe_exec_queue *q;
1840 			u32 create_flags = EXEC_QUEUE_FLAG_VM;
1841 
1842 			if (!vm->pt_root[id] || vm->q)
1843 				continue;
1844 
1845 			if (!xef) /* Not from userspace */
1846 				create_flags |= EXEC_QUEUE_FLAG_KERNEL;
1847 
1848 			q = xe_exec_queue_create_bind(xe, tile, vm, create_flags, 0);
1849 			if (IS_ERR(q)) {
1850 				err = PTR_ERR(q);
1851 				goto err_close;
1852 			}
1853 			vm->q = q;
1854 		}
1855 	}
1856 
1857 	if (xef && xe->info.has_asid) {
1858 		u32 asid;
1859 
1860 		down_write(&xe->usm.lock);
1861 		err = xa_alloc_cyclic(&xe->usm.asid_to_vm, &asid, vm,
1862 				      XA_LIMIT(1, XE_MAX_ASID - 1),
1863 				      &xe->usm.next_asid, GFP_NOWAIT);
1864 		up_write(&xe->usm.lock);
1865 		if (err < 0)
1866 			goto err_close;
1867 
1868 		vm->usm.asid = asid;
1869 	}
1870 
1871 	trace_xe_vm_create(vm);
1872 
1873 	return vm;
1874 
1875 err_close:
1876 	xe_vm_close_and_put(vm);
1877 	return ERR_PTR(err);
1878 
1879 err_svm_fini:
1880 	vm->size = 0; /* close the vm */
1881 	if (flags & XE_VM_FLAG_FAULT_MODE)
1882 		xe_svm_close(vm);
1883 	xe_svm_fini(vm);
1884 err_no_resv:
1885 	mutex_destroy(&vm->snap_mutex);
1886 	xe_range_fence_tree_fini(&vm->rftree);
1887 	ttm_lru_bulk_move_fini(&xe->ttm, &vm->lru_bulk_move);
1888 	if (vm->xef)
1889 		xe_file_put(vm->xef);
1890 	kfree(vm);
1891 	if (flags & XE_VM_FLAG_LR_MODE)
1892 		xe_pm_runtime_put(xe);
1893 	return ERR_PTR(err);
1894 }
1895 
1896 static void xe_vm_close(struct xe_vm *vm)
1897 {
1898 	struct xe_device *xe = vm->xe;
1899 	bool bound;
1900 	int idx;
1901 
1902 	bound = drm_dev_enter(&xe->drm, &idx);
1903 
1904 	down_write(&vm->lock);
1905 	xe_vm_lock(vm, false);
1906 
1907 	if (xe_vm_in_fault_mode(vm))
1908 		xe_svm_notifier_lock(vm);
1909 
1910 	vm->size = 0;
1911 
1912 	if (!((vm->flags & XE_VM_FLAG_MIGRATION))) {
1913 		struct xe_tile *tile;
1914 		struct xe_gt *gt;
1915 		u8 id;
1916 
1917 		/* Wait for pending binds */
1918 		dma_resv_wait_timeout(xe_vm_resv(vm),
1919 				      DMA_RESV_USAGE_BOOKKEEP,
1920 				      false, MAX_SCHEDULE_TIMEOUT);
1921 
1922 		if (bound) {
1923 			for_each_tile(tile, xe, id)
1924 				if (vm->pt_root[id])
1925 					xe_pt_clear(xe, vm->pt_root[id]);
1926 
1927 			for_each_gt(gt, xe, id)
1928 				xe_tlb_inval_vm(&gt->tlb_inval, vm);
1929 		}
1930 	}
1931 
1932 	if (xe_vm_in_fault_mode(vm))
1933 		xe_svm_notifier_unlock(vm);
1934 
1935 	xe_vm_unlock(vm);
1936 	up_write(&vm->lock);
1937 
1938 	if (bound)
1939 		drm_dev_exit(idx);
1940 }
1941 
1942 void xe_vm_close_and_put(struct xe_vm *vm)
1943 {
1944 	LIST_HEAD(contested);
1945 	struct xe_device *xe = vm->xe;
1946 	struct xe_vma *vma, *next_vma;
1947 	struct drm_gpuva *gpuva, *next;
1948 
1949 	xe_assert(xe, !vm->preempt.num_exec_queues);
1950 
1951 	trace_xe_vm_close_and_put(vm);
1952 
1953 	xe_vm_close(vm);
1954 	if (xe_vm_in_preempt_fence_mode(vm)) {
1955 		mutex_lock(&xe->rebind_resume_lock);
1956 		list_del_init(&vm->preempt.pm_activate_link);
1957 		mutex_unlock(&xe->rebind_resume_lock);
1958 		flush_work(&vm->preempt.rebind_work);
1959 	}
1960 	if (xe_vm_in_fault_mode(vm))
1961 		xe_svm_close(vm);
1962 
1963 	if (vm->q) {
1964 		int i;
1965 
1966 		down_write(&vm->lock);
1967 		xe_exec_queue_last_fence_put(vm->q, vm);
1968 		for_each_tlb_inval(vm->q, i)
1969 			xe_exec_queue_tlb_inval_last_fence_put(vm->q, vm, i);
1970 		up_write(&vm->lock);
1971 
1972 		xe_exec_queue_kill(vm->q);
1973 		xe_exec_queue_put(vm->q);
1974 		vm->q = NULL;
1975 	}
1976 
1977 	down_write(&vm->lock);
1978 	xe_vm_lock(vm, false);
1979 	drm_gpuvm_for_each_va_safe(gpuva, next, &vm->gpuvm) {
1980 		vma = gpuva_to_vma(gpuva);
1981 
1982 		if (xe_vma_has_no_bo(vma)) {
1983 			xe_svm_notifier_lock(vm);
1984 			vma->gpuva.flags |= XE_VMA_DESTROYED;
1985 			xe_svm_notifier_unlock(vm);
1986 		}
1987 
1988 		xe_vm_remove_vma(vm, vma);
1989 
1990 		/* easy case, remove from VMA? */
1991 		if (xe_vma_has_no_bo(vma) || xe_vma_bo(vma)->vm) {
1992 			list_del_init(&vma->combined_links.rebind);
1993 			xe_vma_destroy(vma, NULL);
1994 			continue;
1995 		}
1996 
1997 		list_move_tail(&vma->combined_links.destroy, &contested);
1998 		vma->gpuva.flags |= XE_VMA_DESTROYED;
1999 	}
2000 
2001 	xe_vm_unlock(vm);
2002 
2003 	/*
2004 	 * Unlink and destroy all contested external-BO VMAs before destroying
2005 	 * the page tables. Otherwise, concurrent eviction holding only bo->resv
2006 	 * can walk the BO's VMAs and attempt to invalidate/zap page tables that
2007 	 * have already been freed.
2008 	 */
2009 	list_for_each_entry_safe(vma, next_vma, &contested,
2010 				 combined_links.destroy) {
2011 		list_del_init(&vma->combined_links.destroy);
2012 		xe_vma_destroy_unlocked(vma);
2013 	}
2014 
2015 	xe_vm_lock(vm, false);
2016 	xe_vm_free_scratch(vm);
2017 	xe_vm_pt_destroy(vm);
2018 	xe_vm_unlock(vm);
2019 
2020 	xe_svm_fini(vm);
2021 
2022 	up_write(&vm->lock);
2023 
2024 	down_write(&xe->usm.lock);
2025 	if (vm->usm.asid) {
2026 		void *lookup;
2027 
2028 		xe_assert(xe, xe->info.has_asid);
2029 		xe_assert(xe, !(vm->flags & XE_VM_FLAG_MIGRATION));
2030 
2031 		trace_xe_vm_asid_release(vm);
2032 
2033 		lookup = xa_erase(&xe->usm.asid_to_vm, vm->usm.asid);
2034 		xe_assert(xe, lookup == vm);
2035 	}
2036 	up_write(&xe->usm.lock);
2037 
2038 	xe_vm_clear_fault_entries(vm);
2039 
2040 	xe_range_fence_tree_fini(&vm->rftree);
2041 
2042 	xe_vm_put(vm);
2043 }
2044 
2045 static void vm_destroy_work_func(struct work_struct *w)
2046 {
2047 	struct xe_vm *vm =
2048 		container_of(w, struct xe_vm, destroy_work);
2049 	struct xe_device *xe = vm->xe;
2050 	struct xe_tile *tile;
2051 	u8 id;
2052 
2053 	/* xe_vm_close_and_put was not called? */
2054 	xe_assert(xe, !vm->size);
2055 
2056 	if (xe_vm_in_preempt_fence_mode(vm))
2057 		flush_work(&vm->preempt.rebind_work);
2058 
2059 	mutex_destroy(&vm->snap_mutex);
2060 
2061 	if (vm->flags & XE_VM_FLAG_LR_MODE)
2062 		xe_pm_runtime_put(xe);
2063 
2064 	for_each_tile(tile, xe, id)
2065 		XE_WARN_ON(vm->pt_root[id]);
2066 
2067 	trace_xe_vm_free(vm);
2068 
2069 	ttm_lru_bulk_move_fini(&xe->ttm, &vm->lru_bulk_move);
2070 
2071 	if (vm->xef)
2072 		xe_file_put(vm->xef);
2073 
2074 	kfree(vm);
2075 }
2076 
2077 static void xe_vm_free(struct drm_gpuvm *gpuvm)
2078 {
2079 	struct xe_vm *vm = container_of(gpuvm, struct xe_vm, gpuvm);
2080 
2081 	/* To destroy the VM we need to be able to sleep */
2082 	queue_work(system_dfl_wq, &vm->destroy_work);
2083 }
2084 
2085 struct xe_vm *xe_vm_lookup(struct xe_file *xef, u32 id)
2086 {
2087 	struct xe_vm *vm;
2088 
2089 	mutex_lock(&xef->vm.lock);
2090 	vm = xa_load(&xef->vm.xa, id);
2091 	if (vm)
2092 		xe_vm_get(vm);
2093 	mutex_unlock(&xef->vm.lock);
2094 
2095 	return vm;
2096 }
2097 
2098 u64 xe_vm_pdp4_descriptor(struct xe_vm *vm, struct xe_tile *tile)
2099 {
2100 	return vm->pt_ops->pde_encode_bo(xe_vm_pt_root(vm, tile->id)->bo, 0);
2101 }
2102 
2103 static struct xe_exec_queue *
2104 to_wait_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q)
2105 {
2106 	return q ? q : vm->q;
2107 }
2108 
2109 static struct xe_user_fence *
2110 find_ufence_get(struct xe_sync_entry *syncs, u32 num_syncs)
2111 {
2112 	unsigned int i;
2113 
2114 	for (i = 0; i < num_syncs; i++) {
2115 		struct xe_sync_entry *e = &syncs[i];
2116 
2117 		if (xe_sync_is_ufence(e))
2118 			return xe_sync_ufence_get(e);
2119 	}
2120 
2121 	return NULL;
2122 }
2123 
2124 #define ALL_DRM_XE_VM_CREATE_FLAGS (DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE | \
2125 				    DRM_XE_VM_CREATE_FLAG_LR_MODE | \
2126 				    DRM_XE_VM_CREATE_FLAG_FAULT_MODE | \
2127 				    DRM_XE_VM_CREATE_FLAG_NO_VM_OVERCOMMIT)
2128 
2129 int xe_vm_create_ioctl(struct drm_device *dev, void *data,
2130 		       struct drm_file *file)
2131 {
2132 	struct xe_device *xe = to_xe_device(dev);
2133 	struct xe_file *xef = to_xe_file(file);
2134 	struct drm_xe_vm_create *args = data;
2135 	struct xe_gt *wa_gt = xe_root_mmio_gt(xe);
2136 	struct xe_vm *vm;
2137 	u32 id;
2138 	int err;
2139 	u32 flags = 0;
2140 
2141 	if (XE_IOCTL_DBG(xe, args->extensions))
2142 		return -EINVAL;
2143 
2144 	if (wa_gt && XE_GT_WA(wa_gt, 22014953428))
2145 		args->flags |= DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE;
2146 
2147 	if (XE_IOCTL_DBG(xe, args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE &&
2148 			 !xe->info.has_usm))
2149 		return -EINVAL;
2150 
2151 	if (XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
2152 		return -EINVAL;
2153 
2154 	if (XE_IOCTL_DBG(xe, args->flags & ~ALL_DRM_XE_VM_CREATE_FLAGS))
2155 		return -EINVAL;
2156 
2157 	if (XE_IOCTL_DBG(xe, args->flags & DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE &&
2158 			 args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE &&
2159 			 !xe->info.needs_scratch))
2160 		return -EINVAL;
2161 
2162 	if (XE_IOCTL_DBG(xe, !(args->flags & DRM_XE_VM_CREATE_FLAG_LR_MODE) &&
2163 			 args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE))
2164 		return -EINVAL;
2165 
2166 	if (XE_IOCTL_DBG(xe, !(args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE) &&
2167 			 args->flags & DRM_XE_VM_CREATE_FLAG_NO_VM_OVERCOMMIT))
2168 		return -EINVAL;
2169 
2170 	if (args->flags & DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE)
2171 		flags |= XE_VM_FLAG_SCRATCH_PAGE;
2172 	if (args->flags & DRM_XE_VM_CREATE_FLAG_LR_MODE)
2173 		flags |= XE_VM_FLAG_LR_MODE;
2174 	if (args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE)
2175 		flags |= XE_VM_FLAG_FAULT_MODE;
2176 	if (args->flags & DRM_XE_VM_CREATE_FLAG_NO_VM_OVERCOMMIT)
2177 		flags |= XE_VM_FLAG_NO_VM_OVERCOMMIT;
2178 
2179 	vm = xe_vm_create(xe, flags, xef);
2180 	if (IS_ERR(vm))
2181 		return PTR_ERR(vm);
2182 
2183 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_MEM)
2184 	/* Warning: Security issue - never enable by default */
2185 	args->reserved[0] = xe_bo_main_addr(vm->pt_root[0]->bo, XE_PAGE_SIZE);
2186 #endif
2187 
2188 	/* user id alloc must always be last in ioctl to prevent UAF */
2189 	err = xa_alloc(&xef->vm.xa, &id, vm, xa_limit_32b, GFP_KERNEL);
2190 	if (err)
2191 		goto err_close_and_put;
2192 
2193 	args->vm_id = id;
2194 
2195 	return 0;
2196 
2197 err_close_and_put:
2198 	xe_vm_close_and_put(vm);
2199 
2200 	return err;
2201 }
2202 
2203 int xe_vm_destroy_ioctl(struct drm_device *dev, void *data,
2204 			struct drm_file *file)
2205 {
2206 	struct xe_device *xe = to_xe_device(dev);
2207 	struct xe_file *xef = to_xe_file(file);
2208 	struct drm_xe_vm_destroy *args = data;
2209 	struct xe_vm *vm;
2210 	int err = 0;
2211 
2212 	if (XE_IOCTL_DBG(xe, args->pad) ||
2213 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
2214 		return -EINVAL;
2215 
2216 	mutex_lock(&xef->vm.lock);
2217 	vm = xa_load(&xef->vm.xa, args->vm_id);
2218 	if (XE_IOCTL_DBG(xe, !vm))
2219 		err = -ENOENT;
2220 	else if (XE_IOCTL_DBG(xe, vm->preempt.num_exec_queues))
2221 		err = -EBUSY;
2222 	else
2223 		xa_erase(&xef->vm.xa, args->vm_id);
2224 	mutex_unlock(&xef->vm.lock);
2225 
2226 	if (!err)
2227 		xe_vm_close_and_put(vm);
2228 
2229 	return err;
2230 }
2231 
2232 static int xe_vm_query_vmas(struct xe_vm *vm, u64 start, u64 end)
2233 {
2234 	struct drm_gpuva *gpuva;
2235 	u32 num_vmas = 0;
2236 
2237 	xe_vm_assert_write_mode_or_garbage_collector(vm);
2238 	drm_gpuvm_for_each_va_range(gpuva, &vm->gpuvm, start, end)
2239 		num_vmas++;
2240 
2241 	return num_vmas;
2242 }
2243 
2244 static int get_mem_attrs(struct xe_vm *vm, u32 *num_vmas, u64 start,
2245 			 u64 end, struct drm_xe_mem_range_attr *attrs)
2246 {
2247 	struct drm_gpuva *gpuva;
2248 	int i = 0;
2249 
2250 	xe_vm_assert_write_mode_or_garbage_collector(vm);
2251 
2252 	drm_gpuvm_for_each_va_range(gpuva, &vm->gpuvm, start, end) {
2253 		struct xe_vma *vma = gpuva_to_vma(gpuva);
2254 
2255 		if (i == *num_vmas)
2256 			return -ENOSPC;
2257 
2258 		attrs[i].start = xe_vma_start(vma);
2259 		attrs[i].end = xe_vma_end(vma);
2260 		attrs[i].atomic.val = vma->attr.atomic_access;
2261 		attrs[i].pat_index.val = vma->attr.pat_index;
2262 		attrs[i].preferred_mem_loc.devmem_fd = vma->attr.preferred_loc.devmem_fd;
2263 		attrs[i].preferred_mem_loc.migration_policy =
2264 		vma->attr.preferred_loc.migration_policy;
2265 
2266 		i++;
2267 	}
2268 
2269 	*num_vmas = i;
2270 	return 0;
2271 }
2272 
2273 int xe_vm_query_vmas_attrs_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
2274 {
2275 	struct xe_device *xe = to_xe_device(dev);
2276 	struct xe_file *xef = to_xe_file(file);
2277 	struct drm_xe_mem_range_attr *mem_attrs;
2278 	struct drm_xe_vm_query_mem_range_attr *args = data;
2279 	u64 __user *attrs_user = u64_to_user_ptr(args->vector_of_mem_attr);
2280 	struct xe_vm *vm;
2281 	int err = 0;
2282 
2283 	if (XE_IOCTL_DBG(xe,
2284 			 ((args->num_mem_ranges == 0 &&
2285 			  (attrs_user || args->sizeof_mem_range_attr != 0)) ||
2286 			 (args->num_mem_ranges > 0 &&
2287 			  (!attrs_user ||
2288 			   args->sizeof_mem_range_attr !=
2289 			   sizeof(struct drm_xe_mem_range_attr))))))
2290 		return -EINVAL;
2291 
2292 	vm = xe_vm_lookup(xef, args->vm_id);
2293 	if (XE_IOCTL_DBG(xe, !vm))
2294 		return -EINVAL;
2295 
2296 	err = down_write_killable(&vm->lock);
2297 	if (err)
2298 		goto put_vm;
2299 
2300 	attrs_user = u64_to_user_ptr(args->vector_of_mem_attr);
2301 
2302 	if (args->num_mem_ranges == 0 && !attrs_user) {
2303 		args->num_mem_ranges = xe_vm_query_vmas(vm, args->start, args->start + args->range);
2304 		args->sizeof_mem_range_attr = sizeof(struct drm_xe_mem_range_attr);
2305 		goto unlock_vm;
2306 	}
2307 
2308 	mem_attrs = kvmalloc_array(args->num_mem_ranges, args->sizeof_mem_range_attr,
2309 				   GFP_KERNEL | __GFP_ACCOUNT |
2310 				   __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
2311 	if (!mem_attrs) {
2312 		err = args->num_mem_ranges > 1 ? -ENOBUFS : -ENOMEM;
2313 		goto unlock_vm;
2314 	}
2315 
2316 	memset(mem_attrs, 0, args->num_mem_ranges * args->sizeof_mem_range_attr);
2317 	err = get_mem_attrs(vm, &args->num_mem_ranges, args->start,
2318 			    args->start + args->range, mem_attrs);
2319 	if (err)
2320 		goto free_mem_attrs;
2321 
2322 	err = copy_to_user(attrs_user, mem_attrs,
2323 			   args->sizeof_mem_range_attr * args->num_mem_ranges);
2324 	if (err)
2325 		err = -EFAULT;
2326 
2327 free_mem_attrs:
2328 	kvfree(mem_attrs);
2329 unlock_vm:
2330 	up_write(&vm->lock);
2331 put_vm:
2332 	xe_vm_put(vm);
2333 	return err;
2334 }
2335 
2336 /**
2337  * xe_vm_find_vma_by_addr() - Find a VMA by its address
2338  *
2339  * @vm: the xe_vm the vma belongs to
2340  * @page_addr: address to look up
2341  */
2342 struct xe_vma *xe_vm_find_vma_by_addr(struct xe_vm *vm, u64 page_addr)
2343 {
2344 	return xe_vm_find_overlapping_vma(vm, page_addr, SZ_4K);
2345 }
2346 
2347 static const u32 region_to_mem_type[] = {
2348 	XE_PL_TT,
2349 	XE_PL_VRAM0,
2350 	XE_PL_VRAM1,
2351 };
2352 
2353 static void prep_vma_destroy(struct xe_vm *vm, struct xe_vma *vma,
2354 			     bool post_commit)
2355 {
2356 	xe_svm_notifier_lock(vm);
2357 	vma->gpuva.flags |= XE_VMA_DESTROYED;
2358 	xe_svm_notifier_unlock(vm);
2359 	if (post_commit)
2360 		xe_vm_remove_vma(vm, vma);
2361 }
2362 
2363 #undef ULL
2364 #define ULL	unsigned long long
2365 
2366 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM)
2367 static void print_op(struct xe_device *xe, struct drm_gpuva_op *op)
2368 {
2369 	struct xe_vma *vma;
2370 
2371 	switch (op->op) {
2372 	case DRM_GPUVA_OP_MAP:
2373 		vm_dbg(&xe->drm, "MAP: addr=0x%016llx, range=0x%016llx",
2374 		       (ULL)op->map.va.addr, (ULL)op->map.va.range);
2375 		break;
2376 	case DRM_GPUVA_OP_REMAP:
2377 		vma = gpuva_to_vma(op->remap.unmap->va);
2378 		vm_dbg(&xe->drm, "REMAP:UNMAP: addr=0x%016llx, range=0x%016llx, keep=%d",
2379 		       (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma),
2380 		       op->remap.unmap->keep ? 1 : 0);
2381 		if (op->remap.prev)
2382 			vm_dbg(&xe->drm,
2383 			       "REMAP:PREV: addr=0x%016llx, range=0x%016llx",
2384 			       (ULL)op->remap.prev->va.addr,
2385 			       (ULL)op->remap.prev->va.range);
2386 		if (op->remap.next)
2387 			vm_dbg(&xe->drm,
2388 			       "REMAP:NEXT: addr=0x%016llx, range=0x%016llx",
2389 			       (ULL)op->remap.next->va.addr,
2390 			       (ULL)op->remap.next->va.range);
2391 		break;
2392 	case DRM_GPUVA_OP_UNMAP:
2393 		vma = gpuva_to_vma(op->unmap.va);
2394 		vm_dbg(&xe->drm, "UNMAP: addr=0x%016llx, range=0x%016llx, keep=%d",
2395 		       (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma),
2396 		       op->unmap.keep ? 1 : 0);
2397 		break;
2398 	case DRM_GPUVA_OP_PREFETCH:
2399 		vma = gpuva_to_vma(op->prefetch.va);
2400 		vm_dbg(&xe->drm, "PREFETCH: addr=0x%016llx, range=0x%016llx",
2401 		       (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma));
2402 		break;
2403 	default:
2404 		drm_warn(&xe->drm, "NOT POSSIBLE\n");
2405 	}
2406 }
2407 #else
2408 static void print_op(struct xe_device *xe, struct drm_gpuva_op *op)
2409 {
2410 }
2411 #endif
2412 
2413 static bool __xe_vm_needs_clear_scratch_pages(struct xe_vm *vm, u32 bind_flags)
2414 {
2415 	if (!xe_vm_in_fault_mode(vm))
2416 		return false;
2417 
2418 	if (!xe_vm_has_scratch(vm))
2419 		return false;
2420 
2421 	if (bind_flags & DRM_XE_VM_BIND_FLAG_IMMEDIATE)
2422 		return false;
2423 
2424 	return true;
2425 }
2426 
2427 static void xe_svm_prefetch_gpuva_ops_fini(struct drm_gpuva_ops *ops)
2428 {
2429 	struct drm_gpuva_op *__op;
2430 
2431 	drm_gpuva_for_each_op(__op, ops) {
2432 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2433 
2434 		xe_vma_svm_prefetch_op_fini(op);
2435 	}
2436 }
2437 
2438 /*
2439  * Create operations list from IOCTL arguments, setup operations fields so parse
2440  * and commit steps are decoupled from IOCTL arguments. This step can fail.
2441  */
2442 static struct drm_gpuva_ops *
2443 vm_bind_ioctl_ops_create(struct xe_vm *vm, struct xe_vma_ops *vops,
2444 			 struct xe_bo *bo, u64 bo_offset_or_userptr,
2445 			 u64 addr, u64 range,
2446 			 u32 operation, u32 flags,
2447 			 u32 prefetch_region, u16 pat_index)
2448 {
2449 	struct drm_gem_object *obj = bo ? &bo->ttm.base : NULL;
2450 	struct drm_gpuva_ops *ops;
2451 	struct drm_gpuva_op *__op;
2452 	struct drm_gpuvm_bo *vm_bo;
2453 	u64 range_start = addr;
2454 	u64 range_end = addr + range;
2455 	int err;
2456 
2457 	xe_vm_assert_write_mode_or_garbage_collector(vm);
2458 
2459 	vm_dbg(&vm->xe->drm,
2460 	       "op=%d, addr=0x%016llx, range=0x%016llx, bo_offset_or_userptr=0x%016llx",
2461 	       operation, (ULL)addr, (ULL)range,
2462 	       (ULL)bo_offset_or_userptr);
2463 
2464 	switch (operation) {
2465 	case DRM_XE_VM_BIND_OP_MAP:
2466 		if (flags & DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR) {
2467 			xe_vm_find_cpu_addr_mirror_vma_range(vm, &range_start, &range_end);
2468 			vops->flags |= XE_VMA_OPS_FLAG_ALLOW_SVM_UNMAP;
2469 		}
2470 
2471 		fallthrough;
2472 	case DRM_XE_VM_BIND_OP_MAP_USERPTR: {
2473 		struct drm_gpuvm_map_req map_req = {
2474 			.map.va.addr = range_start,
2475 			.map.va.range = range_end - range_start,
2476 			.map.gem.obj = obj,
2477 			.map.gem.offset = bo_offset_or_userptr,
2478 		};
2479 
2480 		vops->flags |= XE_VMA_OPS_FLAG_MODIFIES_GPUVA;
2481 		ops = drm_gpuvm_sm_map_ops_create(&vm->gpuvm, &map_req);
2482 		break;
2483 	}
2484 	case DRM_XE_VM_BIND_OP_UNMAP:
2485 		vops->flags |= XE_VMA_OPS_FLAG_MODIFIES_GPUVA;
2486 		ops = drm_gpuvm_sm_unmap_ops_create(&vm->gpuvm, addr, range);
2487 		break;
2488 	case DRM_XE_VM_BIND_OP_PREFETCH:
2489 		ops = drm_gpuvm_prefetch_ops_create(&vm->gpuvm, addr, range);
2490 		break;
2491 	case DRM_XE_VM_BIND_OP_UNMAP_ALL:
2492 		xe_assert(vm->xe, bo);
2493 
2494 		vops->flags |= XE_VMA_OPS_FLAG_MODIFIES_GPUVA;
2495 		err = xe_bo_lock(bo, true);
2496 		if (err)
2497 			return ERR_PTR(err);
2498 
2499 		vm_bo = drm_gpuvm_bo_obtain_locked(&vm->gpuvm, obj);
2500 		if (IS_ERR(vm_bo)) {
2501 			xe_bo_unlock(bo);
2502 			return ERR_CAST(vm_bo);
2503 		}
2504 
2505 		ops = drm_gpuvm_bo_unmap_ops_create(vm_bo);
2506 		drm_gpuvm_bo_put(vm_bo);
2507 		xe_bo_unlock(bo);
2508 		break;
2509 	default:
2510 		drm_warn(&vm->xe->drm, "NOT POSSIBLE\n");
2511 		ops = ERR_PTR(-EINVAL);
2512 	}
2513 	if (IS_ERR(ops))
2514 		return ops;
2515 
2516 	/* Setup safe unwind */
2517 	drm_gpuva_for_each_op(__op, ops) {
2518 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2519 
2520 		if (__op->op == DRM_GPUVA_OP_PREFETCH) {
2521 			xa_init_flags(&op->prefetch_range.range, XA_FLAGS_ALLOC);
2522 			op->prefetch_range.ranges_count = 0;
2523 		}
2524 	}
2525 
2526 	drm_gpuva_for_each_op(__op, ops) {
2527 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2528 
2529 		if (__op->op == DRM_GPUVA_OP_MAP) {
2530 			op->map.immediate =
2531 				flags & DRM_XE_VM_BIND_FLAG_IMMEDIATE;
2532 			if (flags & DRM_XE_VM_BIND_FLAG_READONLY)
2533 				op->map.vma_flags |= XE_VMA_READ_ONLY;
2534 			if (flags & DRM_XE_VM_BIND_FLAG_NULL)
2535 				op->map.vma_flags |= DRM_GPUVA_SPARSE;
2536 			if (flags & DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR)
2537 				op->map.vma_flags |= XE_VMA_SYSTEM_ALLOCATOR;
2538 			if (flags & DRM_XE_VM_BIND_FLAG_DUMPABLE)
2539 				op->map.vma_flags |= XE_VMA_DUMPABLE;
2540 			if (flags & DRM_XE_VM_BIND_FLAG_MADVISE_AUTORESET)
2541 				op->map.vma_flags |= XE_VMA_MADV_AUTORESET;
2542 			op->map.request_decompress = flags & DRM_XE_VM_BIND_FLAG_DECOMPRESS;
2543 			op->map.pat_index = pat_index;
2544 			op->map.invalidate_on_bind =
2545 				__xe_vm_needs_clear_scratch_pages(vm, flags);
2546 		} else if (__op->op == DRM_GPUVA_OP_PREFETCH) {
2547 			struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2548 			struct xe_tile *tile;
2549 			struct xe_svm_range *svm_range;
2550 			struct drm_gpusvm_ctx ctx = {};
2551 			struct drm_pagemap *dpagemap = NULL;
2552 			u8 id, tile_mask = 0;
2553 			u32 i;
2554 			bool need_put, valid_pages;
2555 
2556 			if (xe_vma_is_userptr(vma))
2557 				vops->flags |= XE_VMA_OPS_FLAG_MODIFIES_GPUVA;
2558 
2559 			if (!xe_vma_is_cpu_addr_mirror(vma)) {
2560 				op->prefetch.region = prefetch_region;
2561 				continue;
2562 			}
2563 
2564 			ctx.read_only = xe_vma_read_only(vma);
2565 			ctx.devmem_possible = IS_DGFX(vm->xe) &&
2566 					      IS_ENABLED(CONFIG_DRM_XE_PAGEMAP);
2567 
2568 			for_each_tile(tile, vm->xe, id) {
2569 				xe_migrate_ulls_enter(tile->migrate);
2570 				tile_mask |= 0x1 << id;
2571 			}
2572 
2573 			if (prefetch_region == DRM_XE_CONSULT_MEM_ADVISE_PREF_LOC) {
2574 				dpagemap = xe_vma_resolve_pagemap(vma,
2575 								  xe_device_get_root_tile(vm->xe));
2576 			} else if (prefetch_region) {
2577 				tile = &vm->xe->tiles[region_to_mem_type[prefetch_region] -
2578 						      XE_PL_VRAM0];
2579 				dpagemap = xe_tile_local_pagemap(tile);
2580 			}
2581 
2582 			op->prefetch_range.dpagemap = dpagemap;
2583 alloc_next_range:
2584 			need_put = false;
2585 			svm_range = xe_svm_range_find_or_insert(vm, addr, vma, &ctx);
2586 
2587 			if (PTR_ERR(svm_range) == -ENOENT) {
2588 				u64 ret = xe_svm_find_vma_start(vm, addr, range_end, vma);
2589 
2590 				addr = ret == ULONG_MAX ? 0 : ret;
2591 				if (addr)
2592 					goto alloc_next_range;
2593 				else
2594 					goto print_op_label;
2595 			}
2596 
2597 			if (IS_ERR(svm_range)) {
2598 				err = PTR_ERR(svm_range);
2599 				goto unwind_prefetch_ops;
2600 			}
2601 
2602 			if (xe_svm_range_validate(vm, svm_range, tile_mask,
2603 						  dpagemap, &valid_pages)) {
2604 				xe_svm_range_debug(svm_range, "PREFETCH - RANGE IS VALID");
2605 				xe_assert(vm->xe, valid_pages);
2606 
2607 				if (dpagemap)
2608 					xe_svm_range_prefetch_lru_bump(vm, vma, svm_range,
2609 								       dpagemap);
2610 
2611 				need_put = true;
2612 				goto check_next_range;
2613 			}
2614 
2615 			err = xa_alloc(&op->prefetch_range.range,
2616 				       &i, svm_range, xa_limit_32b,
2617 				       GFP_KERNEL);
2618 
2619 			if (err) {
2620 				xe_svm_range_put(svm_range);
2621 				goto unwind_prefetch_ops;
2622 			}
2623 
2624 			op->prefetch_range.ranges_count++;
2625 			vops->flags |= XE_VMA_OPS_FLAG_HAS_SVM_PREFETCH;
2626 			if (valid_pages)
2627 				vops->flags |= XE_VMA_OPS_FLAG_HAS_SVM_VALID_RANGE;
2628 			xe_svm_range_debug(svm_range, "PREFETCH - RANGE CREATED");
2629 check_next_range:
2630 			if (range_end > xe_svm_range_end(svm_range) &&
2631 			    xe_svm_range_end(svm_range) < xe_vma_end(vma)) {
2632 				addr = xe_svm_range_end(svm_range);
2633 				if (need_put)
2634 					xe_svm_range_put(svm_range);
2635 				goto alloc_next_range;
2636 			}
2637 			if (need_put)
2638 				xe_svm_range_put(svm_range);
2639 
2640 		}
2641 print_op_label:
2642 		print_op(vm->xe, __op);
2643 	}
2644 
2645 	return ops;
2646 
2647 unwind_prefetch_ops:
2648 	xe_svm_prefetch_gpuva_ops_fini(ops);
2649 	drm_gpuva_ops_free(&vm->gpuvm, ops);
2650 	return ERR_PTR(err);
2651 }
2652 
2653 ALLOW_ERROR_INJECTION(vm_bind_ioctl_ops_create, ERRNO);
2654 
2655 static struct xe_vma *new_vma(struct xe_vm *vm, struct drm_gpuva_op_map *op,
2656 			      struct xe_vma_mem_attr *attr, unsigned int flags)
2657 {
2658 	struct xe_bo *bo = op->gem.obj ? gem_to_xe_bo(op->gem.obj) : NULL;
2659 	struct xe_validation_ctx ctx;
2660 	struct drm_exec exec;
2661 	struct xe_vma *vma;
2662 	int err = 0;
2663 
2664 	xe_vm_assert_write_mode_or_garbage_collector(vm);
2665 
2666 	if (bo) {
2667 		err = 0;
2668 		xe_validation_guard(&ctx, &vm->xe->val, &exec,
2669 				    (struct xe_val_flags) {.interruptible = true}, err) {
2670 			if (!bo->vm) {
2671 				err = drm_exec_lock_obj(&exec, xe_vm_obj(vm));
2672 				drm_exec_retry_on_contention(&exec);
2673 			}
2674 			if (!err) {
2675 				err = drm_exec_lock_obj(&exec, &bo->ttm.base);
2676 				drm_exec_retry_on_contention(&exec);
2677 			}
2678 			if (err)
2679 				return ERR_PTR(err);
2680 
2681 			vma = xe_vma_create(vm, bo, op->gem.offset,
2682 					    op->va.addr, op->va.addr +
2683 					    op->va.range - 1, attr, flags);
2684 			if (IS_ERR(vma))
2685 				return vma;
2686 
2687 			if (!bo->vm) {
2688 				err = add_preempt_fences(vm, bo);
2689 				if (err) {
2690 					prep_vma_destroy(vm, vma, false);
2691 					xe_vma_destroy(vma, NULL);
2692 				}
2693 			}
2694 		}
2695 		if (err)
2696 			return ERR_PTR(err);
2697 	} else {
2698 		vma = xe_vma_create(vm, NULL, op->gem.offset,
2699 				    op->va.addr, op->va.addr +
2700 				    op->va.range - 1, attr, flags);
2701 		if (IS_ERR(vma))
2702 			return vma;
2703 
2704 		if (xe_vma_is_userptr(vma)) {
2705 			err = xe_vma_userptr_pin_pages(to_userptr_vma(vma));
2706 			/*
2707 			 * -EBUSY has dedicated meaning that a user fence
2708 			 * attached to the VMA is busy, in practice
2709 			 * xe_vma_userptr_pin_pages can only fail with -EBUSY if
2710 			 * we are low on memory so convert this to -ENOMEM.
2711 			 */
2712 			if (err == -EBUSY)
2713 				err = -ENOMEM;
2714 		}
2715 	}
2716 	if (err) {
2717 		prep_vma_destroy(vm, vma, false);
2718 		xe_vma_destroy_unlocked(vma);
2719 		vma = ERR_PTR(err);
2720 	}
2721 
2722 	return vma;
2723 }
2724 
2725 static u64 xe_vma_max_pte_size(struct xe_vma *vma)
2726 {
2727 	if (vma->gpuva.flags & XE_VMA_PTE_1G)
2728 		return SZ_1G;
2729 	else if (vma->gpuva.flags & (XE_VMA_PTE_2M | XE_VMA_PTE_COMPACT))
2730 		return SZ_2M;
2731 	else if (vma->gpuva.flags & XE_VMA_PTE_64K)
2732 		return SZ_64K;
2733 	else if (vma->gpuva.flags & XE_VMA_PTE_4K)
2734 		return SZ_4K;
2735 
2736 	return SZ_1G;	/* Uninitialized, used max size */
2737 }
2738 
2739 static void xe_vma_set_pte_size(struct xe_vma *vma, u64 size)
2740 {
2741 	switch (size) {
2742 	case SZ_1G:
2743 		vma->gpuva.flags |= XE_VMA_PTE_1G;
2744 		break;
2745 	case SZ_2M:
2746 		vma->gpuva.flags |= XE_VMA_PTE_2M;
2747 		break;
2748 	case SZ_64K:
2749 		vma->gpuva.flags |= XE_VMA_PTE_64K;
2750 		break;
2751 	case SZ_4K:
2752 		vma->gpuva.flags |= XE_VMA_PTE_4K;
2753 		break;
2754 	}
2755 }
2756 
2757 static int xe_vma_op_commit(struct xe_vm *vm, struct xe_vma_op *op)
2758 {
2759 	int err = 0;
2760 
2761 	lockdep_assert_held(&vm->lock);
2762 
2763 	switch (op->base.op) {
2764 	case DRM_GPUVA_OP_MAP:
2765 		xe_vm_assert_write_mode_or_garbage_collector(vm);
2766 
2767 		err |= xe_vm_insert_vma(vm, op->map.vma);
2768 		if (!err)
2769 			op->flags |= XE_VMA_OP_COMMITTED;
2770 		break;
2771 	case DRM_GPUVA_OP_REMAP:
2772 	{
2773 		u8 tile_present =
2774 			gpuva_to_vma(op->base.remap.unmap->va)->tile_present;
2775 
2776 		xe_vm_assert_write_mode_or_garbage_collector(vm);
2777 
2778 		prep_vma_destroy(vm, gpuva_to_vma(op->base.remap.unmap->va),
2779 				 true);
2780 		op->flags |= XE_VMA_OP_COMMITTED;
2781 
2782 		if (op->remap.prev) {
2783 			err |= xe_vm_insert_vma(vm, op->remap.prev);
2784 			if (!err)
2785 				op->flags |= XE_VMA_OP_PREV_COMMITTED;
2786 			if (!err && op->remap.skip_prev) {
2787 				op->remap.prev->tile_present =
2788 					tile_present;
2789 			}
2790 		}
2791 		if (op->remap.next) {
2792 			err |= xe_vm_insert_vma(vm, op->remap.next);
2793 			if (!err)
2794 				op->flags |= XE_VMA_OP_NEXT_COMMITTED;
2795 			if (!err && op->remap.skip_next) {
2796 				op->remap.next->tile_present =
2797 					tile_present;
2798 			}
2799 		}
2800 
2801 		/*
2802 		 * Adjust for partial unbind after removing VMA from VM. In case
2803 		 * of unwind we might need to undo this later.
2804 		 */
2805 		if (!err) {
2806 			op->base.remap.unmap->va->va.addr = op->remap.start;
2807 			op->base.remap.unmap->va->va.range = op->remap.range;
2808 		}
2809 		break;
2810 	}
2811 	case DRM_GPUVA_OP_UNMAP:
2812 		xe_vm_assert_write_mode_or_garbage_collector(vm);
2813 
2814 		prep_vma_destroy(vm, gpuva_to_vma(op->base.unmap.va), true);
2815 		op->flags |= XE_VMA_OP_COMMITTED;
2816 		break;
2817 	case DRM_GPUVA_OP_PREFETCH:
2818 		op->flags |= XE_VMA_OP_COMMITTED;
2819 		break;
2820 	default:
2821 		drm_warn(&vm->xe->drm, "NOT POSSIBLE\n");
2822 	}
2823 
2824 	return err;
2825 }
2826 
2827 /**
2828  * xe_vma_has_default_mem_attrs - Check if a VMA has default memory attributes
2829  * @vma: Pointer to the xe_vma structure to check
2830  *
2831  * This function determines whether the given VMA (Virtual Memory Area)
2832  * has its memory attributes set to their default values. Specifically,
2833  * it checks the following conditions:
2834  *
2835  * - `atomic_access` is `DRM_XE_VMA_ATOMIC_UNDEFINED`
2836  * - `pat_index` is equal to `default_pat_index`
2837  * - `preferred_loc.devmem_fd` is `DRM_XE_PREFERRED_LOC_DEFAULT_DEVICE`
2838  * - `preferred_loc.migration_policy` is `DRM_XE_MIGRATE_ALL_PAGES`
2839  *
2840  * Return: true if all attributes are at their default values, false otherwise.
2841  */
2842 bool xe_vma_has_default_mem_attrs(struct xe_vma *vma)
2843 {
2844 	return (vma->attr.atomic_access == DRM_XE_ATOMIC_UNDEFINED &&
2845 		vma->attr.pat_index ==  vma->attr.default_pat_index &&
2846 		vma->attr.preferred_loc.devmem_fd == DRM_XE_PREFERRED_LOC_DEFAULT_DEVICE &&
2847 		vma->attr.preferred_loc.migration_policy == DRM_XE_MIGRATE_ALL_PAGES);
2848 }
2849 
2850 static int vm_bind_ioctl_ops_parse(struct xe_vm *vm, struct drm_gpuva_ops *ops,
2851 				   struct xe_vma_ops *vops)
2852 {
2853 	struct xe_device *xe = vm->xe;
2854 	struct drm_gpuva_op *__op;
2855 	struct xe_tile *tile;
2856 	u8 id, tile_mask = 0;
2857 	int err = 0;
2858 
2859 	xe_vm_assert_write_mode_or_garbage_collector(vm);
2860 
2861 	for_each_tile(tile, vm->xe, id)
2862 		tile_mask |= 0x1 << id;
2863 
2864 	drm_gpuva_for_each_op(__op, ops) {
2865 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2866 		struct xe_vma *vma;
2867 		unsigned int flags = 0;
2868 
2869 		INIT_LIST_HEAD(&op->link);
2870 		list_add_tail(&op->link, &vops->list);
2871 		op->tile_mask = tile_mask;
2872 
2873 		switch (op->base.op) {
2874 		case DRM_GPUVA_OP_MAP:
2875 		{
2876 			struct xe_vma_mem_attr default_attr = {
2877 				.preferred_loc = {
2878 					.devmem_fd = DRM_XE_PREFERRED_LOC_DEFAULT_DEVICE,
2879 					.migration_policy = DRM_XE_MIGRATE_ALL_PAGES,
2880 				},
2881 				.atomic_access = DRM_XE_ATOMIC_UNDEFINED,
2882 				.default_pat_index = op->map.pat_index,
2883 				.pat_index = op->map.pat_index,
2884 				.purgeable_state = XE_MADV_PURGEABLE_WILLNEED,
2885 			};
2886 
2887 			flags |= op->map.vma_flags & XE_VMA_CREATE_MASK;
2888 
2889 			vma = new_vma(vm, &op->base.map, &default_attr,
2890 				      flags);
2891 			if (IS_ERR(vma))
2892 				return PTR_ERR(vma);
2893 
2894 			op->map.vma = vma;
2895 			if (((op->map.immediate || !xe_vm_in_fault_mode(vm)) &&
2896 			     !(op->map.vma_flags & XE_VMA_SYSTEM_ALLOCATOR)) ||
2897 			    op->map.invalidate_on_bind)
2898 				xe_vma_ops_incr_pt_update_ops(vops,
2899 							      op->tile_mask, 1);
2900 			break;
2901 		}
2902 		case DRM_GPUVA_OP_REMAP:
2903 		{
2904 			struct xe_vma *old =
2905 				gpuva_to_vma(op->base.remap.unmap->va);
2906 			bool skip = xe_vma_is_cpu_addr_mirror(old);
2907 			u64 start = xe_vma_start(old), end = xe_vma_end(old);
2908 			int num_remap_ops = 0;
2909 
2910 			if (op->base.remap.prev)
2911 				start = op->base.remap.prev->va.addr +
2912 					op->base.remap.prev->va.range;
2913 			if (op->base.remap.next)
2914 				end = op->base.remap.next->va.addr;
2915 
2916 			if (xe_vma_is_cpu_addr_mirror(old) &&
2917 			    xe_svm_has_mapping(vm, start, end)) {
2918 				if (vops->flags & XE_VMA_OPS_FLAG_MADVISE)
2919 					xe_svm_unmap_address_range(vm, start, end);
2920 				else
2921 					return -EBUSY;
2922 			}
2923 
2924 			op->remap.start = xe_vma_start(old);
2925 			op->remap.range = xe_vma_size(old);
2926 			op->remap.old_start = op->remap.start;
2927 			op->remap.old_range = op->remap.range;
2928 
2929 			flags |= op->base.remap.unmap->va->flags & XE_VMA_CREATE_MASK;
2930 			if (op->base.remap.prev) {
2931 				vma = new_vma(vm, op->base.remap.prev,
2932 					      &old->attr, flags);
2933 				if (IS_ERR(vma))
2934 					return PTR_ERR(vma);
2935 
2936 				op->remap.prev = vma;
2937 
2938 				/*
2939 				 * Userptr creates a new SG mapping so
2940 				 * we must also rebind.
2941 				 */
2942 				op->remap.skip_prev = skip ||
2943 					(!xe_vma_is_userptr(old) &&
2944 					IS_ALIGNED(xe_vma_end(vma),
2945 						   xe_vma_max_pte_size(old)));
2946 				if (op->remap.skip_prev) {
2947 					xe_vma_set_pte_size(vma, xe_vma_max_pte_size(old));
2948 					op->remap.range -=
2949 						xe_vma_end(vma) -
2950 						xe_vma_start(old);
2951 					op->remap.start = xe_vma_end(vma);
2952 					vm_dbg(&xe->drm, "REMAP:SKIP_PREV: addr=0x%016llx, range=0x%016llx",
2953 					       (ULL)op->remap.start,
2954 					       (ULL)op->remap.range);
2955 				} else {
2956 					num_remap_ops++;
2957 				}
2958 			}
2959 
2960 			if (op->base.remap.next) {
2961 				vma = new_vma(vm, op->base.remap.next,
2962 					      &old->attr, flags);
2963 				if (IS_ERR(vma))
2964 					return PTR_ERR(vma);
2965 
2966 				op->remap.next = vma;
2967 
2968 				/*
2969 				 * Userptr creates a new SG mapping so
2970 				 * we must also rebind.
2971 				 */
2972 				op->remap.skip_next = skip ||
2973 					(!xe_vma_is_userptr(old) &&
2974 					IS_ALIGNED(xe_vma_start(vma),
2975 						   xe_vma_max_pte_size(old)));
2976 				if (op->remap.skip_next) {
2977 					xe_vma_set_pte_size(vma, xe_vma_max_pte_size(old));
2978 					op->remap.range -=
2979 						xe_vma_end(old) -
2980 						xe_vma_start(vma);
2981 					vm_dbg(&xe->drm, "REMAP:SKIP_NEXT: addr=0x%016llx, range=0x%016llx",
2982 					       (ULL)op->remap.start,
2983 					       (ULL)op->remap.range);
2984 				} else {
2985 					num_remap_ops++;
2986 				}
2987 			}
2988 			if (!skip)
2989 				num_remap_ops++;
2990 
2991 			xe_vma_ops_incr_pt_update_ops(vops, op->tile_mask, num_remap_ops);
2992 			break;
2993 		}
2994 		case DRM_GPUVA_OP_UNMAP:
2995 			vma = gpuva_to_vma(op->base.unmap.va);
2996 
2997 			if (xe_vma_is_cpu_addr_mirror(vma) &&
2998 			    xe_svm_has_mapping(vm, xe_vma_start(vma),
2999 					       xe_vma_end(vma)) &&
3000 			    !(vops->flags & XE_VMA_OPS_FLAG_ALLOW_SVM_UNMAP))
3001 				return -EBUSY;
3002 
3003 			if (!xe_vma_is_cpu_addr_mirror(vma))
3004 				xe_vma_ops_incr_pt_update_ops(vops, op->tile_mask, 1);
3005 			break;
3006 		case DRM_GPUVA_OP_PREFETCH:
3007 			vma = gpuva_to_vma(op->base.prefetch.va);
3008 
3009 			if (xe_vma_is_userptr(vma)) {
3010 				err = xe_vma_userptr_pin_pages(to_userptr_vma(vma));
3011 				if (err)
3012 					return err;
3013 			}
3014 
3015 			if (xe_vma_is_cpu_addr_mirror(vma))
3016 				xe_vma_ops_incr_pt_update_ops(vops, op->tile_mask,
3017 							      op->prefetch_range.ranges_count);
3018 			else
3019 				xe_vma_ops_incr_pt_update_ops(vops, op->tile_mask, 1);
3020 
3021 			break;
3022 		default:
3023 			drm_warn(&vm->xe->drm, "NOT POSSIBLE\n");
3024 		}
3025 
3026 		err = xe_vma_op_commit(vm, op);
3027 		if (err)
3028 			return err;
3029 	}
3030 
3031 	return 0;
3032 }
3033 
3034 static void xe_vma_op_unwind(struct xe_vm *vm, struct xe_vma_op *op,
3035 			     bool post_commit, bool prev_post_commit,
3036 			     bool next_post_commit)
3037 {
3038 	lockdep_assert_held(&vm->lock);
3039 
3040 	switch (op->base.op) {
3041 	case DRM_GPUVA_OP_MAP:
3042 		xe_vm_assert_write_mode_or_garbage_collector(vm);
3043 
3044 		if (op->map.vma) {
3045 			prep_vma_destroy(vm, op->map.vma, post_commit);
3046 			xe_vma_destroy_unlocked(op->map.vma);
3047 		}
3048 		break;
3049 	case DRM_GPUVA_OP_UNMAP:
3050 	{
3051 		struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
3052 
3053 		xe_vm_assert_write_mode_or_garbage_collector(vm);
3054 
3055 		if (vma) {
3056 			xe_svm_notifier_lock(vm);
3057 			vma->gpuva.flags &= ~XE_VMA_DESTROYED;
3058 			xe_svm_notifier_unlock(vm);
3059 			if (post_commit)
3060 				xe_vm_insert_vma(vm, vma);
3061 		}
3062 		break;
3063 	}
3064 	case DRM_GPUVA_OP_REMAP:
3065 	{
3066 		struct xe_vma *vma = gpuva_to_vma(op->base.remap.unmap->va);
3067 
3068 		xe_vm_assert_write_mode_or_garbage_collector(vm);
3069 
3070 		if (op->remap.prev) {
3071 			prep_vma_destroy(vm, op->remap.prev, prev_post_commit);
3072 			xe_vma_destroy_unlocked(op->remap.prev);
3073 		}
3074 		if (op->remap.next) {
3075 			prep_vma_destroy(vm, op->remap.next, next_post_commit);
3076 			xe_vma_destroy_unlocked(op->remap.next);
3077 		}
3078 		if (vma) {
3079 			xe_svm_notifier_lock(vm);
3080 			vma->gpuva.flags &= ~XE_VMA_DESTROYED;
3081 			xe_svm_notifier_unlock(vm);
3082 			if (post_commit) {
3083 				/*
3084 				 * Restore the old va range, in case of the
3085 				 * prev/next skip optimisation. Otherwise what
3086 				 * we re-insert here could be smaller than the
3087 				 * original range.
3088 				 */
3089 				op->base.remap.unmap->va->va.addr =
3090 					op->remap.old_start;
3091 				op->base.remap.unmap->va->va.range =
3092 					op->remap.old_range;
3093 				xe_vm_insert_vma(vm, vma);
3094 			}
3095 		}
3096 		break;
3097 	}
3098 	case DRM_GPUVA_OP_PREFETCH:
3099 		/* Nothing to do */
3100 		break;
3101 	default:
3102 		drm_warn(&vm->xe->drm, "NOT POSSIBLE\n");
3103 	}
3104 }
3105 
3106 static void vm_bind_ioctl_ops_unwind(struct xe_vm *vm,
3107 				     struct drm_gpuva_ops **ops,
3108 				     int num_ops_list)
3109 {
3110 	int i;
3111 
3112 	for (i = num_ops_list - 1; i >= 0; --i) {
3113 		struct drm_gpuva_ops *__ops = ops[i];
3114 		struct drm_gpuva_op *__op;
3115 
3116 		if (!__ops)
3117 			continue;
3118 
3119 		drm_gpuva_for_each_op_reverse(__op, __ops) {
3120 			struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
3121 
3122 			xe_vma_op_unwind(vm, op,
3123 					 op->flags & XE_VMA_OP_COMMITTED,
3124 					 op->flags & XE_VMA_OP_PREV_COMMITTED,
3125 					 op->flags & XE_VMA_OP_NEXT_COMMITTED);
3126 		}
3127 	}
3128 }
3129 
3130 /**
3131  * struct xe_vma_lock_and_validate_flags - Flags for vma_lock_and_validate()
3132  * @res_evict: Allow evicting resources during validation
3133  * @validate: Perform BO validation
3134  * @request_decompress: Request BO decompression
3135  * @check_purged: Reject operation if BO is DONTNEED or PURGED
3136  */
3137 struct xe_vma_lock_and_validate_flags {
3138 	u32 res_evict : 1;
3139 	u32 validate : 1;
3140 	u32 request_decompress : 1;
3141 	u32 check_purged : 1;
3142 };
3143 
3144 static int vma_lock_and_validate(struct drm_exec *exec, struct xe_vma *vma,
3145 				 struct xe_vma_lock_and_validate_flags flags)
3146 {
3147 	struct xe_bo *bo = xe_vma_bo(vma);
3148 	struct xe_vm *vm = xe_vma_vm(vma);
3149 	bool validate_bo = flags.validate;
3150 	int err = 0;
3151 
3152 	if (bo) {
3153 		if (!bo->vm)
3154 			err = drm_exec_lock_obj(exec, &bo->ttm.base);
3155 
3156 		/* Reject new mappings to DONTNEED/purged BOs; allow cleanup operations */
3157 		if (!err && flags.check_purged) {
3158 			if (xe_bo_madv_is_dontneed(bo))
3159 				err = -EBUSY;  /* BO marked purgeable */
3160 			else if (xe_bo_is_purged(bo))
3161 				err = -EINVAL; /* BO already purged */
3162 		}
3163 
3164 		/* Don't validate the BO for DONTNEED/PURGED remap remnants. */
3165 		if (vma->attr.purgeable_state != XE_MADV_PURGEABLE_WILLNEED)
3166 			validate_bo = false;
3167 
3168 		if (!err && validate_bo)
3169 			err = xe_bo_validate(bo, vm,
3170 					     xe_vm_allow_vm_eviction(vm) &&
3171 					     flags.res_evict, exec);
3172 
3173 		if (err)
3174 			return err;
3175 
3176 		if (flags.request_decompress)
3177 			err = xe_bo_decompress(bo);
3178 	}
3179 
3180 	return err;
3181 }
3182 
3183 static int check_ufence(struct xe_vma *vma)
3184 {
3185 	if (vma->ufence) {
3186 		struct xe_user_fence * const f = vma->ufence;
3187 
3188 		if (!xe_sync_ufence_get_status(f))
3189 			return -EBUSY;
3190 
3191 		vma->ufence = NULL;
3192 		xe_sync_ufence_put(f);
3193 	}
3194 
3195 	return 0;
3196 }
3197 
3198 struct prefetch_thread {
3199 	struct work_struct work;
3200 	struct drm_gpusvm_ctx *ctx;
3201 	struct xe_vma *vma;
3202 	struct xe_svm_range *svm_range;
3203 	struct drm_pagemap *dpagemap;
3204 	int err;
3205 };
3206 
3207 static void prefetch_thread_func(struct prefetch_thread *thread)
3208 {
3209 	struct xe_vma *vma = thread->vma;
3210 	struct xe_vm *vm = xe_vma_vm(vma);
3211 	struct xe_svm_range *svm_range = thread->svm_range;
3212 	struct drm_pagemap *dpagemap = thread->dpagemap;
3213 	int err = 0;
3214 
3215 	guard(mutex)(&svm_range->lock);
3216 
3217 	if (xe_svm_range_is_removed(svm_range))
3218 		return;
3219 
3220 	if (!dpagemap)
3221 		xe_svm_range_migrate_to_smem(vm, svm_range);
3222 
3223 	if (IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM)) {
3224 		drm_dbg(&vm->xe->drm,
3225 			"Prefetch pagemap is %s start 0x%016lx end 0x%016lx\n",
3226 			dpagemap ? dpagemap->drm->unique : "system",
3227 			xe_svm_range_start(svm_range), xe_svm_range_end(svm_range));
3228 	}
3229 
3230 	if (xe_svm_range_needs_migrate_to_vram(svm_range, vma, dpagemap)) {
3231 		err = xe_svm_alloc_vram(svm_range, thread->ctx, dpagemap);
3232 		if (err) {
3233 			drm_dbg(&vm->xe->drm, "VRAM allocation failed, retry from userspace, asid=%u, gpusvm=%p, errno=%pe\n",
3234 				vm->usm.asid, &vm->svm.gpusvm, ERR_PTR(err));
3235 			/*
3236 			 * We intentionally return -ENODATA on any races to
3237 			 * commit any VMA updates from other ops without
3238 			 * updating any page tables deferring to page faults to
3239 			 * page updates skipped in the IOCTL.
3240 			 */
3241 			thread->err = -ENODATA;
3242 			return;
3243 		}
3244 		xe_svm_range_debug(svm_range, "PREFETCH - RANGE MIGRATED TO VRAM");
3245 	}
3246 
3247 	err = xe_svm_range_get_pages(vm, svm_range, thread->ctx);
3248 	if (err) {
3249 		drm_dbg(&vm->xe->drm, "Get pages failed, asid=%u, gpusvm=%p, errno=%pe\n",
3250 			vm->usm.asid, &vm->svm.gpusvm, ERR_PTR(err));
3251 		if (err == -EOPNOTSUPP || err == -EFAULT || err == -EPERM)
3252 			err = -ENODATA;
3253 		thread->err = err;
3254 		return;
3255 	}
3256 	xe_svm_range_debug(svm_range, "PREFETCH - RANGE GET PAGES DONE");
3257 }
3258 
3259 static void prefetch_work_func(struct work_struct *w)
3260 {
3261 	struct prefetch_thread *thread =
3262 		container_of(w, struct prefetch_thread, work);
3263 
3264 	prefetch_thread_func(thread);
3265 }
3266 
3267 static int prefetch_ranges(struct xe_vm *vm, struct xe_vma_ops *vops,
3268 			   struct xe_vma_op *op)
3269 {
3270 	bool devmem_possible = IS_DGFX(vm->xe) && IS_ENABLED(CONFIG_DRM_XE_PAGEMAP);
3271 	struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
3272 	struct drm_pagemap *dpagemap = op->prefetch_range.dpagemap;
3273 	struct xe_svm_range *svm_range;
3274 	struct drm_gpusvm_ctx ctx = {};
3275 	struct prefetch_thread stack_thread, *thread, *prefetches;
3276 	unsigned long i;
3277 	int err = 0, idx = 0;
3278 	bool skip_threads;
3279 
3280 	if (!xe_vma_is_cpu_addr_mirror(vma))
3281 		return 0;
3282 
3283 	ctx.read_only = xe_vma_read_only(vma);
3284 	ctx.devmem_possible = devmem_possible;
3285 	ctx.check_pages_threshold = devmem_possible ? SZ_64K : 0;
3286 	ctx.device_private_page_owner = xe_svm_private_page_owner(vm, !dpagemap);
3287 	ctx.devmem_fn = xe_svm_devmem_lru_bump;
3288 
3289 	skip_threads =  op->prefetch_range.ranges_count == 1 ||
3290 		(!dpagemap && !(vops->flags &
3291 				XE_VMA_OPS_FLAG_HAS_SVM_VALID_RANGE)) ||
3292 		!(vops->flags & XE_VMA_OPS_FLAG_DOWNGRADE_LOCK) ||
3293 		vm->xe->info.num_pf_work == 1;
3294 	thread = skip_threads ? &stack_thread : NULL;
3295 
3296 	if (!skip_threads) {
3297 		prefetches = kvmalloc_objs(*prefetches,
3298 					   op->prefetch_range.ranges_count);
3299 		if (!prefetches)
3300 			return -ENOMEM;
3301 	}
3302 
3303 	xa_for_each(&op->prefetch_range.range, i, svm_range) {
3304 		if (!skip_threads) {
3305 			thread = prefetches + idx++;
3306 			INIT_WORK(&thread->work, prefetch_work_func);
3307 		}
3308 
3309 		thread->ctx = &ctx;
3310 		thread->vma = vma;
3311 		thread->svm_range = svm_range;
3312 		thread->dpagemap = dpagemap;
3313 		thread->err = 0;
3314 
3315 		if (skip_threads) {
3316 			prefetch_thread_func(thread);
3317 			if (thread->err)
3318 				return thread->err;
3319 		} else {
3320 			queue_work(vm->xe->usm.prefetch_wq, &thread->work);
3321 		}
3322 	}
3323 
3324 	if (!skip_threads) {
3325 		for (i = 0; i < idx; ++i) {
3326 			thread = prefetches + i;
3327 
3328 			flush_work(&thread->work);
3329 			if (thread->err && !err)
3330 				err = thread->err;
3331 		}
3332 		kvfree(prefetches);
3333 	}
3334 
3335 	return err;
3336 }
3337 
3338 static int op_lock_and_prep(struct drm_exec *exec, struct xe_vm *vm,
3339 			    struct xe_vma_ops *vops, struct xe_vma_op *op)
3340 {
3341 	int err = 0;
3342 	bool res_evict;
3343 
3344 	/*
3345 	 * We only allow evicting a BO within the VM if it is not part of an
3346 	 * array of binds, as an array of binds can evict another BO within the
3347 	 * bind.
3348 	 */
3349 	res_evict = !(vops->flags & XE_VMA_OPS_ARRAY_OF_BINDS);
3350 
3351 	switch (op->base.op) {
3352 	case DRM_GPUVA_OP_MAP:
3353 		if (!op->map.invalidate_on_bind)
3354 			err = vma_lock_and_validate(exec, op->map.vma,
3355 						    (struct xe_vma_lock_and_validate_flags) {
3356 							.res_evict = res_evict,
3357 							.validate = !xe_vm_in_fault_mode(vm) ||
3358 								    op->map.immediate,
3359 							.request_decompress =
3360 							op->map.request_decompress,
3361 							.check_purged = false,
3362 						    });
3363 		break;
3364 	case DRM_GPUVA_OP_REMAP:
3365 		err = check_ufence(gpuva_to_vma(op->base.remap.unmap->va));
3366 		if (err)
3367 			break;
3368 
3369 		err = vma_lock_and_validate(exec,
3370 					    gpuva_to_vma(op->base.remap.unmap->va),
3371 					    (struct xe_vma_lock_and_validate_flags) {
3372 						    .res_evict = res_evict,
3373 						    .validate = false,
3374 						    .request_decompress = false,
3375 						    .check_purged = false,
3376 					    });
3377 		if (!err && op->remap.prev)
3378 			err = vma_lock_and_validate(exec, op->remap.prev,
3379 						    (struct xe_vma_lock_and_validate_flags) {
3380 							    .res_evict = res_evict,
3381 							    .validate = true,
3382 							    .request_decompress = false,
3383 							    .check_purged = false,
3384 						    });
3385 		if (!err && op->remap.next)
3386 			err = vma_lock_and_validate(exec, op->remap.next,
3387 						    (struct xe_vma_lock_and_validate_flags) {
3388 							    .res_evict = res_evict,
3389 							    .validate = true,
3390 							    .request_decompress = false,
3391 							    .check_purged = false,
3392 						    });
3393 		break;
3394 	case DRM_GPUVA_OP_UNMAP:
3395 		err = check_ufence(gpuva_to_vma(op->base.unmap.va));
3396 		if (err)
3397 			break;
3398 
3399 		err = vma_lock_and_validate(exec,
3400 					    gpuva_to_vma(op->base.unmap.va),
3401 					    (struct xe_vma_lock_and_validate_flags) {
3402 						    .res_evict = res_evict,
3403 						    .validate = false,
3404 						    .request_decompress = false,
3405 						    .check_purged = false,
3406 					    });
3407 		break;
3408 	case DRM_GPUVA_OP_PREFETCH:
3409 	{
3410 		struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
3411 		u32 region;
3412 
3413 		if (!xe_vma_is_cpu_addr_mirror(vma)) {
3414 			region = op->prefetch.region;
3415 			xe_assert(vm->xe, region == DRM_XE_CONSULT_MEM_ADVISE_PREF_LOC ||
3416 				  region <= ARRAY_SIZE(region_to_mem_type));
3417 		}
3418 
3419 		/*
3420 		 * PREFETCH is the only op that still gates on BO purge state.
3421 		 * MAP/REMAP handle this inside xe_vma_create() so partial
3422 		 * unbind on a DONTNEED BO still works. PREFETCH skips
3423 		 * xe_vma_create() and would migrate a BO with no backing
3424 		 * store, so reject DONTNEED/PURGED here.
3425 		 */
3426 		err = vma_lock_and_validate(exec,
3427 					    gpuva_to_vma(op->base.prefetch.va),
3428 					    (struct xe_vma_lock_and_validate_flags) {
3429 						    .res_evict = res_evict,
3430 						    .validate = false,
3431 						    .request_decompress = false,
3432 						    .check_purged = true,
3433 					    });
3434 		if (!err && !xe_vma_has_no_bo(vma)) {
3435 			struct xe_bo *bo = xe_vma_bo(vma);
3436 			u32 mem_type;
3437 
3438 			if (region == DRM_XE_CONSULT_MEM_ADVISE_PREF_LOC) {
3439 				unsigned int i;
3440 
3441 				mem_type = XE_PL_TT;
3442 				for (i = 0; i < bo->placement.num_placement; i++) {
3443 					if (mem_type_is_vram(bo->placements[i].mem_type)) {
3444 						mem_type = bo->placements[i].mem_type;
3445 						break;
3446 					}
3447 				}
3448 			} else {
3449 				mem_type = region_to_mem_type[region];
3450 			}
3451 
3452 			err = xe_bo_migrate(bo, mem_type, NULL, exec);
3453 		}
3454 		break;
3455 	}
3456 	default:
3457 		drm_warn(&vm->xe->drm, "NOT POSSIBLE\n");
3458 	}
3459 
3460 	return err;
3461 }
3462 
3463 static int vm_bind_ioctl_ops_prefetch_ranges(struct xe_vm *vm,
3464 					     struct xe_vma_ops *vops)
3465 {
3466 	struct xe_vma_op *op;
3467 	int err;
3468 
3469 	if (!(vops->flags & XE_VMA_OPS_FLAG_HAS_SVM_PREFETCH))
3470 		return 0;
3471 
3472 	list_for_each_entry(op, &vops->list, link) {
3473 		if (op->base.op  == DRM_GPUVA_OP_PREFETCH) {
3474 			err = prefetch_ranges(vm, vops, op);
3475 			if (err)
3476 				return err;
3477 		}
3478 	}
3479 
3480 	return 0;
3481 }
3482 
3483 static int vm_bind_ioctl_ops_lock_and_prep(struct drm_exec *exec,
3484 					   struct xe_vm *vm,
3485 					   struct xe_vma_ops *vops)
3486 {
3487 	struct xe_vma_op *op;
3488 	int err;
3489 
3490 	err = drm_exec_lock_obj(exec, xe_vm_obj(vm));
3491 	if (err)
3492 		return err;
3493 
3494 	list_for_each_entry(op, &vops->list, link) {
3495 		err = op_lock_and_prep(exec, vm, vops, op);
3496 		if (err)
3497 			return err;
3498 	}
3499 
3500 #ifdef TEST_VM_OPS_ERROR
3501 	if (vops->inject_error &&
3502 	    vm->xe->vm_inject_error_position == FORCE_OP_ERROR_LOCK)
3503 		return -ENOSPC;
3504 #endif
3505 
3506 	return 0;
3507 }
3508 
3509 static void op_trace(struct xe_vma_op *op)
3510 {
3511 	switch (op->base.op) {
3512 	case DRM_GPUVA_OP_MAP:
3513 		trace_xe_vma_bind(op->map.vma);
3514 		break;
3515 	case DRM_GPUVA_OP_REMAP:
3516 		trace_xe_vma_unbind(gpuva_to_vma(op->base.remap.unmap->va));
3517 		if (op->remap.prev)
3518 			trace_xe_vma_bind(op->remap.prev);
3519 		if (op->remap.next)
3520 			trace_xe_vma_bind(op->remap.next);
3521 		break;
3522 	case DRM_GPUVA_OP_UNMAP:
3523 		trace_xe_vma_unbind(gpuva_to_vma(op->base.unmap.va));
3524 		break;
3525 	case DRM_GPUVA_OP_PREFETCH:
3526 		trace_xe_vma_bind(gpuva_to_vma(op->base.prefetch.va));
3527 		break;
3528 	case DRM_GPUVA_OP_DRIVER:
3529 		break;
3530 	default:
3531 		XE_WARN_ON("NOT POSSIBLE");
3532 	}
3533 }
3534 
3535 static void trace_xe_vm_ops_execute(struct xe_vma_ops *vops)
3536 {
3537 	struct xe_vma_op *op;
3538 
3539 	list_for_each_entry(op, &vops->list, link)
3540 		op_trace(op);
3541 }
3542 
3543 static int vm_ops_setup(struct xe_vm *vm, struct xe_vma_ops *vops)
3544 {
3545 	struct xe_tile *tile;
3546 	int number_tiles = 0;
3547 	u8 id;
3548 
3549 	for_each_tile(tile, vm->xe, id)
3550 		if (vops->pt_update_ops[id].num_ops)
3551 			++number_tiles;
3552 
3553 	if (!vops->q)
3554 		vops->q = vm->q;
3555 
3556 	return number_tiles;
3557 }
3558 
3559 static struct dma_fence *ops_execute(struct xe_vm *vm,
3560 				     struct xe_vma_ops *vops)
3561 {
3562 	struct xe_device *xe = vm->xe;
3563 	struct dma_fence *fence = NULL;
3564 	struct dma_fence **fences = NULL;
3565 	struct dma_fence_array *cf = NULL;
3566 	int current_fence = 0, n_fence = 1, err, i;
3567 
3568 	if (!vm_ops_setup(vm, vops))
3569 		return ERR_PTR(-ENODATA);
3570 
3571 	if (!(vops->flags & XE_VMA_OPS_FLAG_SKIP_TLB_WAIT)) {
3572 		for_each_tlb_inval(vops->q, i)
3573 			++n_fence;
3574 	}
3575 
3576 	fences = kzalloc_objs(*fences, n_fence);
3577 	if (!fences) {
3578 		fence = ERR_PTR(-ENOMEM);
3579 		goto err_trace;
3580 	}
3581 
3582 	cf = dma_fence_array_alloc(n_fence);
3583 	if (!cf) {
3584 		fence = ERR_PTR(-ENOMEM);
3585 		goto err_out;
3586 	}
3587 
3588 	err = xe_pt_update_ops_prepare(xe, vops);
3589 	if (err) {
3590 		fence = ERR_PTR(err);
3591 		goto err_out;
3592 	}
3593 
3594 	trace_xe_vm_ops_execute(vops);
3595 
3596 	fence = xe_pt_update_ops_run(xe, vops);
3597 	if (IS_ERR(fence))
3598 		goto err_out;
3599 	fences[current_fence++] = fence;
3600 
3601 	if (!(vops->flags & XE_VMA_OPS_FLAG_SKIP_TLB_WAIT)) {
3602 		xe_cpu_bind_job_lock(xe->cpu_bind, vops->q);
3603 		for_each_tlb_inval(vops->q, i)
3604 			fences[current_fence++] =
3605 				xe_exec_queue_tlb_inval_last_fence_get(vops->q,
3606 								       vm, i);
3607 		xe_cpu_bind_job_unlock(xe->cpu_bind, vops->q);
3608 	}
3609 
3610 	xe_assert(xe, current_fence == n_fence);
3611 	dma_fence_array_init(cf, n_fence, fences, dma_fence_context_alloc(1),
3612 			     1);
3613 	fence = &cf->base;
3614 
3615 	xe_pt_update_ops_fini(xe, vops);
3616 
3617 	return fence;
3618 
3619 err_out:
3620 	xe_pt_update_ops_abort(xe, vops);
3621 	kfree(fences);
3622 	kfree(cf);
3623 
3624 err_trace:
3625 	trace_xe_vm_ops_fail(vm);
3626 	return fence;
3627 }
3628 
3629 static void vma_add_ufence(struct xe_vma *vma, struct xe_user_fence *ufence)
3630 {
3631 	if (vma->ufence)
3632 		xe_sync_ufence_put(vma->ufence);
3633 	vma->ufence = __xe_sync_ufence_get(ufence);
3634 }
3635 
3636 static void op_add_ufence(struct xe_vm *vm, struct xe_vma_op *op,
3637 			  struct xe_user_fence *ufence)
3638 {
3639 	switch (op->base.op) {
3640 	case DRM_GPUVA_OP_MAP:
3641 		if (!xe_vma_is_cpu_addr_mirror(op->map.vma))
3642 			vma_add_ufence(op->map.vma, ufence);
3643 		break;
3644 	case DRM_GPUVA_OP_REMAP:
3645 		if (op->remap.prev)
3646 			vma_add_ufence(op->remap.prev, ufence);
3647 		if (op->remap.next)
3648 			vma_add_ufence(op->remap.next, ufence);
3649 		break;
3650 	case DRM_GPUVA_OP_UNMAP:
3651 		break;
3652 	case DRM_GPUVA_OP_PREFETCH:
3653 		vma_add_ufence(gpuva_to_vma(op->base.prefetch.va), ufence);
3654 		break;
3655 	default:
3656 		drm_warn(&vm->xe->drm, "NOT POSSIBLE\n");
3657 	}
3658 }
3659 
3660 static void vm_bind_ioctl_ops_fini(struct xe_vm *vm, struct xe_vma_ops *vops,
3661 				   struct dma_fence *fence)
3662 {
3663 	struct xe_user_fence *ufence;
3664 	struct xe_vma_op *op;
3665 	int i;
3666 
3667 	ufence = find_ufence_get(vops->syncs, vops->num_syncs);
3668 	list_for_each_entry(op, &vops->list, link) {
3669 		if (ufence)
3670 			op_add_ufence(vm, op, ufence);
3671 
3672 		if (op->base.op == DRM_GPUVA_OP_UNMAP)
3673 			xe_vma_destroy(gpuva_to_vma(op->base.unmap.va), fence);
3674 		else if (op->base.op == DRM_GPUVA_OP_REMAP)
3675 			xe_vma_destroy(gpuva_to_vma(op->base.remap.unmap->va),
3676 				       fence);
3677 	}
3678 	if (ufence)
3679 		xe_sync_ufence_put(ufence);
3680 	if (fence) {
3681 		for (i = 0; i < vops->num_syncs; i++)
3682 			xe_sync_entry_signal(vops->syncs + i, fence);
3683 	}
3684 }
3685 
3686 static struct dma_fence *vm_bind_ioctl_ops_execute(struct xe_vm *vm,
3687 						   struct xe_vma_ops *vops)
3688 {
3689 	struct xe_validation_ctx ctx;
3690 	struct drm_exec exec;
3691 	struct dma_fence *fence;
3692 	int err = 0;
3693 
3694 	lockdep_assert_held(&vm->lock);
3695 
3696 	xe_validation_guard(&ctx, &vm->xe->val, &exec,
3697 			    ((struct xe_val_flags) {
3698 				    .interruptible = true,
3699 				    .exec_ignore_duplicates = true,
3700 			    }), err) {
3701 		err = vm_bind_ioctl_ops_lock_and_prep(&exec, vm, vops);
3702 		drm_exec_retry_on_contention(&exec);
3703 		xe_validation_retry_on_oom(&ctx, &err);
3704 		if (err)
3705 			return ERR_PTR(err);
3706 
3707 		xe_vm_set_validation_exec(vm, &exec);
3708 		fence = ops_execute(vm, vops);
3709 		xe_vm_set_validation_exec(vm, NULL);
3710 		if (IS_ERR(fence)) {
3711 			if (PTR_ERR(fence) == -ENODATA)
3712 				vm_bind_ioctl_ops_fini(vm, vops, NULL);
3713 			return fence;
3714 		}
3715 
3716 		vm_bind_ioctl_ops_fini(vm, vops, fence);
3717 	}
3718 
3719 	return err ? ERR_PTR(err) : fence;
3720 }
3721 ALLOW_ERROR_INJECTION(vm_bind_ioctl_ops_execute, ERRNO);
3722 
3723 #define SUPPORTED_FLAGS_STUB  \
3724 	(DRM_XE_VM_BIND_FLAG_READONLY | \
3725 	 DRM_XE_VM_BIND_FLAG_IMMEDIATE | \
3726 	 DRM_XE_VM_BIND_FLAG_NULL | \
3727 	 DRM_XE_VM_BIND_FLAG_DUMPABLE | \
3728 	 DRM_XE_VM_BIND_FLAG_CHECK_PXP | \
3729 	 DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR | \
3730 	 DRM_XE_VM_BIND_FLAG_MADVISE_AUTORESET | \
3731 	 DRM_XE_VM_BIND_FLAG_DECOMPRESS)
3732 
3733 #ifdef TEST_VM_OPS_ERROR
3734 #define SUPPORTED_FLAGS	(SUPPORTED_FLAGS_STUB | FORCE_OP_ERROR)
3735 #else
3736 #define SUPPORTED_FLAGS	SUPPORTED_FLAGS_STUB
3737 #endif
3738 
3739 #define XE_64K_PAGE_MASK 0xffffull
3740 #define ALL_DRM_XE_SYNCS_FLAGS (DRM_XE_SYNCS_FLAG_WAIT_FOR_OP)
3741 
3742 static int vm_bind_ioctl_check_args(struct xe_device *xe, struct xe_vm *vm,
3743 				    struct drm_xe_vm_bind *args,
3744 				    struct drm_xe_vm_bind_op **bind_ops)
3745 {
3746 	int err;
3747 	int i;
3748 
3749 	if (XE_IOCTL_DBG(xe, args->pad || args->pad2) ||
3750 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
3751 		return -EINVAL;
3752 
3753 	if (XE_IOCTL_DBG(xe, args->extensions))
3754 		return -EINVAL;
3755 
3756 	if (XE_IOCTL_DBG(xe, args->num_syncs > DRM_XE_MAX_SYNCS))
3757 		return -EINVAL;
3758 
3759 	if (args->num_binds > 1) {
3760 		u64 __user *bind_user =
3761 			u64_to_user_ptr(args->vector_of_binds);
3762 
3763 		*bind_ops = kvmalloc_objs(struct drm_xe_vm_bind_op,
3764 					  args->num_binds,
3765 					  GFP_KERNEL | __GFP_ACCOUNT | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
3766 		if (!*bind_ops)
3767 			return args->num_binds > 1 ? -ENOBUFS : -ENOMEM;
3768 
3769 		err = copy_from_user(*bind_ops, bind_user,
3770 				     sizeof(struct drm_xe_vm_bind_op) *
3771 				     args->num_binds);
3772 		if (XE_IOCTL_DBG(xe, err)) {
3773 			err = -EFAULT;
3774 			goto free_bind_ops;
3775 		}
3776 	} else {
3777 		*bind_ops = &args->bind;
3778 	}
3779 
3780 	for (i = 0; i < args->num_binds; ++i) {
3781 		u64 range = (*bind_ops)[i].range;
3782 		u64 addr = (*bind_ops)[i].addr;
3783 		u32 op = (*bind_ops)[i].op;
3784 		u32 flags = (*bind_ops)[i].flags;
3785 		u32 obj = (*bind_ops)[i].obj;
3786 		u64 obj_offset = (*bind_ops)[i].obj_offset;
3787 		u32 prefetch_region = (*bind_ops)[i].prefetch_mem_region_instance;
3788 		bool is_null = flags & DRM_XE_VM_BIND_FLAG_NULL;
3789 		bool is_cpu_addr_mirror = flags &
3790 			DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR;
3791 		bool is_decompress = flags & DRM_XE_VM_BIND_FLAG_DECOMPRESS;
3792 		u16 pat_index = (*bind_ops)[i].pat_index;
3793 		u16 coh_mode;
3794 		bool comp_en;
3795 
3796 		if (XE_IOCTL_DBG(xe, is_cpu_addr_mirror &&
3797 				 (!xe_vm_in_fault_mode(vm) ||
3798 				 !IS_ENABLED(CONFIG_DRM_XE_GPUSVM)))) {
3799 			err = -EINVAL;
3800 			goto free_bind_ops;
3801 		}
3802 
3803 		if (XE_IOCTL_DBG(xe, pat_index >= xe->pat.n_entries)) {
3804 			err = -EINVAL;
3805 			goto free_bind_ops;
3806 		}
3807 
3808 		pat_index = array_index_nospec(pat_index, xe->pat.n_entries);
3809 		(*bind_ops)[i].pat_index = pat_index;
3810 		coh_mode = xe_pat_index_get_coh_mode(xe, pat_index);
3811 		comp_en = xe_pat_index_get_comp_en(xe, pat_index);
3812 		if (XE_IOCTL_DBG(xe, !coh_mode)) { /* hw reserved */
3813 			err = -EINVAL;
3814 			goto free_bind_ops;
3815 		}
3816 
3817 		if (XE_WARN_ON(coh_mode > XE_COH_2WAY)) {
3818 			err = -EINVAL;
3819 			goto free_bind_ops;
3820 		}
3821 
3822 		if (XE_IOCTL_DBG(xe, op > DRM_XE_VM_BIND_OP_PREFETCH) ||
3823 		    XE_IOCTL_DBG(xe, flags & ~SUPPORTED_FLAGS) ||
3824 		    XE_IOCTL_DBG(xe, obj && (is_null || is_cpu_addr_mirror)) ||
3825 		    XE_IOCTL_DBG(xe, obj_offset && (is_null ||
3826 						    is_cpu_addr_mirror)) ||
3827 		    XE_IOCTL_DBG(xe, op != DRM_XE_VM_BIND_OP_MAP &&
3828 				 (is_decompress || is_null || is_cpu_addr_mirror)) ||
3829 		    XE_IOCTL_DBG(xe, is_decompress &&
3830 				 xe_pat_index_get_comp_en(xe, pat_index)) ||
3831 		    XE_IOCTL_DBG(xe, !obj &&
3832 				 op == DRM_XE_VM_BIND_OP_MAP &&
3833 				 !is_null && !is_cpu_addr_mirror) ||
3834 		    XE_IOCTL_DBG(xe, !obj &&
3835 				 op == DRM_XE_VM_BIND_OP_UNMAP_ALL) ||
3836 		    XE_IOCTL_DBG(xe, addr &&
3837 				 op == DRM_XE_VM_BIND_OP_UNMAP_ALL) ||
3838 		    XE_IOCTL_DBG(xe, range &&
3839 				 op == DRM_XE_VM_BIND_OP_UNMAP_ALL) ||
3840 		    XE_IOCTL_DBG(xe, obj &&
3841 				 op == DRM_XE_VM_BIND_OP_MAP_USERPTR) ||
3842 		    XE_IOCTL_DBG(xe, coh_mode == XE_COH_NONE &&
3843 				 op == DRM_XE_VM_BIND_OP_MAP_USERPTR) ||
3844 		    XE_IOCTL_DBG(xe, !IS_DGFX(xe) && coh_mode == XE_COH_NONE &&
3845 				 is_cpu_addr_mirror) ||
3846 		    XE_IOCTL_DBG(xe, xe_device_is_l2_flush_optimized(xe) &&
3847 				 (op == DRM_XE_VM_BIND_OP_MAP_USERPTR ||
3848 				  is_cpu_addr_mirror) &&
3849 				 (pat_index != 19 && coh_mode != XE_COH_2WAY)) ||
3850 		    XE_IOCTL_DBG(xe, comp_en &&
3851 				 op == DRM_XE_VM_BIND_OP_MAP_USERPTR) ||
3852 		    XE_IOCTL_DBG(xe, op == DRM_XE_VM_BIND_OP_MAP_USERPTR &&
3853 				 !IS_ENABLED(CONFIG_DRM_GPUSVM)) ||
3854 		    XE_IOCTL_DBG(xe, obj &&
3855 				 op == DRM_XE_VM_BIND_OP_PREFETCH) ||
3856 		    XE_IOCTL_DBG(xe, prefetch_region &&
3857 				 op != DRM_XE_VM_BIND_OP_PREFETCH) ||
3858 		    XE_IOCTL_DBG(xe, (prefetch_region != DRM_XE_CONSULT_MEM_ADVISE_PREF_LOC &&
3859 				      /* Guard against undefined shift in BIT(prefetch_region) */
3860 				      (prefetch_region >= (sizeof(xe->info.mem_region_mask) * 8) ||
3861 				      !(BIT(prefetch_region) & xe->info.mem_region_mask)))) ||
3862 		    XE_IOCTL_DBG(xe, obj &&
3863 				 op == DRM_XE_VM_BIND_OP_UNMAP) ||
3864 		    XE_IOCTL_DBG(xe, (flags & DRM_XE_VM_BIND_FLAG_MADVISE_AUTORESET) &&
3865 				 (!is_cpu_addr_mirror || op != DRM_XE_VM_BIND_OP_MAP))) {
3866 			err = -EINVAL;
3867 			goto free_bind_ops;
3868 		}
3869 
3870 		if (XE_IOCTL_DBG(xe, obj_offset & ~PAGE_MASK) ||
3871 		    XE_IOCTL_DBG(xe, addr & ~PAGE_MASK) ||
3872 		    XE_IOCTL_DBG(xe, range & ~PAGE_MASK) ||
3873 		    XE_IOCTL_DBG(xe, !range &&
3874 				 op != DRM_XE_VM_BIND_OP_UNMAP_ALL)) {
3875 			err = -EINVAL;
3876 			goto free_bind_ops;
3877 		}
3878 
3879 		if (is_decompress && (XE_IOCTL_DBG(xe, !xe_device_has_flat_ccs(xe)) ||
3880 				      XE_IOCTL_DBG(xe, GRAPHICS_VER(xe) < 20) ||
3881 				      XE_IOCTL_DBG(xe, !IS_DGFX(xe)))) {
3882 			err = -EOPNOTSUPP;
3883 			goto free_bind_ops;
3884 		}
3885 	}
3886 
3887 	return 0;
3888 
3889 free_bind_ops:
3890 	if (args->num_binds > 1)
3891 		kvfree(*bind_ops);
3892 	*bind_ops = NULL;
3893 	return err;
3894 }
3895 
3896 static int vm_bind_ioctl_signal_fences(struct xe_vm *vm,
3897 				       struct xe_exec_queue *q,
3898 				       struct xe_sync_entry *syncs,
3899 				       int num_syncs)
3900 {
3901 	struct dma_fence *fence = NULL;
3902 	int i, err = 0;
3903 
3904 	if (num_syncs) {
3905 		fence = xe_sync_in_fence_get(syncs, num_syncs,
3906 					     to_wait_exec_queue(vm, q), vm);
3907 		if (IS_ERR(fence))
3908 			return PTR_ERR(fence);
3909 
3910 		for (i = 0; i < num_syncs; i++)
3911 			xe_sync_entry_signal(&syncs[i], fence);
3912 	}
3913 
3914 	dma_fence_put(fence);
3915 
3916 	return err;
3917 }
3918 
3919 static void xe_vma_ops_init(struct xe_vma_ops *vops, struct xe_vm *vm,
3920 			    struct xe_exec_queue *q,
3921 			    struct xe_sync_entry *syncs, u32 num_syncs)
3922 {
3923 	memset(vops, 0, sizeof(*vops));
3924 	INIT_LIST_HEAD(&vops->list);
3925 	vops->vm = vm;
3926 	vops->q = q;
3927 	vops->syncs = syncs;
3928 	vops->num_syncs = num_syncs;
3929 	vops->flags = 0;
3930 	vops->start = ~0x0ull;
3931 	vops->last = 0x0ull;
3932 }
3933 
3934 static int xe_vm_bind_ioctl_validate_bo(struct xe_device *xe, struct xe_bo *bo,
3935 					u64 addr, u64 range, u64 obj_offset,
3936 					u16 pat_index, u32 op, u32 bind_flags)
3937 {
3938 	u16 coh_mode;
3939 	bool comp_en;
3940 
3941 	if (XE_IOCTL_DBG(xe, (bo->flags & XE_BO_FLAG_NO_COMPRESSION) &&
3942 			 xe_pat_index_get_comp_en(xe, pat_index)))
3943 		return -EINVAL;
3944 
3945 	if (XE_IOCTL_DBG(xe, range > xe_bo_size(bo)) ||
3946 	    XE_IOCTL_DBG(xe, obj_offset >
3947 			 xe_bo_size(bo) - range)) {
3948 		return -EINVAL;
3949 	}
3950 
3951 	/*
3952 	 * Some platforms require 64k VM_BIND alignment,
3953 	 * specifically those with XE_VRAM_FLAGS_NEED64K.
3954 	 *
3955 	 * Other platforms may have BO's set to 64k physical placement,
3956 	 * but can be mapped at 4k offsets anyway. This check is only
3957 	 * there for the former case.
3958 	 */
3959 	if ((bo->flags & XE_BO_FLAG_INTERNAL_64K) &&
3960 	    (xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K)) {
3961 		if (XE_IOCTL_DBG(xe, obj_offset &
3962 				 XE_64K_PAGE_MASK) ||
3963 		    XE_IOCTL_DBG(xe, addr & XE_64K_PAGE_MASK) ||
3964 		    XE_IOCTL_DBG(xe, range & XE_64K_PAGE_MASK)) {
3965 			return -EINVAL;
3966 		}
3967 	}
3968 
3969 	coh_mode = xe_pat_index_get_coh_mode(xe, pat_index);
3970 	if (bo->cpu_caching) {
3971 		if (XE_IOCTL_DBG(xe, coh_mode == XE_COH_NONE &&
3972 				 bo->cpu_caching == DRM_XE_GEM_CPU_CACHING_WB)) {
3973 			return -EINVAL;
3974 		}
3975 	} else if (XE_IOCTL_DBG(xe, coh_mode == XE_COH_NONE)) {
3976 		/*
3977 		 * Imported dma-buf from a different device should
3978 		 * require 1way or 2way coherency since we don't know
3979 		 * how it was mapped on the CPU. Just assume is it
3980 		 * potentially cached on CPU side.
3981 		 */
3982 		return -EINVAL;
3983 	}
3984 
3985 	/*
3986 	 * Ensures that imported buffer objects (dma-bufs) are not mapped
3987 	 * with a PAT index that enables compression.
3988 	 */
3989 	comp_en = xe_pat_index_get_comp_en(xe, pat_index);
3990 	if (XE_IOCTL_DBG(xe, bo->ttm.base.import_attach && comp_en))
3991 		return -EINVAL;
3992 
3993 	if (XE_IOCTL_DBG(xe, bo->ttm.base.import_attach && xe_device_is_l2_flush_optimized(xe) &&
3994 			 (pat_index != 19 && coh_mode != XE_COH_2WAY)))
3995 		return -EINVAL;
3996 
3997 	/* If a BO is protected it can only be mapped if the key is still valid */
3998 	if ((bind_flags & DRM_XE_VM_BIND_FLAG_CHECK_PXP) && xe_bo_is_protected(bo) &&
3999 	    op != DRM_XE_VM_BIND_OP_UNMAP && op != DRM_XE_VM_BIND_OP_UNMAP_ALL)
4000 		if (XE_IOCTL_DBG(xe, xe_pxp_bo_key_check(xe->pxp, bo) != 0))
4001 			return -ENOEXEC;
4002 
4003 	return 0;
4004 }
4005 
4006 int xe_vm_bind_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
4007 {
4008 	struct xe_device *xe = to_xe_device(dev);
4009 	struct xe_file *xef = to_xe_file(file);
4010 	struct drm_xe_vm_bind *args = data;
4011 	struct drm_xe_sync __user *syncs_user;
4012 	struct xe_bo **bos = NULL;
4013 	struct drm_gpuva_ops **ops = NULL;
4014 	struct xe_vm *vm;
4015 	struct xe_exec_queue *q = NULL;
4016 	u32 num_syncs, num_ufence = 0;
4017 	struct xe_sync_entry *syncs = NULL;
4018 	struct drm_xe_vm_bind_op *bind_ops = NULL;
4019 	struct xe_vma_ops vops = { .flags = 0, };
4020 	struct dma_fence *fence;
4021 	int err;
4022 	int i;
4023 
4024 	vm = xe_vm_lookup(xef, args->vm_id);
4025 	if (XE_IOCTL_DBG(xe, !vm))
4026 		return -EINVAL;
4027 
4028 	err = vm_bind_ioctl_check_args(xe, vm, args, &bind_ops);
4029 	if (err)
4030 		goto put_vm;
4031 
4032 	if (args->exec_queue_id) {
4033 		q = xe_exec_queue_lookup(xef, args->exec_queue_id);
4034 		if (XE_IOCTL_DBG(xe, !q)) {
4035 			err = -ENOENT;
4036 			goto free_bind_ops;
4037 		}
4038 
4039 		if (XE_IOCTL_DBG(xe, !(q->flags & EXEC_QUEUE_FLAG_VM))) {
4040 			err = -EINVAL;
4041 			goto put_exec_queue;
4042 		}
4043 	}
4044 
4045 	if (XE_IOCTL_DBG(xe, q && vm != q->user_vm)) {
4046 		err = -EINVAL;
4047 		goto put_exec_queue;
4048 	}
4049 
4050 	/* Ensure all UNMAPs visible */
4051 	xe_svm_flush(vm);
4052 
4053 	err = down_write_killable(&vm->lock);
4054 	if (err)
4055 		goto put_exec_queue;
4056 
4057 	if (XE_IOCTL_DBG(xe, xe_vm_is_closed_or_banned(vm))) {
4058 		err = -ENOENT;
4059 		goto release_vm_lock;
4060 	}
4061 
4062 	for (i = 0; i < args->num_binds; ++i) {
4063 		u64 range = bind_ops[i].range;
4064 		u64 addr = bind_ops[i].addr;
4065 
4066 		if (XE_IOCTL_DBG(xe, range > vm->size) ||
4067 		    XE_IOCTL_DBG(xe, addr > vm->size - range)) {
4068 			err = -EINVAL;
4069 			goto release_vm_lock;
4070 		}
4071 	}
4072 
4073 	if (args->num_binds) {
4074 		bos = kvzalloc_objs(*bos, args->num_binds,
4075 				    GFP_KERNEL | __GFP_ACCOUNT | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
4076 		if (!bos) {
4077 			err = -ENOMEM;
4078 			goto release_vm_lock;
4079 		}
4080 
4081 		ops = kvzalloc_objs(*ops, args->num_binds,
4082 				    GFP_KERNEL | __GFP_ACCOUNT | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
4083 		if (!ops) {
4084 			err = -ENOMEM;
4085 			goto free_bos;
4086 		}
4087 	}
4088 
4089 	for (i = 0; i < args->num_binds; ++i) {
4090 		struct drm_gem_object *gem_obj;
4091 		u64 range = bind_ops[i].range;
4092 		u64 addr = bind_ops[i].addr;
4093 		u32 obj = bind_ops[i].obj;
4094 		u64 obj_offset = bind_ops[i].obj_offset;
4095 		u16 pat_index = bind_ops[i].pat_index;
4096 		u32 op = bind_ops[i].op;
4097 		u32 bind_flags = bind_ops[i].flags;
4098 
4099 		if (!obj)
4100 			continue;
4101 
4102 		gem_obj = drm_gem_object_lookup(file, obj);
4103 		if (XE_IOCTL_DBG(xe, !gem_obj)) {
4104 			err = -ENOENT;
4105 			goto put_obj;
4106 		}
4107 		bos[i] = gem_to_xe_bo(gem_obj);
4108 
4109 		err = xe_vm_bind_ioctl_validate_bo(xe, bos[i], addr, range,
4110 						   obj_offset, pat_index, op,
4111 						   bind_flags);
4112 		if (err)
4113 			goto put_obj;
4114 	}
4115 
4116 	if (args->num_syncs) {
4117 		syncs = kzalloc_objs(*syncs, args->num_syncs);
4118 		if (!syncs) {
4119 			err = -ENOMEM;
4120 			goto put_obj;
4121 		}
4122 	}
4123 
4124 	syncs_user = u64_to_user_ptr(args->syncs);
4125 	for (num_syncs = 0; num_syncs < args->num_syncs; num_syncs++) {
4126 		struct xe_exec_queue *__q = q ?: vm->q;
4127 
4128 		err = xe_sync_entry_parse(xe, xef, &syncs[num_syncs],
4129 					  &syncs_user[num_syncs],
4130 					  __q->ufence_syncobj,
4131 					  ++__q->ufence_timeline_value,
4132 					  (xe_vm_in_lr_mode(vm) ?
4133 					   SYNC_PARSE_FLAG_LR_MODE : 0) |
4134 					  (!args->num_binds ?
4135 					   SYNC_PARSE_FLAG_DISALLOW_USER_FENCE : 0));
4136 		if (err)
4137 			goto free_syncs;
4138 
4139 		if (xe_sync_is_ufence(&syncs[num_syncs]))
4140 			num_ufence++;
4141 	}
4142 
4143 	if (XE_IOCTL_DBG(xe, num_ufence > 1)) {
4144 		err = -EINVAL;
4145 		goto free_syncs;
4146 	}
4147 
4148 	if (!args->num_binds) {
4149 		err = -ENODATA;
4150 		goto free_syncs;
4151 	}
4152 
4153 	xe_vma_ops_init(&vops, vm, q, syncs, num_syncs);
4154 	if (args->num_binds > 1)
4155 		vops.flags |= XE_VMA_OPS_ARRAY_OF_BINDS;
4156 	for (i = 0; i < args->num_binds; ++i) {
4157 		u64 range = bind_ops[i].range;
4158 		u64 addr = bind_ops[i].addr;
4159 		u32 op = bind_ops[i].op;
4160 		u32 flags = bind_ops[i].flags;
4161 		u64 obj_offset = bind_ops[i].obj_offset;
4162 		u32 prefetch_region = bind_ops[i].prefetch_mem_region_instance;
4163 		u16 pat_index = bind_ops[i].pat_index;
4164 
4165 		ops[i] = vm_bind_ioctl_ops_create(vm, &vops, bos[i], obj_offset,
4166 						  addr, range, op, flags,
4167 						  prefetch_region, pat_index);
4168 		if (IS_ERR(ops[i])) {
4169 			err = PTR_ERR(ops[i]);
4170 			ops[i] = NULL;
4171 			goto unwind_ops;
4172 		}
4173 
4174 		err = vm_bind_ioctl_ops_parse(vm, ops[i], &vops);
4175 		if (err)
4176 			goto unwind_ops;
4177 
4178 #ifdef TEST_VM_OPS_ERROR
4179 		if (flags & FORCE_OP_ERROR) {
4180 			vops.inject_error = true;
4181 			vm->xe->vm_inject_error_position =
4182 				(vm->xe->vm_inject_error_position + 1) %
4183 				FORCE_OP_ERROR_COUNT;
4184 		}
4185 #endif
4186 	}
4187 
4188 	/* Nothing to do */
4189 	if (list_empty(&vops.list)) {
4190 		err = -ENODATA;
4191 		goto unwind_ops;
4192 	}
4193 
4194 	if (!(vops.flags & XE_VMA_OPS_FLAG_MODIFIES_GPUVA)) {
4195 		vops.flags |= XE_VMA_OPS_FLAG_DOWNGRADE_LOCK;
4196 		downgrade_write(&vm->lock);
4197 	}
4198 
4199 	err = xe_vma_ops_alloc(&vops, args->num_binds > 1);
4200 	if (err)
4201 		goto unwind_ops;
4202 
4203 	err = vm_bind_ioctl_ops_prefetch_ranges(vm, &vops);
4204 	if (err)
4205 		goto unwind_ops;
4206 
4207 	fence = vm_bind_ioctl_ops_execute(vm, &vops);
4208 	if (IS_ERR(fence))
4209 		err = PTR_ERR(fence);
4210 	else
4211 		dma_fence_put(fence);
4212 
4213 unwind_ops:
4214 	if (err && err != -ENODATA)
4215 		vm_bind_ioctl_ops_unwind(vm, ops, args->num_binds);
4216 	xe_vma_ops_fini(&vops);
4217 	for (i = args->num_binds - 1; i >= 0; --i)
4218 		if (ops[i])
4219 			drm_gpuva_ops_free(&vm->gpuvm, ops[i]);
4220 free_syncs:
4221 	if (err == -ENODATA)
4222 		err = vm_bind_ioctl_signal_fences(vm, q, syncs, num_syncs);
4223 	while (num_syncs--)
4224 		xe_sync_entry_cleanup(&syncs[num_syncs]);
4225 
4226 	kfree(syncs);
4227 put_obj:
4228 	for (i = 0; i < args->num_binds; ++i)
4229 		xe_bo_put(bos[i]);
4230 
4231 	kvfree(ops);
4232 free_bos:
4233 	kvfree(bos);
4234 release_vm_lock:
4235 	if (vops.flags & XE_VMA_OPS_FLAG_DOWNGRADE_LOCK)
4236 		up_read(&vm->lock);
4237 	else
4238 		up_write(&vm->lock);
4239 put_exec_queue:
4240 	if (q)
4241 		xe_exec_queue_put(q);
4242 free_bind_ops:
4243 	if (args->num_binds > 1)
4244 		kvfree(bind_ops);
4245 put_vm:
4246 	xe_vm_put(vm);
4247 	return err;
4248 }
4249 
4250 /*
4251  * Map access type, fault type, and fault level from current bspec
4252  * specification to user spec abstraction.  The current mapping is
4253  * approximately 1-to-1, with access type being the only notable
4254  * exception as it carries additional data with respect to prefetch
4255  * status that needs to be masked out.
4256  */
4257 static u8 xe_to_user_access_type(u8 access_type)
4258 {
4259 	return access_type & XE_PAGEFAULT_ACCESS_TYPE_MASK;
4260 }
4261 
4262 static u8 xe_to_user_fault_type(u8 fault_type)
4263 {
4264 	return fault_type;
4265 }
4266 
4267 static u8 xe_to_user_fault_level(u8 fault_level)
4268 {
4269 	return fault_level;
4270 }
4271 
4272 static u8 xe_to_user_srcid(u8 srcid)
4273 {
4274 	return srcid;
4275 }
4276 
4277 static int fill_faults(struct xe_vm *vm,
4278 		       struct drm_xe_vm_get_property *args)
4279 {
4280 	struct xe_vm_fault __user *usr_ptr = u64_to_user_ptr(args->data);
4281 	struct xe_vm_fault *fault_list, fault_entry = { 0 };
4282 	struct xe_vm_fault_entry *entry;
4283 	int ret = 0, i = 0, count, entry_size;
4284 
4285 	entry_size = sizeof(struct xe_vm_fault);
4286 	count = args->size / entry_size;
4287 
4288 	fault_list = kzalloc_objs(struct xe_vm_fault, count);
4289 	if (!fault_list)
4290 		return -ENOMEM;
4291 
4292 	spin_lock(&vm->faults.lock);
4293 	list_for_each_entry(entry, &vm->faults.list, list) {
4294 		if (i == count)
4295 			break;
4296 
4297 		fault_entry.address = xe_device_canonicalize_addr(vm->xe, entry->address);
4298 		fault_entry.address_precision = entry->address_precision;
4299 
4300 		fault_entry.access_type = xe_to_user_access_type(entry->access_type);
4301 		fault_entry.fault_type = xe_to_user_fault_type(entry->fault_type);
4302 		fault_entry.fault_level = xe_to_user_fault_level(entry->fault_level);
4303 
4304 		fault_entry.srcid = xe_to_user_srcid(entry->srcid);
4305 
4306 		memcpy(&fault_list[i], &fault_entry, entry_size);
4307 
4308 		i++;
4309 	}
4310 	spin_unlock(&vm->faults.lock);
4311 
4312 	ret = copy_to_user(usr_ptr, fault_list, args->size);
4313 
4314 	kfree(fault_list);
4315 	return ret ? -EFAULT : 0;
4316 }
4317 
4318 static int xe_vm_get_property_helper(struct xe_vm *vm,
4319 				     struct drm_xe_vm_get_property *args)
4320 {
4321 	size_t size;
4322 
4323 	switch (args->property) {
4324 	case DRM_XE_VM_GET_PROPERTY_FAULTS:
4325 		spin_lock(&vm->faults.lock);
4326 		size = size_mul(sizeof(struct xe_vm_fault), vm->faults.len);
4327 		spin_unlock(&vm->faults.lock);
4328 
4329 		if (!args->size) {
4330 			args->size = size;
4331 			return 0;
4332 		}
4333 
4334 		/*
4335 		 * Number of faults may increase between calls to
4336 		 * xe_vm_get_property_ioctl, so just report the number of
4337 		 * faults the user requests if it's less than or equal to
4338 		 * the number of faults in the VM fault array.
4339 		 *
4340 		 * We should also at least assert that the args->size value
4341 		 * is a multiple of the xe_vm_fault struct size.
4342 		 */
4343 		if (args->size > size || args->size % sizeof(struct xe_vm_fault))
4344 			return -EINVAL;
4345 
4346 		return fill_faults(vm, args);
4347 	}
4348 	return -EINVAL;
4349 }
4350 
4351 int xe_vm_get_property_ioctl(struct drm_device *drm, void *data,
4352 			     struct drm_file *file)
4353 {
4354 	struct xe_device *xe = to_xe_device(drm);
4355 	struct xe_file *xef = to_xe_file(file);
4356 	struct drm_xe_vm_get_property *args = data;
4357 	struct xe_vm *vm;
4358 	int ret = 0;
4359 
4360 	if (XE_IOCTL_DBG(xe, (args->reserved[0] || args->reserved[1] ||
4361 			      args->reserved[2] || args->extensions ||
4362 			      args->pad)))
4363 		return -EINVAL;
4364 
4365 	vm = xe_vm_lookup(xef, args->vm_id);
4366 	if (XE_IOCTL_DBG(xe, !vm))
4367 		return -ENOENT;
4368 
4369 	ret = xe_vm_get_property_helper(vm, args);
4370 
4371 	xe_vm_put(vm);
4372 	return ret;
4373 }
4374 
4375 /**
4376  * xe_vm_bind_kernel_bo - bind a kernel BO to a VM
4377  * @vm: VM to bind the BO to
4378  * @bo: BO to bind
4379  * @q: exec queue to use for the bind (optional)
4380  * @addr: address at which to bind the BO
4381  * @cache_lvl: PAT cache level to use
4382  *
4383  * Execute a VM bind map operation on a kernel-owned BO to bind it into a
4384  * kernel-owned VM.
4385  *
4386  * Returns a dma_fence to track the binding completion if the job to do so was
4387  * successfully submitted, an error pointer otherwise.
4388  */
4389 struct dma_fence *xe_vm_bind_kernel_bo(struct xe_vm *vm, struct xe_bo *bo,
4390 				       struct xe_exec_queue *q, u64 addr,
4391 				       enum xe_cache_level cache_lvl)
4392 {
4393 	struct xe_vma_ops vops;
4394 	struct drm_gpuva_ops *ops = NULL;
4395 	struct dma_fence *fence;
4396 	int err;
4397 
4398 	xe_bo_get(bo);
4399 	xe_vm_get(vm);
4400 	if (q)
4401 		xe_exec_queue_get(q);
4402 
4403 	down_write(&vm->lock);
4404 
4405 	xe_vma_ops_init(&vops, vm, q, NULL, 0);
4406 
4407 	ops = vm_bind_ioctl_ops_create(vm, &vops, bo, 0, addr, xe_bo_size(bo),
4408 				       DRM_XE_VM_BIND_OP_MAP, 0, 0,
4409 				       xe_cache_pat_idx(vm->xe, cache_lvl));
4410 	if (IS_ERR(ops)) {
4411 		err = PTR_ERR(ops);
4412 		goto release_vm_lock;
4413 	}
4414 
4415 	err = vm_bind_ioctl_ops_parse(vm, ops, &vops);
4416 	if (err)
4417 		goto release_vm_lock;
4418 
4419 	xe_assert(vm->xe, !list_empty(&vops.list));
4420 
4421 	err = xe_vma_ops_alloc(&vops, false);
4422 	if (err)
4423 		goto unwind_ops;
4424 
4425 	fence = vm_bind_ioctl_ops_execute(vm, &vops);
4426 	if (IS_ERR(fence))
4427 		err = PTR_ERR(fence);
4428 
4429 unwind_ops:
4430 	if (err && err != -ENODATA)
4431 		vm_bind_ioctl_ops_unwind(vm, &ops, 1);
4432 
4433 	xe_vma_ops_fini(&vops);
4434 	drm_gpuva_ops_free(&vm->gpuvm, ops);
4435 
4436 release_vm_lock:
4437 	up_write(&vm->lock);
4438 
4439 	if (q)
4440 		xe_exec_queue_put(q);
4441 	xe_vm_put(vm);
4442 	xe_bo_put(bo);
4443 
4444 	if (err)
4445 		fence = ERR_PTR(err);
4446 
4447 	return fence;
4448 }
4449 
4450 /**
4451  * xe_vm_lock() - Lock the vm's dma_resv object
4452  * @vm: The struct xe_vm whose lock is to be locked
4453  * @intr: Whether to perform any wait interruptible
4454  *
4455  * Return: 0 on success, -EINTR if @intr is true and the wait for a
4456  * contended lock was interrupted. If @intr is false, the function
4457  * always returns 0.
4458  */
4459 int xe_vm_lock(struct xe_vm *vm, bool intr)
4460 {
4461 	int ret;
4462 
4463 	if (intr)
4464 		ret = dma_resv_lock_interruptible(xe_vm_resv(vm), NULL);
4465 	else
4466 		ret = dma_resv_lock(xe_vm_resv(vm), NULL);
4467 
4468 	return ret;
4469 }
4470 
4471 /**
4472  * xe_vm_unlock() - Unlock the vm's dma_resv object
4473  * @vm: The struct xe_vm whose lock is to be released.
4474  *
4475  * Unlock a buffer object lock that was locked by xe_vm_lock().
4476  */
4477 void xe_vm_unlock(struct xe_vm *vm)
4478 {
4479 	dma_resv_unlock(xe_vm_resv(vm));
4480 }
4481 
4482 /**
4483  * xe_vm_invalidate_vma_submit - Submit a job to invalidate GPU mappings for
4484  * VMA.
4485  * @vma: VMA to invalidate
4486  * @batch: TLB invalidation batch to populate; caller must later call
4487  *         xe_tlb_inval_batch_wait() on it to wait for completion
4488  *
4489  * Walks a list of page tables leaves which it memset the entries owned by this
4490  * VMA to zero, invalidates the TLBs, but doesn't block waiting for TLB flush
4491  * to complete, but instead populates @batch which can be waited on using
4492  * xe_tlb_inval_batch_wait().
4493  *
4494  * Returns 0 for success, negative error code otherwise.
4495  */
4496 int xe_vm_invalidate_vma_submit(struct xe_vma *vma, struct xe_tlb_inval_batch *batch)
4497 {
4498 	struct xe_device *xe = xe_vma_vm(vma)->xe;
4499 	struct xe_vm *vm = xe_vma_vm(vma);
4500 	struct xe_tile *tile;
4501 	u8 tile_mask = 0;
4502 	int ret = 0;
4503 	u8 id;
4504 
4505 	xe_assert(xe, !xe_vma_is_null(vma));
4506 	xe_assert(xe, !xe_vma_is_cpu_addr_mirror(vma));
4507 	trace_xe_vma_invalidate(vma);
4508 
4509 	vm_dbg(&vm->xe->drm,
4510 	       "INVALIDATE: addr=0x%016llx, range=0x%016llx",
4511 		xe_vma_start(vma), xe_vma_size(vma));
4512 
4513 	/*
4514 	 * Check that we don't race with page-table updates, tile_invalidated
4515 	 * update is safe
4516 	 */
4517 	if (IS_ENABLED(CONFIG_PROVE_LOCKING)) {
4518 		if (xe_vma_is_userptr(vma)) {
4519 			lockdep_assert(lockdep_is_held_type(&vm->svm.gpusvm.notifier_lock, 0) ||
4520 				       (lockdep_is_held_type(&vm->svm.gpusvm.notifier_lock, 1) &&
4521 					lockdep_is_held(&xe_vm_resv(vm)->lock.base)));
4522 
4523 			WARN_ON_ONCE(!mmu_interval_check_retry
4524 				     (&to_userptr_vma(vma)->userptr.notifier,
4525 				      to_userptr_vma(vma)->userptr.pages.notifier_seq));
4526 			WARN_ON_ONCE(!dma_resv_test_signaled(xe_vm_resv(vm),
4527 							     DMA_RESV_USAGE_BOOKKEEP));
4528 
4529 		} else {
4530 			xe_bo_assert_held(xe_vma_bo(vma));
4531 		}
4532 	}
4533 
4534 	for_each_tile(tile, xe, id)
4535 		if (xe_pt_zap_ptes(tile, vma))
4536 			tile_mask |= BIT(id);
4537 
4538 	xe_device_wmb(xe);
4539 
4540 	ret = xe_tlb_inval_range_tilemask_submit(xe, xe_vma_vm(vma)->usm.asid,
4541 						 xe_vma_start(vma), xe_vma_end(vma),
4542 						 tile_mask, batch);
4543 
4544 	/* WRITE_ONCE pairs with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
4545 	WRITE_ONCE(vma->tile_invalidated, vma->tile_mask);
4546 	return ret;
4547 }
4548 
4549 /**
4550  * xe_vm_invalidate_vma - invalidate GPU mappings for VMA without a lock
4551  * @vma: VMA to invalidate
4552  *
4553  * Walks a list of page tables leaves which it memset the entries owned by this
4554  * VMA to zero, invalidates the TLBs, and block until TLBs invalidation is
4555  * complete.
4556  *
4557  * Returns 0 for success, negative error code otherwise.
4558  */
4559 int xe_vm_invalidate_vma(struct xe_vma *vma)
4560 {
4561 	struct xe_tlb_inval_batch batch;
4562 	int ret;
4563 
4564 	ret = xe_vm_invalidate_vma_submit(vma, &batch);
4565 	if (ret)
4566 		return ret;
4567 
4568 	xe_tlb_inval_batch_wait(&batch);
4569 	return ret;
4570 }
4571 
4572 int xe_vm_validate_protected(struct xe_vm *vm)
4573 {
4574 	struct drm_gpuva *gpuva;
4575 	int err = 0;
4576 
4577 	if (!vm)
4578 		return -ENODEV;
4579 
4580 	mutex_lock(&vm->snap_mutex);
4581 
4582 	drm_gpuvm_for_each_va(gpuva, &vm->gpuvm) {
4583 		struct xe_vma *vma = gpuva_to_vma(gpuva);
4584 		struct xe_bo *bo = vma->gpuva.gem.obj ?
4585 			gem_to_xe_bo(vma->gpuva.gem.obj) : NULL;
4586 
4587 		if (!bo)
4588 			continue;
4589 
4590 		if (xe_bo_is_protected(bo)) {
4591 			err = xe_pxp_bo_key_check(vm->xe->pxp, bo);
4592 			if (err)
4593 				break;
4594 		}
4595 	}
4596 
4597 	mutex_unlock(&vm->snap_mutex);
4598 	return err;
4599 }
4600 
4601 struct xe_vm_snapshot {
4602 	int uapi_flags;
4603 	unsigned long num_snaps;
4604 	struct {
4605 		u64 ofs, bo_ofs;
4606 		unsigned long len;
4607 #define XE_VM_SNAP_FLAG_USERPTR		BIT(0)
4608 #define XE_VM_SNAP_FLAG_READ_ONLY	BIT(1)
4609 #define XE_VM_SNAP_FLAG_IS_NULL		BIT(2)
4610 		unsigned long flags;
4611 		int uapi_mem_region;
4612 		u16 pat_index;
4613 		int cpu_caching;
4614 		struct xe_bo *bo;
4615 		void *data;
4616 		struct mm_struct *mm;
4617 	} snap[];
4618 };
4619 
4620 struct xe_vm_snapshot *xe_vm_snapshot_capture(struct xe_vm *vm)
4621 {
4622 	unsigned long num_snaps = 0, i;
4623 	struct xe_vm_snapshot *snap = NULL;
4624 	struct drm_gpuva *gpuva;
4625 
4626 	if (!vm)
4627 		return NULL;
4628 
4629 	mutex_lock(&vm->snap_mutex);
4630 	drm_gpuvm_for_each_va(gpuva, &vm->gpuvm) {
4631 		if (gpuva->flags & XE_VMA_DUMPABLE)
4632 			num_snaps++;
4633 	}
4634 
4635 	if (num_snaps)
4636 		snap = kvzalloc(offsetof(struct xe_vm_snapshot, snap[num_snaps]), GFP_NOWAIT);
4637 	if (!snap) {
4638 		snap = num_snaps ? ERR_PTR(-ENOMEM) : ERR_PTR(-ENODEV);
4639 		goto out_unlock;
4640 	}
4641 
4642 	if (vm->flags & XE_VM_FLAG_FAULT_MODE)
4643 		snap->uapi_flags |= DRM_XE_VM_CREATE_FLAG_FAULT_MODE;
4644 	if (vm->flags & XE_VM_FLAG_LR_MODE)
4645 		snap->uapi_flags |= DRM_XE_VM_CREATE_FLAG_LR_MODE;
4646 	if (vm->flags & XE_VM_FLAG_SCRATCH_PAGE)
4647 		snap->uapi_flags |= DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE;
4648 
4649 	snap->num_snaps = num_snaps;
4650 	i = 0;
4651 	drm_gpuvm_for_each_va(gpuva, &vm->gpuvm) {
4652 		struct xe_vma *vma = gpuva_to_vma(gpuva);
4653 		struct xe_bo *bo = vma->gpuva.gem.obj ?
4654 			gem_to_xe_bo(vma->gpuva.gem.obj) : NULL;
4655 
4656 		if (!(gpuva->flags & XE_VMA_DUMPABLE))
4657 			continue;
4658 
4659 		snap->snap[i].ofs = xe_vma_start(vma);
4660 		snap->snap[i].len = xe_vma_size(vma);
4661 		snap->snap[i].flags = xe_vma_read_only(vma) ?
4662 			XE_VM_SNAP_FLAG_READ_ONLY : 0;
4663 		snap->snap[i].pat_index = vma->attr.pat_index;
4664 		if (bo) {
4665 			snap->snap[i].cpu_caching = bo->cpu_caching;
4666 			snap->snap[i].bo = xe_bo_get(bo);
4667 			snap->snap[i].bo_ofs = xe_vma_bo_offset(vma);
4668 			switch (bo->ttm.resource->mem_type) {
4669 			case XE_PL_SYSTEM:
4670 			case XE_PL_TT:
4671 				snap->snap[i].uapi_mem_region = 0;
4672 				break;
4673 			case XE_PL_VRAM0:
4674 				snap->snap[i].uapi_mem_region = 1;
4675 				break;
4676 			case XE_PL_VRAM1:
4677 				snap->snap[i].uapi_mem_region = 2;
4678 				break;
4679 			}
4680 		} else if (xe_vma_is_userptr(vma)) {
4681 			struct mm_struct *mm =
4682 				to_userptr_vma(vma)->userptr.notifier.mm;
4683 
4684 			if (mmget_not_zero(mm))
4685 				snap->snap[i].mm = mm;
4686 			else
4687 				snap->snap[i].data = ERR_PTR(-EFAULT);
4688 
4689 			snap->snap[i].bo_ofs = xe_vma_userptr(vma);
4690 			snap->snap[i].flags |= XE_VM_SNAP_FLAG_USERPTR;
4691 			snap->snap[i].uapi_mem_region = 0;
4692 		} else if (xe_vma_is_null(vma)) {
4693 			snap->snap[i].flags |= XE_VM_SNAP_FLAG_IS_NULL;
4694 			snap->snap[i].uapi_mem_region = -1;
4695 		} else {
4696 			snap->snap[i].data = ERR_PTR(-ENOENT);
4697 			snap->snap[i].uapi_mem_region = -1;
4698 		}
4699 		i++;
4700 	}
4701 
4702 out_unlock:
4703 	mutex_unlock(&vm->snap_mutex);
4704 	return snap;
4705 }
4706 
4707 void xe_vm_snapshot_capture_delayed(struct xe_vm_snapshot *snap)
4708 {
4709 	if (IS_ERR_OR_NULL(snap))
4710 		return;
4711 
4712 	for (int i = 0; i < snap->num_snaps; i++) {
4713 		struct xe_bo *bo = snap->snap[i].bo;
4714 		int err;
4715 
4716 		if (IS_ERR(snap->snap[i].data) ||
4717 		    snap->snap[i].flags & XE_VM_SNAP_FLAG_IS_NULL)
4718 			continue;
4719 
4720 		snap->snap[i].data = kvmalloc(snap->snap[i].len, GFP_USER);
4721 		if (!snap->snap[i].data) {
4722 			snap->snap[i].data = ERR_PTR(-ENOMEM);
4723 			goto cleanup_bo;
4724 		}
4725 
4726 		if (bo) {
4727 			err = xe_bo_read(bo, snap->snap[i].bo_ofs,
4728 					 snap->snap[i].data, snap->snap[i].len);
4729 		} else {
4730 			void __user *userptr = (void __user *)(size_t)snap->snap[i].bo_ofs;
4731 
4732 			kthread_use_mm(snap->snap[i].mm);
4733 			if (!copy_from_user(snap->snap[i].data, userptr, snap->snap[i].len))
4734 				err = 0;
4735 			else
4736 				err = -EFAULT;
4737 			kthread_unuse_mm(snap->snap[i].mm);
4738 
4739 			mmput(snap->snap[i].mm);
4740 			snap->snap[i].mm = NULL;
4741 		}
4742 
4743 		if (err) {
4744 			kvfree(snap->snap[i].data);
4745 			snap->snap[i].data = ERR_PTR(err);
4746 		}
4747 
4748 cleanup_bo:
4749 		xe_bo_put(bo);
4750 		snap->snap[i].bo = NULL;
4751 	}
4752 }
4753 
4754 void xe_vm_snapshot_print(struct xe_vm_snapshot *snap, struct drm_printer *p)
4755 {
4756 	unsigned long i, j;
4757 
4758 	if (IS_ERR_OR_NULL(snap)) {
4759 		drm_printf(p, "[0].error: %li\n", PTR_ERR(snap));
4760 		return;
4761 	}
4762 
4763 	drm_printf(p, "VM.uapi_flags: 0x%x\n", snap->uapi_flags);
4764 	for (i = 0; i < snap->num_snaps; i++) {
4765 		drm_printf(p, "[%llx].length: 0x%lx\n", snap->snap[i].ofs, snap->snap[i].len);
4766 
4767 		drm_printf(p, "[%llx].properties: %s|%s|mem_region=0x%lx|pat_index=%d|cpu_caching=%d\n",
4768 			   snap->snap[i].ofs,
4769 			   snap->snap[i].flags & XE_VM_SNAP_FLAG_READ_ONLY ?
4770 			   "read_only" : "read_write",
4771 			   snap->snap[i].flags & XE_VM_SNAP_FLAG_IS_NULL ?
4772 			   "null_sparse" :
4773 			   snap->snap[i].flags & XE_VM_SNAP_FLAG_USERPTR ?
4774 			   "userptr" : "bo",
4775 			   snap->snap[i].uapi_mem_region == -1 ? 0 :
4776 			   BIT(snap->snap[i].uapi_mem_region),
4777 			   snap->snap[i].pat_index,
4778 			   snap->snap[i].cpu_caching);
4779 
4780 		if (IS_ERR(snap->snap[i].data)) {
4781 			drm_printf(p, "[%llx].error: %li\n", snap->snap[i].ofs,
4782 				   PTR_ERR(snap->snap[i].data));
4783 			continue;
4784 		}
4785 
4786 		if (snap->snap[i].flags & XE_VM_SNAP_FLAG_IS_NULL)
4787 			continue;
4788 
4789 		drm_printf(p, "[%llx].data: ", snap->snap[i].ofs);
4790 
4791 		for (j = 0; j < snap->snap[i].len; j += sizeof(u32)) {
4792 			u32 *val = snap->snap[i].data + j;
4793 			char dumped[ASCII85_BUFSZ];
4794 
4795 			drm_puts(p, ascii85_encode(*val, dumped));
4796 		}
4797 
4798 		drm_puts(p, "\n");
4799 
4800 		if (drm_coredump_printer_is_full(p))
4801 			return;
4802 	}
4803 }
4804 
4805 void xe_vm_snapshot_free(struct xe_vm_snapshot *snap)
4806 {
4807 	unsigned long i;
4808 
4809 	if (IS_ERR_OR_NULL(snap))
4810 		return;
4811 
4812 	for (i = 0; i < snap->num_snaps; i++) {
4813 		if (!IS_ERR(snap->snap[i].data))
4814 			kvfree(snap->snap[i].data);
4815 		xe_bo_put(snap->snap[i].bo);
4816 		if (snap->snap[i].mm)
4817 			mmput(snap->snap[i].mm);
4818 	}
4819 	kvfree(snap);
4820 }
4821 
4822 /**
4823  * xe_vma_need_vram_for_atomic - Check if VMA needs VRAM migration for atomic operations
4824  * @xe: Pointer to the Xe device structure
4825  * @vma: Pointer to the virtual memory area (VMA) structure
4826  * @is_atomic: In pagefault path and atomic operation
4827  *
4828  * This function determines whether the given VMA needs to be migrated to
4829  * VRAM in order to do atomic GPU operation.
4830  *
4831  * Return:
4832  *   1        - Migration to VRAM is required
4833  *   0        - Migration is not required
4834  *   -EACCES  - Invalid access for atomic memory attr
4835  *
4836  */
4837 int xe_vma_need_vram_for_atomic(struct xe_device *xe, struct xe_vma *vma, bool is_atomic)
4838 {
4839 	u32 atomic_access = xe_vma_bo(vma) ? xe_vma_bo(vma)->attr.atomic_access :
4840 					     vma->attr.atomic_access;
4841 
4842 	if (!IS_DGFX(xe) || !is_atomic)
4843 		return false;
4844 
4845 	/*
4846 	 * NOTE: The checks implemented here are platform-specific. For
4847 	 * instance, on a device supporting CXL atomics, these would ideally
4848 	 * work universally without additional handling.
4849 	 */
4850 	switch (atomic_access) {
4851 	case DRM_XE_ATOMIC_DEVICE:
4852 		return !xe->info.has_device_atomics_on_smem;
4853 
4854 	case DRM_XE_ATOMIC_CPU:
4855 		return -EACCES;
4856 
4857 	case DRM_XE_ATOMIC_UNDEFINED:
4858 	case DRM_XE_ATOMIC_GLOBAL:
4859 	default:
4860 		return 1;
4861 	}
4862 }
4863 
4864 static int xe_vm_alloc_vma(struct xe_vm *vm,
4865 			   struct drm_gpuvm_map_req *map_req,
4866 			   bool is_madvise)
4867 {
4868 	struct xe_vma_ops vops;
4869 	struct drm_gpuva_ops *ops = NULL;
4870 	struct drm_gpuva_op *__op;
4871 	unsigned int vma_flags = 0;
4872 	bool remap_op = false;
4873 	struct xe_vma_mem_attr tmp_attr = {};
4874 	u16 default_pat;
4875 	int err;
4876 
4877 	xe_vm_assert_write_mode_or_garbage_collector(vm);
4878 
4879 	if (is_madvise)
4880 		ops = drm_gpuvm_madvise_ops_create(&vm->gpuvm, map_req);
4881 	else
4882 		ops = drm_gpuvm_sm_map_ops_create(&vm->gpuvm, map_req);
4883 
4884 	if (IS_ERR(ops))
4885 		return PTR_ERR(ops);
4886 
4887 	if (list_empty(&ops->list)) {
4888 		err = 0;
4889 		goto free_ops;
4890 	}
4891 
4892 	drm_gpuva_for_each_op(__op, ops) {
4893 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
4894 		struct xe_vma *vma = NULL;
4895 
4896 		if (!is_madvise) {
4897 			if (__op->op == DRM_GPUVA_OP_UNMAP) {
4898 				vma = gpuva_to_vma(op->base.unmap.va);
4899 				XE_WARN_ON(!xe_vma_has_default_mem_attrs(vma));
4900 				default_pat = vma->attr.default_pat_index;
4901 				vma_flags = vma->gpuva.flags;
4902 			}
4903 
4904 			if (__op->op == DRM_GPUVA_OP_REMAP) {
4905 				vma = gpuva_to_vma(op->base.remap.unmap->va);
4906 				default_pat = vma->attr.default_pat_index;
4907 				vma_flags = vma->gpuva.flags;
4908 			}
4909 
4910 			if (__op->op == DRM_GPUVA_OP_MAP) {
4911 				op->map.vma_flags |= vma_flags & XE_VMA_CREATE_MASK;
4912 				op->map.pat_index = default_pat;
4913 			}
4914 		} else {
4915 			if (__op->op == DRM_GPUVA_OP_REMAP) {
4916 				vma = gpuva_to_vma(op->base.remap.unmap->va);
4917 				xe_assert(vm->xe, !remap_op);
4918 				xe_assert(vm->xe, xe_vma_has_no_bo(vma));
4919 				remap_op = true;
4920 				vma_flags = vma->gpuva.flags;
4921 			}
4922 
4923 			if (__op->op == DRM_GPUVA_OP_MAP) {
4924 				xe_assert(vm->xe, remap_op);
4925 				remap_op = false;
4926 				/*
4927 				 * In case of madvise ops DRM_GPUVA_OP_MAP is
4928 				 * always after DRM_GPUVA_OP_REMAP, so ensure
4929 				 * to propagate the flags from the vma we're
4930 				 * unmapping.
4931 				 */
4932 				op->map.vma_flags |= vma_flags & XE_VMA_CREATE_MASK;
4933 			}
4934 		}
4935 		print_op(vm->xe, __op);
4936 	}
4937 
4938 	xe_vma_ops_init(&vops, vm, NULL, NULL, 0);
4939 
4940 	if (is_madvise)
4941 		vops.flags |= XE_VMA_OPS_FLAG_MADVISE;
4942 	else
4943 		vops.flags |= XE_VMA_OPS_FLAG_ALLOW_SVM_UNMAP;
4944 
4945 	err = vm_bind_ioctl_ops_parse(vm, ops, &vops);
4946 	if (err)
4947 		goto unwind_ops;
4948 
4949 	xe_vm_lock(vm, false);
4950 
4951 	drm_gpuva_for_each_op(__op, ops) {
4952 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
4953 		struct xe_vma *vma;
4954 
4955 		if (__op->op == DRM_GPUVA_OP_UNMAP) {
4956 			vma = gpuva_to_vma(op->base.unmap.va);
4957 			/* There should be no unmap for madvise */
4958 			if (is_madvise)
4959 				XE_WARN_ON("UNEXPECTED UNMAP");
4960 
4961 			xe_vma_destroy(vma, NULL);
4962 		} else if (__op->op == DRM_GPUVA_OP_REMAP) {
4963 			vma = gpuva_to_vma(op->base.remap.unmap->va);
4964 			/* In case of madvise ops Store attributes for REMAP UNMAPPED
4965 			 * VMA, so they can be assigned to newly MAP created vma.
4966 			 */
4967 			if (is_madvise)
4968 				xe_vma_mem_attr_copy(&tmp_attr, &vma->attr);
4969 
4970 			xe_vma_destroy(gpuva_to_vma(op->base.remap.unmap->va), NULL);
4971 		} else if (__op->op == DRM_GPUVA_OP_MAP) {
4972 			vma = op->map.vma;
4973 			/* In case of madvise call, MAP will always be followed by REMAP.
4974 			 * Therefore temp_attr will always have sane values, making it safe to
4975 			 * copy them to new vma.
4976 			 */
4977 			if (is_madvise)
4978 				xe_vma_mem_attr_copy(&vma->attr, &tmp_attr);
4979 		}
4980 	}
4981 
4982 	xe_vm_unlock(vm);
4983 	drm_gpuva_ops_free(&vm->gpuvm, ops);
4984 	xe_vma_mem_attr_fini(&tmp_attr);
4985 	return 0;
4986 
4987 unwind_ops:
4988 	vm_bind_ioctl_ops_unwind(vm, &ops, 1);
4989 free_ops:
4990 	drm_gpuva_ops_free(&vm->gpuvm, ops);
4991 	return err;
4992 }
4993 
4994 /**
4995  * xe_vm_alloc_madvise_vma - Allocate VMA's with madvise ops
4996  * @vm: Pointer to the xe_vm structure
4997  * @start: Starting input address
4998  * @range: Size of the input range
4999  *
5000  * This function splits existing vma to create new vma for user provided input range
5001  *
5002  * Return: 0 if success
5003  */
5004 int xe_vm_alloc_madvise_vma(struct xe_vm *vm, uint64_t start, uint64_t range)
5005 {
5006 	struct drm_gpuvm_map_req map_req = {
5007 		.map.va.addr = start,
5008 		.map.va.range = range,
5009 	};
5010 
5011 	xe_vm_assert_write_mode_or_garbage_collector(vm);
5012 
5013 	vm_dbg(&vm->xe->drm, "MADVISE_OPS_CREATE: addr=0x%016llx, size=0x%016llx", start, range);
5014 
5015 	return xe_vm_alloc_vma(vm, &map_req, true);
5016 }
5017 
5018 static bool is_cpu_addr_vma_with_default_attr(struct xe_vma *vma)
5019 {
5020 	return vma && xe_vma_is_cpu_addr_mirror(vma) &&
5021 	       xe_vma_has_default_mem_attrs(vma);
5022 }
5023 
5024 /**
5025  * xe_vm_find_cpu_addr_mirror_vma_range - Extend a VMA range to include adjacent CPU-mirrored VMAs
5026  * @vm: VM to search within
5027  * @start: Input/output pointer to the starting address of the range
5028  * @end: Input/output pointer to the end address of the range
5029  *
5030  * Given a range defined by @start and @range, this function checks the VMAs
5031  * immediately before and after the range. If those neighboring VMAs are
5032  * CPU-address-mirrored and have default memory attributes, the function
5033  * updates @start and @range to include them. This extended range can then
5034  * be used for merging or other operations that require a unified VMA.
5035  *
5036  * The function does not perform the merge itself; it only computes the
5037  * mergeable boundaries.
5038  */
5039 void xe_vm_find_cpu_addr_mirror_vma_range(struct xe_vm *vm, u64 *start, u64 *end)
5040 {
5041 	struct xe_vma *prev, *next;
5042 
5043 	xe_vm_assert_write_mode_or_garbage_collector(vm);
5044 
5045 	if (*start >= SZ_4K) {
5046 		prev = xe_vm_find_vma_by_addr(vm, *start - SZ_4K);
5047 		if (is_cpu_addr_vma_with_default_attr(prev))
5048 			*start = xe_vma_start(prev);
5049 	}
5050 
5051 	if (*end < vm->size) {
5052 		next = xe_vm_find_vma_by_addr(vm, *end + 1);
5053 		if (is_cpu_addr_vma_with_default_attr(next))
5054 			*end = xe_vma_end(next);
5055 	}
5056 }
5057 
5058 /**
5059  * xe_vm_alloc_cpu_addr_mirror_vma - Allocate CPU addr mirror vma
5060  * @vm: Pointer to the xe_vm structure
5061  * @start: Starting input address
5062  * @range: Size of the input range
5063  *
5064  * This function splits/merges existing vma to create new vma for user provided input range
5065  *
5066  * Return: 0 if success
5067  */
5068 int xe_vm_alloc_cpu_addr_mirror_vma(struct xe_vm *vm, uint64_t start, uint64_t range)
5069 {
5070 	struct drm_gpuvm_map_req map_req = {
5071 		.map.va.addr = start,
5072 		.map.va.range = range,
5073 	};
5074 
5075 	xe_vm_assert_write_mode_or_garbage_collector(vm);
5076 
5077 	vm_dbg(&vm->xe->drm, "CPU_ADDR_MIRROR_VMA_OPS_CREATE: addr=0x%016llx, size=0x%016llx",
5078 	       start, range);
5079 
5080 	return xe_vm_alloc_vma(vm, &map_req, false);
5081 }
5082 
5083 /**
5084  * xe_vm_add_exec_queue() - Add exec queue to VM
5085  * @vm: The VM.
5086  * @q: The exec_queue
5087  *
5088  * Add exec queue to VM, skipped if the device does not have context based TLB
5089  * invalidations.
5090  */
5091 void xe_vm_add_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q)
5092 {
5093 	struct xe_device *xe = vm->xe;
5094 
5095 	/* User VMs and queues only */
5096 	xe_assert(xe, !(q->flags & EXEC_QUEUE_FLAG_KERNEL));
5097 	xe_assert(xe, !(q->flags & EXEC_QUEUE_FLAG_VM));
5098 	xe_assert(xe, !(q->flags & EXEC_QUEUE_FLAG_MIGRATE));
5099 	xe_assert(xe, vm->xef);
5100 	xe_assert(xe, vm == q->vm);
5101 
5102 	if (!xe->info.has_ctx_tlb_inval)
5103 		return;
5104 
5105 	down_write(&vm->exec_queues.lock);
5106 	list_add(&q->vm_exec_queue_link, &vm->exec_queues.list[q->gt->info.id]);
5107 	++vm->exec_queues.count[q->gt->info.id];
5108 	up_write(&vm->exec_queues.lock);
5109 }
5110 
5111 /**
5112  * xe_vm_remove_exec_queue() - Remove exec queue from VM
5113  * @vm: The VM.
5114  * @q: The exec_queue
5115  *
5116  * Remove exec queue from VM, skipped if the device does not have context based
5117  * TLB invalidations.
5118  */
5119 void xe_vm_remove_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q)
5120 {
5121 	if (!vm->xe->info.has_ctx_tlb_inval)
5122 		return;
5123 
5124 	down_write(&vm->exec_queues.lock);
5125 	if (!list_empty(&q->vm_exec_queue_link)) {
5126 		list_del(&q->vm_exec_queue_link);
5127 		--vm->exec_queues.count[q->gt->info.id];
5128 	}
5129 	up_write(&vm->exec_queues.lock);
5130 }
5131 
5132 /**
5133  * xe_vm_pt_root() - Retrieve VM page-table root
5134  * @vm: The VM.
5135  * @tile_id: Tile ID
5136  *
5137  * Retrieve VM page-table root for a tile ID, used to abstract if PT mirroring is
5138  * enabled across tiles.
5139  *
5140  * Return: VM page-table root for a tile ID
5141  */
5142 struct xe_pt *xe_vm_pt_root(struct xe_vm *vm, u8 tile_id)
5143 {
5144 	if (vm->xe->info.has_pt_mirror)
5145 		return vm->pt_root[tile_id];
5146 
5147 	return vm->pt_root[0];
5148 }
5149