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