drm/xe: Reduce the number list links in xe_vma
[linux-2.6-microblaze.git] / drivers / gpu / drm / xe / xe_vm.c
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
10 #include <drm/drm_print.h>
11 #include <drm/ttm/ttm_execbuf_util.h>
12 #include <drm/ttm/ttm_tt.h>
13 #include <drm/xe_drm.h>
14 #include <linux/delay.h>
15 #include <linux/kthread.h>
16 #include <linux/mm.h>
17 #include <linux/swap.h>
18
19 #include "xe_bo.h"
20 #include "xe_device.h"
21 #include "xe_engine.h"
22 #include "xe_gt.h"
23 #include "xe_gt_pagefault.h"
24 #include "xe_gt_tlb_invalidation.h"
25 #include "xe_migrate.h"
26 #include "xe_pm.h"
27 #include "xe_preempt_fence.h"
28 #include "xe_pt.h"
29 #include "xe_res_cursor.h"
30 #include "xe_sync.h"
31 #include "xe_trace.h"
32
33 #define TEST_VM_ASYNC_OPS_ERROR
34
35 /**
36  * xe_vma_userptr_check_repin() - Advisory check for repin needed
37  * @vma: The userptr vma
38  *
39  * Check if the userptr vma has been invalidated since last successful
40  * repin. The check is advisory only and can the function can be called
41  * without the vm->userptr.notifier_lock held. There is no guarantee that the
42  * vma userptr will remain valid after a lockless check, so typically
43  * the call needs to be followed by a proper check under the notifier_lock.
44  *
45  * Return: 0 if userptr vma is valid, -EAGAIN otherwise; repin recommended.
46  */
47 int xe_vma_userptr_check_repin(struct xe_vma *vma)
48 {
49         return mmu_interval_check_retry(&vma->userptr.notifier,
50                                         vma->userptr.notifier_seq) ?
51                 -EAGAIN : 0;
52 }
53
54 int xe_vma_userptr_pin_pages(struct xe_vma *vma)
55 {
56         struct xe_vm *vm = xe_vma_vm(vma);
57         struct xe_device *xe = vm->xe;
58         const unsigned long num_pages = xe_vma_size(vma) >> PAGE_SHIFT;
59         struct page **pages;
60         bool in_kthread = !current->mm;
61         unsigned long notifier_seq;
62         int pinned, ret, i;
63         bool read_only = xe_vma_read_only(vma);
64
65         lockdep_assert_held(&vm->lock);
66         XE_BUG_ON(!xe_vma_is_userptr(vma));
67 retry:
68         if (vma->gpuva.flags & XE_VMA_DESTROYED)
69                 return 0;
70
71         notifier_seq = mmu_interval_read_begin(&vma->userptr.notifier);
72         if (notifier_seq == vma->userptr.notifier_seq)
73                 return 0;
74
75         pages = kvmalloc_array(num_pages, sizeof(*pages), GFP_KERNEL);
76         if (!pages)
77                 return -ENOMEM;
78
79         if (vma->userptr.sg) {
80                 dma_unmap_sgtable(xe->drm.dev,
81                                   vma->userptr.sg,
82                                   read_only ? DMA_TO_DEVICE :
83                                   DMA_BIDIRECTIONAL, 0);
84                 sg_free_table(vma->userptr.sg);
85                 vma->userptr.sg = NULL;
86         }
87
88         pinned = ret = 0;
89         if (in_kthread) {
90                 if (!mmget_not_zero(vma->userptr.notifier.mm)) {
91                         ret = -EFAULT;
92                         goto mm_closed;
93                 }
94                 kthread_use_mm(vma->userptr.notifier.mm);
95         }
96
97         while (pinned < num_pages) {
98                 ret = get_user_pages_fast(xe_vma_userptr(vma) +
99                                           pinned * PAGE_SIZE,
100                                           num_pages - pinned,
101                                           read_only ? 0 : FOLL_WRITE,
102                                           &pages[pinned]);
103                 if (ret < 0) {
104                         if (in_kthread)
105                                 ret = 0;
106                         break;
107                 }
108
109                 pinned += ret;
110                 ret = 0;
111         }
112
113         if (in_kthread) {
114                 kthread_unuse_mm(vma->userptr.notifier.mm);
115                 mmput(vma->userptr.notifier.mm);
116         }
117 mm_closed:
118         if (ret)
119                 goto out;
120
121         ret = sg_alloc_table_from_pages_segment(&vma->userptr.sgt, pages,
122                                                 pinned, 0,
123                                                 (u64)pinned << PAGE_SHIFT,
124                                                 xe_sg_segment_size(xe->drm.dev),
125                                                 GFP_KERNEL);
126         if (ret) {
127                 vma->userptr.sg = NULL;
128                 goto out;
129         }
130         vma->userptr.sg = &vma->userptr.sgt;
131
132         ret = dma_map_sgtable(xe->drm.dev, vma->userptr.sg,
133                               read_only ? DMA_TO_DEVICE :
134                               DMA_BIDIRECTIONAL,
135                               DMA_ATTR_SKIP_CPU_SYNC |
136                               DMA_ATTR_NO_KERNEL_MAPPING);
137         if (ret) {
138                 sg_free_table(vma->userptr.sg);
139                 vma->userptr.sg = NULL;
140                 goto out;
141         }
142
143         for (i = 0; i < pinned; ++i) {
144                 if (!read_only) {
145                         lock_page(pages[i]);
146                         set_page_dirty(pages[i]);
147                         unlock_page(pages[i]);
148                 }
149
150                 mark_page_accessed(pages[i]);
151         }
152
153 out:
154         release_pages(pages, pinned);
155         kvfree(pages);
156
157         if (!(ret < 0)) {
158                 vma->userptr.notifier_seq = notifier_seq;
159                 if (xe_vma_userptr_check_repin(vma) == -EAGAIN)
160                         goto retry;
161         }
162
163         return ret < 0 ? ret : 0;
164 }
165
166 static bool preempt_fences_waiting(struct xe_vm *vm)
167 {
168         struct xe_engine *e;
169
170         lockdep_assert_held(&vm->lock);
171         xe_vm_assert_held(vm);
172
173         list_for_each_entry(e, &vm->preempt.engines, compute.link) {
174                 if (!e->compute.pfence || (e->compute.pfence &&
175                     test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
176                              &e->compute.pfence->flags))) {
177                         return true;
178                 }
179         }
180
181         return false;
182 }
183
184 static void free_preempt_fences(struct list_head *list)
185 {
186         struct list_head *link, *next;
187
188         list_for_each_safe(link, next, list)
189                 xe_preempt_fence_free(to_preempt_fence_from_link(link));
190 }
191
192 static int alloc_preempt_fences(struct xe_vm *vm, struct list_head *list,
193                                 unsigned int *count)
194 {
195         lockdep_assert_held(&vm->lock);
196         xe_vm_assert_held(vm);
197
198         if (*count >= vm->preempt.num_engines)
199                 return 0;
200
201         for (; *count < vm->preempt.num_engines; ++(*count)) {
202                 struct xe_preempt_fence *pfence = xe_preempt_fence_alloc();
203
204                 if (IS_ERR(pfence))
205                         return PTR_ERR(pfence);
206
207                 list_move_tail(xe_preempt_fence_link(pfence), list);
208         }
209
210         return 0;
211 }
212
213 static int wait_for_existing_preempt_fences(struct xe_vm *vm)
214 {
215         struct xe_engine *e;
216
217         xe_vm_assert_held(vm);
218
219         list_for_each_entry(e, &vm->preempt.engines, compute.link) {
220                 if (e->compute.pfence) {
221                         long timeout = dma_fence_wait(e->compute.pfence, false);
222
223                         if (timeout < 0)
224                                 return -ETIME;
225                         dma_fence_put(e->compute.pfence);
226                         e->compute.pfence = NULL;
227                 }
228         }
229
230         return 0;
231 }
232
233 static bool xe_vm_is_idle(struct xe_vm *vm)
234 {
235         struct xe_engine *e;
236
237         xe_vm_assert_held(vm);
238         list_for_each_entry(e, &vm->preempt.engines, compute.link) {
239                 if (!xe_engine_is_idle(e))
240                         return false;
241         }
242
243         return true;
244 }
245
246 static void arm_preempt_fences(struct xe_vm *vm, struct list_head *list)
247 {
248         struct list_head *link;
249         struct xe_engine *e;
250
251         list_for_each_entry(e, &vm->preempt.engines, compute.link) {
252                 struct dma_fence *fence;
253
254                 link = list->next;
255                 XE_BUG_ON(link == list);
256
257                 fence = xe_preempt_fence_arm(to_preempt_fence_from_link(link),
258                                              e, e->compute.context,
259                                              ++e->compute.seqno);
260                 dma_fence_put(e->compute.pfence);
261                 e->compute.pfence = fence;
262         }
263 }
264
265 static int add_preempt_fences(struct xe_vm *vm, struct xe_bo *bo)
266 {
267         struct xe_engine *e;
268         struct ww_acquire_ctx ww;
269         int err;
270
271         err = xe_bo_lock(bo, &ww, vm->preempt.num_engines, true);
272         if (err)
273                 return err;
274
275         list_for_each_entry(e, &vm->preempt.engines, compute.link)
276                 if (e->compute.pfence) {
277                         dma_resv_add_fence(bo->ttm.base.resv,
278                                            e->compute.pfence,
279                                            DMA_RESV_USAGE_BOOKKEEP);
280                 }
281
282         xe_bo_unlock(bo, &ww);
283         return 0;
284 }
285
286 /**
287  * xe_vm_fence_all_extobjs() - Add a fence to vm's external objects' resv
288  * @vm: The vm.
289  * @fence: The fence to add.
290  * @usage: The resv usage for the fence.
291  *
292  * Loops over all of the vm's external object bindings and adds a @fence
293  * with the given @usage to all of the external object's reservation
294  * objects.
295  */
296 void xe_vm_fence_all_extobjs(struct xe_vm *vm, struct dma_fence *fence,
297                              enum dma_resv_usage usage)
298 {
299         struct xe_vma *vma;
300
301         list_for_each_entry(vma, &vm->extobj.list, extobj.link)
302                 dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence, usage);
303 }
304
305 static void resume_and_reinstall_preempt_fences(struct xe_vm *vm)
306 {
307         struct xe_engine *e;
308
309         lockdep_assert_held(&vm->lock);
310         xe_vm_assert_held(vm);
311
312         list_for_each_entry(e, &vm->preempt.engines, compute.link) {
313                 e->ops->resume(e);
314
315                 dma_resv_add_fence(xe_vm_resv(vm), e->compute.pfence,
316                                    DMA_RESV_USAGE_BOOKKEEP);
317                 xe_vm_fence_all_extobjs(vm, e->compute.pfence,
318                                         DMA_RESV_USAGE_BOOKKEEP);
319         }
320 }
321
322 int xe_vm_add_compute_engine(struct xe_vm *vm, struct xe_engine *e)
323 {
324         struct ttm_validate_buffer tv_onstack[XE_ONSTACK_TV];
325         struct ttm_validate_buffer *tv;
326         struct ww_acquire_ctx ww;
327         struct list_head objs;
328         struct dma_fence *pfence;
329         int err;
330         bool wait;
331
332         XE_BUG_ON(!xe_vm_in_compute_mode(vm));
333
334         down_write(&vm->lock);
335
336         err = xe_vm_lock_dma_resv(vm, &ww, tv_onstack, &tv, &objs, true, 1);
337         if (err)
338                 goto out_unlock_outer;
339
340         pfence = xe_preempt_fence_create(e, e->compute.context,
341                                          ++e->compute.seqno);
342         if (!pfence) {
343                 err = -ENOMEM;
344                 goto out_unlock;
345         }
346
347         list_add(&e->compute.link, &vm->preempt.engines);
348         ++vm->preempt.num_engines;
349         e->compute.pfence = pfence;
350
351         down_read(&vm->userptr.notifier_lock);
352
353         dma_resv_add_fence(xe_vm_resv(vm), pfence,
354                            DMA_RESV_USAGE_BOOKKEEP);
355
356         xe_vm_fence_all_extobjs(vm, pfence, DMA_RESV_USAGE_BOOKKEEP);
357
358         /*
359          * Check to see if a preemption on VM is in flight or userptr
360          * invalidation, if so trigger this preempt fence to sync state with
361          * other preempt fences on the VM.
362          */
363         wait = __xe_vm_userptr_needs_repin(vm) || preempt_fences_waiting(vm);
364         if (wait)
365                 dma_fence_enable_sw_signaling(pfence);
366
367         up_read(&vm->userptr.notifier_lock);
368
369 out_unlock:
370         xe_vm_unlock_dma_resv(vm, tv_onstack, tv, &ww, &objs);
371 out_unlock_outer:
372         up_write(&vm->lock);
373
374         return err;
375 }
376
377 /**
378  * __xe_vm_userptr_needs_repin() - Check whether the VM does have userptrs
379  * that need repinning.
380  * @vm: The VM.
381  *
382  * This function checks for whether the VM has userptrs that need repinning,
383  * and provides a release-type barrier on the userptr.notifier_lock after
384  * checking.
385  *
386  * Return: 0 if there are no userptrs needing repinning, -EAGAIN if there are.
387  */
388 int __xe_vm_userptr_needs_repin(struct xe_vm *vm)
389 {
390         lockdep_assert_held_read(&vm->userptr.notifier_lock);
391
392         return (list_empty(&vm->userptr.repin_list) &&
393                 list_empty(&vm->userptr.invalidated)) ? 0 : -EAGAIN;
394 }
395
396 /**
397  * xe_vm_lock_dma_resv() - Lock the vm dma_resv object and the dma_resv
398  * objects of the vm's external buffer objects.
399  * @vm: The vm.
400  * @ww: Pointer to a struct ww_acquire_ctx locking context.
401  * @tv_onstack: Array size XE_ONSTACK_TV of storage for the struct
402  * ttm_validate_buffers used for locking.
403  * @tv: Pointer to a pointer that on output contains the actual storage used.
404  * @objs: List head for the buffer objects locked.
405  * @intr: Whether to lock interruptible.
406  * @num_shared: Number of dma-fence slots to reserve in the locked objects.
407  *
408  * Locks the vm dma-resv objects and all the dma-resv objects of the
409  * buffer objects on the vm external object list. The TTM utilities require
410  * a list of struct ttm_validate_buffers pointing to the actual buffer
411  * objects to lock. Storage for those struct ttm_validate_buffers should
412  * be provided in @tv_onstack, and is typically reserved on the stack
413  * of the caller. If the size of @tv_onstack isn't sufficient, then
414  * storage will be allocated internally using kvmalloc().
415  *
416  * The function performs deadlock handling internally, and after a
417  * successful return the ww locking transaction should be considered
418  * sealed.
419  *
420  * Return: 0 on success, Negative error code on error. In particular if
421  * @intr is set to true, -EINTR or -ERESTARTSYS may be returned. In case
422  * of error, any locking performed has been reverted.
423  */
424 int xe_vm_lock_dma_resv(struct xe_vm *vm, struct ww_acquire_ctx *ww,
425                         struct ttm_validate_buffer *tv_onstack,
426                         struct ttm_validate_buffer **tv,
427                         struct list_head *objs,
428                         bool intr,
429                         unsigned int num_shared)
430 {
431         struct ttm_validate_buffer *tv_vm, *tv_bo;
432         struct xe_vma *vma, *next;
433         LIST_HEAD(dups);
434         int err;
435
436         lockdep_assert_held(&vm->lock);
437
438         if (vm->extobj.entries < XE_ONSTACK_TV) {
439                 tv_vm = tv_onstack;
440         } else {
441                 tv_vm = kvmalloc_array(vm->extobj.entries + 1, sizeof(*tv_vm),
442                                        GFP_KERNEL);
443                 if (!tv_vm)
444                         return -ENOMEM;
445         }
446         tv_bo = tv_vm + 1;
447
448         INIT_LIST_HEAD(objs);
449         list_for_each_entry(vma, &vm->extobj.list, extobj.link) {
450                 tv_bo->num_shared = num_shared;
451                 tv_bo->bo = &xe_vma_bo(vma)->ttm;
452
453                 list_add_tail(&tv_bo->head, objs);
454                 tv_bo++;
455         }
456         tv_vm->num_shared = num_shared;
457         tv_vm->bo = xe_vm_ttm_bo(vm);
458         list_add_tail(&tv_vm->head, objs);
459         err = ttm_eu_reserve_buffers(ww, objs, intr, &dups);
460         if (err)
461                 goto out_err;
462
463         spin_lock(&vm->notifier.list_lock);
464         list_for_each_entry_safe(vma, next, &vm->notifier.rebind_list,
465                                  notifier.rebind_link) {
466                 xe_bo_assert_held(xe_vma_bo(vma));
467
468                 list_del_init(&vma->notifier.rebind_link);
469                 if (vma->tile_present && !(vma->gpuva.flags & XE_VMA_DESTROYED))
470                         list_move_tail(&vma->combined_links.rebind,
471                                        &vm->rebind_list);
472         }
473         spin_unlock(&vm->notifier.list_lock);
474
475         *tv = tv_vm;
476         return 0;
477
478 out_err:
479         if (tv_vm != tv_onstack)
480                 kvfree(tv_vm);
481
482         return err;
483 }
484
485 /**
486  * xe_vm_unlock_dma_resv() - Unlock reservation objects locked by
487  * xe_vm_lock_dma_resv()
488  * @vm: The vm.
489  * @tv_onstack: The @tv_onstack array given to xe_vm_lock_dma_resv().
490  * @tv: The value of *@tv given by xe_vm_lock_dma_resv().
491  * @ww: The ww_acquire_context used for locking.
492  * @objs: The list returned from xe_vm_lock_dma_resv().
493  *
494  * Unlocks the reservation objects and frees any memory allocated by
495  * xe_vm_lock_dma_resv().
496  */
497 void xe_vm_unlock_dma_resv(struct xe_vm *vm,
498                            struct ttm_validate_buffer *tv_onstack,
499                            struct ttm_validate_buffer *tv,
500                            struct ww_acquire_ctx *ww,
501                            struct list_head *objs)
502 {
503         /*
504          * Nothing should've been able to enter the list while we were locked,
505          * since we've held the dma-resvs of all the vm's external objects,
506          * and holding the dma_resv of an object is required for list
507          * addition, and we shouldn't add ourselves.
508          */
509         XE_WARN_ON(!list_empty(&vm->notifier.rebind_list));
510
511         ttm_eu_backoff_reservation(ww, objs);
512         if (tv && tv != tv_onstack)
513                 kvfree(tv);
514 }
515
516 #define XE_VM_REBIND_RETRY_TIMEOUT_MS 1000
517
518 static void xe_vm_kill(struct xe_vm *vm)
519 {
520         struct ww_acquire_ctx ww;
521         struct xe_engine *e;
522
523         lockdep_assert_held(&vm->lock);
524
525         xe_vm_lock(vm, &ww, 0, false);
526         vm->flags |= XE_VM_FLAG_BANNED;
527         trace_xe_vm_kill(vm);
528
529         list_for_each_entry(e, &vm->preempt.engines, compute.link)
530                 e->ops->kill(e);
531         xe_vm_unlock(vm, &ww);
532
533         /* TODO: Inform user the VM is banned */
534 }
535
536 static void preempt_rebind_work_func(struct work_struct *w)
537 {
538         struct xe_vm *vm = container_of(w, struct xe_vm, preempt.rebind_work);
539         struct xe_vma *vma;
540         struct ttm_validate_buffer tv_onstack[XE_ONSTACK_TV];
541         struct ttm_validate_buffer *tv;
542         struct ww_acquire_ctx ww;
543         struct list_head objs;
544         struct dma_fence *rebind_fence;
545         unsigned int fence_count = 0;
546         LIST_HEAD(preempt_fences);
547         ktime_t end = 0;
548         int err;
549         long wait;
550         int __maybe_unused tries = 0;
551
552         XE_BUG_ON(!xe_vm_in_compute_mode(vm));
553         trace_xe_vm_rebind_worker_enter(vm);
554
555         down_write(&vm->lock);
556
557         if (xe_vm_is_closed_or_banned(vm)) {
558                 up_write(&vm->lock);
559                 trace_xe_vm_rebind_worker_exit(vm);
560                 return;
561         }
562
563 retry:
564         if (vm->async_ops.error)
565                 goto out_unlock_outer;
566
567         /*
568          * Extreme corner where we exit a VM error state with a munmap style VM
569          * unbind inflight which requires a rebind. In this case the rebind
570          * needs to install some fences into the dma-resv slots. The worker to
571          * do this queued, let that worker make progress by dropping vm->lock
572          * and trying this again.
573          */
574         if (vm->async_ops.munmap_rebind_inflight) {
575                 up_write(&vm->lock);
576                 flush_work(&vm->async_ops.work);
577                 goto retry;
578         }
579
580         if (xe_vm_userptr_check_repin(vm)) {
581                 err = xe_vm_userptr_pin(vm);
582                 if (err)
583                         goto out_unlock_outer;
584         }
585
586         err = xe_vm_lock_dma_resv(vm, &ww, tv_onstack, &tv, &objs,
587                                   false, vm->preempt.num_engines);
588         if (err)
589                 goto out_unlock_outer;
590
591         if (xe_vm_is_idle(vm)) {
592                 vm->preempt.rebind_deactivated = true;
593                 goto out_unlock;
594         }
595
596         /* Fresh preempt fences already installed. Everyting is running. */
597         if (!preempt_fences_waiting(vm))
598                 goto out_unlock;
599
600         /*
601          * This makes sure vm is completely suspended and also balances
602          * xe_engine suspend- and resume; we resume *all* vm engines below.
603          */
604         err = wait_for_existing_preempt_fences(vm);
605         if (err)
606                 goto out_unlock;
607
608         err = alloc_preempt_fences(vm, &preempt_fences, &fence_count);
609         if (err)
610                 goto out_unlock;
611
612         list_for_each_entry(vma, &vm->rebind_list, combined_links.rebind) {
613                 if (xe_vma_has_no_bo(vma) ||
614                     vma->gpuva.flags & XE_VMA_DESTROYED)
615                         continue;
616
617                 err = xe_bo_validate(xe_vma_bo(vma), vm, false);
618                 if (err)
619                         goto out_unlock;
620         }
621
622         rebind_fence = xe_vm_rebind(vm, true);
623         if (IS_ERR(rebind_fence)) {
624                 err = PTR_ERR(rebind_fence);
625                 goto out_unlock;
626         }
627
628         if (rebind_fence) {
629                 dma_fence_wait(rebind_fence, false);
630                 dma_fence_put(rebind_fence);
631         }
632
633         /* Wait on munmap style VM unbinds */
634         wait = dma_resv_wait_timeout(xe_vm_resv(vm),
635                                      DMA_RESV_USAGE_KERNEL,
636                                      false, MAX_SCHEDULE_TIMEOUT);
637         if (wait <= 0) {
638                 err = -ETIME;
639                 goto out_unlock;
640         }
641
642 #define retry_required(__tries, __vm) \
643         (IS_ENABLED(CONFIG_DRM_XE_USERPTR_INVAL_INJECT) ? \
644         (!(__tries)++ || __xe_vm_userptr_needs_repin(__vm)) : \
645         __xe_vm_userptr_needs_repin(__vm))
646
647         down_read(&vm->userptr.notifier_lock);
648         if (retry_required(tries, vm)) {
649                 up_read(&vm->userptr.notifier_lock);
650                 err = -EAGAIN;
651                 goto out_unlock;
652         }
653
654 #undef retry_required
655
656         spin_lock(&vm->xe->ttm.lru_lock);
657         ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
658         spin_unlock(&vm->xe->ttm.lru_lock);
659
660         /* Point of no return. */
661         arm_preempt_fences(vm, &preempt_fences);
662         resume_and_reinstall_preempt_fences(vm);
663         up_read(&vm->userptr.notifier_lock);
664
665 out_unlock:
666         xe_vm_unlock_dma_resv(vm, tv_onstack, tv, &ww, &objs);
667 out_unlock_outer:
668         if (err == -EAGAIN) {
669                 trace_xe_vm_rebind_worker_retry(vm);
670                 goto retry;
671         }
672
673         /*
674          * With multiple active VMs, under memory pressure, it is possible that
675          * ttm_bo_validate() run into -EDEADLK and in such case returns -ENOMEM.
676          * Until ttm properly handles locking in such scenarios, best thing the
677          * driver can do is retry with a timeout. Killing the VM or putting it
678          * in error state after timeout or other error scenarios is still TBD.
679          */
680         if (err == -ENOMEM) {
681                 ktime_t cur = ktime_get();
682
683                 end = end ? : ktime_add_ms(cur, XE_VM_REBIND_RETRY_TIMEOUT_MS);
684                 if (ktime_before(cur, end)) {
685                         msleep(20);
686                         trace_xe_vm_rebind_worker_retry(vm);
687                         goto retry;
688                 }
689         }
690         if (err) {
691                 drm_warn(&vm->xe->drm, "VM worker error: %d\n", err);
692                 xe_vm_kill(vm);
693         }
694         up_write(&vm->lock);
695
696         free_preempt_fences(&preempt_fences);
697
698         trace_xe_vm_rebind_worker_exit(vm);
699 }
700
701 static bool vma_userptr_invalidate(struct mmu_interval_notifier *mni,
702                                    const struct mmu_notifier_range *range,
703                                    unsigned long cur_seq)
704 {
705         struct xe_vma *vma = container_of(mni, struct xe_vma, userptr.notifier);
706         struct xe_vm *vm = xe_vma_vm(vma);
707         struct dma_resv_iter cursor;
708         struct dma_fence *fence;
709         long err;
710
711         XE_BUG_ON(!xe_vma_is_userptr(vma));
712         trace_xe_vma_userptr_invalidate(vma);
713
714         if (!mmu_notifier_range_blockable(range))
715                 return false;
716
717         down_write(&vm->userptr.notifier_lock);
718         mmu_interval_set_seq(mni, cur_seq);
719
720         /* No need to stop gpu access if the userptr is not yet bound. */
721         if (!vma->userptr.initial_bind) {
722                 up_write(&vm->userptr.notifier_lock);
723                 return true;
724         }
725
726         /*
727          * Tell exec and rebind worker they need to repin and rebind this
728          * userptr.
729          */
730         if (!xe_vm_in_fault_mode(vm) &&
731             !(vma->gpuva.flags & XE_VMA_DESTROYED) && vma->tile_present) {
732                 spin_lock(&vm->userptr.invalidated_lock);
733                 list_move_tail(&vma->userptr.invalidate_link,
734                                &vm->userptr.invalidated);
735                 spin_unlock(&vm->userptr.invalidated_lock);
736         }
737
738         up_write(&vm->userptr.notifier_lock);
739
740         /*
741          * Preempt fences turn into schedule disables, pipeline these.
742          * Note that even in fault mode, we need to wait for binds and
743          * unbinds to complete, and those are attached as BOOKMARK fences
744          * to the vm.
745          */
746         dma_resv_iter_begin(&cursor, xe_vm_resv(vm),
747                             DMA_RESV_USAGE_BOOKKEEP);
748         dma_resv_for_each_fence_unlocked(&cursor, fence)
749                 dma_fence_enable_sw_signaling(fence);
750         dma_resv_iter_end(&cursor);
751
752         err = dma_resv_wait_timeout(xe_vm_resv(vm),
753                                     DMA_RESV_USAGE_BOOKKEEP,
754                                     false, MAX_SCHEDULE_TIMEOUT);
755         XE_WARN_ON(err <= 0);
756
757         if (xe_vm_in_fault_mode(vm)) {
758                 err = xe_vm_invalidate_vma(vma);
759                 XE_WARN_ON(err);
760         }
761
762         trace_xe_vma_userptr_invalidate_complete(vma);
763
764         return true;
765 }
766
767 static const struct mmu_interval_notifier_ops vma_userptr_notifier_ops = {
768         .invalidate = vma_userptr_invalidate,
769 };
770
771 int xe_vm_userptr_pin(struct xe_vm *vm)
772 {
773         struct xe_vma *vma, *next;
774         int err = 0;
775         LIST_HEAD(tmp_evict);
776
777         lockdep_assert_held_write(&vm->lock);
778
779         /* Collect invalidated userptrs */
780         spin_lock(&vm->userptr.invalidated_lock);
781         list_for_each_entry_safe(vma, next, &vm->userptr.invalidated,
782                                  userptr.invalidate_link) {
783                 list_del_init(&vma->userptr.invalidate_link);
784                 if (list_empty(&vma->combined_links.userptr))
785                         list_move_tail(&vma->combined_links.userptr,
786                                        &vm->userptr.repin_list);
787         }
788         spin_unlock(&vm->userptr.invalidated_lock);
789
790         /* Pin and move to temporary list */
791         list_for_each_entry_safe(vma, next, &vm->userptr.repin_list,
792                                  combined_links.userptr) {
793                 err = xe_vma_userptr_pin_pages(vma);
794                 if (err < 0)
795                         goto out_err;
796
797                 list_move_tail(&vma->combined_links.userptr, &tmp_evict);
798         }
799
800         /* Take lock and move to rebind_list for rebinding. */
801         err = dma_resv_lock_interruptible(xe_vm_resv(vm), NULL);
802         if (err)
803                 goto out_err;
804
805         list_for_each_entry_safe(vma, next, &tmp_evict, combined_links.userptr)
806                 list_move_tail(&vma->combined_links.rebind, &vm->rebind_list);
807
808         dma_resv_unlock(xe_vm_resv(vm));
809
810         return 0;
811
812 out_err:
813         list_splice_tail(&tmp_evict, &vm->userptr.repin_list);
814
815         return err;
816 }
817
818 /**
819  * xe_vm_userptr_check_repin() - Check whether the VM might have userptrs
820  * that need repinning.
821  * @vm: The VM.
822  *
823  * This function does an advisory check for whether the VM has userptrs that
824  * need repinning.
825  *
826  * Return: 0 if there are no indications of userptrs needing repinning,
827  * -EAGAIN if there are.
828  */
829 int xe_vm_userptr_check_repin(struct xe_vm *vm)
830 {
831         return (list_empty_careful(&vm->userptr.repin_list) &&
832                 list_empty_careful(&vm->userptr.invalidated)) ? 0 : -EAGAIN;
833 }
834
835 static struct dma_fence *
836 xe_vm_bind_vma(struct xe_vma *vma, struct xe_engine *e,
837                struct xe_sync_entry *syncs, u32 num_syncs,
838                bool first_op, bool last_op);
839
840 struct dma_fence *xe_vm_rebind(struct xe_vm *vm, bool rebind_worker)
841 {
842         struct dma_fence *fence = NULL;
843         struct xe_vma *vma, *next;
844
845         lockdep_assert_held(&vm->lock);
846         if (xe_vm_no_dma_fences(vm) && !rebind_worker)
847                 return NULL;
848
849         xe_vm_assert_held(vm);
850         list_for_each_entry_safe(vma, next, &vm->rebind_list,
851                                  combined_links.rebind) {
852                 XE_WARN_ON(!vma->tile_present);
853
854                 list_del_init(&vma->combined_links.rebind);
855                 dma_fence_put(fence);
856                 if (rebind_worker)
857                         trace_xe_vma_rebind_worker(vma);
858                 else
859                         trace_xe_vma_rebind_exec(vma);
860                 fence = xe_vm_bind_vma(vma, NULL, NULL, 0, false, false);
861                 if (IS_ERR(fence))
862                         return fence;
863         }
864
865         return fence;
866 }
867
868 static struct xe_vma *xe_vma_create(struct xe_vm *vm,
869                                     struct xe_bo *bo,
870                                     u64 bo_offset_or_userptr,
871                                     u64 start, u64 end,
872                                     bool read_only,
873                                     bool is_null,
874                                     u64 tile_mask)
875 {
876         struct xe_vma *vma;
877         struct xe_tile *tile;
878         u8 id;
879
880         XE_BUG_ON(start >= end);
881         XE_BUG_ON(end >= vm->size);
882
883         vma = kzalloc(sizeof(*vma), GFP_KERNEL);
884         if (!vma) {
885                 vma = ERR_PTR(-ENOMEM);
886                 return vma;
887         }
888
889         INIT_LIST_HEAD(&vma->combined_links.rebind);
890         INIT_LIST_HEAD(&vma->userptr.invalidate_link);
891         INIT_LIST_HEAD(&vma->notifier.rebind_link);
892         INIT_LIST_HEAD(&vma->extobj.link);
893
894         INIT_LIST_HEAD(&vma->gpuva.gem.entry);
895         vma->gpuva.vm = &vm->gpuvm;
896         vma->gpuva.va.addr = start;
897         vma->gpuva.va.range = end - start + 1;
898         if (read_only)
899                 vma->gpuva.flags |= XE_VMA_READ_ONLY;
900         if (is_null)
901                 vma->gpuva.flags |= DRM_GPUVA_SPARSE;
902
903         if (tile_mask) {
904                 vma->tile_mask = tile_mask;
905         } else {
906                 for_each_tile(tile, vm->xe, id)
907                         vma->tile_mask |= 0x1 << id;
908         }
909
910         if (vm->xe->info.platform == XE_PVC)
911                 vma->gpuva.flags |= XE_VMA_ATOMIC_PTE_BIT;
912
913         if (bo) {
914                 struct drm_gpuvm_bo *vm_bo;
915
916                 xe_bo_assert_held(bo);
917
918                 vm_bo = drm_gpuvm_bo_obtain(vma->gpuva.vm, &bo->ttm.base);
919                 if (IS_ERR(vm_bo)) {
920                         kfree(vma);
921                         return ERR_CAST(vm_bo);
922                 }
923
924                 drm_gem_object_get(&bo->ttm.base);
925                 vma->gpuva.gem.obj = &bo->ttm.base;
926                 vma->gpuva.gem.offset = bo_offset_or_userptr;
927                 drm_gpuva_link(&vma->gpuva, vm_bo);
928                 drm_gpuvm_bo_put(vm_bo);
929         } else /* userptr or null */ {
930                 if (!is_null) {
931                         u64 size = end - start + 1;
932                         int err;
933
934                         vma->gpuva.gem.offset = bo_offset_or_userptr;
935
936                         err = mmu_interval_notifier_insert(&vma->userptr.notifier,
937                                                            current->mm,
938                                                            xe_vma_userptr(vma), size,
939                                                            &vma_userptr_notifier_ops);
940                         if (err) {
941                                 kfree(vma);
942                                 vma = ERR_PTR(err);
943                                 return vma;
944                         }
945
946                         vma->userptr.notifier_seq = LONG_MAX;
947                 }
948
949                 xe_vm_get(vm);
950         }
951
952         return vma;
953 }
954
955 static bool vm_remove_extobj(struct xe_vma *vma)
956 {
957         if (!list_empty(&vma->extobj.link)) {
958                 xe_vma_vm(vma)->extobj.entries--;
959                 list_del_init(&vma->extobj.link);
960                 return true;
961         }
962         return false;
963 }
964
965 static void xe_vma_destroy_late(struct xe_vma *vma)
966 {
967         struct xe_vm *vm = xe_vma_vm(vma);
968         struct xe_device *xe = vm->xe;
969         bool read_only = xe_vma_read_only(vma);
970
971         if (xe_vma_is_userptr(vma)) {
972                 if (vma->userptr.sg) {
973                         dma_unmap_sgtable(xe->drm.dev,
974                                           vma->userptr.sg,
975                                           read_only ? DMA_TO_DEVICE :
976                                           DMA_BIDIRECTIONAL, 0);
977                         sg_free_table(vma->userptr.sg);
978                         vma->userptr.sg = NULL;
979                 }
980
981                 /*
982                  * Since userptr pages are not pinned, we can't remove
983                  * the notifer until we're sure the GPU is not accessing
984                  * them anymore
985                  */
986                 mmu_interval_notifier_remove(&vma->userptr.notifier);
987                 xe_vm_put(vm);
988         } else if (xe_vma_is_null(vma)) {
989                 xe_vm_put(vm);
990         } else {
991                 xe_bo_put(xe_vma_bo(vma));
992         }
993
994         kfree(vma);
995 }
996
997 static void vma_destroy_work_func(struct work_struct *w)
998 {
999         struct xe_vma *vma =
1000                 container_of(w, struct xe_vma, destroy_work);
1001
1002         xe_vma_destroy_late(vma);
1003 }
1004
1005 static struct xe_vma *
1006 bo_has_vm_references_locked(struct xe_bo *bo, struct xe_vm *vm,
1007                             struct xe_vma *ignore)
1008 {
1009         struct drm_gpuvm_bo *vm_bo;
1010         struct drm_gpuva *va;
1011         struct drm_gem_object *obj = &bo->ttm.base;
1012
1013         xe_bo_assert_held(bo);
1014
1015         drm_gem_for_each_gpuvm_bo(vm_bo, obj) {
1016                 drm_gpuvm_bo_for_each_va(va, vm_bo) {
1017                         struct xe_vma *vma = gpuva_to_vma(va);
1018
1019                         if (vma != ignore && xe_vma_vm(vma) == vm)
1020                                 return vma;
1021                 }
1022         }
1023
1024         return NULL;
1025 }
1026
1027 static bool bo_has_vm_references(struct xe_bo *bo, struct xe_vm *vm,
1028                                  struct xe_vma *ignore)
1029 {
1030         struct ww_acquire_ctx ww;
1031         bool ret;
1032
1033         xe_bo_lock(bo, &ww, 0, false);
1034         ret = !!bo_has_vm_references_locked(bo, vm, ignore);
1035         xe_bo_unlock(bo, &ww);
1036
1037         return ret;
1038 }
1039
1040 static void __vm_insert_extobj(struct xe_vm *vm, struct xe_vma *vma)
1041 {
1042         lockdep_assert_held_write(&vm->lock);
1043
1044         list_add(&vma->extobj.link, &vm->extobj.list);
1045         vm->extobj.entries++;
1046 }
1047
1048 static void vm_insert_extobj(struct xe_vm *vm, struct xe_vma *vma)
1049 {
1050         struct xe_bo *bo = xe_vma_bo(vma);
1051
1052         lockdep_assert_held_write(&vm->lock);
1053
1054         if (bo_has_vm_references(bo, vm, vma))
1055                 return;
1056
1057         __vm_insert_extobj(vm, vma);
1058 }
1059
1060 static void vma_destroy_cb(struct dma_fence *fence,
1061                            struct dma_fence_cb *cb)
1062 {
1063         struct xe_vma *vma = container_of(cb, struct xe_vma, destroy_cb);
1064
1065         INIT_WORK(&vma->destroy_work, vma_destroy_work_func);
1066         queue_work(system_unbound_wq, &vma->destroy_work);
1067 }
1068
1069 static void xe_vma_destroy(struct xe_vma *vma, struct dma_fence *fence)
1070 {
1071         struct xe_vm *vm = xe_vma_vm(vma);
1072
1073         lockdep_assert_held_write(&vm->lock);
1074         XE_BUG_ON(!list_empty(&vma->combined_links.destroy));
1075
1076         if (xe_vma_is_userptr(vma)) {
1077                 XE_WARN_ON(!(vma->gpuva.flags & XE_VMA_DESTROYED));
1078
1079                 spin_lock(&vm->userptr.invalidated_lock);
1080                 list_del_init(&vma->userptr.invalidate_link);
1081                 spin_unlock(&vm->userptr.invalidated_lock);
1082         } else if (!xe_vma_is_null(vma)) {
1083                 xe_bo_assert_held(xe_vma_bo(vma));
1084
1085                 spin_lock(&vm->notifier.list_lock);
1086                 list_del(&vma->notifier.rebind_link);
1087                 spin_unlock(&vm->notifier.list_lock);
1088
1089                 drm_gpuva_unlink(&vma->gpuva);
1090
1091                 if (!xe_vma_bo(vma)->vm && vm_remove_extobj(vma)) {
1092                         struct xe_vma *other;
1093
1094                         other = bo_has_vm_references_locked(xe_vma_bo(vma), vm, NULL);
1095
1096                         if (other)
1097                                 __vm_insert_extobj(vm, other);
1098                 }
1099         }
1100
1101         xe_vm_assert_held(vm);
1102         if (fence) {
1103                 int ret = dma_fence_add_callback(fence, &vma->destroy_cb,
1104                                                  vma_destroy_cb);
1105
1106                 if (ret) {
1107                         XE_WARN_ON(ret != -ENOENT);
1108                         xe_vma_destroy_late(vma);
1109                 }
1110         } else {
1111                 xe_vma_destroy_late(vma);
1112         }
1113 }
1114
1115 static void xe_vma_destroy_unlocked(struct xe_vma *vma)
1116 {
1117         struct ttm_validate_buffer tv[2];
1118         struct ww_acquire_ctx ww;
1119         struct xe_bo *bo = xe_vma_bo(vma);
1120         LIST_HEAD(objs);
1121         LIST_HEAD(dups);
1122         int err;
1123
1124         memset(tv, 0, sizeof(tv));
1125         tv[0].bo = xe_vm_ttm_bo(xe_vma_vm(vma));
1126         list_add(&tv[0].head, &objs);
1127
1128         if (bo) {
1129                 tv[1].bo = &xe_bo_get(bo)->ttm;
1130                 list_add(&tv[1].head, &objs);
1131         }
1132         err = ttm_eu_reserve_buffers(&ww, &objs, false, &dups);
1133         XE_WARN_ON(err);
1134
1135         xe_vma_destroy(vma, NULL);
1136
1137         ttm_eu_backoff_reservation(&ww, &objs);
1138         if (bo)
1139                 xe_bo_put(bo);
1140 }
1141
1142 struct xe_vma *
1143 xe_vm_find_overlapping_vma(struct xe_vm *vm, u64 start, u64 range)
1144 {
1145         struct drm_gpuva *gpuva;
1146
1147         lockdep_assert_held(&vm->lock);
1148
1149         if (xe_vm_is_closed_or_banned(vm))
1150                 return NULL;
1151
1152         XE_BUG_ON(start + range > vm->size);
1153
1154         gpuva = drm_gpuva_find_first(&vm->gpuvm, start, range);
1155
1156         return gpuva ? gpuva_to_vma(gpuva) : NULL;
1157 }
1158
1159 static int xe_vm_insert_vma(struct xe_vm *vm, struct xe_vma *vma)
1160 {
1161         int err;
1162
1163         XE_BUG_ON(xe_vma_vm(vma) != vm);
1164         lockdep_assert_held(&vm->lock);
1165
1166         err = drm_gpuva_insert(&vm->gpuvm, &vma->gpuva);
1167         XE_WARN_ON(err);        /* Shouldn't be possible */
1168
1169         return err;
1170 }
1171
1172 static void xe_vm_remove_vma(struct xe_vm *vm, struct xe_vma *vma)
1173 {
1174         XE_BUG_ON(xe_vma_vm(vma) != vm);
1175         lockdep_assert_held(&vm->lock);
1176
1177         drm_gpuva_remove(&vma->gpuva);
1178         if (vm->usm.last_fault_vma == vma)
1179                 vm->usm.last_fault_vma = NULL;
1180 }
1181
1182 static struct drm_gpuva_op *xe_vm_op_alloc(void)
1183 {
1184         struct xe_vma_op *op;
1185
1186         op = kzalloc(sizeof(*op), GFP_KERNEL);
1187
1188         if (unlikely(!op))
1189                 return NULL;
1190
1191         return &op->base;
1192 }
1193
1194 static void xe_vm_free(struct drm_gpuvm *gpuvm);
1195
1196 static struct drm_gpuvm_ops gpuvm_ops = {
1197         .op_alloc = xe_vm_op_alloc,
1198         .vm_free = xe_vm_free,
1199 };
1200
1201 static void xe_vma_op_work_func(struct work_struct *w);
1202 static void vm_destroy_work_func(struct work_struct *w);
1203
1204 struct xe_vm *xe_vm_create(struct xe_device *xe, u32 flags)
1205 {
1206         struct drm_gem_object *vm_resv_obj;
1207         struct xe_vm *vm;
1208         int err, number_tiles = 0;
1209         struct xe_tile *tile;
1210         u8 id;
1211
1212         vm = kzalloc(sizeof(*vm), GFP_KERNEL);
1213         if (!vm)
1214                 return ERR_PTR(-ENOMEM);
1215
1216         vm->xe = xe;
1217
1218         vm->size = 1ull << xe_pt_shift(xe->info.vm_max_level + 1);
1219
1220         vm->flags = flags;
1221
1222         init_rwsem(&vm->lock);
1223
1224         INIT_LIST_HEAD(&vm->rebind_list);
1225
1226         INIT_LIST_HEAD(&vm->userptr.repin_list);
1227         INIT_LIST_HEAD(&vm->userptr.invalidated);
1228         init_rwsem(&vm->userptr.notifier_lock);
1229         spin_lock_init(&vm->userptr.invalidated_lock);
1230
1231         INIT_LIST_HEAD(&vm->notifier.rebind_list);
1232         spin_lock_init(&vm->notifier.list_lock);
1233
1234         INIT_LIST_HEAD(&vm->async_ops.pending);
1235         INIT_WORK(&vm->async_ops.work, xe_vma_op_work_func);
1236         spin_lock_init(&vm->async_ops.lock);
1237
1238         INIT_WORK(&vm->destroy_work, vm_destroy_work_func);
1239
1240         INIT_LIST_HEAD(&vm->preempt.engines);
1241         vm->preempt.min_run_period_ms = 10;     /* FIXME: Wire up to uAPI */
1242
1243         for_each_tile(tile, xe, id)
1244                 xe_range_fence_tree_init(&vm->rftree[id]);
1245
1246         INIT_LIST_HEAD(&vm->extobj.list);
1247
1248         if (!(flags & XE_VM_FLAG_MIGRATION))
1249                 xe_device_mem_access_get(xe);
1250
1251         vm_resv_obj = drm_gpuvm_resv_object_alloc(&xe->drm);
1252         if (!vm_resv_obj) {
1253                 err = -ENOMEM;
1254                 goto err_no_resv;
1255         }
1256
1257         drm_gpuvm_init(&vm->gpuvm, "Xe VM", 0, &xe->drm, vm_resv_obj,
1258                        0, vm->size, 0, 0, &gpuvm_ops);
1259
1260         drm_gem_object_put(vm_resv_obj);
1261
1262         err = dma_resv_lock_interruptible(xe_vm_resv(vm), NULL);
1263         if (err)
1264                 goto err_close;
1265
1266         if (IS_DGFX(xe) && xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K)
1267                 vm->flags |= XE_VM_FLAG_64K;
1268
1269         for_each_tile(tile, xe, id) {
1270                 if (flags & XE_VM_FLAG_MIGRATION &&
1271                     tile->id != XE_VM_FLAG_TILE_ID(flags))
1272                         continue;
1273
1274                 vm->pt_root[id] = xe_pt_create(vm, tile, xe->info.vm_max_level);
1275                 if (IS_ERR(vm->pt_root[id])) {
1276                         err = PTR_ERR(vm->pt_root[id]);
1277                         vm->pt_root[id] = NULL;
1278                         goto err_unlock_close;
1279                 }
1280         }
1281
1282         if (flags & XE_VM_FLAG_SCRATCH_PAGE) {
1283                 for_each_tile(tile, xe, id) {
1284                         if (!vm->pt_root[id])
1285                                 continue;
1286
1287                         err = xe_pt_create_scratch(xe, tile, vm);
1288                         if (err)
1289                                 goto err_unlock_close;
1290                 }
1291                 vm->batch_invalidate_tlb = true;
1292         }
1293
1294         if (flags & XE_VM_FLAG_COMPUTE_MODE) {
1295                 INIT_WORK(&vm->preempt.rebind_work, preempt_rebind_work_func);
1296                 vm->flags |= XE_VM_FLAG_COMPUTE_MODE;
1297                 vm->batch_invalidate_tlb = false;
1298         }
1299
1300         if (flags & XE_VM_FLAG_ASYNC_BIND_OPS) {
1301                 vm->async_ops.fence.context = dma_fence_context_alloc(1);
1302                 vm->flags |= XE_VM_FLAG_ASYNC_BIND_OPS;
1303         }
1304
1305         /* Fill pt_root after allocating scratch tables */
1306         for_each_tile(tile, xe, id) {
1307                 if (!vm->pt_root[id])
1308                         continue;
1309
1310                 xe_pt_populate_empty(tile, vm, vm->pt_root[id]);
1311         }
1312         dma_resv_unlock(xe_vm_resv(vm));
1313
1314         /* Kernel migration VM shouldn't have a circular loop.. */
1315         if (!(flags & XE_VM_FLAG_MIGRATION)) {
1316                 for_each_tile(tile, xe, id) {
1317                         struct xe_gt *gt = tile->primary_gt;
1318                         struct xe_vm *migrate_vm;
1319                         struct xe_engine *eng;
1320
1321                         if (!vm->pt_root[id])
1322                                 continue;
1323
1324                         migrate_vm = xe_migrate_get_vm(tile->migrate);
1325                         eng = xe_engine_create_class(xe, gt, migrate_vm,
1326                                                      XE_ENGINE_CLASS_COPY,
1327                                                      ENGINE_FLAG_VM);
1328                         xe_vm_put(migrate_vm);
1329                         if (IS_ERR(eng)) {
1330                                 err = PTR_ERR(eng);
1331                                 goto err_close;
1332                         }
1333                         vm->eng[id] = eng;
1334                         number_tiles++;
1335                 }
1336         }
1337
1338         if (number_tiles > 1)
1339                 vm->composite_fence_ctx = dma_fence_context_alloc(1);
1340
1341         mutex_lock(&xe->usm.lock);
1342         if (flags & XE_VM_FLAG_FAULT_MODE)
1343                 xe->usm.num_vm_in_fault_mode++;
1344         else if (!(flags & XE_VM_FLAG_MIGRATION))
1345                 xe->usm.num_vm_in_non_fault_mode++;
1346         mutex_unlock(&xe->usm.lock);
1347
1348         trace_xe_vm_create(vm);
1349
1350         return vm;
1351
1352 err_unlock_close:
1353         dma_resv_unlock(xe_vm_resv(vm));
1354 err_close:
1355         xe_vm_close_and_put(vm);
1356         return ERR_PTR(err);
1357
1358 err_no_resv:
1359         for_each_tile(tile, xe, id)
1360                 xe_range_fence_tree_fini(&vm->rftree[id]);
1361         kfree(vm);
1362         if (!(flags & XE_VM_FLAG_MIGRATION))
1363                 xe_device_mem_access_put(xe);
1364         return ERR_PTR(err);
1365 }
1366
1367 static void flush_async_ops(struct xe_vm *vm)
1368 {
1369         queue_work(system_unbound_wq, &vm->async_ops.work);
1370         flush_work(&vm->async_ops.work);
1371 }
1372
1373 static void vm_error_capture(struct xe_vm *vm, int err,
1374                              u32 op, u64 addr, u64 size)
1375 {
1376         struct drm_xe_vm_bind_op_error_capture capture;
1377         u64 __user *address =
1378                 u64_to_user_ptr(vm->async_ops.error_capture.addr);
1379         bool in_kthread = !current->mm;
1380
1381         capture.error = err;
1382         capture.op = op;
1383         capture.addr = addr;
1384         capture.size = size;
1385
1386         if (in_kthread) {
1387                 if (!mmget_not_zero(vm->async_ops.error_capture.mm))
1388                         goto mm_closed;
1389                 kthread_use_mm(vm->async_ops.error_capture.mm);
1390         }
1391
1392         if (copy_to_user(address, &capture, sizeof(capture)))
1393                 XE_WARN_ON("Copy to user failed");
1394
1395         if (in_kthread) {
1396                 kthread_unuse_mm(vm->async_ops.error_capture.mm);
1397                 mmput(vm->async_ops.error_capture.mm);
1398         }
1399
1400 mm_closed:
1401         wake_up_all(&vm->async_ops.error_capture.wq);
1402 }
1403
1404 static void xe_vm_close(struct xe_vm *vm)
1405 {
1406         down_write(&vm->lock);
1407         vm->size = 0;
1408         up_write(&vm->lock);
1409 }
1410
1411 void xe_vm_close_and_put(struct xe_vm *vm)
1412 {
1413         LIST_HEAD(contested);
1414         struct ww_acquire_ctx ww;
1415         struct xe_device *xe = vm->xe;
1416         struct xe_tile *tile;
1417         struct xe_vma *vma, *next_vma;
1418         struct drm_gpuva *gpuva, *next;
1419         u8 id;
1420
1421         XE_BUG_ON(vm->preempt.num_engines);
1422
1423         xe_vm_close(vm);
1424         flush_async_ops(vm);
1425         if (xe_vm_in_compute_mode(vm))
1426                 flush_work(&vm->preempt.rebind_work);
1427
1428         for_each_tile(tile, xe, id) {
1429                 if (vm->eng[id]) {
1430                         xe_engine_kill(vm->eng[id]);
1431                         xe_engine_put(vm->eng[id]);
1432                         vm->eng[id] = NULL;
1433                 }
1434         }
1435
1436         down_write(&vm->lock);
1437         xe_vm_lock(vm, &ww, 0, false);
1438         drm_gpuvm_for_each_va_safe(gpuva, next, &vm->gpuvm) {
1439                 vma = gpuva_to_vma(gpuva);
1440
1441                 if (xe_vma_has_no_bo(vma)) {
1442                         down_read(&vm->userptr.notifier_lock);
1443                         vma->gpuva.flags |= XE_VMA_DESTROYED;
1444                         up_read(&vm->userptr.notifier_lock);
1445                 }
1446
1447                 xe_vm_remove_vma(vm, vma);
1448
1449                 /* easy case, remove from VMA? */
1450                 if (xe_vma_has_no_bo(vma) || xe_vma_bo(vma)->vm) {
1451                         list_del_init(&vma->combined_links.rebind);
1452                         xe_vma_destroy(vma, NULL);
1453                         continue;
1454                 }
1455
1456                 list_move_tail(&vma->combined_links.destroy, &contested);
1457         }
1458
1459         /*
1460          * All vm operations will add shared fences to resv.
1461          * The only exception is eviction for a shared object,
1462          * but even so, the unbind when evicted would still
1463          * install a fence to resv. Hence it's safe to
1464          * destroy the pagetables immediately.
1465          */
1466         for_each_tile(tile, xe, id) {
1467                 if (vm->scratch_bo[id]) {
1468                         u32 i;
1469
1470                         xe_bo_unpin(vm->scratch_bo[id]);
1471                         xe_bo_put(vm->scratch_bo[id]);
1472                         for (i = 0; i < vm->pt_root[id]->level; i++)
1473                                 xe_pt_destroy(vm->scratch_pt[id][i], vm->flags,
1474                                               NULL);
1475                 }
1476                 if (vm->pt_root[id]) {
1477                         xe_pt_destroy(vm->pt_root[id], vm->flags, NULL);
1478                         vm->pt_root[id] = NULL;
1479                 }
1480         }
1481         xe_vm_unlock(vm, &ww);
1482
1483         /*
1484          * VM is now dead, cannot re-add nodes to vm->vmas if it's NULL
1485          * Since we hold a refcount to the bo, we can remove and free
1486          * the members safely without locking.
1487          */
1488         list_for_each_entry_safe(vma, next_vma, &contested,
1489                                  combined_links.destroy) {
1490                 list_del_init(&vma->combined_links.destroy);
1491                 xe_vma_destroy_unlocked(vma);
1492         }
1493
1494         if (vm->async_ops.error_capture.addr)
1495                 wake_up_all(&vm->async_ops.error_capture.wq);
1496
1497         XE_WARN_ON(!list_empty(&vm->extobj.list));
1498         up_write(&vm->lock);
1499
1500         mutex_lock(&xe->usm.lock);
1501         if (vm->flags & XE_VM_FLAG_FAULT_MODE)
1502                 xe->usm.num_vm_in_fault_mode--;
1503         else if (!(vm->flags & XE_VM_FLAG_MIGRATION))
1504                 xe->usm.num_vm_in_non_fault_mode--;
1505         mutex_unlock(&xe->usm.lock);
1506
1507         for_each_tile(tile, xe, id)
1508                 xe_range_fence_tree_fini(&vm->rftree[id]);
1509
1510         xe_vm_put(vm);
1511 }
1512
1513 static void vm_destroy_work_func(struct work_struct *w)
1514 {
1515         struct xe_vm *vm =
1516                 container_of(w, struct xe_vm, destroy_work);
1517         struct xe_device *xe = vm->xe;
1518         struct xe_tile *tile;
1519         u8 id;
1520         void *lookup;
1521
1522         /* xe_vm_close_and_put was not called? */
1523         XE_WARN_ON(vm->size);
1524
1525         if (!(vm->flags & XE_VM_FLAG_MIGRATION)) {
1526                 xe_device_mem_access_put(xe);
1527
1528                 if (xe->info.has_asid) {
1529                         mutex_lock(&xe->usm.lock);
1530                         lookup = xa_erase(&xe->usm.asid_to_vm, vm->usm.asid);
1531                         XE_WARN_ON(lookup != vm);
1532                         mutex_unlock(&xe->usm.lock);
1533                 }
1534         }
1535
1536         for_each_tile(tile, xe, id)
1537                 XE_WARN_ON(vm->pt_root[id]);
1538
1539         trace_xe_vm_free(vm);
1540         dma_fence_put(vm->rebind_fence);
1541         kfree(vm);
1542 }
1543
1544 static void xe_vm_free(struct drm_gpuvm *gpuvm)
1545 {
1546         struct xe_vm *vm = container_of(gpuvm, struct xe_vm, gpuvm);
1547
1548         /* To destroy the VM we need to be able to sleep */
1549         queue_work(system_unbound_wq, &vm->destroy_work);
1550 }
1551
1552 struct xe_vm *xe_vm_lookup(struct xe_file *xef, u32 id)
1553 {
1554         struct xe_vm *vm;
1555
1556         mutex_lock(&xef->vm.lock);
1557         vm = xa_load(&xef->vm.xa, id);
1558         if (vm)
1559                 xe_vm_get(vm);
1560         mutex_unlock(&xef->vm.lock);
1561
1562         return vm;
1563 }
1564
1565 u64 xe_vm_pdp4_descriptor(struct xe_vm *vm, struct xe_tile *tile)
1566 {
1567         return xe_pde_encode(vm->pt_root[tile->id]->bo, 0,
1568                              XE_CACHE_WB);
1569 }
1570
1571 static struct dma_fence *
1572 xe_vm_unbind_vma(struct xe_vma *vma, struct xe_engine *e,
1573                  struct xe_sync_entry *syncs, u32 num_syncs,
1574                  bool first_op, bool last_op)
1575 {
1576         struct xe_tile *tile;
1577         struct dma_fence *fence = NULL;
1578         struct dma_fence **fences = NULL;
1579         struct dma_fence_array *cf = NULL;
1580         struct xe_vm *vm = xe_vma_vm(vma);
1581         int cur_fence = 0, i;
1582         int number_tiles = hweight_long(vma->tile_present);
1583         int err;
1584         u8 id;
1585
1586         trace_xe_vma_unbind(vma);
1587
1588         if (number_tiles > 1) {
1589                 fences = kmalloc_array(number_tiles, sizeof(*fences),
1590                                        GFP_KERNEL);
1591                 if (!fences)
1592                         return ERR_PTR(-ENOMEM);
1593         }
1594
1595         for_each_tile(tile, vm->xe, id) {
1596                 if (!(vma->tile_present & BIT(id)))
1597                         goto next;
1598
1599                 fence = __xe_pt_unbind_vma(tile, vma, e, first_op ? syncs : NULL,
1600                                            first_op ? num_syncs : 0);
1601                 if (IS_ERR(fence)) {
1602                         err = PTR_ERR(fence);
1603                         goto err_fences;
1604                 }
1605
1606                 if (fences)
1607                         fences[cur_fence++] = fence;
1608
1609 next:
1610                 if (e && vm->pt_root[id] && !list_empty(&e->multi_gt_list))
1611                         e = list_next_entry(e, multi_gt_list);
1612         }
1613
1614         if (fences) {
1615                 cf = dma_fence_array_create(number_tiles, fences,
1616                                             vm->composite_fence_ctx,
1617                                             vm->composite_fence_seqno++,
1618                                             false);
1619                 if (!cf) {
1620                         --vm->composite_fence_seqno;
1621                         err = -ENOMEM;
1622                         goto err_fences;
1623                 }
1624         }
1625
1626         if (last_op) {
1627                 for (i = 0; i < num_syncs; i++)
1628                         xe_sync_entry_signal(&syncs[i], NULL,
1629                                              cf ? &cf->base : fence);
1630         }
1631
1632         return cf ? &cf->base : !fence ? dma_fence_get_stub() : fence;
1633
1634 err_fences:
1635         if (fences) {
1636                 while (cur_fence) {
1637                         /* FIXME: Rewind the previous binds? */
1638                         dma_fence_put(fences[--cur_fence]);
1639                 }
1640                 kfree(fences);
1641         }
1642
1643         return ERR_PTR(err);
1644 }
1645
1646 static struct dma_fence *
1647 xe_vm_bind_vma(struct xe_vma *vma, struct xe_engine *e,
1648                struct xe_sync_entry *syncs, u32 num_syncs,
1649                bool first_op, bool last_op)
1650 {
1651         struct xe_tile *tile;
1652         struct dma_fence *fence;
1653         struct dma_fence **fences = NULL;
1654         struct dma_fence_array *cf = NULL;
1655         struct xe_vm *vm = xe_vma_vm(vma);
1656         int cur_fence = 0, i;
1657         int number_tiles = hweight_long(vma->tile_mask);
1658         int err;
1659         u8 id;
1660
1661         trace_xe_vma_bind(vma);
1662
1663         if (number_tiles > 1) {
1664                 fences = kmalloc_array(number_tiles, sizeof(*fences),
1665                                        GFP_KERNEL);
1666                 if (!fences)
1667                         return ERR_PTR(-ENOMEM);
1668         }
1669
1670         for_each_tile(tile, vm->xe, id) {
1671                 if (!(vma->tile_mask & BIT(id)))
1672                         goto next;
1673
1674                 fence = __xe_pt_bind_vma(tile, vma, e, first_op ? syncs : NULL,
1675                                          first_op ? num_syncs : 0,
1676                                          vma->tile_present & BIT(id));
1677                 if (IS_ERR(fence)) {
1678                         err = PTR_ERR(fence);
1679                         goto err_fences;
1680                 }
1681
1682                 if (fences)
1683                         fences[cur_fence++] = fence;
1684
1685 next:
1686                 if (e && vm->pt_root[id] && !list_empty(&e->multi_gt_list))
1687                         e = list_next_entry(e, multi_gt_list);
1688         }
1689
1690         if (fences) {
1691                 cf = dma_fence_array_create(number_tiles, fences,
1692                                             vm->composite_fence_ctx,
1693                                             vm->composite_fence_seqno++,
1694                                             false);
1695                 if (!cf) {
1696                         --vm->composite_fence_seqno;
1697                         err = -ENOMEM;
1698                         goto err_fences;
1699                 }
1700         }
1701
1702         if (last_op) {
1703                 for (i = 0; i < num_syncs; i++)
1704                         xe_sync_entry_signal(&syncs[i], NULL,
1705                                              cf ? &cf->base : fence);
1706         }
1707
1708         return cf ? &cf->base : fence;
1709
1710 err_fences:
1711         if (fences) {
1712                 while (cur_fence) {
1713                         /* FIXME: Rewind the previous binds? */
1714                         dma_fence_put(fences[--cur_fence]);
1715                 }
1716                 kfree(fences);
1717         }
1718
1719         return ERR_PTR(err);
1720 }
1721
1722 struct async_op_fence {
1723         struct dma_fence fence;
1724         struct dma_fence *wait_fence;
1725         struct dma_fence_cb cb;
1726         struct xe_vm *vm;
1727         wait_queue_head_t wq;
1728         bool started;
1729 };
1730
1731 static const char *async_op_fence_get_driver_name(struct dma_fence *dma_fence)
1732 {
1733         return "xe";
1734 }
1735
1736 static const char *
1737 async_op_fence_get_timeline_name(struct dma_fence *dma_fence)
1738 {
1739         return "async_op_fence";
1740 }
1741
1742 static const struct dma_fence_ops async_op_fence_ops = {
1743         .get_driver_name = async_op_fence_get_driver_name,
1744         .get_timeline_name = async_op_fence_get_timeline_name,
1745 };
1746
1747 static void async_op_fence_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
1748 {
1749         struct async_op_fence *afence =
1750                 container_of(cb, struct async_op_fence, cb);
1751
1752         afence->fence.error = afence->wait_fence->error;
1753         dma_fence_signal(&afence->fence);
1754         xe_vm_put(afence->vm);
1755         dma_fence_put(afence->wait_fence);
1756         dma_fence_put(&afence->fence);
1757 }
1758
1759 static void add_async_op_fence_cb(struct xe_vm *vm,
1760                                   struct dma_fence *fence,
1761                                   struct async_op_fence *afence)
1762 {
1763         int ret;
1764
1765         if (!xe_vm_no_dma_fences(vm)) {
1766                 afence->started = true;
1767                 smp_wmb();
1768                 wake_up_all(&afence->wq);
1769         }
1770
1771         afence->wait_fence = dma_fence_get(fence);
1772         afence->vm = xe_vm_get(vm);
1773         dma_fence_get(&afence->fence);
1774         ret = dma_fence_add_callback(fence, &afence->cb, async_op_fence_cb);
1775         if (ret == -ENOENT) {
1776                 afence->fence.error = afence->wait_fence->error;
1777                 dma_fence_signal(&afence->fence);
1778         }
1779         if (ret) {
1780                 xe_vm_put(vm);
1781                 dma_fence_put(afence->wait_fence);
1782                 dma_fence_put(&afence->fence);
1783         }
1784         XE_WARN_ON(ret && ret != -ENOENT);
1785 }
1786
1787 int xe_vm_async_fence_wait_start(struct dma_fence *fence)
1788 {
1789         if (fence->ops == &async_op_fence_ops) {
1790                 struct async_op_fence *afence =
1791                         container_of(fence, struct async_op_fence, fence);
1792
1793                 XE_BUG_ON(xe_vm_no_dma_fences(afence->vm));
1794
1795                 smp_rmb();
1796                 return wait_event_interruptible(afence->wq, afence->started);
1797         }
1798
1799         return 0;
1800 }
1801
1802 static int __xe_vm_bind(struct xe_vm *vm, struct xe_vma *vma,
1803                         struct xe_engine *e, struct xe_sync_entry *syncs,
1804                         u32 num_syncs, struct async_op_fence *afence,
1805                         bool immediate, bool first_op, bool last_op)
1806 {
1807         struct dma_fence *fence;
1808
1809         xe_vm_assert_held(vm);
1810
1811         if (immediate) {
1812                 fence = xe_vm_bind_vma(vma, e, syncs, num_syncs, first_op,
1813                                        last_op);
1814                 if (IS_ERR(fence))
1815                         return PTR_ERR(fence);
1816         } else {
1817                 int i;
1818
1819                 XE_BUG_ON(!xe_vm_in_fault_mode(vm));
1820
1821                 fence = dma_fence_get_stub();
1822                 if (last_op) {
1823                         for (i = 0; i < num_syncs; i++)
1824                                 xe_sync_entry_signal(&syncs[i], NULL, fence);
1825                 }
1826         }
1827         if (afence)
1828                 add_async_op_fence_cb(vm, fence, afence);
1829
1830         dma_fence_put(fence);
1831         return 0;
1832 }
1833
1834 static int xe_vm_bind(struct xe_vm *vm, struct xe_vma *vma, struct xe_engine *e,
1835                       struct xe_bo *bo, struct xe_sync_entry *syncs,
1836                       u32 num_syncs, struct async_op_fence *afence,
1837                       bool immediate, bool first_op, bool last_op)
1838 {
1839         int err;
1840
1841         xe_vm_assert_held(vm);
1842         xe_bo_assert_held(bo);
1843
1844         if (bo && immediate) {
1845                 err = xe_bo_validate(bo, vm, true);
1846                 if (err)
1847                         return err;
1848         }
1849
1850         return __xe_vm_bind(vm, vma, e, syncs, num_syncs, afence, immediate,
1851                             first_op, last_op);
1852 }
1853
1854 static int xe_vm_unbind(struct xe_vm *vm, struct xe_vma *vma,
1855                         struct xe_engine *e, struct xe_sync_entry *syncs,
1856                         u32 num_syncs, struct async_op_fence *afence,
1857                         bool first_op, bool last_op)
1858 {
1859         struct dma_fence *fence;
1860
1861         xe_vm_assert_held(vm);
1862         xe_bo_assert_held(xe_vma_bo(vma));
1863
1864         fence = xe_vm_unbind_vma(vma, e, syncs, num_syncs, first_op, last_op);
1865         if (IS_ERR(fence))
1866                 return PTR_ERR(fence);
1867         if (afence)
1868                 add_async_op_fence_cb(vm, fence, afence);
1869
1870         xe_vma_destroy(vma, fence);
1871         dma_fence_put(fence);
1872
1873         return 0;
1874 }
1875
1876 static int vm_set_error_capture_address(struct xe_device *xe, struct xe_vm *vm,
1877                                         u64 value)
1878 {
1879         if (XE_IOCTL_DBG(xe, !value))
1880                 return -EINVAL;
1881
1882         if (XE_IOCTL_DBG(xe, !(vm->flags & XE_VM_FLAG_ASYNC_BIND_OPS)))
1883                 return -EOPNOTSUPP;
1884
1885         if (XE_IOCTL_DBG(xe, vm->async_ops.error_capture.addr))
1886                 return -EOPNOTSUPP;
1887
1888         vm->async_ops.error_capture.mm = current->mm;
1889         vm->async_ops.error_capture.addr = value;
1890         init_waitqueue_head(&vm->async_ops.error_capture.wq);
1891
1892         return 0;
1893 }
1894
1895 typedef int (*xe_vm_set_property_fn)(struct xe_device *xe, struct xe_vm *vm,
1896                                      u64 value);
1897
1898 static const xe_vm_set_property_fn vm_set_property_funcs[] = {
1899         [XE_VM_PROPERTY_BIND_OP_ERROR_CAPTURE_ADDRESS] =
1900                 vm_set_error_capture_address,
1901 };
1902
1903 static int vm_user_ext_set_property(struct xe_device *xe, struct xe_vm *vm,
1904                                     u64 extension)
1905 {
1906         u64 __user *address = u64_to_user_ptr(extension);
1907         struct drm_xe_ext_vm_set_property ext;
1908         int err;
1909
1910         err = __copy_from_user(&ext, address, sizeof(ext));
1911         if (XE_IOCTL_DBG(xe, err))
1912                 return -EFAULT;
1913
1914         if (XE_IOCTL_DBG(xe, ext.property >=
1915                          ARRAY_SIZE(vm_set_property_funcs)) ||
1916             XE_IOCTL_DBG(xe, ext.pad) ||
1917             XE_IOCTL_DBG(xe, ext.reserved[0] || ext.reserved[1]))
1918                 return -EINVAL;
1919
1920         return vm_set_property_funcs[ext.property](xe, vm, ext.value);
1921 }
1922
1923 typedef int (*xe_vm_user_extension_fn)(struct xe_device *xe, struct xe_vm *vm,
1924                                        u64 extension);
1925
1926 static const xe_vm_set_property_fn vm_user_extension_funcs[] = {
1927         [XE_VM_EXTENSION_SET_PROPERTY] = vm_user_ext_set_property,
1928 };
1929
1930 #define MAX_USER_EXTENSIONS     16
1931 static int vm_user_extensions(struct xe_device *xe, struct xe_vm *vm,
1932                               u64 extensions, int ext_number)
1933 {
1934         u64 __user *address = u64_to_user_ptr(extensions);
1935         struct xe_user_extension ext;
1936         int err;
1937
1938         if (XE_IOCTL_DBG(xe, ext_number >= MAX_USER_EXTENSIONS))
1939                 return -E2BIG;
1940
1941         err = __copy_from_user(&ext, address, sizeof(ext));
1942         if (XE_IOCTL_DBG(xe, err))
1943                 return -EFAULT;
1944
1945         if (XE_IOCTL_DBG(xe, ext.pad) ||
1946             XE_IOCTL_DBG(xe, ext.name >=
1947                          ARRAY_SIZE(vm_user_extension_funcs)))
1948                 return -EINVAL;
1949
1950         err = vm_user_extension_funcs[ext.name](xe, vm, extensions);
1951         if (XE_IOCTL_DBG(xe, err))
1952                 return err;
1953
1954         if (ext.next_extension)
1955                 return vm_user_extensions(xe, vm, ext.next_extension,
1956                                           ++ext_number);
1957
1958         return 0;
1959 }
1960
1961 #define ALL_DRM_XE_VM_CREATE_FLAGS (DRM_XE_VM_CREATE_SCRATCH_PAGE | \
1962                                     DRM_XE_VM_CREATE_COMPUTE_MODE | \
1963                                     DRM_XE_VM_CREATE_ASYNC_BIND_OPS | \
1964                                     DRM_XE_VM_CREATE_FAULT_MODE)
1965
1966 int xe_vm_create_ioctl(struct drm_device *dev, void *data,
1967                        struct drm_file *file)
1968 {
1969         struct xe_device *xe = to_xe_device(dev);
1970         struct xe_file *xef = to_xe_file(file);
1971         struct drm_xe_vm_create *args = data;
1972         struct xe_vm *vm;
1973         u32 id, asid;
1974         int err;
1975         u32 flags = 0;
1976
1977         if (XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
1978                 return -EINVAL;
1979
1980         if (XE_IOCTL_DBG(xe, args->flags & ~ALL_DRM_XE_VM_CREATE_FLAGS))
1981                 return -EINVAL;
1982
1983         if (XE_IOCTL_DBG(xe, args->flags & DRM_XE_VM_CREATE_SCRATCH_PAGE &&
1984                          args->flags & DRM_XE_VM_CREATE_FAULT_MODE))
1985                 return -EINVAL;
1986
1987         if (XE_IOCTL_DBG(xe, args->flags & DRM_XE_VM_CREATE_COMPUTE_MODE &&
1988                          args->flags & DRM_XE_VM_CREATE_FAULT_MODE))
1989                 return -EINVAL;
1990
1991         if (XE_IOCTL_DBG(xe, args->flags & DRM_XE_VM_CREATE_FAULT_MODE &&
1992                          xe_device_in_non_fault_mode(xe)))
1993                 return -EINVAL;
1994
1995         if (XE_IOCTL_DBG(xe, !(args->flags & DRM_XE_VM_CREATE_FAULT_MODE) &&
1996                          xe_device_in_fault_mode(xe)))
1997                 return -EINVAL;
1998
1999         if (XE_IOCTL_DBG(xe, args->flags & DRM_XE_VM_CREATE_FAULT_MODE &&
2000                          !xe->info.supports_usm))
2001                 return -EINVAL;
2002
2003         if (args->flags & DRM_XE_VM_CREATE_SCRATCH_PAGE)
2004                 flags |= XE_VM_FLAG_SCRATCH_PAGE;
2005         if (args->flags & DRM_XE_VM_CREATE_COMPUTE_MODE)
2006                 flags |= XE_VM_FLAG_COMPUTE_MODE;
2007         if (args->flags & DRM_XE_VM_CREATE_ASYNC_BIND_OPS)
2008                 flags |= XE_VM_FLAG_ASYNC_BIND_OPS;
2009         if (args->flags & DRM_XE_VM_CREATE_FAULT_MODE)
2010                 flags |= XE_VM_FLAG_FAULT_MODE;
2011
2012         vm = xe_vm_create(xe, flags);
2013         if (IS_ERR(vm))
2014                 return PTR_ERR(vm);
2015
2016         if (args->extensions) {
2017                 err = vm_user_extensions(xe, vm, args->extensions, 0);
2018                 if (XE_IOCTL_DBG(xe, err)) {
2019                         xe_vm_close_and_put(vm);
2020                         return err;
2021                 }
2022         }
2023
2024         mutex_lock(&xef->vm.lock);
2025         err = xa_alloc(&xef->vm.xa, &id, vm, xa_limit_32b, GFP_KERNEL);
2026         mutex_unlock(&xef->vm.lock);
2027         if (err) {
2028                 xe_vm_close_and_put(vm);
2029                 return err;
2030         }
2031
2032         if (xe->info.has_asid) {
2033                 mutex_lock(&xe->usm.lock);
2034                 err = xa_alloc_cyclic(&xe->usm.asid_to_vm, &asid, vm,
2035                                       XA_LIMIT(0, XE_MAX_ASID - 1),
2036                                       &xe->usm.next_asid, GFP_KERNEL);
2037                 mutex_unlock(&xe->usm.lock);
2038                 if (err) {
2039                         xe_vm_close_and_put(vm);
2040                         return err;
2041                 }
2042                 vm->usm.asid = asid;
2043         }
2044
2045         args->vm_id = id;
2046
2047 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_MEM)
2048         /* Warning: Security issue - never enable by default */
2049         args->reserved[0] = xe_bo_main_addr(vm->pt_root[0]->bo, XE_PAGE_SIZE);
2050 #endif
2051
2052         return 0;
2053 }
2054
2055 int xe_vm_destroy_ioctl(struct drm_device *dev, void *data,
2056                         struct drm_file *file)
2057 {
2058         struct xe_device *xe = to_xe_device(dev);
2059         struct xe_file *xef = to_xe_file(file);
2060         struct drm_xe_vm_destroy *args = data;
2061         struct xe_vm *vm;
2062         int err = 0;
2063
2064         if (XE_IOCTL_DBG(xe, args->pad) ||
2065             XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
2066                 return -EINVAL;
2067
2068         mutex_lock(&xef->vm.lock);
2069         vm = xa_load(&xef->vm.xa, args->vm_id);
2070         if (XE_IOCTL_DBG(xe, !vm))
2071                 err = -ENOENT;
2072         else if (XE_IOCTL_DBG(xe, vm->preempt.num_engines))
2073                 err = -EBUSY;
2074         else
2075                 xa_erase(&xef->vm.xa, args->vm_id);
2076         mutex_unlock(&xef->vm.lock);
2077
2078         if (!err)
2079                 xe_vm_close_and_put(vm);
2080
2081         return err;
2082 }
2083
2084 static const u32 region_to_mem_type[] = {
2085         XE_PL_TT,
2086         XE_PL_VRAM0,
2087         XE_PL_VRAM1,
2088 };
2089
2090 static int xe_vm_prefetch(struct xe_vm *vm, struct xe_vma *vma,
2091                           struct xe_engine *e, u32 region,
2092                           struct xe_sync_entry *syncs, u32 num_syncs,
2093                           struct async_op_fence *afence, bool first_op,
2094                           bool last_op)
2095 {
2096         int err;
2097
2098         XE_BUG_ON(region > ARRAY_SIZE(region_to_mem_type));
2099
2100         if (!xe_vma_has_no_bo(vma)) {
2101                 err = xe_bo_migrate(xe_vma_bo(vma), region_to_mem_type[region]);
2102                 if (err)
2103                         return err;
2104         }
2105
2106         if (vma->tile_mask != (vma->tile_present & ~vma->usm.tile_invalidated)) {
2107                 return xe_vm_bind(vm, vma, e, xe_vma_bo(vma), syncs, num_syncs,
2108                                   afence, true, first_op, last_op);
2109         } else {
2110                 int i;
2111
2112                 /* Nothing to do, signal fences now */
2113                 if (last_op) {
2114                         for (i = 0; i < num_syncs; i++)
2115                                 xe_sync_entry_signal(&syncs[i], NULL,
2116                                                      dma_fence_get_stub());
2117                 }
2118                 if (afence)
2119                         dma_fence_signal(&afence->fence);
2120                 return 0;
2121         }
2122 }
2123
2124 #define VM_BIND_OP(op)  (op & 0xffff)
2125
2126 struct ttm_buffer_object *xe_vm_ttm_bo(struct xe_vm *vm)
2127 {
2128         int idx = vm->flags & XE_VM_FLAG_MIGRATION ?
2129                 XE_VM_FLAG_TILE_ID(vm->flags) : 0;
2130
2131         /* Safe to use index 0 as all BO in the VM share a single dma-resv lock */
2132         return &vm->pt_root[idx]->bo->ttm;
2133 }
2134
2135 static void xe_vm_tv_populate(struct xe_vm *vm, struct ttm_validate_buffer *tv)
2136 {
2137         tv->num_shared = 1;
2138         tv->bo = xe_vm_ttm_bo(vm);
2139 }
2140
2141 static void vm_set_async_error(struct xe_vm *vm, int err)
2142 {
2143         lockdep_assert_held(&vm->lock);
2144         vm->async_ops.error = err;
2145 }
2146
2147 static int vm_bind_ioctl_lookup_vma(struct xe_vm *vm, struct xe_bo *bo,
2148                                     u64 addr, u64 range, u32 op)
2149 {
2150         struct xe_device *xe = vm->xe;
2151         struct xe_vma *vma;
2152         bool async = !!(op & XE_VM_BIND_FLAG_ASYNC);
2153
2154         lockdep_assert_held(&vm->lock);
2155
2156         switch (VM_BIND_OP(op)) {
2157         case XE_VM_BIND_OP_MAP:
2158         case XE_VM_BIND_OP_MAP_USERPTR:
2159                 vma = xe_vm_find_overlapping_vma(vm, addr, range);
2160                 if (XE_IOCTL_DBG(xe, vma && !async))
2161                         return -EBUSY;
2162                 break;
2163         case XE_VM_BIND_OP_UNMAP:
2164         case XE_VM_BIND_OP_PREFETCH:
2165                 vma = xe_vm_find_overlapping_vma(vm, addr, range);
2166                 if (XE_IOCTL_DBG(xe, !vma))
2167                         /* Not an actual error, IOCTL cleans up returns and 0 */
2168                         return -ENODATA;
2169                 if (XE_IOCTL_DBG(xe, (xe_vma_start(vma) != addr ||
2170                                       xe_vma_end(vma) != addr + range) && !async))
2171                         return -EINVAL;
2172                 break;
2173         case XE_VM_BIND_OP_UNMAP_ALL:
2174                 if (XE_IOCTL_DBG(xe, list_empty(&bo->ttm.base.gpuva.list)))
2175                         /* Not an actual error, IOCTL cleans up returns and 0 */
2176                         return -ENODATA;
2177                 break;
2178         default:
2179                 XE_BUG_ON("NOT POSSIBLE");
2180                 return -EINVAL;
2181         }
2182
2183         return 0;
2184 }
2185
2186 static void prep_vma_destroy(struct xe_vm *vm, struct xe_vma *vma,
2187                              bool post_commit)
2188 {
2189         down_read(&vm->userptr.notifier_lock);
2190         vma->gpuva.flags |= XE_VMA_DESTROYED;
2191         up_read(&vm->userptr.notifier_lock);
2192         if (post_commit)
2193                 xe_vm_remove_vma(vm, vma);
2194 }
2195
2196 #undef ULL
2197 #define ULL     unsigned long long
2198
2199 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM)
2200 static void print_op(struct xe_device *xe, struct drm_gpuva_op *op)
2201 {
2202         struct xe_vma *vma;
2203
2204         switch (op->op) {
2205         case DRM_GPUVA_OP_MAP:
2206                 vm_dbg(&xe->drm, "MAP: addr=0x%016llx, range=0x%016llx",
2207                        (ULL)op->map.va.addr, (ULL)op->map.va.range);
2208                 break;
2209         case DRM_GPUVA_OP_REMAP:
2210                 vma = gpuva_to_vma(op->remap.unmap->va);
2211                 vm_dbg(&xe->drm, "REMAP:UNMAP: addr=0x%016llx, range=0x%016llx, keep=%d",
2212                        (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma),
2213                        op->unmap.keep ? 1 : 0);
2214                 if (op->remap.prev)
2215                         vm_dbg(&xe->drm,
2216                                "REMAP:PREV: addr=0x%016llx, range=0x%016llx",
2217                                (ULL)op->remap.prev->va.addr,
2218                                (ULL)op->remap.prev->va.range);
2219                 if (op->remap.next)
2220                         vm_dbg(&xe->drm,
2221                                "REMAP:NEXT: addr=0x%016llx, range=0x%016llx",
2222                                (ULL)op->remap.next->va.addr,
2223                                (ULL)op->remap.next->va.range);
2224                 break;
2225         case DRM_GPUVA_OP_UNMAP:
2226                 vma = gpuva_to_vma(op->unmap.va);
2227                 vm_dbg(&xe->drm, "UNMAP: addr=0x%016llx, range=0x%016llx, keep=%d",
2228                        (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma),
2229                        op->unmap.keep ? 1 : 0);
2230                 break;
2231         case DRM_GPUVA_OP_PREFETCH:
2232                 vma = gpuva_to_vma(op->prefetch.va);
2233                 vm_dbg(&xe->drm, "PREFETCH: addr=0x%016llx, range=0x%016llx",
2234                        (ULL)xe_vma_start(vma), (ULL)xe_vma_size(vma));
2235                 break;
2236         default:
2237                 XE_BUG_ON("NOT POSSIBLE");
2238         }
2239 }
2240 #else
2241 static void print_op(struct xe_device *xe, struct drm_gpuva_op *op)
2242 {
2243 }
2244 #endif
2245
2246 /*
2247  * Create operations list from IOCTL arguments, setup operations fields so parse
2248  * and commit steps are decoupled from IOCTL arguments. This step can fail.
2249  */
2250 static struct drm_gpuva_ops *
2251 vm_bind_ioctl_ops_create(struct xe_vm *vm, struct xe_bo *bo,
2252                          u64 bo_offset_or_userptr, u64 addr, u64 range,
2253                          u32 operation, u64 tile_mask, u32 region)
2254 {
2255         struct drm_gem_object *obj = bo ? &bo->ttm.base : NULL;
2256         struct ww_acquire_ctx ww;
2257         struct drm_gpuva_ops *ops;
2258         struct drm_gpuva_op *__op;
2259         struct xe_vma_op *op;
2260         struct drm_gpuvm_bo *vm_bo;
2261         int err;
2262
2263         lockdep_assert_held_write(&vm->lock);
2264
2265         vm_dbg(&vm->xe->drm,
2266                "op=%d, addr=0x%016llx, range=0x%016llx, bo_offset_or_userptr=0x%016llx",
2267                VM_BIND_OP(operation), (ULL)addr, (ULL)range,
2268                (ULL)bo_offset_or_userptr);
2269
2270         switch (VM_BIND_OP(operation)) {
2271         case XE_VM_BIND_OP_MAP:
2272         case XE_VM_BIND_OP_MAP_USERPTR:
2273                 ops = drm_gpuvm_sm_map_ops_create(&vm->gpuvm, addr, range,
2274                                                   obj, bo_offset_or_userptr);
2275                 if (IS_ERR(ops))
2276                         return ops;
2277
2278                 drm_gpuva_for_each_op(__op, ops) {
2279                         struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2280
2281                         op->tile_mask = tile_mask;
2282                         op->map.immediate =
2283                                 operation & XE_VM_BIND_FLAG_IMMEDIATE;
2284                         op->map.read_only =
2285                                 operation & XE_VM_BIND_FLAG_READONLY;
2286                         op->map.is_null = operation & XE_VM_BIND_FLAG_NULL;
2287                 }
2288                 break;
2289         case XE_VM_BIND_OP_UNMAP:
2290                 ops = drm_gpuvm_sm_unmap_ops_create(&vm->gpuvm, addr, range);
2291                 if (IS_ERR(ops))
2292                         return ops;
2293
2294                 drm_gpuva_for_each_op(__op, ops) {
2295                         struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2296
2297                         op->tile_mask = tile_mask;
2298                 }
2299                 break;
2300         case XE_VM_BIND_OP_PREFETCH:
2301                 ops = drm_gpuvm_prefetch_ops_create(&vm->gpuvm, addr, range);
2302                 if (IS_ERR(ops))
2303                         return ops;
2304
2305                 drm_gpuva_for_each_op(__op, ops) {
2306                         struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2307
2308                         op->tile_mask = tile_mask;
2309                         op->prefetch.region = region;
2310                 }
2311                 break;
2312         case XE_VM_BIND_OP_UNMAP_ALL:
2313                 XE_BUG_ON(!bo);
2314
2315                 err = xe_bo_lock(bo, &ww, 0, true);
2316                 if (err)
2317                         return ERR_PTR(err);
2318
2319                 vm_bo = drm_gpuvm_bo_find(&vm->gpuvm, obj);
2320                 if (!vm_bo)
2321                         break;
2322
2323                 ops = drm_gpuvm_bo_unmap_ops_create(vm_bo);
2324                 drm_gpuvm_bo_put(vm_bo);
2325                 xe_bo_unlock(bo, &ww);
2326                 if (IS_ERR(ops))
2327                         return ops;
2328
2329                 drm_gpuva_for_each_op(__op, ops) {
2330                         struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2331
2332                         op->tile_mask = tile_mask;
2333                 }
2334                 break;
2335         default:
2336                 XE_BUG_ON("NOT POSSIBLE");
2337                 ops = ERR_PTR(-EINVAL);
2338         }
2339
2340 #ifdef TEST_VM_ASYNC_OPS_ERROR
2341         if (operation & FORCE_ASYNC_OP_ERROR) {
2342                 op = list_first_entry_or_null(&ops->list, struct xe_vma_op,
2343                                               base.entry);
2344                 if (op)
2345                         op->inject_error = true;
2346         }
2347 #endif
2348
2349         if (!IS_ERR(ops))
2350                 drm_gpuva_for_each_op(__op, ops)
2351                         print_op(vm->xe, __op);
2352
2353         return ops;
2354 }
2355
2356 static struct xe_vma *new_vma(struct xe_vm *vm, struct drm_gpuva_op_map *op,
2357                               u64 tile_mask, bool read_only, bool is_null)
2358 {
2359         struct xe_bo *bo = op->gem.obj ? gem_to_xe_bo(op->gem.obj) : NULL;
2360         struct xe_vma *vma;
2361         struct ww_acquire_ctx ww;
2362         int err;
2363
2364         lockdep_assert_held_write(&vm->lock);
2365
2366         if (bo) {
2367                 err = xe_bo_lock(bo, &ww, 0, true);
2368                 if (err)
2369                         return ERR_PTR(err);
2370         }
2371         vma = xe_vma_create(vm, bo, op->gem.offset,
2372                             op->va.addr, op->va.addr +
2373                             op->va.range - 1, read_only, is_null,
2374                             tile_mask);
2375         if (bo)
2376                 xe_bo_unlock(bo, &ww);
2377
2378         if (xe_vma_is_userptr(vma)) {
2379                 err = xe_vma_userptr_pin_pages(vma);
2380                 if (err) {
2381                         prep_vma_destroy(vm, vma, false);
2382                         xe_vma_destroy_unlocked(vma);
2383                         return ERR_PTR(err);
2384                 }
2385         } else if (!xe_vma_has_no_bo(vma) && !bo->vm) {
2386                 vm_insert_extobj(vm, vma);
2387                 err = add_preempt_fences(vm, bo);
2388                 if (err) {
2389                         prep_vma_destroy(vm, vma, false);
2390                         xe_vma_destroy_unlocked(vma);
2391                         return ERR_PTR(err);
2392                 }
2393         }
2394
2395         return vma;
2396 }
2397
2398 static u64 xe_vma_max_pte_size(struct xe_vma *vma)
2399 {
2400         if (vma->gpuva.flags & XE_VMA_PTE_1G)
2401                 return SZ_1G;
2402         else if (vma->gpuva.flags & XE_VMA_PTE_2M)
2403                 return SZ_2M;
2404
2405         return SZ_4K;
2406 }
2407
2408 /*
2409  * Parse operations list and create any resources needed for the operations
2410  * prior to fully committing to the operations. This setup can fail.
2411  */
2412 static int vm_bind_ioctl_ops_parse(struct xe_vm *vm, struct xe_engine *e,
2413                                    struct drm_gpuva_ops **ops, int num_ops_list,
2414                                    struct xe_sync_entry *syncs, u32 num_syncs,
2415                                    struct list_head *ops_list, bool async)
2416 {
2417         struct xe_vma_op *last_op = NULL;
2418         struct list_head *async_list = NULL;
2419         struct async_op_fence *fence = NULL;
2420         int err, i;
2421
2422         lockdep_assert_held_write(&vm->lock);
2423         XE_BUG_ON(num_ops_list > 1 && !async);
2424
2425         if (num_syncs && async) {
2426                 u64 seqno;
2427
2428                 fence = kmalloc(sizeof(*fence), GFP_KERNEL);
2429                 if (!fence)
2430                         return -ENOMEM;
2431
2432                 seqno = e ? ++e->bind.fence_seqno : ++vm->async_ops.fence.seqno;
2433                 dma_fence_init(&fence->fence, &async_op_fence_ops,
2434                                &vm->async_ops.lock, e ? e->bind.fence_ctx :
2435                                vm->async_ops.fence.context, seqno);
2436
2437                 if (!xe_vm_no_dma_fences(vm)) {
2438                         fence->vm = vm;
2439                         fence->started = false;
2440                         init_waitqueue_head(&fence->wq);
2441                 }
2442         }
2443
2444         for (i = 0; i < num_ops_list; ++i) {
2445                 struct drm_gpuva_ops *__ops = ops[i];
2446                 struct drm_gpuva_op *__op;
2447
2448                 drm_gpuva_for_each_op(__op, __ops) {
2449                         struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
2450                         bool first = !async_list;
2451
2452                         XE_BUG_ON(!first && !async);
2453
2454                         INIT_LIST_HEAD(&op->link);
2455                         if (first)
2456                                 async_list = ops_list;
2457                         list_add_tail(&op->link, async_list);
2458
2459                         if (first) {
2460                                 op->flags |= XE_VMA_OP_FIRST;
2461                                 op->num_syncs = num_syncs;
2462                                 op->syncs = syncs;
2463                         }
2464
2465                         op->engine = e;
2466
2467                         switch (op->base.op) {
2468                         case DRM_GPUVA_OP_MAP:
2469                         {
2470                                 struct xe_vma *vma;
2471
2472                                 vma = new_vma(vm, &op->base.map,
2473                                               op->tile_mask, op->map.read_only,
2474                                               op->map.is_null);
2475                                 if (IS_ERR(vma)) {
2476                                         err = PTR_ERR(vma);
2477                                         goto free_fence;
2478                                 }
2479
2480                                 op->map.vma = vma;
2481                                 break;
2482                         }
2483                         case DRM_GPUVA_OP_REMAP:
2484                         {
2485                                 struct xe_vma *old =
2486                                         gpuva_to_vma(op->base.remap.unmap->va);
2487
2488                                 op->remap.start = xe_vma_start(old);
2489                                 op->remap.range = xe_vma_size(old);
2490
2491                                 if (op->base.remap.prev) {
2492                                         struct xe_vma *vma;
2493                                         bool read_only =
2494                                                 op->base.remap.unmap->va->flags &
2495                                                 XE_VMA_READ_ONLY;
2496                                         bool is_null =
2497                                                 op->base.remap.unmap->va->flags &
2498                                                 DRM_GPUVA_SPARSE;
2499
2500                                         vma = new_vma(vm, op->base.remap.prev,
2501                                                       op->tile_mask, read_only,
2502                                                       is_null);
2503                                         if (IS_ERR(vma)) {
2504                                                 err = PTR_ERR(vma);
2505                                                 goto free_fence;
2506                                         }
2507
2508                                         op->remap.prev = vma;
2509
2510                                         /*
2511                                          * Userptr creates a new SG mapping so
2512                                          * we must also rebind.
2513                                          */
2514                                         op->remap.skip_prev = !xe_vma_is_userptr(old) &&
2515                                                 IS_ALIGNED(xe_vma_end(vma),
2516                                                            xe_vma_max_pte_size(old));
2517                                         if (op->remap.skip_prev) {
2518                                                 op->remap.range -=
2519                                                         xe_vma_end(vma) -
2520                                                         xe_vma_start(old);
2521                                                 op->remap.start = xe_vma_end(vma);
2522                                         }
2523                                 }
2524
2525                                 if (op->base.remap.next) {
2526                                         struct xe_vma *vma;
2527                                         bool read_only =
2528                                                 op->base.remap.unmap->va->flags &
2529                                                 XE_VMA_READ_ONLY;
2530
2531                                         bool is_null =
2532                                                 op->base.remap.unmap->va->flags &
2533                                                 DRM_GPUVA_SPARSE;
2534
2535                                         vma = new_vma(vm, op->base.remap.next,
2536                                                       op->tile_mask, read_only,
2537                                                       is_null);
2538                                         if (IS_ERR(vma)) {
2539                                                 err = PTR_ERR(vma);
2540                                                 goto free_fence;
2541                                         }
2542
2543                                         op->remap.next = vma;
2544
2545                                         /*
2546                                          * Userptr creates a new SG mapping so
2547                                          * we must also rebind.
2548                                          */
2549                                         op->remap.skip_next = !xe_vma_is_userptr(old) &&
2550                                                 IS_ALIGNED(xe_vma_start(vma),
2551                                                            xe_vma_max_pte_size(old));
2552                                         if (op->remap.skip_next)
2553                                                 op->remap.range -=
2554                                                         xe_vma_end(old) -
2555                                                         xe_vma_start(vma);
2556                                 }
2557                                 break;
2558                         }
2559                         case DRM_GPUVA_OP_UNMAP:
2560                         case DRM_GPUVA_OP_PREFETCH:
2561                                 /* Nothing to do */
2562                                 break;
2563                         default:
2564                                 XE_BUG_ON("NOT POSSIBLE");
2565                         }
2566
2567                         last_op = op;
2568                 }
2569
2570                 last_op->ops = __ops;
2571         }
2572
2573         if (!last_op)
2574                 return -ENODATA;
2575
2576         last_op->flags |= XE_VMA_OP_LAST;
2577         last_op->num_syncs = num_syncs;
2578         last_op->syncs = syncs;
2579         last_op->fence = fence;
2580
2581         return 0;
2582
2583 free_fence:
2584         kfree(fence);
2585         return err;
2586 }
2587
2588 static int xe_vma_op_commit(struct xe_vm *vm, struct xe_vma_op *op)
2589 {
2590         int err = 0;
2591
2592         lockdep_assert_held_write(&vm->lock);
2593
2594         switch (op->base.op) {
2595         case DRM_GPUVA_OP_MAP:
2596                 err |= xe_vm_insert_vma(vm, op->map.vma);
2597                 break;
2598         case DRM_GPUVA_OP_REMAP:
2599                 prep_vma_destroy(vm, gpuva_to_vma(op->base.remap.unmap->va),
2600                                  true);
2601
2602                 if (op->remap.prev) {
2603                         err |= xe_vm_insert_vma(vm, op->remap.prev);
2604                         if (!err && op->remap.skip_prev)
2605                                 op->remap.prev = NULL;
2606                 }
2607                 if (op->remap.next) {
2608                         err |= xe_vm_insert_vma(vm, op->remap.next);
2609                         if (!err && op->remap.skip_next)
2610                                 op->remap.next = NULL;
2611                 }
2612
2613                 /* Adjust for partial unbind after removin VMA from VM */
2614                 if (!err) {
2615                         op->base.remap.unmap->va->va.addr = op->remap.start;
2616                         op->base.remap.unmap->va->va.range = op->remap.range;
2617                 }
2618                 break;
2619         case DRM_GPUVA_OP_UNMAP:
2620                 prep_vma_destroy(vm, gpuva_to_vma(op->base.unmap.va), true);
2621                 break;
2622         case DRM_GPUVA_OP_PREFETCH:
2623                 /* Nothing to do */
2624                 break;
2625         default:
2626                 XE_BUG_ON("NOT POSSIBLE");
2627         }
2628
2629         op->flags |= XE_VMA_OP_COMMITTED;
2630         return err;
2631 }
2632
2633 static int __xe_vma_op_execute(struct xe_vm *vm, struct xe_vma *vma,
2634                                struct xe_vma_op *op)
2635 {
2636         LIST_HEAD(objs);
2637         LIST_HEAD(dups);
2638         struct ttm_validate_buffer tv_bo, tv_vm;
2639         struct ww_acquire_ctx ww;
2640         struct xe_bo *vbo;
2641         int err;
2642
2643         lockdep_assert_held_write(&vm->lock);
2644
2645         xe_vm_tv_populate(vm, &tv_vm);
2646         list_add_tail(&tv_vm.head, &objs);
2647         vbo = xe_vma_bo(vma);
2648         if (vbo) {
2649                 /*
2650                  * An unbind can drop the last reference to the BO and
2651                  * the BO is needed for ttm_eu_backoff_reservation so
2652                  * take a reference here.
2653                  */
2654                 xe_bo_get(vbo);
2655
2656                 if (!vbo->vm) {
2657                         tv_bo.bo = &vbo->ttm;
2658                         tv_bo.num_shared = 1;
2659                         list_add(&tv_bo.head, &objs);
2660                 }
2661         }
2662
2663 again:
2664         err = ttm_eu_reserve_buffers(&ww, &objs, true, &dups);
2665         if (err) {
2666                 xe_bo_put(vbo);
2667                 return err;
2668         }
2669
2670         xe_vm_assert_held(vm);
2671         xe_bo_assert_held(xe_vma_bo(vma));
2672
2673         switch (op->base.op) {
2674         case DRM_GPUVA_OP_MAP:
2675                 err = xe_vm_bind(vm, vma, op->engine, xe_vma_bo(vma),
2676                                  op->syncs, op->num_syncs, op->fence,
2677                                  op->map.immediate || !xe_vm_in_fault_mode(vm),
2678                                  op->flags & XE_VMA_OP_FIRST,
2679                                  op->flags & XE_VMA_OP_LAST);
2680                 break;
2681         case DRM_GPUVA_OP_REMAP:
2682         {
2683                 bool prev = !!op->remap.prev;
2684                 bool next = !!op->remap.next;
2685
2686                 if (!op->remap.unmap_done) {
2687                         if (prev || next) {
2688                                 vm->async_ops.munmap_rebind_inflight = true;
2689                                 vma->gpuva.flags |= XE_VMA_FIRST_REBIND;
2690                         }
2691                         err = xe_vm_unbind(vm, vma, op->engine, op->syncs,
2692                                            op->num_syncs,
2693                                            !prev && !next ? op->fence : NULL,
2694                                            op->flags & XE_VMA_OP_FIRST,
2695                                            op->flags & XE_VMA_OP_LAST && !prev &&
2696                                            !next);
2697                         if (err)
2698                                 break;
2699                         op->remap.unmap_done = true;
2700                 }
2701
2702                 if (prev) {
2703                         op->remap.prev->gpuva.flags |= XE_VMA_LAST_REBIND;
2704                         err = xe_vm_bind(vm, op->remap.prev, op->engine,
2705                                          xe_vma_bo(op->remap.prev), op->syncs,
2706                                          op->num_syncs,
2707                                          !next ? op->fence : NULL, true, false,
2708                                          op->flags & XE_VMA_OP_LAST && !next);
2709                         op->remap.prev->gpuva.flags &= ~XE_VMA_LAST_REBIND;
2710                         if (err)
2711                                 break;
2712                         op->remap.prev = NULL;
2713                 }
2714
2715                 if (next) {
2716                         op->remap.next->gpuva.flags |= XE_VMA_LAST_REBIND;
2717                         err = xe_vm_bind(vm, op->remap.next, op->engine,
2718                                          xe_vma_bo(op->remap.next),
2719                                          op->syncs, op->num_syncs,
2720                                          op->fence, true, false,
2721                                          op->flags & XE_VMA_OP_LAST);
2722                         op->remap.next->gpuva.flags &= ~XE_VMA_LAST_REBIND;
2723                         if (err)
2724                                 break;
2725                         op->remap.next = NULL;
2726                 }
2727                 vm->async_ops.munmap_rebind_inflight = false;
2728
2729                 break;
2730         }
2731         case DRM_GPUVA_OP_UNMAP:
2732                 err = xe_vm_unbind(vm, vma, op->engine, op->syncs,
2733                                    op->num_syncs, op->fence,
2734                                    op->flags & XE_VMA_OP_FIRST,
2735                                    op->flags & XE_VMA_OP_LAST);
2736                 break;
2737         case DRM_GPUVA_OP_PREFETCH:
2738                 err = xe_vm_prefetch(vm, vma, op->engine, op->prefetch.region,
2739                                      op->syncs, op->num_syncs, op->fence,
2740                                      op->flags & XE_VMA_OP_FIRST,
2741                                      op->flags & XE_VMA_OP_LAST);
2742                 break;
2743         default:
2744                 XE_BUG_ON("NOT POSSIBLE");
2745         }
2746
2747         ttm_eu_backoff_reservation(&ww, &objs);
2748         if (err == -EAGAIN && xe_vma_is_userptr(vma)) {
2749                 lockdep_assert_held_write(&vm->lock);
2750                 err = xe_vma_userptr_pin_pages(vma);
2751                 if (!err)
2752                         goto again;
2753         }
2754         xe_bo_put(vbo);
2755
2756         if (err)
2757                 trace_xe_vma_fail(vma);
2758
2759         return err;
2760 }
2761
2762 static int xe_vma_op_execute(struct xe_vm *vm, struct xe_vma_op *op)
2763 {
2764         int ret = 0;
2765
2766         lockdep_assert_held_write(&vm->lock);
2767
2768 #ifdef TEST_VM_ASYNC_OPS_ERROR
2769         if (op->inject_error) {
2770                 op->inject_error = false;
2771                 return -ENOMEM;
2772         }
2773 #endif
2774
2775         switch (op->base.op) {
2776         case DRM_GPUVA_OP_MAP:
2777                 ret = __xe_vma_op_execute(vm, op->map.vma, op);
2778                 break;
2779         case DRM_GPUVA_OP_REMAP:
2780         {
2781                 struct xe_vma *vma;
2782
2783                 if (!op->remap.unmap_done)
2784                         vma = gpuva_to_vma(op->base.remap.unmap->va);
2785                 else if (op->remap.prev)
2786                         vma = op->remap.prev;
2787                 else
2788                         vma = op->remap.next;
2789
2790                 ret = __xe_vma_op_execute(vm, vma, op);
2791                 break;
2792         }
2793         case DRM_GPUVA_OP_UNMAP:
2794                 ret = __xe_vma_op_execute(vm, gpuva_to_vma(op->base.unmap.va),
2795                                           op);
2796                 break;
2797         case DRM_GPUVA_OP_PREFETCH:
2798                 ret = __xe_vma_op_execute(vm,
2799                                           gpuva_to_vma(op->base.prefetch.va),
2800                                           op);
2801                 break;
2802         default:
2803                 XE_BUG_ON("NOT POSSIBLE");
2804         }
2805
2806         return ret;
2807 }
2808
2809 static void xe_vma_op_cleanup(struct xe_vm *vm, struct xe_vma_op *op)
2810 {
2811         bool last = op->flags & XE_VMA_OP_LAST;
2812
2813         if (last) {
2814                 while (op->num_syncs--)
2815                         xe_sync_entry_cleanup(&op->syncs[op->num_syncs]);
2816                 kfree(op->syncs);
2817                 if (op->engine)
2818                         xe_engine_put(op->engine);
2819                 if (op->fence)
2820                         dma_fence_put(&op->fence->fence);
2821         }
2822         if (!list_empty(&op->link)) {
2823                 spin_lock_irq(&vm->async_ops.lock);
2824                 list_del(&op->link);
2825                 spin_unlock_irq(&vm->async_ops.lock);
2826         }
2827         if (op->ops)
2828                 drm_gpuva_ops_free(&vm->gpuvm, op->ops);
2829         if (last)
2830                 xe_vm_put(vm);
2831 }
2832
2833 static void xe_vma_op_unwind(struct xe_vm *vm, struct xe_vma_op *op,
2834                              bool post_commit)
2835 {
2836         lockdep_assert_held_write(&vm->lock);
2837
2838         switch (op->base.op) {
2839         case DRM_GPUVA_OP_MAP:
2840                 if (op->map.vma) {
2841                         prep_vma_destroy(vm, op->map.vma, post_commit);
2842                         xe_vma_destroy_unlocked(op->map.vma);
2843                 }
2844                 break;
2845         case DRM_GPUVA_OP_UNMAP:
2846         {
2847                 struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
2848
2849                 down_read(&vm->userptr.notifier_lock);
2850                 vma->gpuva.flags &= ~XE_VMA_DESTROYED;
2851                 up_read(&vm->userptr.notifier_lock);
2852                 if (post_commit)
2853                         xe_vm_insert_vma(vm, vma);
2854                 break;
2855         }
2856         case DRM_GPUVA_OP_REMAP:
2857         {
2858                 struct xe_vma *vma = gpuva_to_vma(op->base.remap.unmap->va);
2859
2860                 if (op->remap.prev) {
2861                         prep_vma_destroy(vm, op->remap.prev, post_commit);
2862                         xe_vma_destroy_unlocked(op->remap.prev);
2863                 }
2864                 if (op->remap.next) {
2865                         prep_vma_destroy(vm, op->remap.next, post_commit);
2866                         xe_vma_destroy_unlocked(op->remap.next);
2867                 }
2868                 down_read(&vm->userptr.notifier_lock);
2869                 vma->gpuva.flags &= ~XE_VMA_DESTROYED;
2870                 up_read(&vm->userptr.notifier_lock);
2871                 if (post_commit)
2872                         xe_vm_insert_vma(vm, vma);
2873                 break;
2874         }
2875         case DRM_GPUVA_OP_PREFETCH:
2876                 /* Nothing to do */
2877                 break;
2878         default:
2879                 XE_BUG_ON("NOT POSSIBLE");
2880         }
2881 }
2882
2883 static struct xe_vma_op *next_vma_op(struct xe_vm *vm)
2884 {
2885         return list_first_entry_or_null(&vm->async_ops.pending,
2886                                         struct xe_vma_op, link);
2887 }
2888
2889 static void xe_vma_op_work_func(struct work_struct *w)
2890 {
2891         struct xe_vm *vm = container_of(w, struct xe_vm, async_ops.work);
2892
2893         for (;;) {
2894                 struct xe_vma_op *op;
2895                 int err;
2896
2897                 if (vm->async_ops.error && !xe_vm_is_closed(vm))
2898                         break;
2899
2900                 spin_lock_irq(&vm->async_ops.lock);
2901                 op = next_vma_op(vm);
2902                 spin_unlock_irq(&vm->async_ops.lock);
2903
2904                 if (!op)
2905                         break;
2906
2907                 if (!xe_vm_is_closed(vm)) {
2908                         down_write(&vm->lock);
2909                         err = xe_vma_op_execute(vm, op);
2910                         if (err) {
2911                                 drm_warn(&vm->xe->drm,
2912                                          "Async VM op(%d) failed with %d",
2913                                          op->base.op, err);
2914                                 vm_set_async_error(vm, err);
2915                                 up_write(&vm->lock);
2916
2917                                 if (vm->async_ops.error_capture.addr)
2918                                         vm_error_capture(vm, err, 0, 0, 0);
2919                                 break;
2920                         }
2921                         up_write(&vm->lock);
2922                 } else {
2923                         struct xe_vma *vma;
2924
2925                         switch (op->base.op) {
2926                         case DRM_GPUVA_OP_REMAP:
2927                                 vma = gpuva_to_vma(op->base.remap.unmap->va);
2928                                 trace_xe_vma_flush(vma);
2929
2930                                 down_write(&vm->lock);
2931                                 xe_vma_destroy_unlocked(vma);
2932                                 up_write(&vm->lock);
2933                                 break;
2934                         case DRM_GPUVA_OP_UNMAP:
2935                                 vma = gpuva_to_vma(op->base.unmap.va);
2936                                 trace_xe_vma_flush(vma);
2937
2938                                 down_write(&vm->lock);
2939                                 xe_vma_destroy_unlocked(vma);
2940                                 up_write(&vm->lock);
2941                                 break;
2942                         default:
2943                                 /* Nothing to do */
2944                                 break;
2945                         }
2946
2947                         if (op->fence && !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
2948                                                    &op->fence->fence.flags)) {
2949                                 if (!xe_vm_no_dma_fences(vm)) {
2950                                         op->fence->started = true;
2951                                         wake_up_all(&op->fence->wq);
2952                                 }
2953                                 dma_fence_signal(&op->fence->fence);
2954                         }
2955                 }
2956
2957                 xe_vma_op_cleanup(vm, op);
2958         }
2959 }
2960
2961 static int vm_bind_ioctl_ops_commit(struct xe_vm *vm,
2962                                     struct list_head *ops_list, bool async)
2963 {
2964         struct xe_vma_op *op, *last_op, *next;
2965         int err;
2966
2967         lockdep_assert_held_write(&vm->lock);
2968
2969         list_for_each_entry(op, ops_list, link) {
2970                 last_op = op;
2971                 err = xe_vma_op_commit(vm, op);
2972                 if (err)
2973                         goto unwind;
2974         }
2975
2976         if (!async) {
2977                 err = xe_vma_op_execute(vm, last_op);
2978                 if (err)
2979                         goto unwind;
2980                 xe_vma_op_cleanup(vm, last_op);
2981         } else {
2982                 int i;
2983                 bool installed = false;
2984
2985                 for (i = 0; i < last_op->num_syncs; i++)
2986                         installed |= xe_sync_entry_signal(&last_op->syncs[i],
2987                                                           NULL,
2988                                                           &last_op->fence->fence);
2989                 if (!installed && last_op->fence)
2990                         dma_fence_signal(&last_op->fence->fence);
2991
2992                 spin_lock_irq(&vm->async_ops.lock);
2993                 list_splice_tail(ops_list, &vm->async_ops.pending);
2994                 spin_unlock_irq(&vm->async_ops.lock);
2995
2996                 if (!vm->async_ops.error)
2997                         queue_work(system_unbound_wq, &vm->async_ops.work);
2998         }
2999
3000         return 0;
3001
3002 unwind:
3003         list_for_each_entry_reverse(op, ops_list, link)
3004                 xe_vma_op_unwind(vm, op, op->flags & XE_VMA_OP_COMMITTED);
3005         list_for_each_entry_safe(op, next, ops_list, link)
3006                 xe_vma_op_cleanup(vm, op);
3007
3008         return err;
3009 }
3010
3011 /*
3012  * Unwind operations list, called after a failure of vm_bind_ioctl_ops_create or
3013  * vm_bind_ioctl_ops_parse.
3014  */
3015 static void vm_bind_ioctl_ops_unwind(struct xe_vm *vm,
3016                                      struct drm_gpuva_ops **ops,
3017                                      int num_ops_list)
3018 {
3019         int i;
3020
3021         for (i = 0; i < num_ops_list; ++i) {
3022                 struct drm_gpuva_ops *__ops = ops[i];
3023                 struct drm_gpuva_op *__op;
3024
3025                 if (!__ops)
3026                         continue;
3027
3028                 drm_gpuva_for_each_op(__op, __ops) {
3029                         struct xe_vma_op *op = gpuva_op_to_vma_op(__op);
3030
3031                         xe_vma_op_unwind(vm, op, false);
3032                 }
3033         }
3034 }
3035
3036 #ifdef TEST_VM_ASYNC_OPS_ERROR
3037 #define SUPPORTED_FLAGS \
3038         (FORCE_ASYNC_OP_ERROR | XE_VM_BIND_FLAG_ASYNC | \
3039          XE_VM_BIND_FLAG_READONLY | XE_VM_BIND_FLAG_IMMEDIATE | \
3040          XE_VM_BIND_FLAG_NULL | 0xffff)
3041 #else
3042 #define SUPPORTED_FLAGS \
3043         (XE_VM_BIND_FLAG_ASYNC | XE_VM_BIND_FLAG_READONLY | \
3044          XE_VM_BIND_FLAG_IMMEDIATE | XE_VM_BIND_FLAG_NULL | 0xffff)
3045 #endif
3046 #define XE_64K_PAGE_MASK 0xffffull
3047
3048 #define MAX_BINDS       512     /* FIXME: Picking random upper limit */
3049
3050 static int vm_bind_ioctl_check_args(struct xe_device *xe,
3051                                     struct drm_xe_vm_bind *args,
3052                                     struct drm_xe_vm_bind_op **bind_ops,
3053                                     bool *async)
3054 {
3055         int err;
3056         int i;
3057
3058         if (XE_IOCTL_DBG(xe, args->extensions) ||
3059             XE_IOCTL_DBG(xe, !args->num_binds) ||
3060             XE_IOCTL_DBG(xe, args->num_binds > MAX_BINDS))
3061                 return -EINVAL;
3062
3063         if (args->num_binds > 1) {
3064                 u64 __user *bind_user =
3065                         u64_to_user_ptr(args->vector_of_binds);
3066
3067                 *bind_ops = kmalloc(sizeof(struct drm_xe_vm_bind_op) *
3068                                     args->num_binds, GFP_KERNEL);
3069                 if (!*bind_ops)
3070                         return -ENOMEM;
3071
3072                 err = __copy_from_user(*bind_ops, bind_user,
3073                                        sizeof(struct drm_xe_vm_bind_op) *
3074                                        args->num_binds);
3075                 if (XE_IOCTL_DBG(xe, err)) {
3076                         err = -EFAULT;
3077                         goto free_bind_ops;
3078                 }
3079         } else {
3080                 *bind_ops = &args->bind;
3081         }
3082
3083         for (i = 0; i < args->num_binds; ++i) {
3084                 u64 range = (*bind_ops)[i].range;
3085                 u64 addr = (*bind_ops)[i].addr;
3086                 u32 op = (*bind_ops)[i].op;
3087                 u32 obj = (*bind_ops)[i].obj;
3088                 u64 obj_offset = (*bind_ops)[i].obj_offset;
3089                 u32 region = (*bind_ops)[i].region;
3090                 bool is_null = op & XE_VM_BIND_FLAG_NULL;
3091
3092                 if (i == 0) {
3093                         *async = !!(op & XE_VM_BIND_FLAG_ASYNC);
3094                 } else if (XE_IOCTL_DBG(xe, !*async) ||
3095                            XE_IOCTL_DBG(xe, !(op & XE_VM_BIND_FLAG_ASYNC)) ||
3096                            XE_IOCTL_DBG(xe, VM_BIND_OP(op) ==
3097                                         XE_VM_BIND_OP_RESTART)) {
3098                         err = -EINVAL;
3099                         goto free_bind_ops;
3100                 }
3101
3102                 if (XE_IOCTL_DBG(xe, !*async &&
3103                                  VM_BIND_OP(op) == XE_VM_BIND_OP_UNMAP_ALL)) {
3104                         err = -EINVAL;
3105                         goto free_bind_ops;
3106                 }
3107
3108                 if (XE_IOCTL_DBG(xe, !*async &&
3109                                  VM_BIND_OP(op) == XE_VM_BIND_OP_PREFETCH)) {
3110                         err = -EINVAL;
3111                         goto free_bind_ops;
3112                 }
3113
3114                 if (XE_IOCTL_DBG(xe, VM_BIND_OP(op) >
3115                                  XE_VM_BIND_OP_PREFETCH) ||
3116                     XE_IOCTL_DBG(xe, op & ~SUPPORTED_FLAGS) ||
3117                     XE_IOCTL_DBG(xe, obj && is_null) ||
3118                     XE_IOCTL_DBG(xe, obj_offset && is_null) ||
3119                     XE_IOCTL_DBG(xe, VM_BIND_OP(op) != XE_VM_BIND_OP_MAP &&
3120                                  is_null) ||
3121                     XE_IOCTL_DBG(xe, !obj &&
3122                                  VM_BIND_OP(op) == XE_VM_BIND_OP_MAP &&
3123                                  !is_null) ||
3124                     XE_IOCTL_DBG(xe, !obj &&
3125                                  VM_BIND_OP(op) == XE_VM_BIND_OP_UNMAP_ALL) ||
3126                     XE_IOCTL_DBG(xe, addr &&
3127                                  VM_BIND_OP(op) == XE_VM_BIND_OP_UNMAP_ALL) ||
3128                     XE_IOCTL_DBG(xe, range &&
3129                                  VM_BIND_OP(op) == XE_VM_BIND_OP_UNMAP_ALL) ||
3130                     XE_IOCTL_DBG(xe, obj &&
3131                                  VM_BIND_OP(op) == XE_VM_BIND_OP_MAP_USERPTR) ||
3132                     XE_IOCTL_DBG(xe, obj &&
3133                                  VM_BIND_OP(op) == XE_VM_BIND_OP_PREFETCH) ||
3134                     XE_IOCTL_DBG(xe, region &&
3135                                  VM_BIND_OP(op) != XE_VM_BIND_OP_PREFETCH) ||
3136                     XE_IOCTL_DBG(xe, !(BIT(region) &
3137                                        xe->info.mem_region_mask)) ||
3138                     XE_IOCTL_DBG(xe, obj &&
3139                                  VM_BIND_OP(op) == XE_VM_BIND_OP_UNMAP)) {
3140                         err = -EINVAL;
3141                         goto free_bind_ops;
3142                 }
3143
3144                 if (XE_IOCTL_DBG(xe, obj_offset & ~PAGE_MASK) ||
3145                     XE_IOCTL_DBG(xe, addr & ~PAGE_MASK) ||
3146                     XE_IOCTL_DBG(xe, range & ~PAGE_MASK) ||
3147                     XE_IOCTL_DBG(xe, !range && VM_BIND_OP(op) !=
3148                                  XE_VM_BIND_OP_RESTART &&
3149                                  VM_BIND_OP(op) != XE_VM_BIND_OP_UNMAP_ALL)) {
3150                         err = -EINVAL;
3151                         goto free_bind_ops;
3152                 }
3153         }
3154
3155         return 0;
3156
3157 free_bind_ops:
3158         if (args->num_binds > 1)
3159                 kfree(*bind_ops);
3160         return err;
3161 }
3162
3163 int xe_vm_bind_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3164 {
3165         struct xe_device *xe = to_xe_device(dev);
3166         struct xe_file *xef = to_xe_file(file);
3167         struct drm_xe_vm_bind *args = data;
3168         struct drm_xe_sync __user *syncs_user;
3169         struct xe_bo **bos = NULL;
3170         struct drm_gpuva_ops **ops = NULL;
3171         struct xe_vm *vm;
3172         struct xe_engine *e = NULL;
3173         u32 num_syncs;
3174         struct xe_sync_entry *syncs = NULL;
3175         struct drm_xe_vm_bind_op *bind_ops;
3176         LIST_HEAD(ops_list);
3177         bool async;
3178         int err;
3179         int i;
3180
3181         err = vm_bind_ioctl_check_args(xe, args, &bind_ops, &async);
3182         if (err)
3183                 return err;
3184
3185         if (args->engine_id) {
3186                 e = xe_engine_lookup(xef, args->engine_id);
3187                 if (XE_IOCTL_DBG(xe, !e)) {
3188                         err = -ENOENT;
3189                         goto free_objs;
3190                 }
3191
3192                 if (XE_IOCTL_DBG(xe, !(e->flags & ENGINE_FLAG_VM))) {
3193                         err = -EINVAL;
3194                         goto put_engine;
3195                 }
3196         }
3197
3198         vm = xe_vm_lookup(xef, args->vm_id);
3199         if (XE_IOCTL_DBG(xe, !vm)) {
3200                 err = -EINVAL;
3201                 goto put_engine;
3202         }
3203
3204         err = down_write_killable(&vm->lock);
3205         if (err)
3206                 goto put_vm;
3207
3208         if (XE_IOCTL_DBG(xe, xe_vm_is_closed_or_banned(vm))) {
3209                 err = -ENOENT;
3210                 goto release_vm_lock;
3211         }
3212
3213         if (VM_BIND_OP(bind_ops[0].op) == XE_VM_BIND_OP_RESTART) {
3214                 if (XE_IOCTL_DBG(xe, !(vm->flags & XE_VM_FLAG_ASYNC_BIND_OPS)))
3215                         err = -EOPNOTSUPP;
3216                 if (XE_IOCTL_DBG(xe, !err && args->num_syncs))
3217                         err = EINVAL;
3218                 if (XE_IOCTL_DBG(xe, !err && !vm->async_ops.error))
3219                         err = -EPROTO;
3220
3221                 if (!err) {
3222                         trace_xe_vm_restart(vm);
3223                         vm_set_async_error(vm, 0);
3224
3225                         queue_work(system_unbound_wq, &vm->async_ops.work);
3226
3227                         /* Rebinds may have been blocked, give worker a kick */
3228                         if (xe_vm_in_compute_mode(vm))
3229                                 xe_vm_queue_rebind_worker(vm);
3230                 }
3231
3232                 goto release_vm_lock;
3233         }
3234
3235         if (XE_IOCTL_DBG(xe, !vm->async_ops.error &&
3236                          async != !!(vm->flags & XE_VM_FLAG_ASYNC_BIND_OPS))) {
3237                 err = -EOPNOTSUPP;
3238                 goto release_vm_lock;
3239         }
3240
3241         for (i = 0; i < args->num_binds; ++i) {
3242                 u64 range = bind_ops[i].range;
3243                 u64 addr = bind_ops[i].addr;
3244
3245                 if (XE_IOCTL_DBG(xe, range > vm->size) ||
3246                     XE_IOCTL_DBG(xe, addr > vm->size - range)) {
3247                         err = -EINVAL;
3248                         goto release_vm_lock;
3249                 }
3250
3251                 if (bind_ops[i].tile_mask) {
3252                         u64 valid_tiles = BIT(xe->info.tile_count) - 1;
3253
3254                         if (XE_IOCTL_DBG(xe, bind_ops[i].tile_mask &
3255                                          ~valid_tiles)) {
3256                                 err = -EINVAL;
3257                                 goto release_vm_lock;
3258                         }
3259                 }
3260         }
3261
3262         bos = kzalloc(sizeof(*bos) * args->num_binds, GFP_KERNEL);
3263         if (!bos) {
3264                 err = -ENOMEM;
3265                 goto release_vm_lock;
3266         }
3267
3268         ops = kzalloc(sizeof(*ops) * args->num_binds, GFP_KERNEL);
3269         if (!ops) {
3270                 err = -ENOMEM;
3271                 goto release_vm_lock;
3272         }
3273
3274         for (i = 0; i < args->num_binds; ++i) {
3275                 struct drm_gem_object *gem_obj;
3276                 u64 range = bind_ops[i].range;
3277                 u64 addr = bind_ops[i].addr;
3278                 u32 obj = bind_ops[i].obj;
3279                 u64 obj_offset = bind_ops[i].obj_offset;
3280
3281                 if (!obj)
3282                         continue;
3283
3284                 gem_obj = drm_gem_object_lookup(file, obj);
3285                 if (XE_IOCTL_DBG(xe, !gem_obj)) {
3286                         err = -ENOENT;
3287                         goto put_obj;
3288                 }
3289                 bos[i] = gem_to_xe_bo(gem_obj);
3290
3291                 if (XE_IOCTL_DBG(xe, range > bos[i]->size) ||
3292                     XE_IOCTL_DBG(xe, obj_offset >
3293                                  bos[i]->size - range)) {
3294                         err = -EINVAL;
3295                         goto put_obj;
3296                 }
3297
3298                 if (bos[i]->flags & XE_BO_INTERNAL_64K) {
3299                         if (XE_IOCTL_DBG(xe, obj_offset &
3300                                          XE_64K_PAGE_MASK) ||
3301                             XE_IOCTL_DBG(xe, addr & XE_64K_PAGE_MASK) ||
3302                             XE_IOCTL_DBG(xe, range & XE_64K_PAGE_MASK)) {
3303                                 err = -EINVAL;
3304                                 goto put_obj;
3305                         }
3306                 }
3307         }
3308
3309         if (args->num_syncs) {
3310                 syncs = kcalloc(args->num_syncs, sizeof(*syncs), GFP_KERNEL);
3311                 if (!syncs) {
3312                         err = -ENOMEM;
3313                         goto put_obj;
3314                 }
3315         }
3316
3317         syncs_user = u64_to_user_ptr(args->syncs);
3318         for (num_syncs = 0; num_syncs < args->num_syncs; num_syncs++) {
3319                 err = xe_sync_entry_parse(xe, xef, &syncs[num_syncs],
3320                                           &syncs_user[num_syncs], false,
3321                                           xe_vm_no_dma_fences(vm));
3322                 if (err)
3323                         goto free_syncs;
3324         }
3325
3326         /* Do some error checking first to make the unwind easier */
3327         for (i = 0; i < args->num_binds; ++i) {
3328                 u64 range = bind_ops[i].range;
3329                 u64 addr = bind_ops[i].addr;
3330                 u32 op = bind_ops[i].op;
3331
3332                 err = vm_bind_ioctl_lookup_vma(vm, bos[i], addr, range, op);
3333                 if (err)
3334                         goto free_syncs;
3335         }
3336
3337         for (i = 0; i < args->num_binds; ++i) {
3338                 u64 range = bind_ops[i].range;
3339                 u64 addr = bind_ops[i].addr;
3340                 u32 op = bind_ops[i].op;
3341                 u64 obj_offset = bind_ops[i].obj_offset;
3342                 u64 tile_mask = bind_ops[i].tile_mask;
3343                 u32 region = bind_ops[i].region;
3344
3345                 ops[i] = vm_bind_ioctl_ops_create(vm, bos[i], obj_offset,
3346                                                   addr, range, op, tile_mask,
3347                                                   region);
3348                 if (IS_ERR(ops[i])) {
3349                         err = PTR_ERR(ops[i]);
3350                         ops[i] = NULL;
3351                         goto unwind_ops;
3352                 }
3353         }
3354
3355         err = vm_bind_ioctl_ops_parse(vm, e, ops, args->num_binds,
3356                                       syncs, num_syncs, &ops_list, async);
3357         if (err)
3358                 goto unwind_ops;
3359
3360         err = vm_bind_ioctl_ops_commit(vm, &ops_list, async);
3361         up_write(&vm->lock);
3362
3363         for (i = 0; i < args->num_binds; ++i)
3364                 xe_bo_put(bos[i]);
3365
3366         kfree(bos);
3367         kfree(ops);
3368         if (args->num_binds > 1)
3369                 kfree(bind_ops);
3370
3371         return err;
3372
3373 unwind_ops:
3374         vm_bind_ioctl_ops_unwind(vm, ops, args->num_binds);
3375 free_syncs:
3376         while (num_syncs--)
3377                 xe_sync_entry_cleanup(&syncs[num_syncs]);
3378
3379         kfree(syncs);
3380 put_obj:
3381         for (i = 0; i < args->num_binds; ++i)
3382                 xe_bo_put(bos[i]);
3383 release_vm_lock:
3384         up_write(&vm->lock);
3385 put_vm:
3386         xe_vm_put(vm);
3387 put_engine:
3388         if (e)
3389                 xe_engine_put(e);
3390 free_objs:
3391         kfree(bos);
3392         kfree(ops);
3393         if (args->num_binds > 1)
3394                 kfree(bind_ops);
3395         return err == -ENODATA ? 0 : err;
3396 }
3397
3398 /*
3399  * XXX: Using the TTM wrappers for now, likely can call into dma-resv code
3400  * directly to optimize. Also this likely should be an inline function.
3401  */
3402 int xe_vm_lock(struct xe_vm *vm, struct ww_acquire_ctx *ww,
3403                int num_resv, bool intr)
3404 {
3405         struct ttm_validate_buffer tv_vm;
3406         LIST_HEAD(objs);
3407         LIST_HEAD(dups);
3408
3409         XE_BUG_ON(!ww);
3410
3411         tv_vm.num_shared = num_resv;
3412         tv_vm.bo = xe_vm_ttm_bo(vm);
3413         list_add_tail(&tv_vm.head, &objs);
3414
3415         return ttm_eu_reserve_buffers(ww, &objs, intr, &dups);
3416 }
3417
3418 void xe_vm_unlock(struct xe_vm *vm, struct ww_acquire_ctx *ww)
3419 {
3420         dma_resv_unlock(xe_vm_resv(vm));
3421         ww_acquire_fini(ww);
3422 }
3423
3424 /**
3425  * xe_vm_invalidate_vma - invalidate GPU mappings for VMA without a lock
3426  * @vma: VMA to invalidate
3427  *
3428  * Walks a list of page tables leaves which it memset the entries owned by this
3429  * VMA to zero, invalidates the TLBs, and block until TLBs invalidation is
3430  * complete.
3431  *
3432  * Returns 0 for success, negative error code otherwise.
3433  */
3434 int xe_vm_invalidate_vma(struct xe_vma *vma)
3435 {
3436         struct xe_device *xe = xe_vma_vm(vma)->xe;
3437         struct xe_tile *tile;
3438         u32 tile_needs_invalidate = 0;
3439         int seqno[XE_MAX_TILES_PER_DEVICE];
3440         u8 id;
3441         int ret;
3442
3443         XE_BUG_ON(!xe_vm_in_fault_mode(xe_vma_vm(vma)));
3444         XE_WARN_ON(xe_vma_is_null(vma));
3445         trace_xe_vma_usm_invalidate(vma);
3446
3447         /* Check that we don't race with page-table updates */
3448         if (IS_ENABLED(CONFIG_PROVE_LOCKING)) {
3449                 if (xe_vma_is_userptr(vma)) {
3450                         WARN_ON_ONCE(!mmu_interval_check_retry
3451                                      (&vma->userptr.notifier,
3452                                       vma->userptr.notifier_seq));
3453                         WARN_ON_ONCE(!dma_resv_test_signaled(xe_vm_resv(xe_vma_vm(vma)),
3454                                                              DMA_RESV_USAGE_BOOKKEEP));
3455
3456                 } else {
3457                         xe_bo_assert_held(xe_vma_bo(vma));
3458                 }
3459         }
3460
3461         for_each_tile(tile, xe, id) {
3462                 if (xe_pt_zap_ptes(tile, vma)) {
3463                         tile_needs_invalidate |= BIT(id);
3464                         xe_device_wmb(xe);
3465                         /*
3466                          * FIXME: We potentially need to invalidate multiple
3467                          * GTs within the tile
3468                          */
3469                         seqno[id] = xe_gt_tlb_invalidation_vma(tile->primary_gt, NULL, vma);
3470                         if (seqno[id] < 0)
3471                                 return seqno[id];
3472                 }
3473         }
3474
3475         for_each_tile(tile, xe, id) {
3476                 if (tile_needs_invalidate & BIT(id)) {
3477                         ret = xe_gt_tlb_invalidation_wait(tile->primary_gt, seqno[id]);
3478                         if (ret < 0)
3479                                 return ret;
3480                 }
3481         }
3482
3483         vma->usm.tile_invalidated = vma->tile_mask;
3484
3485         return 0;
3486 }
3487
3488 int xe_analyze_vm(struct drm_printer *p, struct xe_vm *vm, int gt_id)
3489 {
3490         struct drm_gpuva *gpuva;
3491         bool is_vram;
3492         uint64_t addr;
3493
3494         if (!down_read_trylock(&vm->lock)) {
3495                 drm_printf(p, " Failed to acquire VM lock to dump capture");
3496                 return 0;
3497         }
3498         if (vm->pt_root[gt_id]) {
3499                 addr = xe_bo_addr(vm->pt_root[gt_id]->bo, 0, XE_PAGE_SIZE,
3500                                   &is_vram);
3501                 drm_printf(p, " VM root: A:0x%llx %s\n", addr, is_vram ? "VRAM" : "SYS");
3502         }
3503
3504         drm_gpuvm_for_each_va(gpuva, &vm->gpuvm) {
3505                 struct xe_vma *vma = gpuva_to_vma(gpuva);
3506                 bool is_userptr = xe_vma_is_userptr(vma);
3507                 bool is_null = xe_vma_is_null(vma);
3508
3509                 if (is_null) {
3510                         addr = 0;
3511                 } else if (is_userptr) {
3512                         struct xe_res_cursor cur;
3513
3514                         if (vma->userptr.sg) {
3515                                 xe_res_first_sg(vma->userptr.sg, 0, XE_PAGE_SIZE,
3516                                                 &cur);
3517                                 addr = xe_res_dma(&cur);
3518                         } else {
3519                                 addr = 0;
3520                         }
3521                 } else {
3522                         addr = __xe_bo_addr(xe_vma_bo(vma), 0, XE_PAGE_SIZE, &is_vram);
3523                 }
3524                 drm_printf(p, " [%016llx-%016llx] S:0x%016llx A:%016llx %s\n",
3525                            xe_vma_start(vma), xe_vma_end(vma) - 1,
3526                            xe_vma_size(vma),
3527                            addr, is_null ? "NULL" : is_userptr ? "USR" :
3528                            is_vram ? "VRAM" : "SYS");
3529         }
3530         up_read(&vm->lock);
3531
3532         return 0;
3533 }