xref: /linux/drivers/gpu/drm/xe/xe_vm.c (revision 0d2ab5f922e75d10162e7199826e14df9cfae5cc)
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/nospec.h>
10 
11 #include <drm/drm_drv.h>
12 #include <drm/drm_exec.h>
13 #include <drm/drm_print.h>
14 #include <drm/ttm/ttm_tt.h>
15 #include <uapi/drm/xe_drm.h>
16 #include <linux/ascii85.h>
17 #include <linux/delay.h>
18 #include <linux/kthread.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 
22 #include <generated/xe_wa_oob.h>
23 
24 #include "regs/xe_gtt_defs.h"
25 #include "xe_assert.h"
26 #include "xe_bo.h"
27 #include "xe_device.h"
28 #include "xe_drm_client.h"
29 #include "xe_exec_queue.h"
30 #include "xe_gt_pagefault.h"
31 #include "xe_gt_tlb_invalidation.h"
32 #include "xe_migrate.h"
33 #include "xe_pat.h"
34 #include "xe_pm.h"
35 #include "xe_preempt_fence.h"
36 #include "xe_pt.h"
37 #include "xe_pxp.h"
38 #include "xe_res_cursor.h"
39 #include "xe_svm.h"
40 #include "xe_sync.h"
41 #include "xe_trace_bo.h"
42 #include "xe_wa.h"
43 #include "xe_hmm.h"
44 
45 static struct drm_gem_object *xe_vm_obj(struct xe_vm *vm)
46 {
47 	return vm->gpuvm.r_obj;
48 }
49 
50 /**
51  * xe_vma_userptr_check_repin() - Advisory check for repin needed
52  * @uvma: The userptr vma
53  *
54  * Check if the userptr vma has been invalidated since last successful
55  * repin. The check is advisory only and can the function can be called
56  * without the vm->userptr.notifier_lock held. There is no guarantee that the
57  * vma userptr will remain valid after a lockless check, so typically
58  * the call needs to be followed by a proper check under the notifier_lock.
59  *
60  * Return: 0 if userptr vma is valid, -EAGAIN otherwise; repin recommended.
61  */
62 int xe_vma_userptr_check_repin(struct xe_userptr_vma *uvma)
63 {
64 	return mmu_interval_check_retry(&uvma->userptr.notifier,
65 					uvma->userptr.notifier_seq) ?
66 		-EAGAIN : 0;
67 }
68 
69 int xe_vma_userptr_pin_pages(struct xe_userptr_vma *uvma)
70 {
71 	struct xe_vma *vma = &uvma->vma;
72 	struct xe_vm *vm = xe_vma_vm(vma);
73 	struct xe_device *xe = vm->xe;
74 
75 	lockdep_assert_held(&vm->lock);
76 	xe_assert(xe, xe_vma_is_userptr(vma));
77 
78 	return xe_hmm_userptr_populate_range(uvma, false);
79 }
80 
81 static bool preempt_fences_waiting(struct xe_vm *vm)
82 {
83 	struct xe_exec_queue *q;
84 
85 	lockdep_assert_held(&vm->lock);
86 	xe_vm_assert_held(vm);
87 
88 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
89 		if (!q->lr.pfence ||
90 		    test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
91 			     &q->lr.pfence->flags)) {
92 			return true;
93 		}
94 	}
95 
96 	return false;
97 }
98 
99 static void free_preempt_fences(struct list_head *list)
100 {
101 	struct list_head *link, *next;
102 
103 	list_for_each_safe(link, next, list)
104 		xe_preempt_fence_free(to_preempt_fence_from_link(link));
105 }
106 
107 static int alloc_preempt_fences(struct xe_vm *vm, struct list_head *list,
108 				unsigned int *count)
109 {
110 	lockdep_assert_held(&vm->lock);
111 	xe_vm_assert_held(vm);
112 
113 	if (*count >= vm->preempt.num_exec_queues)
114 		return 0;
115 
116 	for (; *count < vm->preempt.num_exec_queues; ++(*count)) {
117 		struct xe_preempt_fence *pfence = xe_preempt_fence_alloc();
118 
119 		if (IS_ERR(pfence))
120 			return PTR_ERR(pfence);
121 
122 		list_move_tail(xe_preempt_fence_link(pfence), list);
123 	}
124 
125 	return 0;
126 }
127 
128 static int wait_for_existing_preempt_fences(struct xe_vm *vm)
129 {
130 	struct xe_exec_queue *q;
131 
132 	xe_vm_assert_held(vm);
133 
134 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
135 		if (q->lr.pfence) {
136 			long timeout = dma_fence_wait(q->lr.pfence, false);
137 
138 			/* Only -ETIME on fence indicates VM needs to be killed */
139 			if (timeout < 0 || q->lr.pfence->error == -ETIME)
140 				return -ETIME;
141 
142 			dma_fence_put(q->lr.pfence);
143 			q->lr.pfence = NULL;
144 		}
145 	}
146 
147 	return 0;
148 }
149 
150 static bool xe_vm_is_idle(struct xe_vm *vm)
151 {
152 	struct xe_exec_queue *q;
153 
154 	xe_vm_assert_held(vm);
155 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
156 		if (!xe_exec_queue_is_idle(q))
157 			return false;
158 	}
159 
160 	return true;
161 }
162 
163 static void arm_preempt_fences(struct xe_vm *vm, struct list_head *list)
164 {
165 	struct list_head *link;
166 	struct xe_exec_queue *q;
167 
168 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
169 		struct dma_fence *fence;
170 
171 		link = list->next;
172 		xe_assert(vm->xe, link != list);
173 
174 		fence = xe_preempt_fence_arm(to_preempt_fence_from_link(link),
175 					     q, q->lr.context,
176 					     ++q->lr.seqno);
177 		dma_fence_put(q->lr.pfence);
178 		q->lr.pfence = fence;
179 	}
180 }
181 
182 static int add_preempt_fences(struct xe_vm *vm, struct xe_bo *bo)
183 {
184 	struct xe_exec_queue *q;
185 	int err;
186 
187 	xe_bo_assert_held(bo);
188 
189 	if (!vm->preempt.num_exec_queues)
190 		return 0;
191 
192 	err = dma_resv_reserve_fences(bo->ttm.base.resv, vm->preempt.num_exec_queues);
193 	if (err)
194 		return err;
195 
196 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link)
197 		if (q->lr.pfence) {
198 			dma_resv_add_fence(bo->ttm.base.resv,
199 					   q->lr.pfence,
200 					   DMA_RESV_USAGE_BOOKKEEP);
201 		}
202 
203 	return 0;
204 }
205 
206 static void resume_and_reinstall_preempt_fences(struct xe_vm *vm,
207 						struct drm_exec *exec)
208 {
209 	struct xe_exec_queue *q;
210 
211 	lockdep_assert_held(&vm->lock);
212 	xe_vm_assert_held(vm);
213 
214 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link) {
215 		q->ops->resume(q);
216 
217 		drm_gpuvm_resv_add_fence(&vm->gpuvm, exec, q->lr.pfence,
218 					 DMA_RESV_USAGE_BOOKKEEP, DMA_RESV_USAGE_BOOKKEEP);
219 	}
220 }
221 
222 int xe_vm_add_compute_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q)
223 {
224 	struct drm_gpuvm_exec vm_exec = {
225 		.vm = &vm->gpuvm,
226 		.flags = DRM_EXEC_INTERRUPTIBLE_WAIT,
227 		.num_fences = 1,
228 	};
229 	struct drm_exec *exec = &vm_exec.exec;
230 	struct dma_fence *pfence;
231 	int err;
232 	bool wait;
233 
234 	xe_assert(vm->xe, xe_vm_in_preempt_fence_mode(vm));
235 
236 	down_write(&vm->lock);
237 	err = drm_gpuvm_exec_lock(&vm_exec);
238 	if (err)
239 		goto out_up_write;
240 
241 	pfence = xe_preempt_fence_create(q, q->lr.context,
242 					 ++q->lr.seqno);
243 	if (!pfence) {
244 		err = -ENOMEM;
245 		goto out_fini;
246 	}
247 
248 	list_add(&q->lr.link, &vm->preempt.exec_queues);
249 	++vm->preempt.num_exec_queues;
250 	q->lr.pfence = pfence;
251 
252 	down_read(&vm->userptr.notifier_lock);
253 
254 	drm_gpuvm_resv_add_fence(&vm->gpuvm, exec, pfence,
255 				 DMA_RESV_USAGE_BOOKKEEP, DMA_RESV_USAGE_BOOKKEEP);
256 
257 	/*
258 	 * Check to see if a preemption on VM is in flight or userptr
259 	 * invalidation, if so trigger this preempt fence to sync state with
260 	 * other preempt fences on the VM.
261 	 */
262 	wait = __xe_vm_userptr_needs_repin(vm) || preempt_fences_waiting(vm);
263 	if (wait)
264 		dma_fence_enable_sw_signaling(pfence);
265 
266 	up_read(&vm->userptr.notifier_lock);
267 
268 out_fini:
269 	drm_exec_fini(exec);
270 out_up_write:
271 	up_write(&vm->lock);
272 
273 	return err;
274 }
275 ALLOW_ERROR_INJECTION(xe_vm_add_compute_exec_queue, ERRNO);
276 
277 /**
278  * xe_vm_remove_compute_exec_queue() - Remove compute exec queue from VM
279  * @vm: The VM.
280  * @q: The exec_queue
281  *
282  * Note that this function might be called multiple times on the same queue.
283  */
284 void xe_vm_remove_compute_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q)
285 {
286 	if (!xe_vm_in_preempt_fence_mode(vm))
287 		return;
288 
289 	down_write(&vm->lock);
290 	if (!list_empty(&q->lr.link)) {
291 		list_del_init(&q->lr.link);
292 		--vm->preempt.num_exec_queues;
293 	}
294 	if (q->lr.pfence) {
295 		dma_fence_enable_sw_signaling(q->lr.pfence);
296 		dma_fence_put(q->lr.pfence);
297 		q->lr.pfence = NULL;
298 	}
299 	up_write(&vm->lock);
300 }
301 
302 /**
303  * __xe_vm_userptr_needs_repin() - Check whether the VM does have userptrs
304  * that need repinning.
305  * @vm: The VM.
306  *
307  * This function checks for whether the VM has userptrs that need repinning,
308  * and provides a release-type barrier on the userptr.notifier_lock after
309  * checking.
310  *
311  * Return: 0 if there are no userptrs needing repinning, -EAGAIN if there are.
312  */
313 int __xe_vm_userptr_needs_repin(struct xe_vm *vm)
314 {
315 	lockdep_assert_held_read(&vm->userptr.notifier_lock);
316 
317 	return (list_empty(&vm->userptr.repin_list) &&
318 		list_empty(&vm->userptr.invalidated)) ? 0 : -EAGAIN;
319 }
320 
321 #define XE_VM_REBIND_RETRY_TIMEOUT_MS 1000
322 
323 /**
324  * xe_vm_kill() - VM Kill
325  * @vm: The VM.
326  * @unlocked: Flag indicates the VM's dma-resv is not held
327  *
328  * Kill the VM by setting banned flag indicated VM is no longer available for
329  * use. If in preempt fence mode, also kill all exec queue attached to the VM.
330  */
331 void xe_vm_kill(struct xe_vm *vm, bool unlocked)
332 {
333 	struct xe_exec_queue *q;
334 
335 	lockdep_assert_held(&vm->lock);
336 
337 	if (unlocked)
338 		xe_vm_lock(vm, false);
339 
340 	vm->flags |= XE_VM_FLAG_BANNED;
341 	trace_xe_vm_kill(vm);
342 
343 	list_for_each_entry(q, &vm->preempt.exec_queues, lr.link)
344 		q->ops->kill(q);
345 
346 	if (unlocked)
347 		xe_vm_unlock(vm);
348 
349 	/* TODO: Inform user the VM is banned */
350 }
351 
352 /**
353  * xe_vm_validate_should_retry() - Whether to retry after a validate error.
354  * @exec: The drm_exec object used for locking before validation.
355  * @err: The error returned from ttm_bo_validate().
356  * @end: A ktime_t cookie that should be set to 0 before first use and
357  * that should be reused on subsequent calls.
358  *
359  * With multiple active VMs, under memory pressure, it is possible that
360  * ttm_bo_validate() run into -EDEADLK and in such case returns -ENOMEM.
361  * Until ttm properly handles locking in such scenarios, best thing the
362  * driver can do is retry with a timeout. Check if that is necessary, and
363  * if so unlock the drm_exec's objects while keeping the ticket to prepare
364  * for a rerun.
365  *
366  * Return: true if a retry after drm_exec_init() is recommended;
367  * false otherwise.
368  */
369 bool xe_vm_validate_should_retry(struct drm_exec *exec, int err, ktime_t *end)
370 {
371 	ktime_t cur;
372 
373 	if (err != -ENOMEM)
374 		return false;
375 
376 	cur = ktime_get();
377 	*end = *end ? : ktime_add_ms(cur, XE_VM_REBIND_RETRY_TIMEOUT_MS);
378 	if (!ktime_before(cur, *end))
379 		return false;
380 
381 	msleep(20);
382 	return true;
383 }
384 
385 static int xe_gpuvm_validate(struct drm_gpuvm_bo *vm_bo, struct drm_exec *exec)
386 {
387 	struct xe_vm *vm = gpuvm_to_vm(vm_bo->vm);
388 	struct drm_gpuva *gpuva;
389 	int ret;
390 
391 	lockdep_assert_held(&vm->lock);
392 	drm_gpuvm_bo_for_each_va(gpuva, vm_bo)
393 		list_move_tail(&gpuva_to_vma(gpuva)->combined_links.rebind,
394 			       &vm->rebind_list);
395 
396 	ret = xe_bo_validate(gem_to_xe_bo(vm_bo->obj), vm, false);
397 	if (ret)
398 		return ret;
399 
400 	vm_bo->evicted = false;
401 	return 0;
402 }
403 
404 /**
405  * xe_vm_validate_rebind() - Validate buffer objects and rebind vmas
406  * @vm: The vm for which we are rebinding.
407  * @exec: The struct drm_exec with the locked GEM objects.
408  * @num_fences: The number of fences to reserve for the operation, not
409  * including rebinds and validations.
410  *
411  * Validates all evicted gem objects and rebinds their vmas. Note that
412  * rebindings may cause evictions and hence the validation-rebind
413  * sequence is rerun until there are no more objects to validate.
414  *
415  * Return: 0 on success, negative error code on error. In particular,
416  * may return -EINTR or -ERESTARTSYS if interrupted, and -EDEADLK if
417  * the drm_exec transaction needs to be restarted.
418  */
419 int xe_vm_validate_rebind(struct xe_vm *vm, struct drm_exec *exec,
420 			  unsigned int num_fences)
421 {
422 	struct drm_gem_object *obj;
423 	unsigned long index;
424 	int ret;
425 
426 	do {
427 		ret = drm_gpuvm_validate(&vm->gpuvm, exec);
428 		if (ret)
429 			return ret;
430 
431 		ret = xe_vm_rebind(vm, false);
432 		if (ret)
433 			return ret;
434 	} while (!list_empty(&vm->gpuvm.evict.list));
435 
436 	drm_exec_for_each_locked_object(exec, index, obj) {
437 		ret = dma_resv_reserve_fences(obj->resv, num_fences);
438 		if (ret)
439 			return ret;
440 	}
441 
442 	return 0;
443 }
444 
445 static int xe_preempt_work_begin(struct drm_exec *exec, struct xe_vm *vm,
446 				 bool *done)
447 {
448 	int err;
449 
450 	err = drm_gpuvm_prepare_vm(&vm->gpuvm, exec, 0);
451 	if (err)
452 		return err;
453 
454 	if (xe_vm_is_idle(vm)) {
455 		vm->preempt.rebind_deactivated = true;
456 		*done = true;
457 		return 0;
458 	}
459 
460 	if (!preempt_fences_waiting(vm)) {
461 		*done = true;
462 		return 0;
463 	}
464 
465 	err = drm_gpuvm_prepare_objects(&vm->gpuvm, exec, 0);
466 	if (err)
467 		return err;
468 
469 	err = wait_for_existing_preempt_fences(vm);
470 	if (err)
471 		return err;
472 
473 	/*
474 	 * Add validation and rebinding to the locking loop since both can
475 	 * cause evictions which may require blocing dma_resv locks.
476 	 * The fence reservation here is intended for the new preempt fences
477 	 * we attach at the end of the rebind work.
478 	 */
479 	return xe_vm_validate_rebind(vm, exec, vm->preempt.num_exec_queues);
480 }
481 
482 static void preempt_rebind_work_func(struct work_struct *w)
483 {
484 	struct xe_vm *vm = container_of(w, struct xe_vm, preempt.rebind_work);
485 	struct drm_exec exec;
486 	unsigned int fence_count = 0;
487 	LIST_HEAD(preempt_fences);
488 	ktime_t end = 0;
489 	int err = 0;
490 	long wait;
491 	int __maybe_unused tries = 0;
492 
493 	xe_assert(vm->xe, xe_vm_in_preempt_fence_mode(vm));
494 	trace_xe_vm_rebind_worker_enter(vm);
495 
496 	down_write(&vm->lock);
497 
498 	if (xe_vm_is_closed_or_banned(vm)) {
499 		up_write(&vm->lock);
500 		trace_xe_vm_rebind_worker_exit(vm);
501 		return;
502 	}
503 
504 retry:
505 	if (xe_vm_userptr_check_repin(vm)) {
506 		err = xe_vm_userptr_pin(vm);
507 		if (err)
508 			goto out_unlock_outer;
509 	}
510 
511 	drm_exec_init(&exec, DRM_EXEC_INTERRUPTIBLE_WAIT, 0);
512 
513 	drm_exec_until_all_locked(&exec) {
514 		bool done = false;
515 
516 		err = xe_preempt_work_begin(&exec, vm, &done);
517 		drm_exec_retry_on_contention(&exec);
518 		if (err || done) {
519 			drm_exec_fini(&exec);
520 			if (err && xe_vm_validate_should_retry(&exec, err, &end))
521 				err = -EAGAIN;
522 
523 			goto out_unlock_outer;
524 		}
525 	}
526 
527 	err = alloc_preempt_fences(vm, &preempt_fences, &fence_count);
528 	if (err)
529 		goto out_unlock;
530 
531 	err = xe_vm_rebind(vm, true);
532 	if (err)
533 		goto out_unlock;
534 
535 	/* Wait on rebinds and munmap style VM unbinds */
536 	wait = dma_resv_wait_timeout(xe_vm_resv(vm),
537 				     DMA_RESV_USAGE_KERNEL,
538 				     false, MAX_SCHEDULE_TIMEOUT);
539 	if (wait <= 0) {
540 		err = -ETIME;
541 		goto out_unlock;
542 	}
543 
544 #define retry_required(__tries, __vm) \
545 	(IS_ENABLED(CONFIG_DRM_XE_USERPTR_INVAL_INJECT) ? \
546 	(!(__tries)++ || __xe_vm_userptr_needs_repin(__vm)) : \
547 	__xe_vm_userptr_needs_repin(__vm))
548 
549 	down_read(&vm->userptr.notifier_lock);
550 	if (retry_required(tries, vm)) {
551 		up_read(&vm->userptr.notifier_lock);
552 		err = -EAGAIN;
553 		goto out_unlock;
554 	}
555 
556 #undef retry_required
557 
558 	spin_lock(&vm->xe->ttm.lru_lock);
559 	ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
560 	spin_unlock(&vm->xe->ttm.lru_lock);
561 
562 	/* Point of no return. */
563 	arm_preempt_fences(vm, &preempt_fences);
564 	resume_and_reinstall_preempt_fences(vm, &exec);
565 	up_read(&vm->userptr.notifier_lock);
566 
567 out_unlock:
568 	drm_exec_fini(&exec);
569 out_unlock_outer:
570 	if (err == -EAGAIN) {
571 		trace_xe_vm_rebind_worker_retry(vm);
572 		goto retry;
573 	}
574 
575 	if (err) {
576 		drm_warn(&vm->xe->drm, "VM worker error: %d\n", err);
577 		xe_vm_kill(vm, true);
578 	}
579 	up_write(&vm->lock);
580 
581 	free_preempt_fences(&preempt_fences);
582 
583 	trace_xe_vm_rebind_worker_exit(vm);
584 }
585 
586 static void __vma_userptr_invalidate(struct xe_vm *vm, struct xe_userptr_vma *uvma)
587 {
588 	struct xe_userptr *userptr = &uvma->userptr;
589 	struct xe_vma *vma = &uvma->vma;
590 	struct dma_resv_iter cursor;
591 	struct dma_fence *fence;
592 	long err;
593 
594 	/*
595 	 * Tell exec and rebind worker they need to repin and rebind this
596 	 * userptr.
597 	 */
598 	if (!xe_vm_in_fault_mode(vm) &&
599 	    !(vma->gpuva.flags & XE_VMA_DESTROYED)) {
600 		spin_lock(&vm->userptr.invalidated_lock);
601 		list_move_tail(&userptr->invalidate_link,
602 			       &vm->userptr.invalidated);
603 		spin_unlock(&vm->userptr.invalidated_lock);
604 	}
605 
606 	/*
607 	 * Preempt fences turn into schedule disables, pipeline these.
608 	 * Note that even in fault mode, we need to wait for binds and
609 	 * unbinds to complete, and those are attached as BOOKMARK fences
610 	 * to the vm.
611 	 */
612 	dma_resv_iter_begin(&cursor, xe_vm_resv(vm),
613 			    DMA_RESV_USAGE_BOOKKEEP);
614 	dma_resv_for_each_fence_unlocked(&cursor, fence)
615 		dma_fence_enable_sw_signaling(fence);
616 	dma_resv_iter_end(&cursor);
617 
618 	err = dma_resv_wait_timeout(xe_vm_resv(vm),
619 				    DMA_RESV_USAGE_BOOKKEEP,
620 				    false, MAX_SCHEDULE_TIMEOUT);
621 	XE_WARN_ON(err <= 0);
622 
623 	if (xe_vm_in_fault_mode(vm) && userptr->initial_bind) {
624 		err = xe_vm_invalidate_vma(vma);
625 		XE_WARN_ON(err);
626 	}
627 
628 	xe_hmm_userptr_unmap(uvma);
629 }
630 
631 static bool vma_userptr_invalidate(struct mmu_interval_notifier *mni,
632 				   const struct mmu_notifier_range *range,
633 				   unsigned long cur_seq)
634 {
635 	struct xe_userptr_vma *uvma = container_of(mni, typeof(*uvma), userptr.notifier);
636 	struct xe_vma *vma = &uvma->vma;
637 	struct xe_vm *vm = xe_vma_vm(vma);
638 
639 	xe_assert(vm->xe, xe_vma_is_userptr(vma));
640 	trace_xe_vma_userptr_invalidate(vma);
641 
642 	if (!mmu_notifier_range_blockable(range))
643 		return false;
644 
645 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
646 	       "NOTIFIER: addr=0x%016llx, range=0x%016llx",
647 		xe_vma_start(vma), xe_vma_size(vma));
648 
649 	down_write(&vm->userptr.notifier_lock);
650 	mmu_interval_set_seq(mni, cur_seq);
651 
652 	__vma_userptr_invalidate(vm, uvma);
653 	up_write(&vm->userptr.notifier_lock);
654 	trace_xe_vma_userptr_invalidate_complete(vma);
655 
656 	return true;
657 }
658 
659 static const struct mmu_interval_notifier_ops vma_userptr_notifier_ops = {
660 	.invalidate = vma_userptr_invalidate,
661 };
662 
663 #if IS_ENABLED(CONFIG_DRM_XE_USERPTR_INVAL_INJECT)
664 /**
665  * xe_vma_userptr_force_invalidate() - force invalidate a userptr
666  * @uvma: The userptr vma to invalidate
667  *
668  * Perform a forced userptr invalidation for testing purposes.
669  */
670 void xe_vma_userptr_force_invalidate(struct xe_userptr_vma *uvma)
671 {
672 	struct xe_vm *vm = xe_vma_vm(&uvma->vma);
673 
674 	/* Protect against concurrent userptr pinning */
675 	lockdep_assert_held(&vm->lock);
676 	/* Protect against concurrent notifiers */
677 	lockdep_assert_held(&vm->userptr.notifier_lock);
678 	/*
679 	 * Protect against concurrent instances of this function and
680 	 * the critical exec sections
681 	 */
682 	xe_vm_assert_held(vm);
683 
684 	if (!mmu_interval_read_retry(&uvma->userptr.notifier,
685 				     uvma->userptr.notifier_seq))
686 		uvma->userptr.notifier_seq -= 2;
687 	__vma_userptr_invalidate(vm, uvma);
688 }
689 #endif
690 
691 int xe_vm_userptr_pin(struct xe_vm *vm)
692 {
693 	struct xe_userptr_vma *uvma, *next;
694 	int err = 0;
695 
696 	xe_assert(vm->xe, !xe_vm_in_fault_mode(vm));
697 	lockdep_assert_held_write(&vm->lock);
698 
699 	/* Collect invalidated userptrs */
700 	spin_lock(&vm->userptr.invalidated_lock);
701 	xe_assert(vm->xe, list_empty(&vm->userptr.repin_list));
702 	list_for_each_entry_safe(uvma, next, &vm->userptr.invalidated,
703 				 userptr.invalidate_link) {
704 		list_del_init(&uvma->userptr.invalidate_link);
705 		list_add_tail(&uvma->userptr.repin_link,
706 			      &vm->userptr.repin_list);
707 	}
708 	spin_unlock(&vm->userptr.invalidated_lock);
709 
710 	/* Pin and move to bind list */
711 	list_for_each_entry_safe(uvma, next, &vm->userptr.repin_list,
712 				 userptr.repin_link) {
713 		err = xe_vma_userptr_pin_pages(uvma);
714 		if (err == -EFAULT) {
715 			list_del_init(&uvma->userptr.repin_link);
716 			/*
717 			 * We might have already done the pin once already, but
718 			 * then had to retry before the re-bind happened, due
719 			 * some other condition in the caller, but in the
720 			 * meantime the userptr got dinged by the notifier such
721 			 * that we need to revalidate here, but this time we hit
722 			 * the EFAULT. In such a case make sure we remove
723 			 * ourselves from the rebind list to avoid going down in
724 			 * flames.
725 			 */
726 			if (!list_empty(&uvma->vma.combined_links.rebind))
727 				list_del_init(&uvma->vma.combined_links.rebind);
728 
729 			/* Wait for pending binds */
730 			xe_vm_lock(vm, false);
731 			dma_resv_wait_timeout(xe_vm_resv(vm),
732 					      DMA_RESV_USAGE_BOOKKEEP,
733 					      false, MAX_SCHEDULE_TIMEOUT);
734 
735 			down_read(&vm->userptr.notifier_lock);
736 			err = xe_vm_invalidate_vma(&uvma->vma);
737 			up_read(&vm->userptr.notifier_lock);
738 			xe_vm_unlock(vm);
739 			if (err)
740 				break;
741 		} else {
742 			if (err)
743 				break;
744 
745 			list_del_init(&uvma->userptr.repin_link);
746 			list_move_tail(&uvma->vma.combined_links.rebind,
747 				       &vm->rebind_list);
748 		}
749 	}
750 
751 	if (err) {
752 		down_write(&vm->userptr.notifier_lock);
753 		spin_lock(&vm->userptr.invalidated_lock);
754 		list_for_each_entry_safe(uvma, next, &vm->userptr.repin_list,
755 					 userptr.repin_link) {
756 			list_del_init(&uvma->userptr.repin_link);
757 			list_move_tail(&uvma->userptr.invalidate_link,
758 				       &vm->userptr.invalidated);
759 		}
760 		spin_unlock(&vm->userptr.invalidated_lock);
761 		up_write(&vm->userptr.notifier_lock);
762 	}
763 	return err;
764 }
765 
766 /**
767  * xe_vm_userptr_check_repin() - Check whether the VM might have userptrs
768  * that need repinning.
769  * @vm: The VM.
770  *
771  * This function does an advisory check for whether the VM has userptrs that
772  * need repinning.
773  *
774  * Return: 0 if there are no indications of userptrs needing repinning,
775  * -EAGAIN if there are.
776  */
777 int xe_vm_userptr_check_repin(struct xe_vm *vm)
778 {
779 	return (list_empty_careful(&vm->userptr.repin_list) &&
780 		list_empty_careful(&vm->userptr.invalidated)) ? 0 : -EAGAIN;
781 }
782 
783 static int xe_vma_ops_alloc(struct xe_vma_ops *vops, bool array_of_binds)
784 {
785 	int i;
786 
787 	for (i = 0; i < XE_MAX_TILES_PER_DEVICE; ++i) {
788 		if (!vops->pt_update_ops[i].num_ops)
789 			continue;
790 
791 		vops->pt_update_ops[i].ops =
792 			kmalloc_array(vops->pt_update_ops[i].num_ops,
793 				      sizeof(*vops->pt_update_ops[i].ops),
794 				      GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
795 		if (!vops->pt_update_ops[i].ops)
796 			return array_of_binds ? -ENOBUFS : -ENOMEM;
797 	}
798 
799 	return 0;
800 }
801 ALLOW_ERROR_INJECTION(xe_vma_ops_alloc, ERRNO);
802 
803 static void xe_vma_svm_prefetch_op_fini(struct xe_vma_op *op)
804 {
805 	struct xe_vma *vma;
806 
807 	vma = gpuva_to_vma(op->base.prefetch.va);
808 
809 	if (op->base.op == DRM_GPUVA_OP_PREFETCH && xe_vma_is_cpu_addr_mirror(vma))
810 		xa_destroy(&op->prefetch_range.range);
811 }
812 
813 static void xe_vma_svm_prefetch_ops_fini(struct xe_vma_ops *vops)
814 {
815 	struct xe_vma_op *op;
816 
817 	if (!(vops->flags & XE_VMA_OPS_FLAG_HAS_SVM_PREFETCH))
818 		return;
819 
820 	list_for_each_entry(op, &vops->list, link)
821 		xe_vma_svm_prefetch_op_fini(op);
822 }
823 
824 static void xe_vma_ops_fini(struct xe_vma_ops *vops)
825 {
826 	int i;
827 
828 	xe_vma_svm_prefetch_ops_fini(vops);
829 
830 	for (i = 0; i < XE_MAX_TILES_PER_DEVICE; ++i)
831 		kfree(vops->pt_update_ops[i].ops);
832 }
833 
834 static void xe_vma_ops_incr_pt_update_ops(struct xe_vma_ops *vops, u8 tile_mask, int inc_val)
835 {
836 	int i;
837 
838 	if (!inc_val)
839 		return;
840 
841 	for (i = 0; i < XE_MAX_TILES_PER_DEVICE; ++i)
842 		if (BIT(i) & tile_mask)
843 			vops->pt_update_ops[i].num_ops += inc_val;
844 }
845 
846 static void xe_vm_populate_rebind(struct xe_vma_op *op, struct xe_vma *vma,
847 				  u8 tile_mask)
848 {
849 	INIT_LIST_HEAD(&op->link);
850 	op->tile_mask = tile_mask;
851 	op->base.op = DRM_GPUVA_OP_MAP;
852 	op->base.map.va.addr = vma->gpuva.va.addr;
853 	op->base.map.va.range = vma->gpuva.va.range;
854 	op->base.map.gem.obj = vma->gpuva.gem.obj;
855 	op->base.map.gem.offset = vma->gpuva.gem.offset;
856 	op->map.vma = vma;
857 	op->map.immediate = true;
858 	op->map.dumpable = vma->gpuva.flags & XE_VMA_DUMPABLE;
859 	op->map.is_null = xe_vma_is_null(vma);
860 }
861 
862 static int xe_vm_ops_add_rebind(struct xe_vma_ops *vops, struct xe_vma *vma,
863 				u8 tile_mask)
864 {
865 	struct xe_vma_op *op;
866 
867 	op = kzalloc(sizeof(*op), GFP_KERNEL);
868 	if (!op)
869 		return -ENOMEM;
870 
871 	xe_vm_populate_rebind(op, vma, tile_mask);
872 	list_add_tail(&op->link, &vops->list);
873 	xe_vma_ops_incr_pt_update_ops(vops, tile_mask, 1);
874 
875 	return 0;
876 }
877 
878 static struct dma_fence *ops_execute(struct xe_vm *vm,
879 				     struct xe_vma_ops *vops);
880 static void xe_vma_ops_init(struct xe_vma_ops *vops, struct xe_vm *vm,
881 			    struct xe_exec_queue *q,
882 			    struct xe_sync_entry *syncs, u32 num_syncs);
883 
884 int xe_vm_rebind(struct xe_vm *vm, bool rebind_worker)
885 {
886 	struct dma_fence *fence;
887 	struct xe_vma *vma, *next;
888 	struct xe_vma_ops vops;
889 	struct xe_vma_op *op, *next_op;
890 	int err, i;
891 
892 	lockdep_assert_held(&vm->lock);
893 	if ((xe_vm_in_lr_mode(vm) && !rebind_worker) ||
894 	    list_empty(&vm->rebind_list))
895 		return 0;
896 
897 	xe_vma_ops_init(&vops, vm, NULL, NULL, 0);
898 	for (i = 0; i < XE_MAX_TILES_PER_DEVICE; ++i)
899 		vops.pt_update_ops[i].wait_vm_bookkeep = true;
900 
901 	xe_vm_assert_held(vm);
902 	list_for_each_entry(vma, &vm->rebind_list, combined_links.rebind) {
903 		xe_assert(vm->xe, vma->tile_present);
904 
905 		if (rebind_worker)
906 			trace_xe_vma_rebind_worker(vma);
907 		else
908 			trace_xe_vma_rebind_exec(vma);
909 
910 		err = xe_vm_ops_add_rebind(&vops, vma,
911 					   vma->tile_present);
912 		if (err)
913 			goto free_ops;
914 	}
915 
916 	err = xe_vma_ops_alloc(&vops, false);
917 	if (err)
918 		goto free_ops;
919 
920 	fence = ops_execute(vm, &vops);
921 	if (IS_ERR(fence)) {
922 		err = PTR_ERR(fence);
923 	} else {
924 		dma_fence_put(fence);
925 		list_for_each_entry_safe(vma, next, &vm->rebind_list,
926 					 combined_links.rebind)
927 			list_del_init(&vma->combined_links.rebind);
928 	}
929 free_ops:
930 	list_for_each_entry_safe(op, next_op, &vops.list, link) {
931 		list_del(&op->link);
932 		kfree(op);
933 	}
934 	xe_vma_ops_fini(&vops);
935 
936 	return err;
937 }
938 
939 struct dma_fence *xe_vma_rebind(struct xe_vm *vm, struct xe_vma *vma, u8 tile_mask)
940 {
941 	struct dma_fence *fence = NULL;
942 	struct xe_vma_ops vops;
943 	struct xe_vma_op *op, *next_op;
944 	struct xe_tile *tile;
945 	u8 id;
946 	int err;
947 
948 	lockdep_assert_held(&vm->lock);
949 	xe_vm_assert_held(vm);
950 	xe_assert(vm->xe, xe_vm_in_fault_mode(vm));
951 
952 	xe_vma_ops_init(&vops, vm, NULL, NULL, 0);
953 	for_each_tile(tile, vm->xe, id) {
954 		vops.pt_update_ops[id].wait_vm_bookkeep = true;
955 		vops.pt_update_ops[tile->id].q =
956 			xe_tile_migrate_exec_queue(tile);
957 	}
958 
959 	err = xe_vm_ops_add_rebind(&vops, vma, tile_mask);
960 	if (err)
961 		return ERR_PTR(err);
962 
963 	err = xe_vma_ops_alloc(&vops, false);
964 	if (err) {
965 		fence = ERR_PTR(err);
966 		goto free_ops;
967 	}
968 
969 	fence = ops_execute(vm, &vops);
970 
971 free_ops:
972 	list_for_each_entry_safe(op, next_op, &vops.list, link) {
973 		list_del(&op->link);
974 		kfree(op);
975 	}
976 	xe_vma_ops_fini(&vops);
977 
978 	return fence;
979 }
980 
981 static void xe_vm_populate_range_rebind(struct xe_vma_op *op,
982 					struct xe_vma *vma,
983 					struct xe_svm_range *range,
984 					u8 tile_mask)
985 {
986 	INIT_LIST_HEAD(&op->link);
987 	op->tile_mask = tile_mask;
988 	op->base.op = DRM_GPUVA_OP_DRIVER;
989 	op->subop = XE_VMA_SUBOP_MAP_RANGE;
990 	op->map_range.vma = vma;
991 	op->map_range.range = range;
992 }
993 
994 static int
995 xe_vm_ops_add_range_rebind(struct xe_vma_ops *vops,
996 			   struct xe_vma *vma,
997 			   struct xe_svm_range *range,
998 			   u8 tile_mask)
999 {
1000 	struct xe_vma_op *op;
1001 
1002 	op = kzalloc(sizeof(*op), GFP_KERNEL);
1003 	if (!op)
1004 		return -ENOMEM;
1005 
1006 	xe_vm_populate_range_rebind(op, vma, range, tile_mask);
1007 	list_add_tail(&op->link, &vops->list);
1008 	xe_vma_ops_incr_pt_update_ops(vops, tile_mask, 1);
1009 
1010 	return 0;
1011 }
1012 
1013 /**
1014  * xe_vm_range_rebind() - VM range (re)bind
1015  * @vm: The VM which the range belongs to.
1016  * @vma: The VMA which the range belongs to.
1017  * @range: SVM range to rebind.
1018  * @tile_mask: Tile mask to bind the range to.
1019  *
1020  * (re)bind SVM range setting up GPU page tables for the range.
1021  *
1022  * Return: dma fence for rebind to signal completion on succees, ERR_PTR on
1023  * failure
1024  */
1025 struct dma_fence *xe_vm_range_rebind(struct xe_vm *vm,
1026 				     struct xe_vma *vma,
1027 				     struct xe_svm_range *range,
1028 				     u8 tile_mask)
1029 {
1030 	struct dma_fence *fence = NULL;
1031 	struct xe_vma_ops vops;
1032 	struct xe_vma_op *op, *next_op;
1033 	struct xe_tile *tile;
1034 	u8 id;
1035 	int err;
1036 
1037 	lockdep_assert_held(&vm->lock);
1038 	xe_vm_assert_held(vm);
1039 	xe_assert(vm->xe, xe_vm_in_fault_mode(vm));
1040 	xe_assert(vm->xe, xe_vma_is_cpu_addr_mirror(vma));
1041 
1042 	xe_vma_ops_init(&vops, vm, NULL, NULL, 0);
1043 	for_each_tile(tile, vm->xe, id) {
1044 		vops.pt_update_ops[id].wait_vm_bookkeep = true;
1045 		vops.pt_update_ops[tile->id].q =
1046 			xe_tile_migrate_exec_queue(tile);
1047 	}
1048 
1049 	err = xe_vm_ops_add_range_rebind(&vops, vma, range, tile_mask);
1050 	if (err)
1051 		return ERR_PTR(err);
1052 
1053 	err = xe_vma_ops_alloc(&vops, false);
1054 	if (err) {
1055 		fence = ERR_PTR(err);
1056 		goto free_ops;
1057 	}
1058 
1059 	fence = ops_execute(vm, &vops);
1060 
1061 free_ops:
1062 	list_for_each_entry_safe(op, next_op, &vops.list, link) {
1063 		list_del(&op->link);
1064 		kfree(op);
1065 	}
1066 	xe_vma_ops_fini(&vops);
1067 
1068 	return fence;
1069 }
1070 
1071 static void xe_vm_populate_range_unbind(struct xe_vma_op *op,
1072 					struct xe_svm_range *range)
1073 {
1074 	INIT_LIST_HEAD(&op->link);
1075 	op->tile_mask = range->tile_present;
1076 	op->base.op = DRM_GPUVA_OP_DRIVER;
1077 	op->subop = XE_VMA_SUBOP_UNMAP_RANGE;
1078 	op->unmap_range.range = range;
1079 }
1080 
1081 static int
1082 xe_vm_ops_add_range_unbind(struct xe_vma_ops *vops,
1083 			   struct xe_svm_range *range)
1084 {
1085 	struct xe_vma_op *op;
1086 
1087 	op = kzalloc(sizeof(*op), GFP_KERNEL);
1088 	if (!op)
1089 		return -ENOMEM;
1090 
1091 	xe_vm_populate_range_unbind(op, range);
1092 	list_add_tail(&op->link, &vops->list);
1093 	xe_vma_ops_incr_pt_update_ops(vops, range->tile_present, 1);
1094 
1095 	return 0;
1096 }
1097 
1098 /**
1099  * xe_vm_range_unbind() - VM range unbind
1100  * @vm: The VM which the range belongs to.
1101  * @range: SVM range to rebind.
1102  *
1103  * Unbind SVM range removing the GPU page tables for the range.
1104  *
1105  * Return: dma fence for unbind to signal completion on succees, ERR_PTR on
1106  * failure
1107  */
1108 struct dma_fence *xe_vm_range_unbind(struct xe_vm *vm,
1109 				     struct xe_svm_range *range)
1110 {
1111 	struct dma_fence *fence = NULL;
1112 	struct xe_vma_ops vops;
1113 	struct xe_vma_op *op, *next_op;
1114 	struct xe_tile *tile;
1115 	u8 id;
1116 	int err;
1117 
1118 	lockdep_assert_held(&vm->lock);
1119 	xe_vm_assert_held(vm);
1120 	xe_assert(vm->xe, xe_vm_in_fault_mode(vm));
1121 
1122 	if (!range->tile_present)
1123 		return dma_fence_get_stub();
1124 
1125 	xe_vma_ops_init(&vops, vm, NULL, NULL, 0);
1126 	for_each_tile(tile, vm->xe, id) {
1127 		vops.pt_update_ops[id].wait_vm_bookkeep = true;
1128 		vops.pt_update_ops[tile->id].q =
1129 			xe_tile_migrate_exec_queue(tile);
1130 	}
1131 
1132 	err = xe_vm_ops_add_range_unbind(&vops, range);
1133 	if (err)
1134 		return ERR_PTR(err);
1135 
1136 	err = xe_vma_ops_alloc(&vops, false);
1137 	if (err) {
1138 		fence = ERR_PTR(err);
1139 		goto free_ops;
1140 	}
1141 
1142 	fence = ops_execute(vm, &vops);
1143 
1144 free_ops:
1145 	list_for_each_entry_safe(op, next_op, &vops.list, link) {
1146 		list_del(&op->link);
1147 		kfree(op);
1148 	}
1149 	xe_vma_ops_fini(&vops);
1150 
1151 	return fence;
1152 }
1153 
1154 static void xe_vma_free(struct xe_vma *vma)
1155 {
1156 	if (xe_vma_is_userptr(vma))
1157 		kfree(to_userptr_vma(vma));
1158 	else
1159 		kfree(vma);
1160 }
1161 
1162 #define VMA_CREATE_FLAG_READ_ONLY		BIT(0)
1163 #define VMA_CREATE_FLAG_IS_NULL			BIT(1)
1164 #define VMA_CREATE_FLAG_DUMPABLE		BIT(2)
1165 #define VMA_CREATE_FLAG_IS_SYSTEM_ALLOCATOR	BIT(3)
1166 
1167 static struct xe_vma *xe_vma_create(struct xe_vm *vm,
1168 				    struct xe_bo *bo,
1169 				    u64 bo_offset_or_userptr,
1170 				    u64 start, u64 end,
1171 				    u16 pat_index, unsigned int flags)
1172 {
1173 	struct xe_vma *vma;
1174 	struct xe_tile *tile;
1175 	u8 id;
1176 	bool read_only = (flags & VMA_CREATE_FLAG_READ_ONLY);
1177 	bool is_null = (flags & VMA_CREATE_FLAG_IS_NULL);
1178 	bool dumpable = (flags & VMA_CREATE_FLAG_DUMPABLE);
1179 	bool is_cpu_addr_mirror =
1180 		(flags & VMA_CREATE_FLAG_IS_SYSTEM_ALLOCATOR);
1181 
1182 	xe_assert(vm->xe, start < end);
1183 	xe_assert(vm->xe, end < vm->size);
1184 
1185 	/*
1186 	 * Allocate and ensure that the xe_vma_is_userptr() return
1187 	 * matches what was allocated.
1188 	 */
1189 	if (!bo && !is_null && !is_cpu_addr_mirror) {
1190 		struct xe_userptr_vma *uvma = kzalloc(sizeof(*uvma), GFP_KERNEL);
1191 
1192 		if (!uvma)
1193 			return ERR_PTR(-ENOMEM);
1194 
1195 		vma = &uvma->vma;
1196 	} else {
1197 		vma = kzalloc(sizeof(*vma), GFP_KERNEL);
1198 		if (!vma)
1199 			return ERR_PTR(-ENOMEM);
1200 
1201 		if (is_cpu_addr_mirror)
1202 			vma->gpuva.flags |= XE_VMA_SYSTEM_ALLOCATOR;
1203 		if (is_null)
1204 			vma->gpuva.flags |= DRM_GPUVA_SPARSE;
1205 		if (bo)
1206 			vma->gpuva.gem.obj = &bo->ttm.base;
1207 	}
1208 
1209 	INIT_LIST_HEAD(&vma->combined_links.rebind);
1210 
1211 	INIT_LIST_HEAD(&vma->gpuva.gem.entry);
1212 	vma->gpuva.vm = &vm->gpuvm;
1213 	vma->gpuva.va.addr = start;
1214 	vma->gpuva.va.range = end - start + 1;
1215 	if (read_only)
1216 		vma->gpuva.flags |= XE_VMA_READ_ONLY;
1217 	if (dumpable)
1218 		vma->gpuva.flags |= XE_VMA_DUMPABLE;
1219 
1220 	for_each_tile(tile, vm->xe, id)
1221 		vma->tile_mask |= 0x1 << id;
1222 
1223 	if (vm->xe->info.has_atomic_enable_pte_bit)
1224 		vma->gpuva.flags |= XE_VMA_ATOMIC_PTE_BIT;
1225 
1226 	vma->pat_index = pat_index;
1227 
1228 	if (bo) {
1229 		struct drm_gpuvm_bo *vm_bo;
1230 
1231 		xe_bo_assert_held(bo);
1232 
1233 		vm_bo = drm_gpuvm_bo_obtain(vma->gpuva.vm, &bo->ttm.base);
1234 		if (IS_ERR(vm_bo)) {
1235 			xe_vma_free(vma);
1236 			return ERR_CAST(vm_bo);
1237 		}
1238 
1239 		drm_gpuvm_bo_extobj_add(vm_bo);
1240 		drm_gem_object_get(&bo->ttm.base);
1241 		vma->gpuva.gem.offset = bo_offset_or_userptr;
1242 		drm_gpuva_link(&vma->gpuva, vm_bo);
1243 		drm_gpuvm_bo_put(vm_bo);
1244 	} else /* userptr or null */ {
1245 		if (!is_null && !is_cpu_addr_mirror) {
1246 			struct xe_userptr *userptr = &to_userptr_vma(vma)->userptr;
1247 			u64 size = end - start + 1;
1248 			int err;
1249 
1250 			INIT_LIST_HEAD(&userptr->invalidate_link);
1251 			INIT_LIST_HEAD(&userptr->repin_link);
1252 			vma->gpuva.gem.offset = bo_offset_or_userptr;
1253 			mutex_init(&userptr->unmap_mutex);
1254 
1255 			err = mmu_interval_notifier_insert(&userptr->notifier,
1256 							   current->mm,
1257 							   xe_vma_userptr(vma), size,
1258 							   &vma_userptr_notifier_ops);
1259 			if (err) {
1260 				xe_vma_free(vma);
1261 				return ERR_PTR(err);
1262 			}
1263 
1264 			userptr->notifier_seq = LONG_MAX;
1265 		}
1266 
1267 		xe_vm_get(vm);
1268 	}
1269 
1270 	return vma;
1271 }
1272 
1273 static void xe_vma_destroy_late(struct xe_vma *vma)
1274 {
1275 	struct xe_vm *vm = xe_vma_vm(vma);
1276 
1277 	if (vma->ufence) {
1278 		xe_sync_ufence_put(vma->ufence);
1279 		vma->ufence = NULL;
1280 	}
1281 
1282 	if (xe_vma_is_userptr(vma)) {
1283 		struct xe_userptr_vma *uvma = to_userptr_vma(vma);
1284 		struct xe_userptr *userptr = &uvma->userptr;
1285 
1286 		if (userptr->sg)
1287 			xe_hmm_userptr_free_sg(uvma);
1288 
1289 		/*
1290 		 * Since userptr pages are not pinned, we can't remove
1291 		 * the notifier until we're sure the GPU is not accessing
1292 		 * them anymore
1293 		 */
1294 		mmu_interval_notifier_remove(&userptr->notifier);
1295 		mutex_destroy(&userptr->unmap_mutex);
1296 		xe_vm_put(vm);
1297 	} else if (xe_vma_is_null(vma) || xe_vma_is_cpu_addr_mirror(vma)) {
1298 		xe_vm_put(vm);
1299 	} else {
1300 		xe_bo_put(xe_vma_bo(vma));
1301 	}
1302 
1303 	xe_vma_free(vma);
1304 }
1305 
1306 static void vma_destroy_work_func(struct work_struct *w)
1307 {
1308 	struct xe_vma *vma =
1309 		container_of(w, struct xe_vma, destroy_work);
1310 
1311 	xe_vma_destroy_late(vma);
1312 }
1313 
1314 static void vma_destroy_cb(struct dma_fence *fence,
1315 			   struct dma_fence_cb *cb)
1316 {
1317 	struct xe_vma *vma = container_of(cb, struct xe_vma, destroy_cb);
1318 
1319 	INIT_WORK(&vma->destroy_work, vma_destroy_work_func);
1320 	queue_work(system_unbound_wq, &vma->destroy_work);
1321 }
1322 
1323 static void xe_vma_destroy(struct xe_vma *vma, struct dma_fence *fence)
1324 {
1325 	struct xe_vm *vm = xe_vma_vm(vma);
1326 
1327 	lockdep_assert_held_write(&vm->lock);
1328 	xe_assert(vm->xe, list_empty(&vma->combined_links.destroy));
1329 
1330 	if (xe_vma_is_userptr(vma)) {
1331 		xe_assert(vm->xe, vma->gpuva.flags & XE_VMA_DESTROYED);
1332 
1333 		spin_lock(&vm->userptr.invalidated_lock);
1334 		xe_assert(vm->xe, list_empty(&to_userptr_vma(vma)->userptr.repin_link));
1335 		list_del(&to_userptr_vma(vma)->userptr.invalidate_link);
1336 		spin_unlock(&vm->userptr.invalidated_lock);
1337 	} else if (!xe_vma_is_null(vma) && !xe_vma_is_cpu_addr_mirror(vma)) {
1338 		xe_bo_assert_held(xe_vma_bo(vma));
1339 
1340 		drm_gpuva_unlink(&vma->gpuva);
1341 	}
1342 
1343 	xe_vm_assert_held(vm);
1344 	if (fence) {
1345 		int ret = dma_fence_add_callback(fence, &vma->destroy_cb,
1346 						 vma_destroy_cb);
1347 
1348 		if (ret) {
1349 			XE_WARN_ON(ret != -ENOENT);
1350 			xe_vma_destroy_late(vma);
1351 		}
1352 	} else {
1353 		xe_vma_destroy_late(vma);
1354 	}
1355 }
1356 
1357 /**
1358  * xe_vm_lock_vma() - drm_exec utility to lock a vma
1359  * @exec: The drm_exec object we're currently locking for.
1360  * @vma: The vma for witch we want to lock the vm resv and any attached
1361  * object's resv.
1362  *
1363  * Return: 0 on success, negative error code on error. In particular
1364  * may return -EDEADLK on WW transaction contention and -EINTR if
1365  * an interruptible wait is terminated by a signal.
1366  */
1367 int xe_vm_lock_vma(struct drm_exec *exec, struct xe_vma *vma)
1368 {
1369 	struct xe_vm *vm = xe_vma_vm(vma);
1370 	struct xe_bo *bo = xe_vma_bo(vma);
1371 	int err;
1372 
1373 	XE_WARN_ON(!vm);
1374 
1375 	err = drm_exec_lock_obj(exec, xe_vm_obj(vm));
1376 	if (!err && bo && !bo->vm)
1377 		err = drm_exec_lock_obj(exec, &bo->ttm.base);
1378 
1379 	return err;
1380 }
1381 
1382 static void xe_vma_destroy_unlocked(struct xe_vma *vma)
1383 {
1384 	struct drm_exec exec;
1385 	int err;
1386 
1387 	drm_exec_init(&exec, 0, 0);
1388 	drm_exec_until_all_locked(&exec) {
1389 		err = xe_vm_lock_vma(&exec, vma);
1390 		drm_exec_retry_on_contention(&exec);
1391 		if (XE_WARN_ON(err))
1392 			break;
1393 	}
1394 
1395 	xe_vma_destroy(vma, NULL);
1396 
1397 	drm_exec_fini(&exec);
1398 }
1399 
1400 struct xe_vma *
1401 xe_vm_find_overlapping_vma(struct xe_vm *vm, u64 start, u64 range)
1402 {
1403 	struct drm_gpuva *gpuva;
1404 
1405 	lockdep_assert_held(&vm->lock);
1406 
1407 	if (xe_vm_is_closed_or_banned(vm))
1408 		return NULL;
1409 
1410 	xe_assert(vm->xe, start + range <= vm->size);
1411 
1412 	gpuva = drm_gpuva_find_first(&vm->gpuvm, start, range);
1413 
1414 	return gpuva ? gpuva_to_vma(gpuva) : NULL;
1415 }
1416 
1417 static int xe_vm_insert_vma(struct xe_vm *vm, struct xe_vma *vma)
1418 {
1419 	int err;
1420 
1421 	xe_assert(vm->xe, xe_vma_vm(vma) == vm);
1422 	lockdep_assert_held(&vm->lock);
1423 
1424 	mutex_lock(&vm->snap_mutex);
1425 	err = drm_gpuva_insert(&vm->gpuvm, &vma->gpuva);
1426 	mutex_unlock(&vm->snap_mutex);
1427 	XE_WARN_ON(err);	/* Shouldn't be possible */
1428 
1429 	return err;
1430 }
1431 
1432 static void xe_vm_remove_vma(struct xe_vm *vm, struct xe_vma *vma)
1433 {
1434 	xe_assert(vm->xe, xe_vma_vm(vma) == vm);
1435 	lockdep_assert_held(&vm->lock);
1436 
1437 	mutex_lock(&vm->snap_mutex);
1438 	drm_gpuva_remove(&vma->gpuva);
1439 	mutex_unlock(&vm->snap_mutex);
1440 	if (vm->usm.last_fault_vma == vma)
1441 		vm->usm.last_fault_vma = NULL;
1442 }
1443 
1444 static struct drm_gpuva_op *xe_vm_op_alloc(void)
1445 {
1446 	struct xe_vma_op *op;
1447 
1448 	op = kzalloc(sizeof(*op), GFP_KERNEL);
1449 
1450 	if (unlikely(!op))
1451 		return NULL;
1452 
1453 	return &op->base;
1454 }
1455 
1456 static void xe_vm_free(struct drm_gpuvm *gpuvm);
1457 
1458 static const struct drm_gpuvm_ops gpuvm_ops = {
1459 	.op_alloc = xe_vm_op_alloc,
1460 	.vm_bo_validate = xe_gpuvm_validate,
1461 	.vm_free = xe_vm_free,
1462 };
1463 
1464 static u64 pde_encode_pat_index(u16 pat_index)
1465 {
1466 	u64 pte = 0;
1467 
1468 	if (pat_index & BIT(0))
1469 		pte |= XE_PPGTT_PTE_PAT0;
1470 
1471 	if (pat_index & BIT(1))
1472 		pte |= XE_PPGTT_PTE_PAT1;
1473 
1474 	return pte;
1475 }
1476 
1477 static u64 pte_encode_pat_index(u16 pat_index, u32 pt_level)
1478 {
1479 	u64 pte = 0;
1480 
1481 	if (pat_index & BIT(0))
1482 		pte |= XE_PPGTT_PTE_PAT0;
1483 
1484 	if (pat_index & BIT(1))
1485 		pte |= XE_PPGTT_PTE_PAT1;
1486 
1487 	if (pat_index & BIT(2)) {
1488 		if (pt_level)
1489 			pte |= XE_PPGTT_PDE_PDPE_PAT2;
1490 		else
1491 			pte |= XE_PPGTT_PTE_PAT2;
1492 	}
1493 
1494 	if (pat_index & BIT(3))
1495 		pte |= XELPG_PPGTT_PTE_PAT3;
1496 
1497 	if (pat_index & (BIT(4)))
1498 		pte |= XE2_PPGTT_PTE_PAT4;
1499 
1500 	return pte;
1501 }
1502 
1503 static u64 pte_encode_ps(u32 pt_level)
1504 {
1505 	XE_WARN_ON(pt_level > MAX_HUGEPTE_LEVEL);
1506 
1507 	if (pt_level == 1)
1508 		return XE_PDE_PS_2M;
1509 	else if (pt_level == 2)
1510 		return XE_PDPE_PS_1G;
1511 
1512 	return 0;
1513 }
1514 
1515 static u64 xelp_pde_encode_bo(struct xe_bo *bo, u64 bo_offset,
1516 			      const u16 pat_index)
1517 {
1518 	u64 pde;
1519 
1520 	pde = xe_bo_addr(bo, bo_offset, XE_PAGE_SIZE);
1521 	pde |= XE_PAGE_PRESENT | XE_PAGE_RW;
1522 	pde |= pde_encode_pat_index(pat_index);
1523 
1524 	return pde;
1525 }
1526 
1527 static u64 xelp_pte_encode_bo(struct xe_bo *bo, u64 bo_offset,
1528 			      u16 pat_index, u32 pt_level)
1529 {
1530 	u64 pte;
1531 
1532 	pte = xe_bo_addr(bo, bo_offset, XE_PAGE_SIZE);
1533 	pte |= XE_PAGE_PRESENT | XE_PAGE_RW;
1534 	pte |= pte_encode_pat_index(pat_index, pt_level);
1535 	pte |= pte_encode_ps(pt_level);
1536 
1537 	if (xe_bo_is_vram(bo) || xe_bo_is_stolen_devmem(bo))
1538 		pte |= XE_PPGTT_PTE_DM;
1539 
1540 	return pte;
1541 }
1542 
1543 static u64 xelp_pte_encode_vma(u64 pte, struct xe_vma *vma,
1544 			       u16 pat_index, u32 pt_level)
1545 {
1546 	pte |= XE_PAGE_PRESENT;
1547 
1548 	if (likely(!xe_vma_read_only(vma)))
1549 		pte |= XE_PAGE_RW;
1550 
1551 	pte |= pte_encode_pat_index(pat_index, pt_level);
1552 	pte |= pte_encode_ps(pt_level);
1553 
1554 	if (unlikely(xe_vma_is_null(vma)))
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  *
1598  * Sets up a pagetable tree with one page-table per level and a single
1599  * leaf PTE. All pagetable entries point to the single page-table or,
1600  * for MAX_HUGEPTE_LEVEL, a NULL huge PTE returning 0 on read and
1601  * writes become NOPs.
1602  *
1603  * Return: 0 on success, negative error code on error.
1604  */
1605 static int xe_vm_create_scratch(struct xe_device *xe, struct xe_tile *tile,
1606 				struct xe_vm *vm)
1607 {
1608 	u8 id = tile->id;
1609 	int i;
1610 
1611 	for (i = MAX_HUGEPTE_LEVEL; i < vm->pt_root[id]->level; i++) {
1612 		vm->scratch_pt[id][i] = xe_pt_create(vm, tile, i);
1613 		if (IS_ERR(vm->scratch_pt[id][i]))
1614 			return PTR_ERR(vm->scratch_pt[id][i]);
1615 
1616 		xe_pt_populate_empty(tile, vm, vm->scratch_pt[id][i]);
1617 	}
1618 
1619 	return 0;
1620 }
1621 ALLOW_ERROR_INJECTION(xe_vm_create_scratch, ERRNO);
1622 
1623 static void xe_vm_free_scratch(struct xe_vm *vm)
1624 {
1625 	struct xe_tile *tile;
1626 	u8 id;
1627 
1628 	if (!xe_vm_has_scratch(vm))
1629 		return;
1630 
1631 	for_each_tile(tile, vm->xe, id) {
1632 		u32 i;
1633 
1634 		if (!vm->pt_root[id])
1635 			continue;
1636 
1637 		for (i = MAX_HUGEPTE_LEVEL; i < vm->pt_root[id]->level; ++i)
1638 			if (vm->scratch_pt[id][i])
1639 				xe_pt_destroy(vm->scratch_pt[id][i], vm->flags, NULL);
1640 	}
1641 }
1642 
1643 struct xe_vm *xe_vm_create(struct xe_device *xe, u32 flags, struct xe_file *xef)
1644 {
1645 	struct drm_gem_object *vm_resv_obj;
1646 	struct xe_vm *vm;
1647 	int err, number_tiles = 0;
1648 	struct xe_tile *tile;
1649 	u8 id;
1650 
1651 	/*
1652 	 * Since the GSCCS is not user-accessible, we don't expect a GSC VM to
1653 	 * ever be in faulting mode.
1654 	 */
1655 	xe_assert(xe, !((flags & XE_VM_FLAG_GSC) && (flags & XE_VM_FLAG_FAULT_MODE)));
1656 
1657 	vm = kzalloc(sizeof(*vm), GFP_KERNEL);
1658 	if (!vm)
1659 		return ERR_PTR(-ENOMEM);
1660 
1661 	vm->xe = xe;
1662 
1663 	vm->size = 1ull << xe->info.va_bits;
1664 	vm->flags = flags;
1665 
1666 	if (xef)
1667 		vm->xef = xe_file_get(xef);
1668 	/**
1669 	 * GSC VMs are kernel-owned, only used for PXP ops and can sometimes be
1670 	 * manipulated under the PXP mutex. However, the PXP mutex can be taken
1671 	 * under a user-VM lock when the PXP session is started at exec_queue
1672 	 * creation time. Those are different VMs and therefore there is no risk
1673 	 * of deadlock, but we need to tell lockdep that this is the case or it
1674 	 * will print a warning.
1675 	 */
1676 	if (flags & XE_VM_FLAG_GSC) {
1677 		static struct lock_class_key gsc_vm_key;
1678 
1679 		__init_rwsem(&vm->lock, "gsc_vm", &gsc_vm_key);
1680 	} else {
1681 		init_rwsem(&vm->lock);
1682 	}
1683 	mutex_init(&vm->snap_mutex);
1684 
1685 	INIT_LIST_HEAD(&vm->rebind_list);
1686 
1687 	INIT_LIST_HEAD(&vm->userptr.repin_list);
1688 	INIT_LIST_HEAD(&vm->userptr.invalidated);
1689 	init_rwsem(&vm->userptr.notifier_lock);
1690 	spin_lock_init(&vm->userptr.invalidated_lock);
1691 
1692 	ttm_lru_bulk_move_init(&vm->lru_bulk_move);
1693 
1694 	INIT_WORK(&vm->destroy_work, vm_destroy_work_func);
1695 
1696 	INIT_LIST_HEAD(&vm->preempt.exec_queues);
1697 	vm->preempt.min_run_period_ms = 10;	/* FIXME: Wire up to uAPI */
1698 
1699 	for_each_tile(tile, xe, id)
1700 		xe_range_fence_tree_init(&vm->rftree[id]);
1701 
1702 	vm->pt_ops = &xelp_pt_ops;
1703 
1704 	/*
1705 	 * Long-running workloads are not protected by the scheduler references.
1706 	 * By design, run_job for long-running workloads returns NULL and the
1707 	 * scheduler drops all the references of it, hence protecting the VM
1708 	 * for this case is necessary.
1709 	 */
1710 	if (flags & XE_VM_FLAG_LR_MODE) {
1711 		INIT_WORK(&vm->preempt.rebind_work, preempt_rebind_work_func);
1712 		xe_pm_runtime_get_noresume(xe);
1713 	}
1714 
1715 	if (flags & XE_VM_FLAG_FAULT_MODE) {
1716 		err = xe_svm_init(vm);
1717 		if (err)
1718 			goto err_no_resv;
1719 	}
1720 
1721 	vm_resv_obj = drm_gpuvm_resv_object_alloc(&xe->drm);
1722 	if (!vm_resv_obj) {
1723 		err = -ENOMEM;
1724 		goto err_svm_fini;
1725 	}
1726 
1727 	drm_gpuvm_init(&vm->gpuvm, "Xe VM", DRM_GPUVM_RESV_PROTECTED, &xe->drm,
1728 		       vm_resv_obj, 0, vm->size, 0, 0, &gpuvm_ops);
1729 
1730 	drm_gem_object_put(vm_resv_obj);
1731 
1732 	err = xe_vm_lock(vm, true);
1733 	if (err)
1734 		goto err_close;
1735 
1736 	if (IS_DGFX(xe) && xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K)
1737 		vm->flags |= XE_VM_FLAG_64K;
1738 
1739 	for_each_tile(tile, xe, id) {
1740 		if (flags & XE_VM_FLAG_MIGRATION &&
1741 		    tile->id != XE_VM_FLAG_TILE_ID(flags))
1742 			continue;
1743 
1744 		vm->pt_root[id] = xe_pt_create(vm, tile, xe->info.vm_max_level);
1745 		if (IS_ERR(vm->pt_root[id])) {
1746 			err = PTR_ERR(vm->pt_root[id]);
1747 			vm->pt_root[id] = NULL;
1748 			goto err_unlock_close;
1749 		}
1750 	}
1751 
1752 	if (xe_vm_has_scratch(vm)) {
1753 		for_each_tile(tile, xe, id) {
1754 			if (!vm->pt_root[id])
1755 				continue;
1756 
1757 			err = xe_vm_create_scratch(xe, tile, vm);
1758 			if (err)
1759 				goto err_unlock_close;
1760 		}
1761 		vm->batch_invalidate_tlb = true;
1762 	}
1763 
1764 	if (vm->flags & XE_VM_FLAG_LR_MODE)
1765 		vm->batch_invalidate_tlb = false;
1766 
1767 	/* Fill pt_root after allocating scratch tables */
1768 	for_each_tile(tile, xe, id) {
1769 		if (!vm->pt_root[id])
1770 			continue;
1771 
1772 		xe_pt_populate_empty(tile, vm, vm->pt_root[id]);
1773 	}
1774 	xe_vm_unlock(vm);
1775 
1776 	/* Kernel migration VM shouldn't have a circular loop.. */
1777 	if (!(flags & XE_VM_FLAG_MIGRATION)) {
1778 		for_each_tile(tile, xe, id) {
1779 			struct xe_exec_queue *q;
1780 			u32 create_flags = EXEC_QUEUE_FLAG_VM;
1781 
1782 			if (!vm->pt_root[id])
1783 				continue;
1784 
1785 			q = xe_exec_queue_create_bind(xe, tile, create_flags, 0);
1786 			if (IS_ERR(q)) {
1787 				err = PTR_ERR(q);
1788 				goto err_close;
1789 			}
1790 			vm->q[id] = q;
1791 			number_tiles++;
1792 		}
1793 	}
1794 
1795 	if (number_tiles > 1)
1796 		vm->composite_fence_ctx = dma_fence_context_alloc(1);
1797 
1798 	if (xef && xe->info.has_asid) {
1799 		u32 asid;
1800 
1801 		down_write(&xe->usm.lock);
1802 		err = xa_alloc_cyclic(&xe->usm.asid_to_vm, &asid, vm,
1803 				      XA_LIMIT(1, XE_MAX_ASID - 1),
1804 				      &xe->usm.next_asid, GFP_KERNEL);
1805 		up_write(&xe->usm.lock);
1806 		if (err < 0)
1807 			goto err_unlock_close;
1808 
1809 		vm->usm.asid = asid;
1810 	}
1811 
1812 	trace_xe_vm_create(vm);
1813 
1814 	return vm;
1815 
1816 err_unlock_close:
1817 	xe_vm_unlock(vm);
1818 err_close:
1819 	xe_vm_close_and_put(vm);
1820 	return ERR_PTR(err);
1821 
1822 err_svm_fini:
1823 	if (flags & XE_VM_FLAG_FAULT_MODE) {
1824 		vm->size = 0; /* close the vm */
1825 		xe_svm_fini(vm);
1826 	}
1827 err_no_resv:
1828 	mutex_destroy(&vm->snap_mutex);
1829 	for_each_tile(tile, xe, id)
1830 		xe_range_fence_tree_fini(&vm->rftree[id]);
1831 	ttm_lru_bulk_move_fini(&xe->ttm, &vm->lru_bulk_move);
1832 	if (vm->xef)
1833 		xe_file_put(vm->xef);
1834 	kfree(vm);
1835 	if (flags & XE_VM_FLAG_LR_MODE)
1836 		xe_pm_runtime_put(xe);
1837 	return ERR_PTR(err);
1838 }
1839 
1840 static void xe_vm_close(struct xe_vm *vm)
1841 {
1842 	struct xe_device *xe = vm->xe;
1843 	bool bound;
1844 	int idx;
1845 
1846 	bound = drm_dev_enter(&xe->drm, &idx);
1847 
1848 	down_write(&vm->lock);
1849 	if (xe_vm_in_fault_mode(vm))
1850 		xe_svm_notifier_lock(vm);
1851 
1852 	vm->size = 0;
1853 
1854 	if (!((vm->flags & XE_VM_FLAG_MIGRATION))) {
1855 		struct xe_tile *tile;
1856 		struct xe_gt *gt;
1857 		u8 id;
1858 
1859 		/* Wait for pending binds */
1860 		dma_resv_wait_timeout(xe_vm_resv(vm),
1861 				      DMA_RESV_USAGE_BOOKKEEP,
1862 				      false, MAX_SCHEDULE_TIMEOUT);
1863 
1864 		if (bound) {
1865 			for_each_tile(tile, xe, id)
1866 				if (vm->pt_root[id])
1867 					xe_pt_clear(xe, vm->pt_root[id]);
1868 
1869 			for_each_gt(gt, xe, id)
1870 				xe_gt_tlb_invalidation_vm(gt, vm);
1871 		}
1872 	}
1873 
1874 	if (xe_vm_in_fault_mode(vm))
1875 		xe_svm_notifier_unlock(vm);
1876 	up_write(&vm->lock);
1877 
1878 	if (bound)
1879 		drm_dev_exit(idx);
1880 }
1881 
1882 void xe_vm_close_and_put(struct xe_vm *vm)
1883 {
1884 	LIST_HEAD(contested);
1885 	struct xe_device *xe = vm->xe;
1886 	struct xe_tile *tile;
1887 	struct xe_vma *vma, *next_vma;
1888 	struct drm_gpuva *gpuva, *next;
1889 	u8 id;
1890 
1891 	xe_assert(xe, !vm->preempt.num_exec_queues);
1892 
1893 	xe_vm_close(vm);
1894 	if (xe_vm_in_preempt_fence_mode(vm))
1895 		flush_work(&vm->preempt.rebind_work);
1896 	if (xe_vm_in_fault_mode(vm))
1897 		xe_svm_close(vm);
1898 
1899 	down_write(&vm->lock);
1900 	for_each_tile(tile, xe, id) {
1901 		if (vm->q[id])
1902 			xe_exec_queue_last_fence_put(vm->q[id], vm);
1903 	}
1904 	up_write(&vm->lock);
1905 
1906 	for_each_tile(tile, xe, id) {
1907 		if (vm->q[id]) {
1908 			xe_exec_queue_kill(vm->q[id]);
1909 			xe_exec_queue_put(vm->q[id]);
1910 			vm->q[id] = NULL;
1911 		}
1912 	}
1913 
1914 	down_write(&vm->lock);
1915 	xe_vm_lock(vm, false);
1916 	drm_gpuvm_for_each_va_safe(gpuva, next, &vm->gpuvm) {
1917 		vma = gpuva_to_vma(gpuva);
1918 
1919 		if (xe_vma_has_no_bo(vma)) {
1920 			down_read(&vm->userptr.notifier_lock);
1921 			vma->gpuva.flags |= XE_VMA_DESTROYED;
1922 			up_read(&vm->userptr.notifier_lock);
1923 		}
1924 
1925 		xe_vm_remove_vma(vm, vma);
1926 
1927 		/* easy case, remove from VMA? */
1928 		if (xe_vma_has_no_bo(vma) || xe_vma_bo(vma)->vm) {
1929 			list_del_init(&vma->combined_links.rebind);
1930 			xe_vma_destroy(vma, NULL);
1931 			continue;
1932 		}
1933 
1934 		list_move_tail(&vma->combined_links.destroy, &contested);
1935 		vma->gpuva.flags |= XE_VMA_DESTROYED;
1936 	}
1937 
1938 	/*
1939 	 * All vm operations will add shared fences to resv.
1940 	 * The only exception is eviction for a shared object,
1941 	 * but even so, the unbind when evicted would still
1942 	 * install a fence to resv. Hence it's safe to
1943 	 * destroy the pagetables immediately.
1944 	 */
1945 	xe_vm_free_scratch(vm);
1946 
1947 	for_each_tile(tile, xe, id) {
1948 		if (vm->pt_root[id]) {
1949 			xe_pt_destroy(vm->pt_root[id], vm->flags, NULL);
1950 			vm->pt_root[id] = NULL;
1951 		}
1952 	}
1953 	xe_vm_unlock(vm);
1954 
1955 	/*
1956 	 * VM is now dead, cannot re-add nodes to vm->vmas if it's NULL
1957 	 * Since we hold a refcount to the bo, we can remove and free
1958 	 * the members safely without locking.
1959 	 */
1960 	list_for_each_entry_safe(vma, next_vma, &contested,
1961 				 combined_links.destroy) {
1962 		list_del_init(&vma->combined_links.destroy);
1963 		xe_vma_destroy_unlocked(vma);
1964 	}
1965 
1966 	if (xe_vm_in_fault_mode(vm))
1967 		xe_svm_fini(vm);
1968 
1969 	up_write(&vm->lock);
1970 
1971 	down_write(&xe->usm.lock);
1972 	if (vm->usm.asid) {
1973 		void *lookup;
1974 
1975 		xe_assert(xe, xe->info.has_asid);
1976 		xe_assert(xe, !(vm->flags & XE_VM_FLAG_MIGRATION));
1977 
1978 		lookup = xa_erase(&xe->usm.asid_to_vm, vm->usm.asid);
1979 		xe_assert(xe, lookup == vm);
1980 	}
1981 	up_write(&xe->usm.lock);
1982 
1983 	for_each_tile(tile, xe, id)
1984 		xe_range_fence_tree_fini(&vm->rftree[id]);
1985 
1986 	xe_vm_put(vm);
1987 }
1988 
1989 static void vm_destroy_work_func(struct work_struct *w)
1990 {
1991 	struct xe_vm *vm =
1992 		container_of(w, struct xe_vm, destroy_work);
1993 	struct xe_device *xe = vm->xe;
1994 	struct xe_tile *tile;
1995 	u8 id;
1996 
1997 	/* xe_vm_close_and_put was not called? */
1998 	xe_assert(xe, !vm->size);
1999 
2000 	if (xe_vm_in_preempt_fence_mode(vm))
2001 		flush_work(&vm->preempt.rebind_work);
2002 
2003 	mutex_destroy(&vm->snap_mutex);
2004 
2005 	if (vm->flags & XE_VM_FLAG_LR_MODE)
2006 		xe_pm_runtime_put(xe);
2007 
2008 	for_each_tile(tile, xe, id)
2009 		XE_WARN_ON(vm->pt_root[id]);
2010 
2011 	trace_xe_vm_free(vm);
2012 
2013 	ttm_lru_bulk_move_fini(&xe->ttm, &vm->lru_bulk_move);
2014 
2015 	if (vm->xef)
2016 		xe_file_put(vm->xef);
2017 
2018 	kfree(vm);
2019 }
2020 
2021 static void xe_vm_free(struct drm_gpuvm *gpuvm)
2022 {
2023 	struct xe_vm *vm = container_of(gpuvm, struct xe_vm, gpuvm);
2024 
2025 	/* To destroy the VM we need to be able to sleep */
2026 	queue_work(system_unbound_wq, &vm->destroy_work);
2027 }
2028 
2029 struct xe_vm *xe_vm_lookup(struct xe_file *xef, u32 id)
2030 {
2031 	struct xe_vm *vm;
2032 
2033 	mutex_lock(&xef->vm.lock);
2034 	vm = xa_load(&xef->vm.xa, id);
2035 	if (vm)
2036 		xe_vm_get(vm);
2037 	mutex_unlock(&xef->vm.lock);
2038 
2039 	return vm;
2040 }
2041 
2042 u64 xe_vm_pdp4_descriptor(struct xe_vm *vm, struct xe_tile *tile)
2043 {
2044 	return vm->pt_ops->pde_encode_bo(vm->pt_root[tile->id]->bo, 0,
2045 					 tile_to_xe(tile)->pat.idx[XE_CACHE_WB]);
2046 }
2047 
2048 static struct xe_exec_queue *
2049 to_wait_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q)
2050 {
2051 	return q ? q : vm->q[0];
2052 }
2053 
2054 static struct xe_user_fence *
2055 find_ufence_get(struct xe_sync_entry *syncs, u32 num_syncs)
2056 {
2057 	unsigned int i;
2058 
2059 	for (i = 0; i < num_syncs; i++) {
2060 		struct xe_sync_entry *e = &syncs[i];
2061 
2062 		if (xe_sync_is_ufence(e))
2063 			return xe_sync_ufence_get(e);
2064 	}
2065 
2066 	return NULL;
2067 }
2068 
2069 #define ALL_DRM_XE_VM_CREATE_FLAGS (DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE | \
2070 				    DRM_XE_VM_CREATE_FLAG_LR_MODE | \
2071 				    DRM_XE_VM_CREATE_FLAG_FAULT_MODE)
2072 
2073 int xe_vm_create_ioctl(struct drm_device *dev, void *data,
2074 		       struct drm_file *file)
2075 {
2076 	struct xe_device *xe = to_xe_device(dev);
2077 	struct xe_file *xef = to_xe_file(file);
2078 	struct drm_xe_vm_create *args = data;
2079 	struct xe_vm *vm;
2080 	u32 id;
2081 	int err;
2082 	u32 flags = 0;
2083 
2084 	if (XE_IOCTL_DBG(xe, args->extensions))
2085 		return -EINVAL;
2086 
2087 	if (XE_WA(xe_root_mmio_gt(xe), 14016763929))
2088 		args->flags |= DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE;
2089 
2090 	if (XE_IOCTL_DBG(xe, args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE &&
2091 			 !xe->info.has_usm))
2092 		return -EINVAL;
2093 
2094 	if (XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
2095 		return -EINVAL;
2096 
2097 	if (XE_IOCTL_DBG(xe, args->flags & ~ALL_DRM_XE_VM_CREATE_FLAGS))
2098 		return -EINVAL;
2099 
2100 	if (XE_IOCTL_DBG(xe, args->flags & DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE &&
2101 			 args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE &&
2102 			 !xe->info.needs_scratch))
2103 		return -EINVAL;
2104 
2105 	if (XE_IOCTL_DBG(xe, !(args->flags & DRM_XE_VM_CREATE_FLAG_LR_MODE) &&
2106 			 args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE))
2107 		return -EINVAL;
2108 
2109 	if (args->flags & DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE)
2110 		flags |= XE_VM_FLAG_SCRATCH_PAGE;
2111 	if (args->flags & DRM_XE_VM_CREATE_FLAG_LR_MODE)
2112 		flags |= XE_VM_FLAG_LR_MODE;
2113 	if (args->flags & DRM_XE_VM_CREATE_FLAG_FAULT_MODE)
2114 		flags |= XE_VM_FLAG_FAULT_MODE;
2115 
2116 	vm = xe_vm_create(xe, flags, xef);
2117 	if (IS_ERR(vm))
2118 		return PTR_ERR(vm);
2119 
2120 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_MEM)
2121 	/* Warning: Security issue - never enable by default */
2122 	args->reserved[0] = xe_bo_main_addr(vm->pt_root[0]->bo, XE_PAGE_SIZE);
2123 #endif
2124 
2125 	/* user id alloc must always be last in ioctl to prevent UAF */
2126 	err = xa_alloc(&xef->vm.xa, &id, vm, xa_limit_32b, GFP_KERNEL);
2127 	if (err)
2128 		goto err_close_and_put;
2129 
2130 	args->vm_id = id;
2131 
2132 	return 0;
2133 
2134 err_close_and_put:
2135 	xe_vm_close_and_put(vm);
2136 
2137 	return err;
2138 }
2139 
2140 int xe_vm_destroy_ioctl(struct drm_device *dev, void *data,
2141 			struct drm_file *file)
2142 {
2143 	struct xe_device *xe = to_xe_device(dev);
2144 	struct xe_file *xef = to_xe_file(file);
2145 	struct drm_xe_vm_destroy *args = data;
2146 	struct xe_vm *vm;
2147 	int err = 0;
2148 
2149 	if (XE_IOCTL_DBG(xe, args->pad) ||
2150 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
2151 		return -EINVAL;
2152 
2153 	mutex_lock(&xef->vm.lock);
2154 	vm = xa_load(&xef->vm.xa, args->vm_id);
2155 	if (XE_IOCTL_DBG(xe, !vm))
2156 		err = -ENOENT;
2157 	else if (XE_IOCTL_DBG(xe, vm->preempt.num_exec_queues))
2158 		err = -EBUSY;
2159 	else
2160 		xa_erase(&xef->vm.xa, args->vm_id);
2161 	mutex_unlock(&xef->vm.lock);
2162 
2163 	if (!err)
2164 		xe_vm_close_and_put(vm);
2165 
2166 	return err;
2167 }
2168 
2169 static bool vma_matches(struct xe_vma *vma, u64 page_addr)
2170 {
2171 	if (page_addr > xe_vma_end(vma) - 1 ||
2172 	    page_addr + SZ_4K - 1 < xe_vma_start(vma))
2173 		return false;
2174 
2175 	return true;
2176 }
2177 
2178 /**
2179  * xe_vm_find_vma_by_addr() - Find a VMA by its address
2180  *
2181  * @vm: the xe_vm the vma belongs to
2182  * @page_addr: address to look up
2183  */
2184 struct xe_vma *xe_vm_find_vma_by_addr(struct xe_vm *vm, u64 page_addr)
2185 {
2186 	struct xe_vma *vma = NULL;
2187 
2188 	if (vm->usm.last_fault_vma) {   /* Fast lookup */
2189 		if (vma_matches(vm->usm.last_fault_vma, page_addr))
2190 			vma = vm->usm.last_fault_vma;
2191 	}
2192 	if (!vma)
2193 		vma = xe_vm_find_overlapping_vma(vm, page_addr, SZ_4K);
2194 
2195 	return vma;
2196 }
2197 
2198 static const u32 region_to_mem_type[] = {
2199 	XE_PL_TT,
2200 	XE_PL_VRAM0,
2201 	XE_PL_VRAM1,
2202 };
2203 
2204 static void prep_vma_destroy(struct xe_vm *vm, struct xe_vma *vma,
2205 			     bool post_commit)
2206 {
2207 	down_read(&vm->userptr.notifier_lock);
2208 	vma->gpuva.flags |= XE_VMA_DESTROYED;
2209 	up_read(&vm->userptr.notifier_lock);
2210 	if (post_commit)
2211 		xe_vm_remove_vma(vm, vma);
2212 }
2213 
2214 #undef ULL
2215 #define ULL	unsigned long long
2216 
2217 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM)
2218 static void print_op(struct xe_device *xe, struct drm_gpuva_op *op)
2219 {
2220 	struct xe_vma *vma;
2221 
2222 	switch (op->op) {
2223 	case DRM_GPUVA_OP_MAP:
2224 		vm_dbg(&xe->drm, "MAP: addr=0x%016llx, range=0x%016llx",
2225 		       (ULL)op->map.va.addr, (ULL)op->map.va.range);
2226 		break;
2227 	case DRM_GPUVA_OP_REMAP:
2228 		vma = gpuva_to_vma(op->remap.unmap->va);
2229 		vm_dbg(&xe->drm, "REMAP:UNMAP: addr=0x%016llx, range=0x%016llx, keep=%d",
2230 		       (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma),
2231 		       op->remap.unmap->keep ? 1 : 0);
2232 		if (op->remap.prev)
2233 			vm_dbg(&xe->drm,
2234 			       "REMAP:PREV: addr=0x%016llx, range=0x%016llx",
2235 			       (ULL)op->remap.prev->va.addr,
2236 			       (ULL)op->remap.prev->va.range);
2237 		if (op->remap.next)
2238 			vm_dbg(&xe->drm,
2239 			       "REMAP:NEXT: addr=0x%016llx, range=0x%016llx",
2240 			       (ULL)op->remap.next->va.addr,
2241 			       (ULL)op->remap.next->va.range);
2242 		break;
2243 	case DRM_GPUVA_OP_UNMAP:
2244 		vma = gpuva_to_vma(op->unmap.va);
2245 		vm_dbg(&xe->drm, "UNMAP: addr=0x%016llx, range=0x%016llx, keep=%d",
2246 		       (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma),
2247 		       op->unmap.keep ? 1 : 0);
2248 		break;
2249 	case DRM_GPUVA_OP_PREFETCH:
2250 		vma = gpuva_to_vma(op->prefetch.va);
2251 		vm_dbg(&xe->drm, "PREFETCH: addr=0x%016llx, range=0x%016llx",
2252 		       (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma));
2253 		break;
2254 	default:
2255 		drm_warn(&xe->drm, "NOT POSSIBLE");
2256 	}
2257 }
2258 #else
2259 static void print_op(struct xe_device *xe, struct drm_gpuva_op *op)
2260 {
2261 }
2262 #endif
2263 
2264 static bool __xe_vm_needs_clear_scratch_pages(struct xe_vm *vm, u32 bind_flags)
2265 {
2266 	if (!xe_vm_in_fault_mode(vm))
2267 		return false;
2268 
2269 	if (!xe_vm_has_scratch(vm))
2270 		return false;
2271 
2272 	if (bind_flags & DRM_XE_VM_BIND_FLAG_IMMEDIATE)
2273 		return false;
2274 
2275 	return true;
2276 }
2277 
2278 static void xe_svm_prefetch_gpuva_ops_fini(struct drm_gpuva_ops *ops)
2279 {
2280 	struct drm_gpuva_op *__op;
2281 
2282 	drm_gpuva_for_each_op(__op, ops) {
2283 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2284 
2285 		xe_vma_svm_prefetch_op_fini(op);
2286 	}
2287 }
2288 
2289 /*
2290  * Create operations list from IOCTL arguments, setup operations fields so parse
2291  * and commit steps are decoupled from IOCTL arguments. This step can fail.
2292  */
2293 static struct drm_gpuva_ops *
2294 vm_bind_ioctl_ops_create(struct xe_vm *vm, struct xe_vma_ops *vops,
2295 			 struct xe_bo *bo, u64 bo_offset_or_userptr,
2296 			 u64 addr, u64 range,
2297 			 u32 operation, u32 flags,
2298 			 u32 prefetch_region, u16 pat_index)
2299 {
2300 	struct drm_gem_object *obj = bo ? &bo->ttm.base : NULL;
2301 	struct drm_gpuva_ops *ops;
2302 	struct drm_gpuva_op *__op;
2303 	struct drm_gpuvm_bo *vm_bo;
2304 	u64 range_end = addr + range;
2305 	int err;
2306 
2307 	lockdep_assert_held_write(&vm->lock);
2308 
2309 	vm_dbg(&vm->xe->drm,
2310 	       "op=%d, addr=0x%016llx, range=0x%016llx, bo_offset_or_userptr=0x%016llx",
2311 	       operation, (ULL)addr, (ULL)range,
2312 	       (ULL)bo_offset_or_userptr);
2313 
2314 	switch (operation) {
2315 	case DRM_XE_VM_BIND_OP_MAP:
2316 	case DRM_XE_VM_BIND_OP_MAP_USERPTR:
2317 		ops = drm_gpuvm_sm_map_ops_create(&vm->gpuvm, addr, range,
2318 						  obj, bo_offset_or_userptr);
2319 		break;
2320 	case DRM_XE_VM_BIND_OP_UNMAP:
2321 		ops = drm_gpuvm_sm_unmap_ops_create(&vm->gpuvm, addr, range);
2322 		break;
2323 	case DRM_XE_VM_BIND_OP_PREFETCH:
2324 		ops = drm_gpuvm_prefetch_ops_create(&vm->gpuvm, addr, range);
2325 		break;
2326 	case DRM_XE_VM_BIND_OP_UNMAP_ALL:
2327 		xe_assert(vm->xe, bo);
2328 
2329 		err = xe_bo_lock(bo, true);
2330 		if (err)
2331 			return ERR_PTR(err);
2332 
2333 		vm_bo = drm_gpuvm_bo_obtain(&vm->gpuvm, obj);
2334 		if (IS_ERR(vm_bo)) {
2335 			xe_bo_unlock(bo);
2336 			return ERR_CAST(vm_bo);
2337 		}
2338 
2339 		ops = drm_gpuvm_bo_unmap_ops_create(vm_bo);
2340 		drm_gpuvm_bo_put(vm_bo);
2341 		xe_bo_unlock(bo);
2342 		break;
2343 	default:
2344 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2345 		ops = ERR_PTR(-EINVAL);
2346 	}
2347 	if (IS_ERR(ops))
2348 		return ops;
2349 
2350 	drm_gpuva_for_each_op(__op, ops) {
2351 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2352 
2353 		if (__op->op == DRM_GPUVA_OP_MAP) {
2354 			op->map.immediate =
2355 				flags & DRM_XE_VM_BIND_FLAG_IMMEDIATE;
2356 			op->map.read_only =
2357 				flags & DRM_XE_VM_BIND_FLAG_READONLY;
2358 			op->map.is_null = flags & DRM_XE_VM_BIND_FLAG_NULL;
2359 			op->map.is_cpu_addr_mirror = flags &
2360 				DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR;
2361 			op->map.dumpable = flags & DRM_XE_VM_BIND_FLAG_DUMPABLE;
2362 			op->map.pat_index = pat_index;
2363 			op->map.invalidate_on_bind =
2364 				__xe_vm_needs_clear_scratch_pages(vm, flags);
2365 		} else if (__op->op == DRM_GPUVA_OP_PREFETCH) {
2366 			struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2367 			struct xe_svm_range *svm_range;
2368 			struct drm_gpusvm_ctx ctx = {};
2369 			struct xe_tile *tile;
2370 			u8 id, tile_mask = 0;
2371 			u32 i;
2372 
2373 			if (!xe_vma_is_cpu_addr_mirror(vma)) {
2374 				op->prefetch.region = prefetch_region;
2375 				break;
2376 			}
2377 
2378 			ctx.read_only = xe_vma_read_only(vma);
2379 			ctx.devmem_possible = IS_DGFX(vm->xe) &&
2380 					      IS_ENABLED(CONFIG_DRM_XE_PAGEMAP);
2381 
2382 			for_each_tile(tile, vm->xe, id)
2383 				tile_mask |= 0x1 << id;
2384 
2385 			xa_init_flags(&op->prefetch_range.range, XA_FLAGS_ALLOC);
2386 			op->prefetch_range.region = prefetch_region;
2387 			op->prefetch_range.ranges_count = 0;
2388 alloc_next_range:
2389 			svm_range = xe_svm_range_find_or_insert(vm, addr, vma, &ctx);
2390 
2391 			if (PTR_ERR(svm_range) == -ENOENT) {
2392 				u64 ret = xe_svm_find_vma_start(vm, addr, range_end, vma);
2393 
2394 				addr = ret == ULONG_MAX ? 0 : ret;
2395 				if (addr)
2396 					goto alloc_next_range;
2397 				else
2398 					goto print_op_label;
2399 			}
2400 
2401 			if (IS_ERR(svm_range)) {
2402 				err = PTR_ERR(svm_range);
2403 				goto unwind_prefetch_ops;
2404 			}
2405 
2406 			if (xe_svm_range_validate(vm, svm_range, tile_mask, !!prefetch_region)) {
2407 				xe_svm_range_debug(svm_range, "PREFETCH - RANGE IS VALID");
2408 				goto check_next_range;
2409 			}
2410 
2411 			err = xa_alloc(&op->prefetch_range.range,
2412 				       &i, svm_range, xa_limit_32b,
2413 				       GFP_KERNEL);
2414 
2415 			if (err)
2416 				goto unwind_prefetch_ops;
2417 
2418 			op->prefetch_range.ranges_count++;
2419 			vops->flags |= XE_VMA_OPS_FLAG_HAS_SVM_PREFETCH;
2420 			xe_svm_range_debug(svm_range, "PREFETCH - RANGE CREATED");
2421 check_next_range:
2422 			if (range_end > xe_svm_range_end(svm_range) &&
2423 			    xe_svm_range_end(svm_range) < xe_vma_end(vma)) {
2424 				addr = xe_svm_range_end(svm_range);
2425 				goto alloc_next_range;
2426 			}
2427 		}
2428 print_op_label:
2429 		print_op(vm->xe, __op);
2430 	}
2431 
2432 	return ops;
2433 
2434 unwind_prefetch_ops:
2435 	xe_svm_prefetch_gpuva_ops_fini(ops);
2436 	drm_gpuva_ops_free(&vm->gpuvm, ops);
2437 	return ERR_PTR(err);
2438 }
2439 
2440 ALLOW_ERROR_INJECTION(vm_bind_ioctl_ops_create, ERRNO);
2441 
2442 static struct xe_vma *new_vma(struct xe_vm *vm, struct drm_gpuva_op_map *op,
2443 			      u16 pat_index, unsigned int flags)
2444 {
2445 	struct xe_bo *bo = op->gem.obj ? gem_to_xe_bo(op->gem.obj) : NULL;
2446 	struct drm_exec exec;
2447 	struct xe_vma *vma;
2448 	int err = 0;
2449 
2450 	lockdep_assert_held_write(&vm->lock);
2451 
2452 	if (bo) {
2453 		drm_exec_init(&exec, DRM_EXEC_INTERRUPTIBLE_WAIT, 0);
2454 		drm_exec_until_all_locked(&exec) {
2455 			err = 0;
2456 			if (!bo->vm) {
2457 				err = drm_exec_lock_obj(&exec, xe_vm_obj(vm));
2458 				drm_exec_retry_on_contention(&exec);
2459 			}
2460 			if (!err) {
2461 				err = drm_exec_lock_obj(&exec, &bo->ttm.base);
2462 				drm_exec_retry_on_contention(&exec);
2463 			}
2464 			if (err) {
2465 				drm_exec_fini(&exec);
2466 				return ERR_PTR(err);
2467 			}
2468 		}
2469 	}
2470 	vma = xe_vma_create(vm, bo, op->gem.offset,
2471 			    op->va.addr, op->va.addr +
2472 			    op->va.range - 1, pat_index, flags);
2473 	if (IS_ERR(vma))
2474 		goto err_unlock;
2475 
2476 	if (xe_vma_is_userptr(vma))
2477 		err = xe_vma_userptr_pin_pages(to_userptr_vma(vma));
2478 	else if (!xe_vma_has_no_bo(vma) && !bo->vm)
2479 		err = add_preempt_fences(vm, bo);
2480 
2481 err_unlock:
2482 	if (bo)
2483 		drm_exec_fini(&exec);
2484 
2485 	if (err) {
2486 		prep_vma_destroy(vm, vma, false);
2487 		xe_vma_destroy_unlocked(vma);
2488 		vma = ERR_PTR(err);
2489 	}
2490 
2491 	return vma;
2492 }
2493 
2494 static u64 xe_vma_max_pte_size(struct xe_vma *vma)
2495 {
2496 	if (vma->gpuva.flags & XE_VMA_PTE_1G)
2497 		return SZ_1G;
2498 	else if (vma->gpuva.flags & (XE_VMA_PTE_2M | XE_VMA_PTE_COMPACT))
2499 		return SZ_2M;
2500 	else if (vma->gpuva.flags & XE_VMA_PTE_64K)
2501 		return SZ_64K;
2502 	else if (vma->gpuva.flags & XE_VMA_PTE_4K)
2503 		return SZ_4K;
2504 
2505 	return SZ_1G;	/* Uninitialized, used max size */
2506 }
2507 
2508 static void xe_vma_set_pte_size(struct xe_vma *vma, u64 size)
2509 {
2510 	switch (size) {
2511 	case SZ_1G:
2512 		vma->gpuva.flags |= XE_VMA_PTE_1G;
2513 		break;
2514 	case SZ_2M:
2515 		vma->gpuva.flags |= XE_VMA_PTE_2M;
2516 		break;
2517 	case SZ_64K:
2518 		vma->gpuva.flags |= XE_VMA_PTE_64K;
2519 		break;
2520 	case SZ_4K:
2521 		vma->gpuva.flags |= XE_VMA_PTE_4K;
2522 		break;
2523 	}
2524 }
2525 
2526 static int xe_vma_op_commit(struct xe_vm *vm, struct xe_vma_op *op)
2527 {
2528 	int err = 0;
2529 
2530 	lockdep_assert_held_write(&vm->lock);
2531 
2532 	switch (op->base.op) {
2533 	case DRM_GPUVA_OP_MAP:
2534 		err |= xe_vm_insert_vma(vm, op->map.vma);
2535 		if (!err)
2536 			op->flags |= XE_VMA_OP_COMMITTED;
2537 		break;
2538 	case DRM_GPUVA_OP_REMAP:
2539 	{
2540 		u8 tile_present =
2541 			gpuva_to_vma(op->base.remap.unmap->va)->tile_present;
2542 
2543 		prep_vma_destroy(vm, gpuva_to_vma(op->base.remap.unmap->va),
2544 				 true);
2545 		op->flags |= XE_VMA_OP_COMMITTED;
2546 
2547 		if (op->remap.prev) {
2548 			err |= xe_vm_insert_vma(vm, op->remap.prev);
2549 			if (!err)
2550 				op->flags |= XE_VMA_OP_PREV_COMMITTED;
2551 			if (!err && op->remap.skip_prev) {
2552 				op->remap.prev->tile_present =
2553 					tile_present;
2554 				op->remap.prev = NULL;
2555 			}
2556 		}
2557 		if (op->remap.next) {
2558 			err |= xe_vm_insert_vma(vm, op->remap.next);
2559 			if (!err)
2560 				op->flags |= XE_VMA_OP_NEXT_COMMITTED;
2561 			if (!err && op->remap.skip_next) {
2562 				op->remap.next->tile_present =
2563 					tile_present;
2564 				op->remap.next = NULL;
2565 			}
2566 		}
2567 
2568 		/* Adjust for partial unbind after removing VMA from VM */
2569 		if (!err) {
2570 			op->base.remap.unmap->va->va.addr = op->remap.start;
2571 			op->base.remap.unmap->va->va.range = op->remap.range;
2572 		}
2573 		break;
2574 	}
2575 	case DRM_GPUVA_OP_UNMAP:
2576 		prep_vma_destroy(vm, gpuva_to_vma(op->base.unmap.va), true);
2577 		op->flags |= XE_VMA_OP_COMMITTED;
2578 		break;
2579 	case DRM_GPUVA_OP_PREFETCH:
2580 		op->flags |= XE_VMA_OP_COMMITTED;
2581 		break;
2582 	default:
2583 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2584 	}
2585 
2586 	return err;
2587 }
2588 
2589 static int vm_bind_ioctl_ops_parse(struct xe_vm *vm, struct drm_gpuva_ops *ops,
2590 				   struct xe_vma_ops *vops)
2591 {
2592 	struct xe_device *xe = vm->xe;
2593 	struct drm_gpuva_op *__op;
2594 	struct xe_tile *tile;
2595 	u8 id, tile_mask = 0;
2596 	int err = 0;
2597 
2598 	lockdep_assert_held_write(&vm->lock);
2599 
2600 	for_each_tile(tile, vm->xe, id)
2601 		tile_mask |= 0x1 << id;
2602 
2603 	drm_gpuva_for_each_op(__op, ops) {
2604 		struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2605 		struct xe_vma *vma;
2606 		unsigned int flags = 0;
2607 
2608 		INIT_LIST_HEAD(&op->link);
2609 		list_add_tail(&op->link, &vops->list);
2610 		op->tile_mask = tile_mask;
2611 
2612 		switch (op->base.op) {
2613 		case DRM_GPUVA_OP_MAP:
2614 		{
2615 			flags |= op->map.read_only ?
2616 				VMA_CREATE_FLAG_READ_ONLY : 0;
2617 			flags |= op->map.is_null ?
2618 				VMA_CREATE_FLAG_IS_NULL : 0;
2619 			flags |= op->map.dumpable ?
2620 				VMA_CREATE_FLAG_DUMPABLE : 0;
2621 			flags |= op->map.is_cpu_addr_mirror ?
2622 				VMA_CREATE_FLAG_IS_SYSTEM_ALLOCATOR : 0;
2623 
2624 			vma = new_vma(vm, &op->base.map, op->map.pat_index,
2625 				      flags);
2626 			if (IS_ERR(vma))
2627 				return PTR_ERR(vma);
2628 
2629 			op->map.vma = vma;
2630 			if (((op->map.immediate || !xe_vm_in_fault_mode(vm)) &&
2631 			     !op->map.is_cpu_addr_mirror) ||
2632 			    op->map.invalidate_on_bind)
2633 				xe_vma_ops_incr_pt_update_ops(vops,
2634 							      op->tile_mask, 1);
2635 			break;
2636 		}
2637 		case DRM_GPUVA_OP_REMAP:
2638 		{
2639 			struct xe_vma *old =
2640 				gpuva_to_vma(op->base.remap.unmap->va);
2641 			bool skip = xe_vma_is_cpu_addr_mirror(old);
2642 			u64 start = xe_vma_start(old), end = xe_vma_end(old);
2643 			int num_remap_ops = 0;
2644 
2645 			if (op->base.remap.prev)
2646 				start = op->base.remap.prev->va.addr +
2647 					op->base.remap.prev->va.range;
2648 			if (op->base.remap.next)
2649 				end = op->base.remap.next->va.addr;
2650 
2651 			if (xe_vma_is_cpu_addr_mirror(old) &&
2652 			    xe_svm_has_mapping(vm, start, end))
2653 				return -EBUSY;
2654 
2655 			op->remap.start = xe_vma_start(old);
2656 			op->remap.range = xe_vma_size(old);
2657 
2658 			flags |= op->base.remap.unmap->va->flags &
2659 				XE_VMA_READ_ONLY ?
2660 				VMA_CREATE_FLAG_READ_ONLY : 0;
2661 			flags |= op->base.remap.unmap->va->flags &
2662 				DRM_GPUVA_SPARSE ?
2663 				VMA_CREATE_FLAG_IS_NULL : 0;
2664 			flags |= op->base.remap.unmap->va->flags &
2665 				XE_VMA_DUMPABLE ?
2666 				VMA_CREATE_FLAG_DUMPABLE : 0;
2667 			flags |= xe_vma_is_cpu_addr_mirror(old) ?
2668 				VMA_CREATE_FLAG_IS_SYSTEM_ALLOCATOR : 0;
2669 
2670 			if (op->base.remap.prev) {
2671 				vma = new_vma(vm, op->base.remap.prev,
2672 					      old->pat_index, flags);
2673 				if (IS_ERR(vma))
2674 					return PTR_ERR(vma);
2675 
2676 				op->remap.prev = vma;
2677 
2678 				/*
2679 				 * Userptr creates a new SG mapping so
2680 				 * we must also rebind.
2681 				 */
2682 				op->remap.skip_prev = skip ||
2683 					(!xe_vma_is_userptr(old) &&
2684 					IS_ALIGNED(xe_vma_end(vma),
2685 						   xe_vma_max_pte_size(old)));
2686 				if (op->remap.skip_prev) {
2687 					xe_vma_set_pte_size(vma, xe_vma_max_pte_size(old));
2688 					op->remap.range -=
2689 						xe_vma_end(vma) -
2690 						xe_vma_start(old);
2691 					op->remap.start = xe_vma_end(vma);
2692 					vm_dbg(&xe->drm, "REMAP:SKIP_PREV: addr=0x%016llx, range=0x%016llx",
2693 					       (ULL)op->remap.start,
2694 					       (ULL)op->remap.range);
2695 				} else {
2696 					num_remap_ops++;
2697 				}
2698 			}
2699 
2700 			if (op->base.remap.next) {
2701 				vma = new_vma(vm, op->base.remap.next,
2702 					      old->pat_index, flags);
2703 				if (IS_ERR(vma))
2704 					return PTR_ERR(vma);
2705 
2706 				op->remap.next = vma;
2707 
2708 				/*
2709 				 * Userptr creates a new SG mapping so
2710 				 * we must also rebind.
2711 				 */
2712 				op->remap.skip_next = skip ||
2713 					(!xe_vma_is_userptr(old) &&
2714 					IS_ALIGNED(xe_vma_start(vma),
2715 						   xe_vma_max_pte_size(old)));
2716 				if (op->remap.skip_next) {
2717 					xe_vma_set_pte_size(vma, xe_vma_max_pte_size(old));
2718 					op->remap.range -=
2719 						xe_vma_end(old) -
2720 						xe_vma_start(vma);
2721 					vm_dbg(&xe->drm, "REMAP:SKIP_NEXT: addr=0x%016llx, range=0x%016llx",
2722 					       (ULL)op->remap.start,
2723 					       (ULL)op->remap.range);
2724 				} else {
2725 					num_remap_ops++;
2726 				}
2727 			}
2728 			if (!skip)
2729 				num_remap_ops++;
2730 
2731 			xe_vma_ops_incr_pt_update_ops(vops, op->tile_mask, num_remap_ops);
2732 			break;
2733 		}
2734 		case DRM_GPUVA_OP_UNMAP:
2735 			vma = gpuva_to_vma(op->base.unmap.va);
2736 
2737 			if (xe_vma_is_cpu_addr_mirror(vma) &&
2738 			    xe_svm_has_mapping(vm, xe_vma_start(vma),
2739 					       xe_vma_end(vma)))
2740 				return -EBUSY;
2741 
2742 			if (!xe_vma_is_cpu_addr_mirror(vma))
2743 				xe_vma_ops_incr_pt_update_ops(vops, op->tile_mask, 1);
2744 			break;
2745 		case DRM_GPUVA_OP_PREFETCH:
2746 			vma = gpuva_to_vma(op->base.prefetch.va);
2747 
2748 			if (xe_vma_is_userptr(vma)) {
2749 				err = xe_vma_userptr_pin_pages(to_userptr_vma(vma));
2750 				if (err)
2751 					return err;
2752 			}
2753 
2754 			if (xe_vma_is_cpu_addr_mirror(vma))
2755 				xe_vma_ops_incr_pt_update_ops(vops, op->tile_mask,
2756 							      op->prefetch_range.ranges_count);
2757 			else
2758 				xe_vma_ops_incr_pt_update_ops(vops, op->tile_mask, 1);
2759 
2760 			break;
2761 		default:
2762 			drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2763 		}
2764 
2765 		err = xe_vma_op_commit(vm, op);
2766 		if (err)
2767 			return err;
2768 	}
2769 
2770 	return 0;
2771 }
2772 
2773 static void xe_vma_op_unwind(struct xe_vm *vm, struct xe_vma_op *op,
2774 			     bool post_commit, bool prev_post_commit,
2775 			     bool next_post_commit)
2776 {
2777 	lockdep_assert_held_write(&vm->lock);
2778 
2779 	switch (op->base.op) {
2780 	case DRM_GPUVA_OP_MAP:
2781 		if (op->map.vma) {
2782 			prep_vma_destroy(vm, op->map.vma, post_commit);
2783 			xe_vma_destroy_unlocked(op->map.vma);
2784 		}
2785 		break;
2786 	case DRM_GPUVA_OP_UNMAP:
2787 	{
2788 		struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
2789 
2790 		if (vma) {
2791 			down_read(&vm->userptr.notifier_lock);
2792 			vma->gpuva.flags &= ~XE_VMA_DESTROYED;
2793 			up_read(&vm->userptr.notifier_lock);
2794 			if (post_commit)
2795 				xe_vm_insert_vma(vm, vma);
2796 		}
2797 		break;
2798 	}
2799 	case DRM_GPUVA_OP_REMAP:
2800 	{
2801 		struct xe_vma *vma = gpuva_to_vma(op->base.remap.unmap->va);
2802 
2803 		if (op->remap.prev) {
2804 			prep_vma_destroy(vm, op->remap.prev, prev_post_commit);
2805 			xe_vma_destroy_unlocked(op->remap.prev);
2806 		}
2807 		if (op->remap.next) {
2808 			prep_vma_destroy(vm, op->remap.next, next_post_commit);
2809 			xe_vma_destroy_unlocked(op->remap.next);
2810 		}
2811 		if (vma) {
2812 			down_read(&vm->userptr.notifier_lock);
2813 			vma->gpuva.flags &= ~XE_VMA_DESTROYED;
2814 			up_read(&vm->userptr.notifier_lock);
2815 			if (post_commit)
2816 				xe_vm_insert_vma(vm, vma);
2817 		}
2818 		break;
2819 	}
2820 	case DRM_GPUVA_OP_PREFETCH:
2821 		/* Nothing to do */
2822 		break;
2823 	default:
2824 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2825 	}
2826 }
2827 
2828 static void vm_bind_ioctl_ops_unwind(struct xe_vm *vm,
2829 				     struct drm_gpuva_ops **ops,
2830 				     int num_ops_list)
2831 {
2832 	int i;
2833 
2834 	for (i = num_ops_list - 1; i >= 0; --i) {
2835 		struct drm_gpuva_ops *__ops = ops[i];
2836 		struct drm_gpuva_op *__op;
2837 
2838 		if (!__ops)
2839 			continue;
2840 
2841 		drm_gpuva_for_each_op_reverse(__op, __ops) {
2842 			struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2843 
2844 			xe_vma_op_unwind(vm, op,
2845 					 op->flags & XE_VMA_OP_COMMITTED,
2846 					 op->flags & XE_VMA_OP_PREV_COMMITTED,
2847 					 op->flags & XE_VMA_OP_NEXT_COMMITTED);
2848 		}
2849 	}
2850 }
2851 
2852 static int vma_lock_and_validate(struct drm_exec *exec, struct xe_vma *vma,
2853 				 bool validate)
2854 {
2855 	struct xe_bo *bo = xe_vma_bo(vma);
2856 	struct xe_vm *vm = xe_vma_vm(vma);
2857 	int err = 0;
2858 
2859 	if (bo) {
2860 		if (!bo->vm)
2861 			err = drm_exec_lock_obj(exec, &bo->ttm.base);
2862 		if (!err && validate)
2863 			err = xe_bo_validate(bo, vm,
2864 					     !xe_vm_in_preempt_fence_mode(vm));
2865 	}
2866 
2867 	return err;
2868 }
2869 
2870 static int check_ufence(struct xe_vma *vma)
2871 {
2872 	if (vma->ufence) {
2873 		struct xe_user_fence * const f = vma->ufence;
2874 
2875 		if (!xe_sync_ufence_get_status(f))
2876 			return -EBUSY;
2877 
2878 		vma->ufence = NULL;
2879 		xe_sync_ufence_put(f);
2880 	}
2881 
2882 	return 0;
2883 }
2884 
2885 static int prefetch_ranges(struct xe_vm *vm, struct xe_vma_op *op)
2886 {
2887 	bool devmem_possible = IS_DGFX(vm->xe) && IS_ENABLED(CONFIG_DRM_XE_PAGEMAP);
2888 	struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2889 	int err = 0;
2890 
2891 	struct xe_svm_range *svm_range;
2892 	struct drm_gpusvm_ctx ctx = {};
2893 	struct xe_tile *tile;
2894 	unsigned long i;
2895 	u32 region;
2896 
2897 	if (!xe_vma_is_cpu_addr_mirror(vma))
2898 		return 0;
2899 
2900 	region = op->prefetch_range.region;
2901 
2902 	ctx.read_only = xe_vma_read_only(vma);
2903 	ctx.devmem_possible = devmem_possible;
2904 	ctx.check_pages_threshold = devmem_possible ? SZ_64K : 0;
2905 
2906 	/* TODO: Threading the migration */
2907 	xa_for_each(&op->prefetch_range.range, i, svm_range) {
2908 		if (!region)
2909 			xe_svm_range_migrate_to_smem(vm, svm_range);
2910 
2911 		if (xe_svm_range_needs_migrate_to_vram(svm_range, vma, region)) {
2912 			tile = &vm->xe->tiles[region_to_mem_type[region] - XE_PL_VRAM0];
2913 			err = xe_svm_alloc_vram(tile, svm_range, &ctx);
2914 			if (err) {
2915 				drm_dbg(&vm->xe->drm, "VRAM allocation failed, retry from userspace, asid=%u, gpusvm=%p, errno=%pe\n",
2916 					vm->usm.asid, &vm->svm.gpusvm, ERR_PTR(err));
2917 				return -ENODATA;
2918 			}
2919 			xe_svm_range_debug(svm_range, "PREFETCH - RANGE MIGRATED TO VRAM");
2920 		}
2921 
2922 		err = xe_svm_range_get_pages(vm, svm_range, &ctx);
2923 		if (err) {
2924 			drm_dbg(&vm->xe->drm, "Get pages failed, asid=%u, gpusvm=%p, errno=%pe\n",
2925 				vm->usm.asid, &vm->svm.gpusvm, ERR_PTR(err));
2926 			if (err == -EOPNOTSUPP || err == -EFAULT || err == -EPERM)
2927 				err = -ENODATA;
2928 			return err;
2929 		}
2930 		xe_svm_range_debug(svm_range, "PREFETCH - RANGE GET PAGES DONE");
2931 	}
2932 
2933 	return err;
2934 }
2935 
2936 static int op_lock_and_prep(struct drm_exec *exec, struct xe_vm *vm,
2937 			    struct xe_vma_op *op)
2938 {
2939 	int err = 0;
2940 
2941 	switch (op->base.op) {
2942 	case DRM_GPUVA_OP_MAP:
2943 		if (!op->map.invalidate_on_bind)
2944 			err = vma_lock_and_validate(exec, op->map.vma,
2945 						    !xe_vm_in_fault_mode(vm) ||
2946 						    op->map.immediate);
2947 		break;
2948 	case DRM_GPUVA_OP_REMAP:
2949 		err = check_ufence(gpuva_to_vma(op->base.remap.unmap->va));
2950 		if (err)
2951 			break;
2952 
2953 		err = vma_lock_and_validate(exec,
2954 					    gpuva_to_vma(op->base.remap.unmap->va),
2955 					    false);
2956 		if (!err && op->remap.prev)
2957 			err = vma_lock_and_validate(exec, op->remap.prev, true);
2958 		if (!err && op->remap.next)
2959 			err = vma_lock_and_validate(exec, op->remap.next, true);
2960 		break;
2961 	case DRM_GPUVA_OP_UNMAP:
2962 		err = check_ufence(gpuva_to_vma(op->base.unmap.va));
2963 		if (err)
2964 			break;
2965 
2966 		err = vma_lock_and_validate(exec,
2967 					    gpuva_to_vma(op->base.unmap.va),
2968 					    false);
2969 		break;
2970 	case DRM_GPUVA_OP_PREFETCH:
2971 	{
2972 		struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2973 		u32 region;
2974 
2975 		if (xe_vma_is_cpu_addr_mirror(vma))
2976 			region = op->prefetch_range.region;
2977 		else
2978 			region = op->prefetch.region;
2979 
2980 		xe_assert(vm->xe, region <= ARRAY_SIZE(region_to_mem_type));
2981 
2982 		err = vma_lock_and_validate(exec,
2983 					    gpuva_to_vma(op->base.prefetch.va),
2984 					    false);
2985 		if (!err && !xe_vma_has_no_bo(vma))
2986 			err = xe_bo_migrate(xe_vma_bo(vma),
2987 					    region_to_mem_type[region]);
2988 		break;
2989 	}
2990 	default:
2991 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2992 	}
2993 
2994 	return err;
2995 }
2996 
2997 static int vm_bind_ioctl_ops_prefetch_ranges(struct xe_vm *vm, struct xe_vma_ops *vops)
2998 {
2999 	struct xe_vma_op *op;
3000 	int err;
3001 
3002 	if (!(vops->flags & XE_VMA_OPS_FLAG_HAS_SVM_PREFETCH))
3003 		return 0;
3004 
3005 	list_for_each_entry(op, &vops->list, link) {
3006 		if (op->base.op  == DRM_GPUVA_OP_PREFETCH) {
3007 			err = prefetch_ranges(vm, op);
3008 			if (err)
3009 				return err;
3010 		}
3011 	}
3012 
3013 	return 0;
3014 }
3015 
3016 static int vm_bind_ioctl_ops_lock_and_prep(struct drm_exec *exec,
3017 					   struct xe_vm *vm,
3018 					   struct xe_vma_ops *vops)
3019 {
3020 	struct xe_vma_op *op;
3021 	int err;
3022 
3023 	err = drm_exec_lock_obj(exec, xe_vm_obj(vm));
3024 	if (err)
3025 		return err;
3026 
3027 	list_for_each_entry(op, &vops->list, link) {
3028 		err = op_lock_and_prep(exec, vm, op);
3029 		if (err)
3030 			return err;
3031 	}
3032 
3033 #ifdef TEST_VM_OPS_ERROR
3034 	if (vops->inject_error &&
3035 	    vm->xe->vm_inject_error_position == FORCE_OP_ERROR_LOCK)
3036 		return -ENOSPC;
3037 #endif
3038 
3039 	return 0;
3040 }
3041 
3042 static void op_trace(struct xe_vma_op *op)
3043 {
3044 	switch (op->base.op) {
3045 	case DRM_GPUVA_OP_MAP:
3046 		trace_xe_vma_bind(op->map.vma);
3047 		break;
3048 	case DRM_GPUVA_OP_REMAP:
3049 		trace_xe_vma_unbind(gpuva_to_vma(op->base.remap.unmap->va));
3050 		if (op->remap.prev)
3051 			trace_xe_vma_bind(op->remap.prev);
3052 		if (op->remap.next)
3053 			trace_xe_vma_bind(op->remap.next);
3054 		break;
3055 	case DRM_GPUVA_OP_UNMAP:
3056 		trace_xe_vma_unbind(gpuva_to_vma(op->base.unmap.va));
3057 		break;
3058 	case DRM_GPUVA_OP_PREFETCH:
3059 		trace_xe_vma_bind(gpuva_to_vma(op->base.prefetch.va));
3060 		break;
3061 	case DRM_GPUVA_OP_DRIVER:
3062 		break;
3063 	default:
3064 		XE_WARN_ON("NOT POSSIBLE");
3065 	}
3066 }
3067 
3068 static void trace_xe_vm_ops_execute(struct xe_vma_ops *vops)
3069 {
3070 	struct xe_vma_op *op;
3071 
3072 	list_for_each_entry(op, &vops->list, link)
3073 		op_trace(op);
3074 }
3075 
3076 static int vm_ops_setup_tile_args(struct xe_vm *vm, struct xe_vma_ops *vops)
3077 {
3078 	struct xe_exec_queue *q = vops->q;
3079 	struct xe_tile *tile;
3080 	int number_tiles = 0;
3081 	u8 id;
3082 
3083 	for_each_tile(tile, vm->xe, id) {
3084 		if (vops->pt_update_ops[id].num_ops)
3085 			++number_tiles;
3086 
3087 		if (vops->pt_update_ops[id].q)
3088 			continue;
3089 
3090 		if (q) {
3091 			vops->pt_update_ops[id].q = q;
3092 			if (vm->pt_root[id] && !list_empty(&q->multi_gt_list))
3093 				q = list_next_entry(q, multi_gt_list);
3094 		} else {
3095 			vops->pt_update_ops[id].q = vm->q[id];
3096 		}
3097 	}
3098 
3099 	return number_tiles;
3100 }
3101 
3102 static struct dma_fence *ops_execute(struct xe_vm *vm,
3103 				     struct xe_vma_ops *vops)
3104 {
3105 	struct xe_tile *tile;
3106 	struct dma_fence *fence = NULL;
3107 	struct dma_fence **fences = NULL;
3108 	struct dma_fence_array *cf = NULL;
3109 	int number_tiles = 0, current_fence = 0, err;
3110 	u8 id;
3111 
3112 	number_tiles = vm_ops_setup_tile_args(vm, vops);
3113 	if (number_tiles == 0)
3114 		return ERR_PTR(-ENODATA);
3115 
3116 	if (number_tiles > 1) {
3117 		fences = kmalloc_array(number_tiles, sizeof(*fences),
3118 				       GFP_KERNEL);
3119 		if (!fences) {
3120 			fence = ERR_PTR(-ENOMEM);
3121 			goto err_trace;
3122 		}
3123 	}
3124 
3125 	for_each_tile(tile, vm->xe, id) {
3126 		if (!vops->pt_update_ops[id].num_ops)
3127 			continue;
3128 
3129 		err = xe_pt_update_ops_prepare(tile, vops);
3130 		if (err) {
3131 			fence = ERR_PTR(err);
3132 			goto err_out;
3133 		}
3134 	}
3135 
3136 	trace_xe_vm_ops_execute(vops);
3137 
3138 	for_each_tile(tile, vm->xe, id) {
3139 		if (!vops->pt_update_ops[id].num_ops)
3140 			continue;
3141 
3142 		fence = xe_pt_update_ops_run(tile, vops);
3143 		if (IS_ERR(fence))
3144 			goto err_out;
3145 
3146 		if (fences)
3147 			fences[current_fence++] = fence;
3148 	}
3149 
3150 	if (fences) {
3151 		cf = dma_fence_array_create(number_tiles, fences,
3152 					    vm->composite_fence_ctx,
3153 					    vm->composite_fence_seqno++,
3154 					    false);
3155 		if (!cf) {
3156 			--vm->composite_fence_seqno;
3157 			fence = ERR_PTR(-ENOMEM);
3158 			goto err_out;
3159 		}
3160 		fence = &cf->base;
3161 	}
3162 
3163 	for_each_tile(tile, vm->xe, id) {
3164 		if (!vops->pt_update_ops[id].num_ops)
3165 			continue;
3166 
3167 		xe_pt_update_ops_fini(tile, vops);
3168 	}
3169 
3170 	return fence;
3171 
3172 err_out:
3173 	for_each_tile(tile, vm->xe, id) {
3174 		if (!vops->pt_update_ops[id].num_ops)
3175 			continue;
3176 
3177 		xe_pt_update_ops_abort(tile, vops);
3178 	}
3179 	while (current_fence)
3180 		dma_fence_put(fences[--current_fence]);
3181 	kfree(fences);
3182 	kfree(cf);
3183 
3184 err_trace:
3185 	trace_xe_vm_ops_fail(vm);
3186 	return fence;
3187 }
3188 
3189 static void vma_add_ufence(struct xe_vma *vma, struct xe_user_fence *ufence)
3190 {
3191 	if (vma->ufence)
3192 		xe_sync_ufence_put(vma->ufence);
3193 	vma->ufence = __xe_sync_ufence_get(ufence);
3194 }
3195 
3196 static void op_add_ufence(struct xe_vm *vm, struct xe_vma_op *op,
3197 			  struct xe_user_fence *ufence)
3198 {
3199 	switch (op->base.op) {
3200 	case DRM_GPUVA_OP_MAP:
3201 		vma_add_ufence(op->map.vma, ufence);
3202 		break;
3203 	case DRM_GPUVA_OP_REMAP:
3204 		if (op->remap.prev)
3205 			vma_add_ufence(op->remap.prev, ufence);
3206 		if (op->remap.next)
3207 			vma_add_ufence(op->remap.next, ufence);
3208 		break;
3209 	case DRM_GPUVA_OP_UNMAP:
3210 		break;
3211 	case DRM_GPUVA_OP_PREFETCH:
3212 		vma_add_ufence(gpuva_to_vma(op->base.prefetch.va), ufence);
3213 		break;
3214 	default:
3215 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
3216 	}
3217 }
3218 
3219 static void vm_bind_ioctl_ops_fini(struct xe_vm *vm, struct xe_vma_ops *vops,
3220 				   struct dma_fence *fence)
3221 {
3222 	struct xe_exec_queue *wait_exec_queue = to_wait_exec_queue(vm, vops->q);
3223 	struct xe_user_fence *ufence;
3224 	struct xe_vma_op *op;
3225 	int i;
3226 
3227 	ufence = find_ufence_get(vops->syncs, vops->num_syncs);
3228 	list_for_each_entry(op, &vops->list, link) {
3229 		if (ufence)
3230 			op_add_ufence(vm, op, ufence);
3231 
3232 		if (op->base.op == DRM_GPUVA_OP_UNMAP)
3233 			xe_vma_destroy(gpuva_to_vma(op->base.unmap.va), fence);
3234 		else if (op->base.op == DRM_GPUVA_OP_REMAP)
3235 			xe_vma_destroy(gpuva_to_vma(op->base.remap.unmap->va),
3236 				       fence);
3237 	}
3238 	if (ufence)
3239 		xe_sync_ufence_put(ufence);
3240 	if (fence) {
3241 		for (i = 0; i < vops->num_syncs; i++)
3242 			xe_sync_entry_signal(vops->syncs + i, fence);
3243 		xe_exec_queue_last_fence_set(wait_exec_queue, vm, fence);
3244 	}
3245 }
3246 
3247 static struct dma_fence *vm_bind_ioctl_ops_execute(struct xe_vm *vm,
3248 						   struct xe_vma_ops *vops)
3249 {
3250 	struct drm_exec exec;
3251 	struct dma_fence *fence;
3252 	int err;
3253 
3254 	lockdep_assert_held_write(&vm->lock);
3255 
3256 	drm_exec_init(&exec, DRM_EXEC_INTERRUPTIBLE_WAIT |
3257 		      DRM_EXEC_IGNORE_DUPLICATES, 0);
3258 	drm_exec_until_all_locked(&exec) {
3259 		err = vm_bind_ioctl_ops_lock_and_prep(&exec, vm, vops);
3260 		drm_exec_retry_on_contention(&exec);
3261 		if (err) {
3262 			fence = ERR_PTR(err);
3263 			goto unlock;
3264 		}
3265 
3266 		fence = ops_execute(vm, vops);
3267 		if (IS_ERR(fence)) {
3268 			if (PTR_ERR(fence) == -ENODATA)
3269 				vm_bind_ioctl_ops_fini(vm, vops, NULL);
3270 			goto unlock;
3271 		}
3272 
3273 		vm_bind_ioctl_ops_fini(vm, vops, fence);
3274 	}
3275 
3276 unlock:
3277 	drm_exec_fini(&exec);
3278 	return fence;
3279 }
3280 ALLOW_ERROR_INJECTION(vm_bind_ioctl_ops_execute, ERRNO);
3281 
3282 #define SUPPORTED_FLAGS_STUB  \
3283 	(DRM_XE_VM_BIND_FLAG_READONLY | \
3284 	 DRM_XE_VM_BIND_FLAG_IMMEDIATE | \
3285 	 DRM_XE_VM_BIND_FLAG_NULL | \
3286 	 DRM_XE_VM_BIND_FLAG_DUMPABLE | \
3287 	 DRM_XE_VM_BIND_FLAG_CHECK_PXP | \
3288 	 DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR)
3289 
3290 #ifdef TEST_VM_OPS_ERROR
3291 #define SUPPORTED_FLAGS	(SUPPORTED_FLAGS_STUB | FORCE_OP_ERROR)
3292 #else
3293 #define SUPPORTED_FLAGS	SUPPORTED_FLAGS_STUB
3294 #endif
3295 
3296 #define XE_64K_PAGE_MASK 0xffffull
3297 #define ALL_DRM_XE_SYNCS_FLAGS (DRM_XE_SYNCS_FLAG_WAIT_FOR_OP)
3298 
3299 static int vm_bind_ioctl_check_args(struct xe_device *xe, struct xe_vm *vm,
3300 				    struct drm_xe_vm_bind *args,
3301 				    struct drm_xe_vm_bind_op **bind_ops)
3302 {
3303 	int err;
3304 	int i;
3305 
3306 	if (XE_IOCTL_DBG(xe, args->pad || args->pad2) ||
3307 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
3308 		return -EINVAL;
3309 
3310 	if (XE_IOCTL_DBG(xe, args->extensions))
3311 		return -EINVAL;
3312 
3313 	if (args->num_binds > 1) {
3314 		u64 __user *bind_user =
3315 			u64_to_user_ptr(args->vector_of_binds);
3316 
3317 		*bind_ops = kvmalloc_array(args->num_binds,
3318 					   sizeof(struct drm_xe_vm_bind_op),
3319 					   GFP_KERNEL | __GFP_ACCOUNT |
3320 					   __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
3321 		if (!*bind_ops)
3322 			return args->num_binds > 1 ? -ENOBUFS : -ENOMEM;
3323 
3324 		err = copy_from_user(*bind_ops, bind_user,
3325 				     sizeof(struct drm_xe_vm_bind_op) *
3326 				     args->num_binds);
3327 		if (XE_IOCTL_DBG(xe, err)) {
3328 			err = -EFAULT;
3329 			goto free_bind_ops;
3330 		}
3331 	} else {
3332 		*bind_ops = &args->bind;
3333 	}
3334 
3335 	for (i = 0; i < args->num_binds; ++i) {
3336 		u64 range = (*bind_ops)[i].range;
3337 		u64 addr = (*bind_ops)[i].addr;
3338 		u32 op = (*bind_ops)[i].op;
3339 		u32 flags = (*bind_ops)[i].flags;
3340 		u32 obj = (*bind_ops)[i].obj;
3341 		u64 obj_offset = (*bind_ops)[i].obj_offset;
3342 		u32 prefetch_region = (*bind_ops)[i].prefetch_mem_region_instance;
3343 		bool is_null = flags & DRM_XE_VM_BIND_FLAG_NULL;
3344 		bool is_cpu_addr_mirror = flags &
3345 			DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR;
3346 		u16 pat_index = (*bind_ops)[i].pat_index;
3347 		u16 coh_mode;
3348 
3349 		if (XE_IOCTL_DBG(xe, is_cpu_addr_mirror &&
3350 				 (!xe_vm_in_fault_mode(vm) ||
3351 				 !IS_ENABLED(CONFIG_DRM_XE_GPUSVM)))) {
3352 			err = -EINVAL;
3353 			goto free_bind_ops;
3354 		}
3355 
3356 		if (XE_IOCTL_DBG(xe, pat_index >= xe->pat.n_entries)) {
3357 			err = -EINVAL;
3358 			goto free_bind_ops;
3359 		}
3360 
3361 		pat_index = array_index_nospec(pat_index, xe->pat.n_entries);
3362 		(*bind_ops)[i].pat_index = pat_index;
3363 		coh_mode = xe_pat_index_get_coh_mode(xe, pat_index);
3364 		if (XE_IOCTL_DBG(xe, !coh_mode)) { /* hw reserved */
3365 			err = -EINVAL;
3366 			goto free_bind_ops;
3367 		}
3368 
3369 		if (XE_WARN_ON(coh_mode > XE_COH_AT_LEAST_1WAY)) {
3370 			err = -EINVAL;
3371 			goto free_bind_ops;
3372 		}
3373 
3374 		if (XE_IOCTL_DBG(xe, op > DRM_XE_VM_BIND_OP_PREFETCH) ||
3375 		    XE_IOCTL_DBG(xe, flags & ~SUPPORTED_FLAGS) ||
3376 		    XE_IOCTL_DBG(xe, obj && (is_null || is_cpu_addr_mirror)) ||
3377 		    XE_IOCTL_DBG(xe, obj_offset && (is_null ||
3378 						    is_cpu_addr_mirror)) ||
3379 		    XE_IOCTL_DBG(xe, op != DRM_XE_VM_BIND_OP_MAP &&
3380 				 (is_null || is_cpu_addr_mirror)) ||
3381 		    XE_IOCTL_DBG(xe, !obj &&
3382 				 op == DRM_XE_VM_BIND_OP_MAP &&
3383 				 !is_null && !is_cpu_addr_mirror) ||
3384 		    XE_IOCTL_DBG(xe, !obj &&
3385 				 op == DRM_XE_VM_BIND_OP_UNMAP_ALL) ||
3386 		    XE_IOCTL_DBG(xe, addr &&
3387 				 op == DRM_XE_VM_BIND_OP_UNMAP_ALL) ||
3388 		    XE_IOCTL_DBG(xe, range &&
3389 				 op == DRM_XE_VM_BIND_OP_UNMAP_ALL) ||
3390 		    XE_IOCTL_DBG(xe, obj &&
3391 				 op == DRM_XE_VM_BIND_OP_MAP_USERPTR) ||
3392 		    XE_IOCTL_DBG(xe, coh_mode == XE_COH_NONE &&
3393 				 op == DRM_XE_VM_BIND_OP_MAP_USERPTR) ||
3394 		    XE_IOCTL_DBG(xe, obj &&
3395 				 op == DRM_XE_VM_BIND_OP_PREFETCH) ||
3396 		    XE_IOCTL_DBG(xe, prefetch_region &&
3397 				 op != DRM_XE_VM_BIND_OP_PREFETCH) ||
3398 		    XE_IOCTL_DBG(xe, !(BIT(prefetch_region) &
3399 				       xe->info.mem_region_mask)) ||
3400 		    XE_IOCTL_DBG(xe, obj &&
3401 				 op == DRM_XE_VM_BIND_OP_UNMAP)) {
3402 			err = -EINVAL;
3403 			goto free_bind_ops;
3404 		}
3405 
3406 		if (XE_IOCTL_DBG(xe, obj_offset & ~PAGE_MASK) ||
3407 		    XE_IOCTL_DBG(xe, addr & ~PAGE_MASK) ||
3408 		    XE_IOCTL_DBG(xe, range & ~PAGE_MASK) ||
3409 		    XE_IOCTL_DBG(xe, !range &&
3410 				 op != DRM_XE_VM_BIND_OP_UNMAP_ALL)) {
3411 			err = -EINVAL;
3412 			goto free_bind_ops;
3413 		}
3414 	}
3415 
3416 	return 0;
3417 
3418 free_bind_ops:
3419 	if (args->num_binds > 1)
3420 		kvfree(*bind_ops);
3421 	*bind_ops = NULL;
3422 	return err;
3423 }
3424 
3425 static int vm_bind_ioctl_signal_fences(struct xe_vm *vm,
3426 				       struct xe_exec_queue *q,
3427 				       struct xe_sync_entry *syncs,
3428 				       int num_syncs)
3429 {
3430 	struct dma_fence *fence;
3431 	int i, err = 0;
3432 
3433 	fence = xe_sync_in_fence_get(syncs, num_syncs,
3434 				     to_wait_exec_queue(vm, q), vm);
3435 	if (IS_ERR(fence))
3436 		return PTR_ERR(fence);
3437 
3438 	for (i = 0; i < num_syncs; i++)
3439 		xe_sync_entry_signal(&syncs[i], fence);
3440 
3441 	xe_exec_queue_last_fence_set(to_wait_exec_queue(vm, q), vm,
3442 				     fence);
3443 	dma_fence_put(fence);
3444 
3445 	return err;
3446 }
3447 
3448 static void xe_vma_ops_init(struct xe_vma_ops *vops, struct xe_vm *vm,
3449 			    struct xe_exec_queue *q,
3450 			    struct xe_sync_entry *syncs, u32 num_syncs)
3451 {
3452 	memset(vops, 0, sizeof(*vops));
3453 	INIT_LIST_HEAD(&vops->list);
3454 	vops->vm = vm;
3455 	vops->q = q;
3456 	vops->syncs = syncs;
3457 	vops->num_syncs = num_syncs;
3458 	vops->flags = 0;
3459 }
3460 
3461 static int xe_vm_bind_ioctl_validate_bo(struct xe_device *xe, struct xe_bo *bo,
3462 					u64 addr, u64 range, u64 obj_offset,
3463 					u16 pat_index, u32 op, u32 bind_flags)
3464 {
3465 	u16 coh_mode;
3466 
3467 	if (XE_IOCTL_DBG(xe, range > xe_bo_size(bo)) ||
3468 	    XE_IOCTL_DBG(xe, obj_offset >
3469 			 xe_bo_size(bo) - range)) {
3470 		return -EINVAL;
3471 	}
3472 
3473 	/*
3474 	 * Some platforms require 64k VM_BIND alignment,
3475 	 * specifically those with XE_VRAM_FLAGS_NEED64K.
3476 	 *
3477 	 * Other platforms may have BO's set to 64k physical placement,
3478 	 * but can be mapped at 4k offsets anyway. This check is only
3479 	 * there for the former case.
3480 	 */
3481 	if ((bo->flags & XE_BO_FLAG_INTERNAL_64K) &&
3482 	    (xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K)) {
3483 		if (XE_IOCTL_DBG(xe, obj_offset &
3484 				 XE_64K_PAGE_MASK) ||
3485 		    XE_IOCTL_DBG(xe, addr & XE_64K_PAGE_MASK) ||
3486 		    XE_IOCTL_DBG(xe, range & XE_64K_PAGE_MASK)) {
3487 			return -EINVAL;
3488 		}
3489 	}
3490 
3491 	coh_mode = xe_pat_index_get_coh_mode(xe, pat_index);
3492 	if (bo->cpu_caching) {
3493 		if (XE_IOCTL_DBG(xe, coh_mode == XE_COH_NONE &&
3494 				 bo->cpu_caching == DRM_XE_GEM_CPU_CACHING_WB)) {
3495 			return -EINVAL;
3496 		}
3497 	} else if (XE_IOCTL_DBG(xe, coh_mode == XE_COH_NONE)) {
3498 		/*
3499 		 * Imported dma-buf from a different device should
3500 		 * require 1way or 2way coherency since we don't know
3501 		 * how it was mapped on the CPU. Just assume is it
3502 		 * potentially cached on CPU side.
3503 		 */
3504 		return -EINVAL;
3505 	}
3506 
3507 	/* If a BO is protected it can only be mapped if the key is still valid */
3508 	if ((bind_flags & DRM_XE_VM_BIND_FLAG_CHECK_PXP) && xe_bo_is_protected(bo) &&
3509 	    op != DRM_XE_VM_BIND_OP_UNMAP && op != DRM_XE_VM_BIND_OP_UNMAP_ALL)
3510 		if (XE_IOCTL_DBG(xe, xe_pxp_bo_key_check(xe->pxp, bo) != 0))
3511 			return -ENOEXEC;
3512 
3513 	return 0;
3514 }
3515 
3516 int xe_vm_bind_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3517 {
3518 	struct xe_device *xe = to_xe_device(dev);
3519 	struct xe_file *xef = to_xe_file(file);
3520 	struct drm_xe_vm_bind *args = data;
3521 	struct drm_xe_sync __user *syncs_user;
3522 	struct xe_bo **bos = NULL;
3523 	struct drm_gpuva_ops **ops = NULL;
3524 	struct xe_vm *vm;
3525 	struct xe_exec_queue *q = NULL;
3526 	u32 num_syncs, num_ufence = 0;
3527 	struct xe_sync_entry *syncs = NULL;
3528 	struct drm_xe_vm_bind_op *bind_ops = NULL;
3529 	struct xe_vma_ops vops;
3530 	struct dma_fence *fence;
3531 	int err;
3532 	int i;
3533 
3534 	vm = xe_vm_lookup(xef, args->vm_id);
3535 	if (XE_IOCTL_DBG(xe, !vm))
3536 		return -EINVAL;
3537 
3538 	err = vm_bind_ioctl_check_args(xe, vm, args, &bind_ops);
3539 	if (err)
3540 		goto put_vm;
3541 
3542 	if (args->exec_queue_id) {
3543 		q = xe_exec_queue_lookup(xef, args->exec_queue_id);
3544 		if (XE_IOCTL_DBG(xe, !q)) {
3545 			err = -ENOENT;
3546 			goto put_vm;
3547 		}
3548 
3549 		if (XE_IOCTL_DBG(xe, !(q->flags & EXEC_QUEUE_FLAG_VM))) {
3550 			err = -EINVAL;
3551 			goto put_exec_queue;
3552 		}
3553 	}
3554 
3555 	/* Ensure all UNMAPs visible */
3556 	xe_svm_flush(vm);
3557 
3558 	err = down_write_killable(&vm->lock);
3559 	if (err)
3560 		goto put_exec_queue;
3561 
3562 	if (XE_IOCTL_DBG(xe, xe_vm_is_closed_or_banned(vm))) {
3563 		err = -ENOENT;
3564 		goto release_vm_lock;
3565 	}
3566 
3567 	for (i = 0; i < args->num_binds; ++i) {
3568 		u64 range = bind_ops[i].range;
3569 		u64 addr = bind_ops[i].addr;
3570 
3571 		if (XE_IOCTL_DBG(xe, range > vm->size) ||
3572 		    XE_IOCTL_DBG(xe, addr > vm->size - range)) {
3573 			err = -EINVAL;
3574 			goto release_vm_lock;
3575 		}
3576 	}
3577 
3578 	if (args->num_binds) {
3579 		bos = kvcalloc(args->num_binds, sizeof(*bos),
3580 			       GFP_KERNEL | __GFP_ACCOUNT |
3581 			       __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
3582 		if (!bos) {
3583 			err = -ENOMEM;
3584 			goto release_vm_lock;
3585 		}
3586 
3587 		ops = kvcalloc(args->num_binds, sizeof(*ops),
3588 			       GFP_KERNEL | __GFP_ACCOUNT |
3589 			       __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
3590 		if (!ops) {
3591 			err = -ENOMEM;
3592 			goto release_vm_lock;
3593 		}
3594 	}
3595 
3596 	for (i = 0; i < args->num_binds; ++i) {
3597 		struct drm_gem_object *gem_obj;
3598 		u64 range = bind_ops[i].range;
3599 		u64 addr = bind_ops[i].addr;
3600 		u32 obj = bind_ops[i].obj;
3601 		u64 obj_offset = bind_ops[i].obj_offset;
3602 		u16 pat_index = bind_ops[i].pat_index;
3603 		u32 op = bind_ops[i].op;
3604 		u32 bind_flags = bind_ops[i].flags;
3605 
3606 		if (!obj)
3607 			continue;
3608 
3609 		gem_obj = drm_gem_object_lookup(file, obj);
3610 		if (XE_IOCTL_DBG(xe, !gem_obj)) {
3611 			err = -ENOENT;
3612 			goto put_obj;
3613 		}
3614 		bos[i] = gem_to_xe_bo(gem_obj);
3615 
3616 		err = xe_vm_bind_ioctl_validate_bo(xe, bos[i], addr, range,
3617 						   obj_offset, pat_index, op,
3618 						   bind_flags);
3619 		if (err)
3620 			goto put_obj;
3621 	}
3622 
3623 	if (args->num_syncs) {
3624 		syncs = kcalloc(args->num_syncs, sizeof(*syncs), GFP_KERNEL);
3625 		if (!syncs) {
3626 			err = -ENOMEM;
3627 			goto put_obj;
3628 		}
3629 	}
3630 
3631 	syncs_user = u64_to_user_ptr(args->syncs);
3632 	for (num_syncs = 0; num_syncs < args->num_syncs; num_syncs++) {
3633 		err = xe_sync_entry_parse(xe, xef, &syncs[num_syncs],
3634 					  &syncs_user[num_syncs],
3635 					  (xe_vm_in_lr_mode(vm) ?
3636 					   SYNC_PARSE_FLAG_LR_MODE : 0) |
3637 					  (!args->num_binds ?
3638 					   SYNC_PARSE_FLAG_DISALLOW_USER_FENCE : 0));
3639 		if (err)
3640 			goto free_syncs;
3641 
3642 		if (xe_sync_is_ufence(&syncs[num_syncs]))
3643 			num_ufence++;
3644 	}
3645 
3646 	if (XE_IOCTL_DBG(xe, num_ufence > 1)) {
3647 		err = -EINVAL;
3648 		goto free_syncs;
3649 	}
3650 
3651 	if (!args->num_binds) {
3652 		err = -ENODATA;
3653 		goto free_syncs;
3654 	}
3655 
3656 	xe_vma_ops_init(&vops, vm, q, syncs, num_syncs);
3657 	for (i = 0; i < args->num_binds; ++i) {
3658 		u64 range = bind_ops[i].range;
3659 		u64 addr = bind_ops[i].addr;
3660 		u32 op = bind_ops[i].op;
3661 		u32 flags = bind_ops[i].flags;
3662 		u64 obj_offset = bind_ops[i].obj_offset;
3663 		u32 prefetch_region = bind_ops[i].prefetch_mem_region_instance;
3664 		u16 pat_index = bind_ops[i].pat_index;
3665 
3666 		ops[i] = vm_bind_ioctl_ops_create(vm, &vops, bos[i], obj_offset,
3667 						  addr, range, op, flags,
3668 						  prefetch_region, pat_index);
3669 		if (IS_ERR(ops[i])) {
3670 			err = PTR_ERR(ops[i]);
3671 			ops[i] = NULL;
3672 			goto unwind_ops;
3673 		}
3674 
3675 		err = vm_bind_ioctl_ops_parse(vm, ops[i], &vops);
3676 		if (err)
3677 			goto unwind_ops;
3678 
3679 #ifdef TEST_VM_OPS_ERROR
3680 		if (flags & FORCE_OP_ERROR) {
3681 			vops.inject_error = true;
3682 			vm->xe->vm_inject_error_position =
3683 				(vm->xe->vm_inject_error_position + 1) %
3684 				FORCE_OP_ERROR_COUNT;
3685 		}
3686 #endif
3687 	}
3688 
3689 	/* Nothing to do */
3690 	if (list_empty(&vops.list)) {
3691 		err = -ENODATA;
3692 		goto unwind_ops;
3693 	}
3694 
3695 	err = xe_vma_ops_alloc(&vops, args->num_binds > 1);
3696 	if (err)
3697 		goto unwind_ops;
3698 
3699 	err = vm_bind_ioctl_ops_prefetch_ranges(vm, &vops);
3700 	if (err)
3701 		goto unwind_ops;
3702 
3703 	fence = vm_bind_ioctl_ops_execute(vm, &vops);
3704 	if (IS_ERR(fence))
3705 		err = PTR_ERR(fence);
3706 	else
3707 		dma_fence_put(fence);
3708 
3709 unwind_ops:
3710 	if (err && err != -ENODATA)
3711 		vm_bind_ioctl_ops_unwind(vm, ops, args->num_binds);
3712 	xe_vma_ops_fini(&vops);
3713 	for (i = args->num_binds - 1; i >= 0; --i)
3714 		if (ops[i])
3715 			drm_gpuva_ops_free(&vm->gpuvm, ops[i]);
3716 free_syncs:
3717 	if (err == -ENODATA)
3718 		err = vm_bind_ioctl_signal_fences(vm, q, syncs, num_syncs);
3719 	while (num_syncs--)
3720 		xe_sync_entry_cleanup(&syncs[num_syncs]);
3721 
3722 	kfree(syncs);
3723 put_obj:
3724 	for (i = 0; i < args->num_binds; ++i)
3725 		xe_bo_put(bos[i]);
3726 release_vm_lock:
3727 	up_write(&vm->lock);
3728 put_exec_queue:
3729 	if (q)
3730 		xe_exec_queue_put(q);
3731 put_vm:
3732 	xe_vm_put(vm);
3733 	kvfree(bos);
3734 	kvfree(ops);
3735 	if (args->num_binds > 1)
3736 		kvfree(bind_ops);
3737 	return err;
3738 }
3739 
3740 /**
3741  * xe_vm_bind_kernel_bo - bind a kernel BO to a VM
3742  * @vm: VM to bind the BO to
3743  * @bo: BO to bind
3744  * @q: exec queue to use for the bind (optional)
3745  * @addr: address at which to bind the BO
3746  * @cache_lvl: PAT cache level to use
3747  *
3748  * Execute a VM bind map operation on a kernel-owned BO to bind it into a
3749  * kernel-owned VM.
3750  *
3751  * Returns a dma_fence to track the binding completion if the job to do so was
3752  * successfully submitted, an error pointer otherwise.
3753  */
3754 struct dma_fence *xe_vm_bind_kernel_bo(struct xe_vm *vm, struct xe_bo *bo,
3755 				       struct xe_exec_queue *q, u64 addr,
3756 				       enum xe_cache_level cache_lvl)
3757 {
3758 	struct xe_vma_ops vops;
3759 	struct drm_gpuva_ops *ops = NULL;
3760 	struct dma_fence *fence;
3761 	int err;
3762 
3763 	xe_bo_get(bo);
3764 	xe_vm_get(vm);
3765 	if (q)
3766 		xe_exec_queue_get(q);
3767 
3768 	down_write(&vm->lock);
3769 
3770 	xe_vma_ops_init(&vops, vm, q, NULL, 0);
3771 
3772 	ops = vm_bind_ioctl_ops_create(vm, &vops, bo, 0, addr, xe_bo_size(bo),
3773 				       DRM_XE_VM_BIND_OP_MAP, 0, 0,
3774 				       vm->xe->pat.idx[cache_lvl]);
3775 	if (IS_ERR(ops)) {
3776 		err = PTR_ERR(ops);
3777 		goto release_vm_lock;
3778 	}
3779 
3780 	err = vm_bind_ioctl_ops_parse(vm, ops, &vops);
3781 	if (err)
3782 		goto release_vm_lock;
3783 
3784 	xe_assert(vm->xe, !list_empty(&vops.list));
3785 
3786 	err = xe_vma_ops_alloc(&vops, false);
3787 	if (err)
3788 		goto unwind_ops;
3789 
3790 	fence = vm_bind_ioctl_ops_execute(vm, &vops);
3791 	if (IS_ERR(fence))
3792 		err = PTR_ERR(fence);
3793 
3794 unwind_ops:
3795 	if (err && err != -ENODATA)
3796 		vm_bind_ioctl_ops_unwind(vm, &ops, 1);
3797 
3798 	xe_vma_ops_fini(&vops);
3799 	drm_gpuva_ops_free(&vm->gpuvm, ops);
3800 
3801 release_vm_lock:
3802 	up_write(&vm->lock);
3803 
3804 	if (q)
3805 		xe_exec_queue_put(q);
3806 	xe_vm_put(vm);
3807 	xe_bo_put(bo);
3808 
3809 	if (err)
3810 		fence = ERR_PTR(err);
3811 
3812 	return fence;
3813 }
3814 
3815 /**
3816  * xe_vm_lock() - Lock the vm's dma_resv object
3817  * @vm: The struct xe_vm whose lock is to be locked
3818  * @intr: Whether to perform any wait interruptible
3819  *
3820  * Return: 0 on success, -EINTR if @intr is true and the wait for a
3821  * contended lock was interrupted. If @intr is false, the function
3822  * always returns 0.
3823  */
3824 int xe_vm_lock(struct xe_vm *vm, bool intr)
3825 {
3826 	if (intr)
3827 		return dma_resv_lock_interruptible(xe_vm_resv(vm), NULL);
3828 
3829 	return dma_resv_lock(xe_vm_resv(vm), NULL);
3830 }
3831 
3832 /**
3833  * xe_vm_unlock() - Unlock the vm's dma_resv object
3834  * @vm: The struct xe_vm whose lock is to be released.
3835  *
3836  * Unlock a buffer object lock that was locked by xe_vm_lock().
3837  */
3838 void xe_vm_unlock(struct xe_vm *vm)
3839 {
3840 	dma_resv_unlock(xe_vm_resv(vm));
3841 }
3842 
3843 /**
3844  * xe_vm_range_tilemask_tlb_invalidation - Issue a TLB invalidation on this tilemask for an
3845  * address range
3846  * @vm: The VM
3847  * @start: start address
3848  * @end: end address
3849  * @tile_mask: mask for which gt's issue tlb invalidation
3850  *
3851  * Issue a range based TLB invalidation for gt's in tilemask
3852  *
3853  * Returns 0 for success, negative error code otherwise.
3854  */
3855 int xe_vm_range_tilemask_tlb_invalidation(struct xe_vm *vm, u64 start,
3856 					  u64 end, u8 tile_mask)
3857 {
3858 	struct xe_gt_tlb_invalidation_fence fence[XE_MAX_TILES_PER_DEVICE * XE_MAX_GT_PER_TILE];
3859 	struct xe_tile *tile;
3860 	u32 fence_id = 0;
3861 	u8 id;
3862 	int err;
3863 
3864 	if (!tile_mask)
3865 		return 0;
3866 
3867 	for_each_tile(tile, vm->xe, id) {
3868 		if (tile_mask & BIT(id)) {
3869 			xe_gt_tlb_invalidation_fence_init(tile->primary_gt,
3870 							  &fence[fence_id], true);
3871 
3872 			err = xe_gt_tlb_invalidation_range(tile->primary_gt,
3873 							   &fence[fence_id],
3874 							   start,
3875 							   end,
3876 							   vm->usm.asid);
3877 			if (err)
3878 				goto wait;
3879 			++fence_id;
3880 
3881 			if (!tile->media_gt)
3882 				continue;
3883 
3884 			xe_gt_tlb_invalidation_fence_init(tile->media_gt,
3885 							  &fence[fence_id], true);
3886 
3887 			err = xe_gt_tlb_invalidation_range(tile->media_gt,
3888 							   &fence[fence_id],
3889 							   start,
3890 							   end,
3891 							   vm->usm.asid);
3892 			if (err)
3893 				goto wait;
3894 			++fence_id;
3895 		}
3896 	}
3897 
3898 wait:
3899 	for (id = 0; id < fence_id; ++id)
3900 		xe_gt_tlb_invalidation_fence_wait(&fence[id]);
3901 
3902 	return err;
3903 }
3904 
3905 /**
3906  * xe_vm_invalidate_vma - invalidate GPU mappings for VMA without a lock
3907  * @vma: VMA to invalidate
3908  *
3909  * Walks a list of page tables leaves which it memset the entries owned by this
3910  * VMA to zero, invalidates the TLBs, and block until TLBs invalidation is
3911  * complete.
3912  *
3913  * Returns 0 for success, negative error code otherwise.
3914  */
3915 int xe_vm_invalidate_vma(struct xe_vma *vma)
3916 {
3917 	struct xe_device *xe = xe_vma_vm(vma)->xe;
3918 	struct xe_vm *vm = xe_vma_vm(vma);
3919 	struct xe_tile *tile;
3920 	u8 tile_mask = 0;
3921 	int ret = 0;
3922 	u8 id;
3923 
3924 	xe_assert(xe, !xe_vma_is_null(vma));
3925 	xe_assert(xe, !xe_vma_is_cpu_addr_mirror(vma));
3926 	trace_xe_vma_invalidate(vma);
3927 
3928 	vm_dbg(&vm->xe->drm,
3929 	       "INVALIDATE: addr=0x%016llx, range=0x%016llx",
3930 		xe_vma_start(vma), xe_vma_size(vma));
3931 
3932 	/*
3933 	 * Check that we don't race with page-table updates, tile_invalidated
3934 	 * update is safe
3935 	 */
3936 	if (IS_ENABLED(CONFIG_PROVE_LOCKING)) {
3937 		if (xe_vma_is_userptr(vma)) {
3938 			lockdep_assert(lockdep_is_held_type(&vm->userptr.notifier_lock, 0) ||
3939 				       (lockdep_is_held_type(&vm->userptr.notifier_lock, 1) &&
3940 					lockdep_is_held(&xe_vm_resv(vm)->lock.base)));
3941 
3942 			WARN_ON_ONCE(!mmu_interval_check_retry
3943 				     (&to_userptr_vma(vma)->userptr.notifier,
3944 				      to_userptr_vma(vma)->userptr.notifier_seq));
3945 			WARN_ON_ONCE(!dma_resv_test_signaled(xe_vm_resv(vm),
3946 							     DMA_RESV_USAGE_BOOKKEEP));
3947 
3948 		} else {
3949 			xe_bo_assert_held(xe_vma_bo(vma));
3950 		}
3951 	}
3952 
3953 	for_each_tile(tile, xe, id)
3954 		if (xe_pt_zap_ptes(tile, vma))
3955 			tile_mask |= BIT(id);
3956 
3957 	xe_device_wmb(xe);
3958 
3959 	ret = xe_vm_range_tilemask_tlb_invalidation(xe_vma_vm(vma), xe_vma_start(vma),
3960 						    xe_vma_end(vma), tile_mask);
3961 
3962 	/* WRITE_ONCE pairs with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
3963 	WRITE_ONCE(vma->tile_invalidated, vma->tile_mask);
3964 
3965 	return ret;
3966 }
3967 
3968 int xe_vm_validate_protected(struct xe_vm *vm)
3969 {
3970 	struct drm_gpuva *gpuva;
3971 	int err = 0;
3972 
3973 	if (!vm)
3974 		return -ENODEV;
3975 
3976 	mutex_lock(&vm->snap_mutex);
3977 
3978 	drm_gpuvm_for_each_va(gpuva, &vm->gpuvm) {
3979 		struct xe_vma *vma = gpuva_to_vma(gpuva);
3980 		struct xe_bo *bo = vma->gpuva.gem.obj ?
3981 			gem_to_xe_bo(vma->gpuva.gem.obj) : NULL;
3982 
3983 		if (!bo)
3984 			continue;
3985 
3986 		if (xe_bo_is_protected(bo)) {
3987 			err = xe_pxp_bo_key_check(vm->xe->pxp, bo);
3988 			if (err)
3989 				break;
3990 		}
3991 	}
3992 
3993 	mutex_unlock(&vm->snap_mutex);
3994 	return err;
3995 }
3996 
3997 struct xe_vm_snapshot {
3998 	unsigned long num_snaps;
3999 	struct {
4000 		u64 ofs, bo_ofs;
4001 		unsigned long len;
4002 		struct xe_bo *bo;
4003 		void *data;
4004 		struct mm_struct *mm;
4005 	} snap[];
4006 };
4007 
4008 struct xe_vm_snapshot *xe_vm_snapshot_capture(struct xe_vm *vm)
4009 {
4010 	unsigned long num_snaps = 0, i;
4011 	struct xe_vm_snapshot *snap = NULL;
4012 	struct drm_gpuva *gpuva;
4013 
4014 	if (!vm)
4015 		return NULL;
4016 
4017 	mutex_lock(&vm->snap_mutex);
4018 	drm_gpuvm_for_each_va(gpuva, &vm->gpuvm) {
4019 		if (gpuva->flags & XE_VMA_DUMPABLE)
4020 			num_snaps++;
4021 	}
4022 
4023 	if (num_snaps)
4024 		snap = kvzalloc(offsetof(struct xe_vm_snapshot, snap[num_snaps]), GFP_NOWAIT);
4025 	if (!snap) {
4026 		snap = num_snaps ? ERR_PTR(-ENOMEM) : ERR_PTR(-ENODEV);
4027 		goto out_unlock;
4028 	}
4029 
4030 	snap->num_snaps = num_snaps;
4031 	i = 0;
4032 	drm_gpuvm_for_each_va(gpuva, &vm->gpuvm) {
4033 		struct xe_vma *vma = gpuva_to_vma(gpuva);
4034 		struct xe_bo *bo = vma->gpuva.gem.obj ?
4035 			gem_to_xe_bo(vma->gpuva.gem.obj) : NULL;
4036 
4037 		if (!(gpuva->flags & XE_VMA_DUMPABLE))
4038 			continue;
4039 
4040 		snap->snap[i].ofs = xe_vma_start(vma);
4041 		snap->snap[i].len = xe_vma_size(vma);
4042 		if (bo) {
4043 			snap->snap[i].bo = xe_bo_get(bo);
4044 			snap->snap[i].bo_ofs = xe_vma_bo_offset(vma);
4045 		} else if (xe_vma_is_userptr(vma)) {
4046 			struct mm_struct *mm =
4047 				to_userptr_vma(vma)->userptr.notifier.mm;
4048 
4049 			if (mmget_not_zero(mm))
4050 				snap->snap[i].mm = mm;
4051 			else
4052 				snap->snap[i].data = ERR_PTR(-EFAULT);
4053 
4054 			snap->snap[i].bo_ofs = xe_vma_userptr(vma);
4055 		} else {
4056 			snap->snap[i].data = ERR_PTR(-ENOENT);
4057 		}
4058 		i++;
4059 	}
4060 
4061 out_unlock:
4062 	mutex_unlock(&vm->snap_mutex);
4063 	return snap;
4064 }
4065 
4066 void xe_vm_snapshot_capture_delayed(struct xe_vm_snapshot *snap)
4067 {
4068 	if (IS_ERR_OR_NULL(snap))
4069 		return;
4070 
4071 	for (int i = 0; i < snap->num_snaps; i++) {
4072 		struct xe_bo *bo = snap->snap[i].bo;
4073 		int err;
4074 
4075 		if (IS_ERR(snap->snap[i].data))
4076 			continue;
4077 
4078 		snap->snap[i].data = kvmalloc(snap->snap[i].len, GFP_USER);
4079 		if (!snap->snap[i].data) {
4080 			snap->snap[i].data = ERR_PTR(-ENOMEM);
4081 			goto cleanup_bo;
4082 		}
4083 
4084 		if (bo) {
4085 			err = xe_bo_read(bo, snap->snap[i].bo_ofs,
4086 					 snap->snap[i].data, snap->snap[i].len);
4087 		} else {
4088 			void __user *userptr = (void __user *)(size_t)snap->snap[i].bo_ofs;
4089 
4090 			kthread_use_mm(snap->snap[i].mm);
4091 			if (!copy_from_user(snap->snap[i].data, userptr, snap->snap[i].len))
4092 				err = 0;
4093 			else
4094 				err = -EFAULT;
4095 			kthread_unuse_mm(snap->snap[i].mm);
4096 
4097 			mmput(snap->snap[i].mm);
4098 			snap->snap[i].mm = NULL;
4099 		}
4100 
4101 		if (err) {
4102 			kvfree(snap->snap[i].data);
4103 			snap->snap[i].data = ERR_PTR(err);
4104 		}
4105 
4106 cleanup_bo:
4107 		xe_bo_put(bo);
4108 		snap->snap[i].bo = NULL;
4109 	}
4110 }
4111 
4112 void xe_vm_snapshot_print(struct xe_vm_snapshot *snap, struct drm_printer *p)
4113 {
4114 	unsigned long i, j;
4115 
4116 	if (IS_ERR_OR_NULL(snap)) {
4117 		drm_printf(p, "[0].error: %li\n", PTR_ERR(snap));
4118 		return;
4119 	}
4120 
4121 	for (i = 0; i < snap->num_snaps; i++) {
4122 		drm_printf(p, "[%llx].length: 0x%lx\n", snap->snap[i].ofs, snap->snap[i].len);
4123 
4124 		if (IS_ERR(snap->snap[i].data)) {
4125 			drm_printf(p, "[%llx].error: %li\n", snap->snap[i].ofs,
4126 				   PTR_ERR(snap->snap[i].data));
4127 			continue;
4128 		}
4129 
4130 		drm_printf(p, "[%llx].data: ", snap->snap[i].ofs);
4131 
4132 		for (j = 0; j < snap->snap[i].len; j += sizeof(u32)) {
4133 			u32 *val = snap->snap[i].data + j;
4134 			char dumped[ASCII85_BUFSZ];
4135 
4136 			drm_puts(p, ascii85_encode(*val, dumped));
4137 		}
4138 
4139 		drm_puts(p, "\n");
4140 
4141 		if (drm_coredump_printer_is_full(p))
4142 			return;
4143 	}
4144 }
4145 
4146 void xe_vm_snapshot_free(struct xe_vm_snapshot *snap)
4147 {
4148 	unsigned long i;
4149 
4150 	if (IS_ERR_OR_NULL(snap))
4151 		return;
4152 
4153 	for (i = 0; i < snap->num_snaps; i++) {
4154 		if (!IS_ERR(snap->snap[i].data))
4155 			kvfree(snap->snap[i].data);
4156 		xe_bo_put(snap->snap[i].bo);
4157 		if (snap->snap[i].mm)
4158 			mmput(snap->snap[i].mm);
4159 	}
4160 	kvfree(snap);
4161 }
4162