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