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