xref: /linux/drivers/gpu/drm/xe/xe_pt.c (revision 38fc73b8c7d692a099ddda37b700eeb330a03ff1)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2022 Intel Corporation
4  */
5 
6 #include <linux/dma-fence-array.h>
7 
8 #include "xe_pt.h"
9 
10 #include "regs/xe_gtt_defs.h"
11 #include "xe_bo.h"
12 #include "xe_device.h"
13 #include "xe_drm_client.h"
14 #include "xe_exec_queue.h"
15 #include "xe_gt.h"
16 #include "xe_gt_tlb_inval_job.h"
17 #include "xe_migrate.h"
18 #include "xe_pt_types.h"
19 #include "xe_pt_walk.h"
20 #include "xe_res_cursor.h"
21 #include "xe_sched_job.h"
22 #include "xe_sync.h"
23 #include "xe_svm.h"
24 #include "xe_trace.h"
25 #include "xe_ttm_stolen_mgr.h"
26 #include "xe_vm.h"
27 
28 struct xe_pt_dir {
29 	struct xe_pt pt;
30 	/** @children: Array of page-table child nodes */
31 	struct xe_ptw *children[XE_PDES];
32 	/** @staging: Array of page-table staging nodes */
33 	struct xe_ptw *staging[XE_PDES];
34 };
35 
36 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM)
37 #define xe_pt_set_addr(__xe_pt, __addr) ((__xe_pt)->addr = (__addr))
38 #define xe_pt_addr(__xe_pt) ((__xe_pt)->addr)
39 #else
40 #define xe_pt_set_addr(__xe_pt, __addr)
41 #define xe_pt_addr(__xe_pt) 0ull
42 #endif
43 
44 static const u64 xe_normal_pt_shifts[] = {12, 21, 30, 39, 48};
45 static const u64 xe_compact_pt_shifts[] = {16, 21, 30, 39, 48};
46 
47 #define XE_PT_HIGHEST_LEVEL (ARRAY_SIZE(xe_normal_pt_shifts) - 1)
48 
49 static struct xe_pt_dir *as_xe_pt_dir(struct xe_pt *pt)
50 {
51 	return container_of(pt, struct xe_pt_dir, pt);
52 }
53 
54 static struct xe_pt *
55 xe_pt_entry_staging(struct xe_pt_dir *pt_dir, unsigned int index)
56 {
57 	return container_of(pt_dir->staging[index], struct xe_pt, base);
58 }
59 
60 static u64 __xe_pt_empty_pte(struct xe_tile *tile, struct xe_vm *vm,
61 			     unsigned int level)
62 {
63 	struct xe_device *xe = tile_to_xe(tile);
64 	u16 pat_index = xe->pat.idx[XE_CACHE_WB];
65 	u8 id = tile->id;
66 
67 	if (!xe_vm_has_scratch(vm))
68 		return 0;
69 
70 	if (level > MAX_HUGEPTE_LEVEL)
71 		return vm->pt_ops->pde_encode_bo(vm->scratch_pt[id][level - 1]->bo,
72 						 0);
73 
74 	return vm->pt_ops->pte_encode_addr(xe, 0, pat_index, level, IS_DGFX(xe), 0) |
75 		XE_PTE_NULL;
76 }
77 
78 static void xe_pt_free(struct xe_pt *pt)
79 {
80 	if (pt->level)
81 		kfree(as_xe_pt_dir(pt));
82 	else
83 		kfree(pt);
84 }
85 
86 /**
87  * xe_pt_create() - Create a page-table.
88  * @vm: The vm to create for.
89  * @tile: The tile to create for.
90  * @level: The page-table level.
91  *
92  * Allocate and initialize a single struct xe_pt metadata structure. Also
93  * create the corresponding page-table bo, but don't initialize it. If the
94  * level is grater than zero, then it's assumed to be a directory page-
95  * table and the directory structure is also allocated and initialized to
96  * NULL pointers.
97  *
98  * Return: A valid struct xe_pt pointer on success, Pointer error code on
99  * error.
100  */
101 struct xe_pt *xe_pt_create(struct xe_vm *vm, struct xe_tile *tile,
102 			   unsigned int level)
103 {
104 	struct xe_pt *pt;
105 	struct xe_bo *bo;
106 	u32 bo_flags;
107 	int err;
108 
109 	if (level) {
110 		struct xe_pt_dir *dir = kzalloc(sizeof(*dir), GFP_KERNEL);
111 
112 		pt = (dir) ? &dir->pt : NULL;
113 	} else {
114 		pt = kzalloc(sizeof(*pt), GFP_KERNEL);
115 	}
116 	if (!pt)
117 		return ERR_PTR(-ENOMEM);
118 
119 	bo_flags = XE_BO_FLAG_VRAM_IF_DGFX(tile) |
120 		   XE_BO_FLAG_IGNORE_MIN_PAGE_SIZE |
121 		   XE_BO_FLAG_NO_RESV_EVICT | XE_BO_FLAG_PAGETABLE;
122 	if (vm->xef) /* userspace */
123 		bo_flags |= XE_BO_FLAG_PINNED_LATE_RESTORE;
124 
125 	pt->level = level;
126 	bo = xe_bo_create_pin_map(vm->xe, tile, vm, SZ_4K,
127 				  ttm_bo_type_kernel,
128 				  bo_flags);
129 	if (IS_ERR(bo)) {
130 		err = PTR_ERR(bo);
131 		goto err_kfree;
132 	}
133 	pt->bo = bo;
134 	pt->base.children = level ? as_xe_pt_dir(pt)->children : NULL;
135 	pt->base.staging = level ? as_xe_pt_dir(pt)->staging : NULL;
136 
137 	if (vm->xef)
138 		xe_drm_client_add_bo(vm->xef->client, pt->bo);
139 	xe_tile_assert(tile, level <= XE_VM_MAX_LEVEL);
140 
141 	return pt;
142 
143 err_kfree:
144 	xe_pt_free(pt);
145 	return ERR_PTR(err);
146 }
147 ALLOW_ERROR_INJECTION(xe_pt_create, ERRNO);
148 
149 /**
150  * xe_pt_populate_empty() - Populate a page-table bo with scratch- or zero
151  * entries.
152  * @tile: The tile the scratch pagetable of which to use.
153  * @vm: The vm we populate for.
154  * @pt: The pagetable the bo of which to initialize.
155  *
156  * Populate the page-table bo of @pt with entries pointing into the tile's
157  * scratch page-table tree if any. Otherwise populate with zeros.
158  */
159 void xe_pt_populate_empty(struct xe_tile *tile, struct xe_vm *vm,
160 			  struct xe_pt *pt)
161 {
162 	struct iosys_map *map = &pt->bo->vmap;
163 	u64 empty;
164 	int i;
165 
166 	if (!xe_vm_has_scratch(vm)) {
167 		/*
168 		 * FIXME: Some memory is allocated already allocated to zero?
169 		 * Find out which memory that is and avoid this memset...
170 		 */
171 		xe_map_memset(vm->xe, map, 0, 0, SZ_4K);
172 	} else {
173 		empty = __xe_pt_empty_pte(tile, vm, pt->level);
174 		for (i = 0; i < XE_PDES; i++)
175 			xe_pt_write(vm->xe, map, i, empty);
176 	}
177 }
178 
179 /**
180  * xe_pt_shift() - Return the ilog2 value of the size of the address range of
181  * a page-table at a certain level.
182  * @level: The level.
183  *
184  * Return: The ilog2 value of the size of the address range of a page-table
185  * at level @level.
186  */
187 unsigned int xe_pt_shift(unsigned int level)
188 {
189 	return XE_PTE_SHIFT + XE_PDE_SHIFT * level;
190 }
191 
192 /**
193  * xe_pt_destroy() - Destroy a page-table tree.
194  * @pt: The root of the page-table tree to destroy.
195  * @flags: vm flags. Currently unused.
196  * @deferred: List head of lockless list for deferred putting. NULL for
197  *            immediate putting.
198  *
199  * Puts the page-table bo, recursively calls xe_pt_destroy on all children
200  * and finally frees @pt. TODO: Can we remove the @flags argument?
201  */
202 void xe_pt_destroy(struct xe_pt *pt, u32 flags, struct llist_head *deferred)
203 {
204 	int i;
205 
206 	if (!pt)
207 		return;
208 
209 	XE_WARN_ON(!list_empty(&pt->bo->ttm.base.gpuva.list));
210 	xe_bo_unpin(pt->bo);
211 	xe_bo_put_deferred(pt->bo, deferred);
212 
213 	if (pt->level > 0 && pt->num_live) {
214 		struct xe_pt_dir *pt_dir = as_xe_pt_dir(pt);
215 
216 		for (i = 0; i < XE_PDES; i++) {
217 			if (xe_pt_entry_staging(pt_dir, i))
218 				xe_pt_destroy(xe_pt_entry_staging(pt_dir, i), flags,
219 					      deferred);
220 		}
221 	}
222 	xe_pt_free(pt);
223 }
224 
225 /**
226  * xe_pt_clear() - Clear a page-table.
227  * @xe: xe device.
228  * @pt: The page-table.
229  *
230  * Clears page-table by setting to zero.
231  */
232 void xe_pt_clear(struct xe_device *xe, struct xe_pt *pt)
233 {
234 	struct iosys_map *map = &pt->bo->vmap;
235 
236 	xe_map_memset(xe, map, 0, 0, SZ_4K);
237 }
238 
239 /**
240  * DOC: Pagetable building
241  *
242  * Below we use the term "page-table" for both page-directories, containing
243  * pointers to lower level page-directories or page-tables, and level 0
244  * page-tables that contain only page-table-entries pointing to memory pages.
245  *
246  * When inserting an address range in an already existing page-table tree
247  * there will typically be a set of page-tables that are shared with other
248  * address ranges, and a set that are private to this address range.
249  * The set of shared page-tables can be at most two per level,
250  * and those can't be updated immediately because the entries of those
251  * page-tables may still be in use by the gpu for other mappings. Therefore
252  * when inserting entries into those, we instead stage those insertions by
253  * adding insertion data into struct xe_vm_pgtable_update structures. This
254  * data, (subtrees for the cpu and page-table-entries for the gpu) is then
255  * added in a separate commit step. CPU-data is committed while still under the
256  * vm lock, the object lock and for userptr, the notifier lock in read mode.
257  * The GPU async data is committed either by the GPU or CPU after fulfilling
258  * relevant dependencies.
259  * For non-shared page-tables (and, in fact, for shared ones that aren't
260  * existing at the time of staging), we add the data in-place without the
261  * special update structures. This private part of the page-table tree will
262  * remain disconnected from the vm page-table tree until data is committed to
263  * the shared page tables of the vm tree in the commit phase.
264  */
265 
266 struct xe_pt_update {
267 	/** @update: The update structure we're building for this parent. */
268 	struct xe_vm_pgtable_update *update;
269 	/** @parent: The parent. Used to detect a parent change. */
270 	struct xe_pt *parent;
271 	/** @preexisting: Whether the parent was pre-existing or allocated */
272 	bool preexisting;
273 };
274 
275 /**
276  * struct xe_pt_stage_bind_walk - Walk state for the stage_bind walk.
277  */
278 struct xe_pt_stage_bind_walk {
279 	/** @base: The base class. */
280 	struct xe_pt_walk base;
281 
282 	/* Input parameters for the walk */
283 	/** @vm: The vm we're building for. */
284 	struct xe_vm *vm;
285 	/** @tile: The tile we're building for. */
286 	struct xe_tile *tile;
287 	/** @default_vram_pte: PTE flag only template for VRAM. No address is associated */
288 	u64 default_vram_pte;
289 	/** @default_system_pte: PTE flag only template for System. No address is associated */
290 	u64 default_system_pte;
291 	/** @dma_offset: DMA offset to add to the PTE. */
292 	u64 dma_offset;
293 	/**
294 	 * @needs_64K: This address range enforces 64K alignment and
295 	 * granularity on VRAM.
296 	 */
297 	bool needs_64K;
298 	/** @clear_pt: clear page table entries during the bind walk */
299 	bool clear_pt;
300 	/**
301 	 * @vma: VMA being mapped
302 	 */
303 	struct xe_vma *vma;
304 
305 	/* Also input, but is updated during the walk*/
306 	/** @curs: The DMA address cursor. */
307 	struct xe_res_cursor *curs;
308 	/** @va_curs_start: The Virtual address corresponding to @curs->start */
309 	u64 va_curs_start;
310 
311 	/* Output */
312 	/** @wupd: Walk output data for page-table updates. */
313 	struct xe_walk_update {
314 		/** @wupd.entries: Caller provided storage. */
315 		struct xe_vm_pgtable_update *entries;
316 		/** @wupd.num_used_entries: Number of update @entries used. */
317 		unsigned int num_used_entries;
318 		/** @wupd.updates: Tracks the update entry at a given level */
319 		struct xe_pt_update updates[XE_VM_MAX_LEVEL + 1];
320 	} wupd;
321 
322 	/* Walk state */
323 	/**
324 	 * @l0_end_addr: The end address of the current l0 leaf. Used for
325 	 * 64K granularity detection.
326 	 */
327 	u64 l0_end_addr;
328 	/** @addr_64K: The start address of the current 64K chunk. */
329 	u64 addr_64K;
330 	/** @found_64K: Whether @add_64K actually points to a 64K chunk. */
331 	bool found_64K;
332 };
333 
334 static int
335 xe_pt_new_shared(struct xe_walk_update *wupd, struct xe_pt *parent,
336 		 pgoff_t offset, bool alloc_entries)
337 {
338 	struct xe_pt_update *upd = &wupd->updates[parent->level];
339 	struct xe_vm_pgtable_update *entry;
340 
341 	/*
342 	 * For *each level*, we could only have one active
343 	 * struct xt_pt_update at any one time. Once we move on to a
344 	 * new parent and page-directory, the old one is complete, and
345 	 * updates are either already stored in the build tree or in
346 	 * @wupd->entries
347 	 */
348 	if (likely(upd->parent == parent))
349 		return 0;
350 
351 	upd->parent = parent;
352 	upd->preexisting = true;
353 
354 	if (wupd->num_used_entries == XE_VM_MAX_LEVEL * 2 + 1)
355 		return -EINVAL;
356 
357 	entry = wupd->entries + wupd->num_used_entries++;
358 	upd->update = entry;
359 	entry->ofs = offset;
360 	entry->pt_bo = parent->bo;
361 	entry->pt = parent;
362 	entry->flags = 0;
363 	entry->qwords = 0;
364 	entry->pt_bo->update_index = -1;
365 
366 	if (alloc_entries) {
367 		entry->pt_entries = kmalloc_array(XE_PDES,
368 						  sizeof(*entry->pt_entries),
369 						  GFP_KERNEL);
370 		if (!entry->pt_entries)
371 			return -ENOMEM;
372 	}
373 
374 	return 0;
375 }
376 
377 /*
378  * NOTE: This is a very frequently called function so we allow ourselves
379  * to annotate (using branch prediction hints) the fastpath of updating a
380  * non-pre-existing pagetable with leaf ptes.
381  */
382 static int
383 xe_pt_insert_entry(struct xe_pt_stage_bind_walk *xe_walk, struct xe_pt *parent,
384 		   pgoff_t offset, struct xe_pt *xe_child, u64 pte)
385 {
386 	struct xe_pt_update *upd = &xe_walk->wupd.updates[parent->level];
387 	struct xe_pt_update *child_upd = xe_child ?
388 		&xe_walk->wupd.updates[xe_child->level] : NULL;
389 	int ret;
390 
391 	ret = xe_pt_new_shared(&xe_walk->wupd, parent, offset, true);
392 	if (unlikely(ret))
393 		return ret;
394 
395 	/*
396 	 * Register this new pagetable so that it won't be recognized as
397 	 * a shared pagetable by a subsequent insertion.
398 	 */
399 	if (unlikely(child_upd)) {
400 		child_upd->update = NULL;
401 		child_upd->parent = xe_child;
402 		child_upd->preexisting = false;
403 	}
404 
405 	if (likely(!upd->preexisting)) {
406 		/* Continue building a non-connected subtree. */
407 		struct iosys_map *map = &parent->bo->vmap;
408 
409 		if (unlikely(xe_child)) {
410 			parent->base.children[offset] = &xe_child->base;
411 			parent->base.staging[offset] = &xe_child->base;
412 		}
413 
414 		xe_pt_write(xe_walk->vm->xe, map, offset, pte);
415 		parent->num_live++;
416 	} else {
417 		/* Shared pt. Stage update. */
418 		unsigned int idx;
419 		struct xe_vm_pgtable_update *entry = upd->update;
420 
421 		idx = offset - entry->ofs;
422 		entry->pt_entries[idx].pt = xe_child;
423 		entry->pt_entries[idx].pte = pte;
424 		entry->qwords++;
425 	}
426 
427 	return 0;
428 }
429 
430 static bool xe_pt_hugepte_possible(u64 addr, u64 next, unsigned int level,
431 				   struct xe_pt_stage_bind_walk *xe_walk)
432 {
433 	u64 size, dma;
434 
435 	if (level > MAX_HUGEPTE_LEVEL)
436 		return false;
437 
438 	/* Does the virtual range requested cover a huge pte? */
439 	if (!xe_pt_covers(addr, next, level, &xe_walk->base))
440 		return false;
441 
442 	/* Does the DMA segment cover the whole pte? */
443 	if (next - xe_walk->va_curs_start > xe_walk->curs->size)
444 		return false;
445 
446 	/* null VMA's do not have dma addresses */
447 	if (xe_vma_is_null(xe_walk->vma))
448 		return true;
449 
450 	/* if we are clearing page table, no dma addresses*/
451 	if (xe_walk->clear_pt)
452 		return true;
453 
454 	/* Is the DMA address huge PTE size aligned? */
455 	size = next - addr;
456 	dma = addr - xe_walk->va_curs_start + xe_res_dma(xe_walk->curs);
457 
458 	return IS_ALIGNED(dma, size);
459 }
460 
461 /*
462  * Scan the requested mapping to check whether it can be done entirely
463  * with 64K PTEs.
464  */
465 static bool
466 xe_pt_scan_64K(u64 addr, u64 next, struct xe_pt_stage_bind_walk *xe_walk)
467 {
468 	struct xe_res_cursor curs = *xe_walk->curs;
469 
470 	if (!IS_ALIGNED(addr, SZ_64K))
471 		return false;
472 
473 	if (next > xe_walk->l0_end_addr)
474 		return false;
475 
476 	/* null VMA's do not have dma addresses */
477 	if (xe_vma_is_null(xe_walk->vma))
478 		return true;
479 
480 	xe_res_next(&curs, addr - xe_walk->va_curs_start);
481 	for (; addr < next; addr += SZ_64K) {
482 		if (!IS_ALIGNED(xe_res_dma(&curs), SZ_64K) || curs.size < SZ_64K)
483 			return false;
484 
485 		xe_res_next(&curs, SZ_64K);
486 	}
487 
488 	return addr == next;
489 }
490 
491 /*
492  * For non-compact "normal" 4K level-0 pagetables, we want to try to group
493  * addresses together in 64K-contigous regions to add a 64K TLB hint for the
494  * device to the PTE.
495  * This function determines whether the address is part of such a
496  * segment. For VRAM in normal pagetables, this is strictly necessary on
497  * some devices.
498  */
499 static bool
500 xe_pt_is_pte_ps64K(u64 addr, u64 next, struct xe_pt_stage_bind_walk *xe_walk)
501 {
502 	/* Address is within an already found 64k region */
503 	if (xe_walk->found_64K && addr - xe_walk->addr_64K < SZ_64K)
504 		return true;
505 
506 	xe_walk->found_64K = xe_pt_scan_64K(addr, addr + SZ_64K, xe_walk);
507 	xe_walk->addr_64K = addr;
508 
509 	return xe_walk->found_64K;
510 }
511 
512 static int
513 xe_pt_stage_bind_entry(struct xe_ptw *parent, pgoff_t offset,
514 		       unsigned int level, u64 addr, u64 next,
515 		       struct xe_ptw **child,
516 		       enum page_walk_action *action,
517 		       struct xe_pt_walk *walk)
518 {
519 	struct xe_pt_stage_bind_walk *xe_walk =
520 		container_of(walk, typeof(*xe_walk), base);
521 	u16 pat_index = xe_walk->vma->attr.pat_index;
522 	struct xe_pt *xe_parent = container_of(parent, typeof(*xe_parent), base);
523 	struct xe_vm *vm = xe_walk->vm;
524 	struct xe_pt *xe_child;
525 	bool covers;
526 	int ret = 0;
527 	u64 pte;
528 
529 	/* Is this a leaf entry ?*/
530 	if (level == 0 || xe_pt_hugepte_possible(addr, next, level, xe_walk)) {
531 		struct xe_res_cursor *curs = xe_walk->curs;
532 		bool is_null = xe_vma_is_null(xe_walk->vma);
533 		bool is_vram = is_null ? false : xe_res_is_vram(curs);
534 
535 		XE_WARN_ON(xe_walk->va_curs_start != addr);
536 
537 		if (xe_walk->clear_pt) {
538 			pte = 0;
539 		} else {
540 			pte = vm->pt_ops->pte_encode_vma(is_null ? 0 :
541 							 xe_res_dma(curs) +
542 							 xe_walk->dma_offset,
543 							 xe_walk->vma,
544 							 pat_index, level);
545 			if (!is_null)
546 				pte |= is_vram ? xe_walk->default_vram_pte :
547 					xe_walk->default_system_pte;
548 
549 			/*
550 			 * Set the XE_PTE_PS64 hint if possible, otherwise if
551 			 * this device *requires* 64K PTE size for VRAM, fail.
552 			 */
553 			if (level == 0 && !xe_parent->is_compact) {
554 				if (xe_pt_is_pte_ps64K(addr, next, xe_walk)) {
555 					xe_walk->vma->gpuva.flags |=
556 							XE_VMA_PTE_64K;
557 					pte |= XE_PTE_PS64;
558 				} else if (XE_WARN_ON(xe_walk->needs_64K &&
559 					   is_vram)) {
560 					return -EINVAL;
561 				}
562 			}
563 		}
564 
565 		ret = xe_pt_insert_entry(xe_walk, xe_parent, offset, NULL, pte);
566 		if (unlikely(ret))
567 			return ret;
568 
569 		if (!is_null && !xe_walk->clear_pt)
570 			xe_res_next(curs, next - addr);
571 		xe_walk->va_curs_start = next;
572 		xe_walk->vma->gpuva.flags |= (XE_VMA_PTE_4K << level);
573 		*action = ACTION_CONTINUE;
574 
575 		return ret;
576 	}
577 
578 	/*
579 	 * Descending to lower level. Determine if we need to allocate a
580 	 * new page table or -directory, which we do if there is no
581 	 * previous one or there is one we can completely replace.
582 	 */
583 	if (level == 1) {
584 		walk->shifts = xe_normal_pt_shifts;
585 		xe_walk->l0_end_addr = next;
586 	}
587 
588 	covers = xe_pt_covers(addr, next, level, &xe_walk->base);
589 	if (covers || !*child) {
590 		u64 flags = 0;
591 
592 		xe_child = xe_pt_create(xe_walk->vm, xe_walk->tile, level - 1);
593 		if (IS_ERR(xe_child))
594 			return PTR_ERR(xe_child);
595 
596 		xe_pt_set_addr(xe_child,
597 			       round_down(addr, 1ull << walk->shifts[level]));
598 
599 		if (!covers)
600 			xe_pt_populate_empty(xe_walk->tile, xe_walk->vm, xe_child);
601 
602 		*child = &xe_child->base;
603 
604 		/*
605 		 * Prefer the compact pagetable layout for L0 if possible. Only
606 		 * possible if VMA covers entire 2MB region as compact 64k and
607 		 * 4k pages cannot be mixed within a 2MB region.
608 		 * TODO: Suballocate the pt bo to avoid wasting a lot of
609 		 * memory.
610 		 */
611 		if (GRAPHICS_VERx100(tile_to_xe(xe_walk->tile)) >= 1250 && level == 1 &&
612 		    covers && xe_pt_scan_64K(addr, next, xe_walk)) {
613 			walk->shifts = xe_compact_pt_shifts;
614 			xe_walk->vma->gpuva.flags |= XE_VMA_PTE_COMPACT;
615 			flags |= XE_PDE_64K;
616 			xe_child->is_compact = true;
617 		}
618 
619 		pte = vm->pt_ops->pde_encode_bo(xe_child->bo, 0) | flags;
620 		ret = xe_pt_insert_entry(xe_walk, xe_parent, offset, xe_child,
621 					 pte);
622 	}
623 
624 	*action = ACTION_SUBTREE;
625 	return ret;
626 }
627 
628 static const struct xe_pt_walk_ops xe_pt_stage_bind_ops = {
629 	.pt_entry = xe_pt_stage_bind_entry,
630 };
631 
632 /*
633  * Default atomic expectations for different allocation scenarios are as follows:
634  *
635  * 1. Traditional API: When the VM is not in LR mode:
636  *    - Device atomics are expected to function with all allocations.
637  *
638  * 2. Compute/SVM API: When the VM is in LR mode:
639  *    - Device atomics are the default behavior when the bo is placed in a single region.
640  *    - In all other cases device atomics will be disabled with AE=0 until an application
641  *      request differently using a ioctl like madvise.
642  */
643 static bool xe_atomic_for_vram(struct xe_vm *vm, struct xe_vma *vma)
644 {
645 	if (vma->attr.atomic_access == DRM_XE_ATOMIC_CPU)
646 		return false;
647 
648 	return true;
649 }
650 
651 static bool xe_atomic_for_system(struct xe_vm *vm, struct xe_vma *vma)
652 {
653 	struct xe_device *xe = vm->xe;
654 	struct xe_bo *bo = xe_vma_bo(vma);
655 
656 	if (!xe->info.has_device_atomics_on_smem ||
657 	    vma->attr.atomic_access == DRM_XE_ATOMIC_CPU)
658 		return false;
659 
660 	if (vma->attr.atomic_access == DRM_XE_ATOMIC_DEVICE)
661 		return true;
662 
663 	/*
664 	 * If a SMEM+LMEM allocation is backed by SMEM, a device
665 	 * atomics will cause a gpu page fault and which then
666 	 * gets migrated to LMEM, bind such allocations with
667 	 * device atomics enabled.
668 	 */
669 	return (!IS_DGFX(xe) || (!xe_vm_in_lr_mode(vm) ||
670 				 (bo && xe_bo_has_single_placement(bo))));
671 }
672 
673 /**
674  * xe_pt_stage_bind() - Build a disconnected page-table tree for a given address
675  * range.
676  * @tile: The tile we're building for.
677  * @vma: The vma indicating the address range.
678  * @range: The range indicating the address range.
679  * @entries: Storage for the update entries used for connecting the tree to
680  * the main tree at commit time.
681  * @num_entries: On output contains the number of @entries used.
682  * @clear_pt: Clear the page table entries.
683  *
684  * This function builds a disconnected page-table tree for a given address
685  * range. The tree is connected to the main vm tree for the gpu using
686  * xe_migrate_update_pgtables() and for the cpu using xe_pt_commit_bind().
687  * The function builds xe_vm_pgtable_update structures for already existing
688  * shared page-tables, and non-existing shared and non-shared page-tables
689  * are built and populated directly.
690  *
691  * Return 0 on success, negative error code on error.
692  */
693 static int
694 xe_pt_stage_bind(struct xe_tile *tile, struct xe_vma *vma,
695 		 struct xe_svm_range *range,
696 		 struct xe_vm_pgtable_update *entries,
697 		 u32 *num_entries, bool clear_pt)
698 {
699 	struct xe_device *xe = tile_to_xe(tile);
700 	struct xe_bo *bo = xe_vma_bo(vma);
701 	struct xe_res_cursor curs;
702 	struct xe_vm *vm = xe_vma_vm(vma);
703 	struct xe_pt_stage_bind_walk xe_walk = {
704 		.base = {
705 			.ops = &xe_pt_stage_bind_ops,
706 			.shifts = xe_normal_pt_shifts,
707 			.max_level = XE_PT_HIGHEST_LEVEL,
708 			.staging = true,
709 		},
710 		.vm = vm,
711 		.tile = tile,
712 		.curs = &curs,
713 		.va_curs_start = range ? range->base.itree.start :
714 			xe_vma_start(vma),
715 		.vma = vma,
716 		.wupd.entries = entries,
717 		.clear_pt = clear_pt,
718 	};
719 	struct xe_pt *pt = vm->pt_root[tile->id];
720 	int ret;
721 
722 	if (range) {
723 		/* Move this entire thing to xe_svm.c? */
724 		xe_svm_notifier_lock(vm);
725 		if (!xe_svm_range_pages_valid(range)) {
726 			xe_svm_range_debug(range, "BIND PREPARE - RETRY");
727 			xe_svm_notifier_unlock(vm);
728 			return -EAGAIN;
729 		}
730 		if (xe_svm_range_has_dma_mapping(range)) {
731 			xe_res_first_dma(range->base.dma_addr, 0,
732 					 range->base.itree.last + 1 - range->base.itree.start,
733 					 &curs);
734 			xe_svm_range_debug(range, "BIND PREPARE - MIXED");
735 		} else {
736 			xe_assert(xe, false);
737 		}
738 		/*
739 		 * Note, when unlocking the resource cursor dma addresses may become
740 		 * stale, but the bind will be aborted anyway at commit time.
741 		 */
742 		xe_svm_notifier_unlock(vm);
743 	}
744 
745 	xe_walk.needs_64K = (vm->flags & XE_VM_FLAG_64K);
746 	if (clear_pt)
747 		goto walk_pt;
748 
749 	if (vma->gpuva.flags & XE_VMA_ATOMIC_PTE_BIT) {
750 		xe_walk.default_vram_pte = xe_atomic_for_vram(vm, vma) ? XE_USM_PPGTT_PTE_AE : 0;
751 		xe_walk.default_system_pte = xe_atomic_for_system(vm, vma) ?
752 			XE_USM_PPGTT_PTE_AE : 0;
753 	}
754 
755 	xe_walk.default_vram_pte |= XE_PPGTT_PTE_DM;
756 	xe_walk.dma_offset = bo ? vram_region_gpu_offset(bo->ttm.resource) : 0;
757 	if (!range)
758 		xe_bo_assert_held(bo);
759 
760 	if (!xe_vma_is_null(vma) && !range) {
761 		if (xe_vma_is_userptr(vma))
762 			xe_res_first_sg(to_userptr_vma(vma)->userptr.sg, 0,
763 					xe_vma_size(vma), &curs);
764 		else if (xe_bo_is_vram(bo) || xe_bo_is_stolen(bo))
765 			xe_res_first(bo->ttm.resource, xe_vma_bo_offset(vma),
766 				     xe_vma_size(vma), &curs);
767 		else
768 			xe_res_first_sg(xe_bo_sg(bo), xe_vma_bo_offset(vma),
769 					xe_vma_size(vma), &curs);
770 	} else if (!range) {
771 		curs.size = xe_vma_size(vma);
772 	}
773 
774 walk_pt:
775 	ret = xe_pt_walk_range(&pt->base, pt->level,
776 			       range ? range->base.itree.start : xe_vma_start(vma),
777 			       range ? range->base.itree.last + 1 : xe_vma_end(vma),
778 			       &xe_walk.base);
779 
780 	*num_entries = xe_walk.wupd.num_used_entries;
781 	return ret;
782 }
783 
784 /**
785  * xe_pt_nonshared_offsets() - Determine the non-shared entry offsets of a
786  * shared pagetable.
787  * @addr: The start address within the non-shared pagetable.
788  * @end: The end address within the non-shared pagetable.
789  * @level: The level of the non-shared pagetable.
790  * @walk: Walk info. The function adjusts the walk action.
791  * @action: next action to perform (see enum page_walk_action)
792  * @offset: Ignored on input, First non-shared entry on output.
793  * @end_offset: Ignored on input, Last non-shared entry + 1 on output.
794  *
795  * A non-shared page-table has some entries that belong to the address range
796  * and others that don't. This function determines the entries that belong
797  * fully to the address range. Depending on level, some entries may
798  * partially belong to the address range (that can't happen at level 0).
799  * The function detects that and adjust those offsets to not include those
800  * partial entries. Iff it does detect partial entries, we know that there must
801  * be shared page tables also at lower levels, so it adjusts the walk action
802  * accordingly.
803  *
804  * Return: true if there were non-shared entries, false otherwise.
805  */
806 static bool xe_pt_nonshared_offsets(u64 addr, u64 end, unsigned int level,
807 				    struct xe_pt_walk *walk,
808 				    enum page_walk_action *action,
809 				    pgoff_t *offset, pgoff_t *end_offset)
810 {
811 	u64 size = 1ull << walk->shifts[level];
812 
813 	*offset = xe_pt_offset(addr, level, walk);
814 	*end_offset = xe_pt_num_entries(addr, end, level, walk) + *offset;
815 
816 	if (!level)
817 		return true;
818 
819 	/*
820 	 * If addr or next are not size aligned, there are shared pts at lower
821 	 * level, so in that case traverse down the subtree
822 	 */
823 	*action = ACTION_CONTINUE;
824 	if (!IS_ALIGNED(addr, size)) {
825 		*action = ACTION_SUBTREE;
826 		(*offset)++;
827 	}
828 
829 	if (!IS_ALIGNED(end, size)) {
830 		*action = ACTION_SUBTREE;
831 		(*end_offset)--;
832 	}
833 
834 	return *end_offset > *offset;
835 }
836 
837 struct xe_pt_zap_ptes_walk {
838 	/** @base: The walk base-class */
839 	struct xe_pt_walk base;
840 
841 	/* Input parameters for the walk */
842 	/** @tile: The tile we're building for */
843 	struct xe_tile *tile;
844 
845 	/* Output */
846 	/** @needs_invalidate: Whether we need to invalidate TLB*/
847 	bool needs_invalidate;
848 };
849 
850 static int xe_pt_zap_ptes_entry(struct xe_ptw *parent, pgoff_t offset,
851 				unsigned int level, u64 addr, u64 next,
852 				struct xe_ptw **child,
853 				enum page_walk_action *action,
854 				struct xe_pt_walk *walk)
855 {
856 	struct xe_pt_zap_ptes_walk *xe_walk =
857 		container_of(walk, typeof(*xe_walk), base);
858 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
859 	pgoff_t end_offset;
860 
861 	XE_WARN_ON(!*child);
862 	XE_WARN_ON(!level);
863 
864 	/*
865 	 * Note that we're called from an entry callback, and we're dealing
866 	 * with the child of that entry rather than the parent, so need to
867 	 * adjust level down.
868 	 */
869 	if (xe_pt_nonshared_offsets(addr, next, --level, walk, action, &offset,
870 				    &end_offset)) {
871 		xe_map_memset(tile_to_xe(xe_walk->tile), &xe_child->bo->vmap,
872 			      offset * sizeof(u64), 0,
873 			      (end_offset - offset) * sizeof(u64));
874 		xe_walk->needs_invalidate = true;
875 	}
876 
877 	return 0;
878 }
879 
880 static const struct xe_pt_walk_ops xe_pt_zap_ptes_ops = {
881 	.pt_entry = xe_pt_zap_ptes_entry,
882 };
883 
884 /**
885  * xe_pt_zap_ptes() - Zap (zero) gpu ptes of an address range
886  * @tile: The tile we're zapping for.
887  * @vma: GPU VMA detailing address range.
888  *
889  * Eviction and Userptr invalidation needs to be able to zap the
890  * gpu ptes of a given address range in pagefaulting mode.
891  * In order to be able to do that, that function needs access to the shared
892  * page-table entrieaso it can either clear the leaf PTEs or
893  * clear the pointers to lower-level page-tables. The caller is required
894  * to hold the necessary locks to ensure neither the page-table connectivity
895  * nor the page-table entries of the range is updated from under us.
896  *
897  * Return: Whether ptes were actually updated and a TLB invalidation is
898  * required.
899  */
900 bool xe_pt_zap_ptes(struct xe_tile *tile, struct xe_vma *vma)
901 {
902 	struct xe_pt_zap_ptes_walk xe_walk = {
903 		.base = {
904 			.ops = &xe_pt_zap_ptes_ops,
905 			.shifts = xe_normal_pt_shifts,
906 			.max_level = XE_PT_HIGHEST_LEVEL,
907 		},
908 		.tile = tile,
909 	};
910 	struct xe_pt *pt = xe_vma_vm(vma)->pt_root[tile->id];
911 	u8 pt_mask = (vma->tile_present & ~vma->tile_invalidated);
912 
913 	if (xe_vma_bo(vma))
914 		xe_bo_assert_held(xe_vma_bo(vma));
915 	else if (xe_vma_is_userptr(vma))
916 		lockdep_assert_held(&xe_vma_vm(vma)->userptr.notifier_lock);
917 
918 	if (!(pt_mask & BIT(tile->id)))
919 		return false;
920 
921 	(void)xe_pt_walk_shared(&pt->base, pt->level, xe_vma_start(vma),
922 				xe_vma_end(vma), &xe_walk.base);
923 
924 	return xe_walk.needs_invalidate;
925 }
926 
927 /**
928  * xe_pt_zap_ptes_range() - Zap (zero) gpu ptes of a SVM range
929  * @tile: The tile we're zapping for.
930  * @vm: The VM we're zapping for.
931  * @range: The SVM range we're zapping for.
932  *
933  * SVM invalidation needs to be able to zap the gpu ptes of a given address
934  * range. In order to be able to do that, that function needs access to the
935  * shared page-table entries so it can either clear the leaf PTEs or
936  * clear the pointers to lower-level page-tables. The caller is required
937  * to hold the SVM notifier lock.
938  *
939  * Return: Whether ptes were actually updated and a TLB invalidation is
940  * required.
941  */
942 bool xe_pt_zap_ptes_range(struct xe_tile *tile, struct xe_vm *vm,
943 			  struct xe_svm_range *range)
944 {
945 	struct xe_pt_zap_ptes_walk xe_walk = {
946 		.base = {
947 			.ops = &xe_pt_zap_ptes_ops,
948 			.shifts = xe_normal_pt_shifts,
949 			.max_level = XE_PT_HIGHEST_LEVEL,
950 		},
951 		.tile = tile,
952 	};
953 	struct xe_pt *pt = vm->pt_root[tile->id];
954 	u8 pt_mask = (range->tile_present & ~range->tile_invalidated);
955 
956 	/*
957 	 * Locking rules:
958 	 *
959 	 * - notifier_lock (write): full protection against page table changes
960 	 *   and MMU notifier invalidations.
961 	 *
962 	 * - notifier_lock (read) + vm_lock (write): combined protection against
963 	 *   invalidations and concurrent page table modifications. (e.g., madvise)
964 	 *
965 	 */
966 	lockdep_assert(lockdep_is_held_type(&vm->svm.gpusvm.notifier_lock, 0) ||
967 		       (lockdep_is_held_type(&vm->svm.gpusvm.notifier_lock, 1) &&
968 		       lockdep_is_held_type(&vm->lock, 0)));
969 
970 	if (!(pt_mask & BIT(tile->id)))
971 		return false;
972 
973 	(void)xe_pt_walk_shared(&pt->base, pt->level, range->base.itree.start,
974 				range->base.itree.last + 1, &xe_walk.base);
975 
976 	return xe_walk.needs_invalidate;
977 }
978 
979 static void
980 xe_vm_populate_pgtable(struct xe_migrate_pt_update *pt_update, struct xe_tile *tile,
981 		       struct iosys_map *map, void *data,
982 		       u32 qword_ofs, u32 num_qwords,
983 		       const struct xe_vm_pgtable_update *update)
984 {
985 	struct xe_pt_entry *ptes = update->pt_entries;
986 	u64 *ptr = data;
987 	u32 i;
988 
989 	for (i = 0; i < num_qwords; i++) {
990 		if (map)
991 			xe_map_wr(tile_to_xe(tile), map, (qword_ofs + i) *
992 				  sizeof(u64), u64, ptes[i].pte);
993 		else
994 			ptr[i] = ptes[i].pte;
995 	}
996 }
997 
998 static void xe_pt_cancel_bind(struct xe_vma *vma,
999 			      struct xe_vm_pgtable_update *entries,
1000 			      u32 num_entries)
1001 {
1002 	u32 i, j;
1003 
1004 	for (i = 0; i < num_entries; i++) {
1005 		struct xe_pt *pt = entries[i].pt;
1006 
1007 		if (!pt)
1008 			continue;
1009 
1010 		if (pt->level) {
1011 			for (j = 0; j < entries[i].qwords; j++)
1012 				xe_pt_destroy(entries[i].pt_entries[j].pt,
1013 					      xe_vma_vm(vma)->flags, NULL);
1014 		}
1015 
1016 		kfree(entries[i].pt_entries);
1017 		entries[i].pt_entries = NULL;
1018 		entries[i].qwords = 0;
1019 	}
1020 }
1021 
1022 #define XE_INVALID_VMA	((struct xe_vma *)(0xdeaddeadull))
1023 
1024 static void xe_pt_commit_prepare_locks_assert(struct xe_vma *vma)
1025 {
1026 	struct xe_vm *vm;
1027 
1028 	if (vma == XE_INVALID_VMA)
1029 		return;
1030 
1031 	vm = xe_vma_vm(vma);
1032 	lockdep_assert_held(&vm->lock);
1033 
1034 	if (!xe_vma_has_no_bo(vma))
1035 		dma_resv_assert_held(xe_vma_bo(vma)->ttm.base.resv);
1036 
1037 	xe_vm_assert_held(vm);
1038 }
1039 
1040 static void xe_pt_commit_locks_assert(struct xe_vma *vma)
1041 {
1042 	struct xe_vm *vm;
1043 
1044 	if (vma == XE_INVALID_VMA)
1045 		return;
1046 
1047 	vm = xe_vma_vm(vma);
1048 	xe_pt_commit_prepare_locks_assert(vma);
1049 
1050 	if (xe_vma_is_userptr(vma))
1051 		lockdep_assert_held_read(&vm->userptr.notifier_lock);
1052 }
1053 
1054 static void xe_pt_commit(struct xe_vma *vma,
1055 			 struct xe_vm_pgtable_update *entries,
1056 			 u32 num_entries, struct llist_head *deferred)
1057 {
1058 	u32 i, j;
1059 
1060 	xe_pt_commit_locks_assert(vma);
1061 
1062 	for (i = 0; i < num_entries; i++) {
1063 		struct xe_pt *pt = entries[i].pt;
1064 		struct xe_pt_dir *pt_dir;
1065 
1066 		if (!pt->level)
1067 			continue;
1068 
1069 		pt_dir = as_xe_pt_dir(pt);
1070 		for (j = 0; j < entries[i].qwords; j++) {
1071 			struct xe_pt *oldpte = entries[i].pt_entries[j].pt;
1072 			int j_ = j + entries[i].ofs;
1073 
1074 			pt_dir->children[j_] = pt_dir->staging[j_];
1075 			xe_pt_destroy(oldpte, (vma == XE_INVALID_VMA) ? 0 :
1076 				      xe_vma_vm(vma)->flags, deferred);
1077 		}
1078 	}
1079 }
1080 
1081 static void xe_pt_abort_bind(struct xe_vma *vma,
1082 			     struct xe_vm_pgtable_update *entries,
1083 			     u32 num_entries, bool rebind)
1084 {
1085 	int i, j;
1086 
1087 	xe_pt_commit_prepare_locks_assert(vma);
1088 
1089 	for (i = num_entries - 1; i >= 0; --i) {
1090 		struct xe_pt *pt = entries[i].pt;
1091 		struct xe_pt_dir *pt_dir;
1092 
1093 		if (!rebind)
1094 			pt->num_live -= entries[i].qwords;
1095 
1096 		if (!pt->level)
1097 			continue;
1098 
1099 		pt_dir = as_xe_pt_dir(pt);
1100 		for (j = 0; j < entries[i].qwords; j++) {
1101 			u32 j_ = j + entries[i].ofs;
1102 			struct xe_pt *newpte = xe_pt_entry_staging(pt_dir, j_);
1103 			struct xe_pt *oldpte = entries[i].pt_entries[j].pt;
1104 
1105 			pt_dir->staging[j_] = oldpte ? &oldpte->base : 0;
1106 			xe_pt_destroy(newpte, xe_vma_vm(vma)->flags, NULL);
1107 		}
1108 	}
1109 }
1110 
1111 static void xe_pt_commit_prepare_bind(struct xe_vma *vma,
1112 				      struct xe_vm_pgtable_update *entries,
1113 				      u32 num_entries, bool rebind)
1114 {
1115 	u32 i, j;
1116 
1117 	xe_pt_commit_prepare_locks_assert(vma);
1118 
1119 	for (i = 0; i < num_entries; i++) {
1120 		struct xe_pt *pt = entries[i].pt;
1121 		struct xe_pt_dir *pt_dir;
1122 
1123 		if (!rebind)
1124 			pt->num_live += entries[i].qwords;
1125 
1126 		if (!pt->level)
1127 			continue;
1128 
1129 		pt_dir = as_xe_pt_dir(pt);
1130 		for (j = 0; j < entries[i].qwords; j++) {
1131 			u32 j_ = j + entries[i].ofs;
1132 			struct xe_pt *newpte = entries[i].pt_entries[j].pt;
1133 			struct xe_pt *oldpte = NULL;
1134 
1135 			if (xe_pt_entry_staging(pt_dir, j_))
1136 				oldpte = xe_pt_entry_staging(pt_dir, j_);
1137 
1138 			pt_dir->staging[j_] = &newpte->base;
1139 			entries[i].pt_entries[j].pt = oldpte;
1140 		}
1141 	}
1142 }
1143 
1144 static void xe_pt_free_bind(struct xe_vm_pgtable_update *entries,
1145 			    u32 num_entries)
1146 {
1147 	u32 i;
1148 
1149 	for (i = 0; i < num_entries; i++)
1150 		kfree(entries[i].pt_entries);
1151 }
1152 
1153 static int
1154 xe_pt_prepare_bind(struct xe_tile *tile, struct xe_vma *vma,
1155 		   struct xe_svm_range *range,
1156 		   struct xe_vm_pgtable_update *entries,
1157 		   u32 *num_entries, bool invalidate_on_bind)
1158 {
1159 	int err;
1160 
1161 	*num_entries = 0;
1162 	err = xe_pt_stage_bind(tile, vma, range, entries, num_entries,
1163 			       invalidate_on_bind);
1164 	if (!err)
1165 		xe_tile_assert(tile, *num_entries);
1166 
1167 	return err;
1168 }
1169 
1170 static void xe_vm_dbg_print_entries(struct xe_device *xe,
1171 				    const struct xe_vm_pgtable_update *entries,
1172 				    unsigned int num_entries, bool bind)
1173 #if (IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM))
1174 {
1175 	unsigned int i;
1176 
1177 	vm_dbg(&xe->drm, "%s: %u entries to update\n", bind ? "bind" : "unbind",
1178 	       num_entries);
1179 	for (i = 0; i < num_entries; i++) {
1180 		const struct xe_vm_pgtable_update *entry = &entries[i];
1181 		struct xe_pt *xe_pt = entry->pt;
1182 		u64 page_size = 1ull << xe_pt_shift(xe_pt->level);
1183 		u64 end;
1184 		u64 start;
1185 
1186 		xe_assert(xe, !entry->pt->is_compact);
1187 		start = entry->ofs * page_size;
1188 		end = start + page_size * entry->qwords;
1189 		vm_dbg(&xe->drm,
1190 		       "\t%u: Update level %u at (%u + %u) [%llx...%llx) f:%x\n",
1191 		       i, xe_pt->level, entry->ofs, entry->qwords,
1192 		       xe_pt_addr(xe_pt) + start, xe_pt_addr(xe_pt) + end, 0);
1193 	}
1194 }
1195 #else
1196 {}
1197 #endif
1198 
1199 static bool no_in_syncs(struct xe_sync_entry *syncs, u32 num_syncs)
1200 {
1201 	int i;
1202 
1203 	for (i = 0; i < num_syncs; i++) {
1204 		struct dma_fence *fence = syncs[i].fence;
1205 
1206 		if (fence && !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
1207 				       &fence->flags))
1208 			return false;
1209 	}
1210 
1211 	return true;
1212 }
1213 
1214 static int job_test_add_deps(struct xe_sched_job *job,
1215 			     struct dma_resv *resv,
1216 			     enum dma_resv_usage usage)
1217 {
1218 	if (!job) {
1219 		if (!dma_resv_test_signaled(resv, usage))
1220 			return -ETIME;
1221 
1222 		return 0;
1223 	}
1224 
1225 	return xe_sched_job_add_deps(job, resv, usage);
1226 }
1227 
1228 static int vma_add_deps(struct xe_vma *vma, struct xe_sched_job *job)
1229 {
1230 	struct xe_bo *bo = xe_vma_bo(vma);
1231 
1232 	xe_bo_assert_held(bo);
1233 
1234 	if (bo && !bo->vm)
1235 		return job_test_add_deps(job, bo->ttm.base.resv,
1236 					 DMA_RESV_USAGE_KERNEL);
1237 
1238 	return 0;
1239 }
1240 
1241 static int op_add_deps(struct xe_vm *vm, struct xe_vma_op *op,
1242 		       struct xe_sched_job *job)
1243 {
1244 	int err = 0;
1245 
1246 	/*
1247 	 * No need to check for is_cpu_addr_mirror here as vma_add_deps is a
1248 	 * NOP if VMA is_cpu_addr_mirror
1249 	 */
1250 
1251 	switch (op->base.op) {
1252 	case DRM_GPUVA_OP_MAP:
1253 		if (!op->map.immediate && xe_vm_in_fault_mode(vm))
1254 			break;
1255 
1256 		err = vma_add_deps(op->map.vma, job);
1257 		break;
1258 	case DRM_GPUVA_OP_REMAP:
1259 		if (op->remap.prev)
1260 			err = vma_add_deps(op->remap.prev, job);
1261 		if (!err && op->remap.next)
1262 			err = vma_add_deps(op->remap.next, job);
1263 		break;
1264 	case DRM_GPUVA_OP_UNMAP:
1265 		break;
1266 	case DRM_GPUVA_OP_PREFETCH:
1267 		err = vma_add_deps(gpuva_to_vma(op->base.prefetch.va), job);
1268 		break;
1269 	case DRM_GPUVA_OP_DRIVER:
1270 		break;
1271 	default:
1272 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
1273 	}
1274 
1275 	return err;
1276 }
1277 
1278 static int xe_pt_vm_dependencies(struct xe_sched_job *job,
1279 				 struct xe_gt_tlb_inval_job *ijob,
1280 				 struct xe_gt_tlb_inval_job *mjob,
1281 				 struct xe_vm *vm,
1282 				 struct xe_vma_ops *vops,
1283 				 struct xe_vm_pgtable_update_ops *pt_update_ops,
1284 				 struct xe_range_fence_tree *rftree)
1285 {
1286 	struct xe_range_fence *rtfence;
1287 	struct dma_fence *fence;
1288 	struct xe_vma_op *op;
1289 	int err = 0, i;
1290 
1291 	xe_vm_assert_held(vm);
1292 
1293 	if (!job && !no_in_syncs(vops->syncs, vops->num_syncs))
1294 		return -ETIME;
1295 
1296 	if (!job && !xe_exec_queue_is_idle(pt_update_ops->q))
1297 		return -ETIME;
1298 
1299 	if (pt_update_ops->wait_vm_bookkeep || pt_update_ops->wait_vm_kernel) {
1300 		err = job_test_add_deps(job, xe_vm_resv(vm),
1301 					pt_update_ops->wait_vm_bookkeep ?
1302 					DMA_RESV_USAGE_BOOKKEEP :
1303 					DMA_RESV_USAGE_KERNEL);
1304 		if (err)
1305 			return err;
1306 	}
1307 
1308 	rtfence = xe_range_fence_tree_first(rftree, pt_update_ops->start,
1309 					    pt_update_ops->last);
1310 	while (rtfence) {
1311 		fence = rtfence->fence;
1312 
1313 		if (!dma_fence_is_signaled(fence)) {
1314 			/*
1315 			 * Is this a CPU update? GPU is busy updating, so return
1316 			 * an error
1317 			 */
1318 			if (!job)
1319 				return -ETIME;
1320 
1321 			dma_fence_get(fence);
1322 			err = drm_sched_job_add_dependency(&job->drm, fence);
1323 			if (err)
1324 				return err;
1325 		}
1326 
1327 		rtfence = xe_range_fence_tree_next(rtfence,
1328 						   pt_update_ops->start,
1329 						   pt_update_ops->last);
1330 	}
1331 
1332 	list_for_each_entry(op, &vops->list, link) {
1333 		err = op_add_deps(vm, op, job);
1334 		if (err)
1335 			return err;
1336 	}
1337 
1338 	if (!(pt_update_ops->q->flags & EXEC_QUEUE_FLAG_KERNEL)) {
1339 		if (job)
1340 			err = xe_sched_job_last_fence_add_dep(job, vm);
1341 		else
1342 			err = xe_exec_queue_last_fence_test_dep(pt_update_ops->q, vm);
1343 	}
1344 
1345 	for (i = 0; job && !err && i < vops->num_syncs; i++)
1346 		err = xe_sync_entry_add_deps(&vops->syncs[i], job);
1347 
1348 	if (job) {
1349 		if (ijob) {
1350 			err = xe_gt_tlb_inval_job_alloc_dep(ijob);
1351 			if (err)
1352 				return err;
1353 		}
1354 
1355 		if (mjob) {
1356 			err = xe_gt_tlb_inval_job_alloc_dep(mjob);
1357 			if (err)
1358 				return err;
1359 		}
1360 	}
1361 
1362 	return err;
1363 }
1364 
1365 static int xe_pt_pre_commit(struct xe_migrate_pt_update *pt_update)
1366 {
1367 	struct xe_vma_ops *vops = pt_update->vops;
1368 	struct xe_vm *vm = vops->vm;
1369 	struct xe_range_fence_tree *rftree = &vm->rftree[pt_update->tile_id];
1370 	struct xe_vm_pgtable_update_ops *pt_update_ops =
1371 		&vops->pt_update_ops[pt_update->tile_id];
1372 
1373 	return xe_pt_vm_dependencies(pt_update->job, pt_update->ijob,
1374 				     pt_update->mjob, vm, pt_update->vops,
1375 				     pt_update_ops, rftree);
1376 }
1377 
1378 #ifdef CONFIG_DRM_XE_USERPTR_INVAL_INJECT
1379 
1380 static bool xe_pt_userptr_inject_eagain(struct xe_userptr_vma *uvma)
1381 {
1382 	u32 divisor = uvma->userptr.divisor ? uvma->userptr.divisor : 2;
1383 	static u32 count;
1384 
1385 	if (count++ % divisor == divisor - 1) {
1386 		uvma->userptr.divisor = divisor << 1;
1387 		return true;
1388 	}
1389 
1390 	return false;
1391 }
1392 
1393 #else
1394 
1395 static bool xe_pt_userptr_inject_eagain(struct xe_userptr_vma *uvma)
1396 {
1397 	return false;
1398 }
1399 
1400 #endif
1401 
1402 static int vma_check_userptr(struct xe_vm *vm, struct xe_vma *vma,
1403 			     struct xe_vm_pgtable_update_ops *pt_update)
1404 {
1405 	struct xe_userptr_vma *uvma;
1406 	unsigned long notifier_seq;
1407 
1408 	lockdep_assert_held_read(&vm->userptr.notifier_lock);
1409 
1410 	if (!xe_vma_is_userptr(vma))
1411 		return 0;
1412 
1413 	uvma = to_userptr_vma(vma);
1414 	if (xe_pt_userptr_inject_eagain(uvma))
1415 		xe_vma_userptr_force_invalidate(uvma);
1416 
1417 	notifier_seq = uvma->userptr.notifier_seq;
1418 
1419 	if (!mmu_interval_read_retry(&uvma->userptr.notifier,
1420 				     notifier_seq))
1421 		return 0;
1422 
1423 	if (xe_vm_in_fault_mode(vm))
1424 		return -EAGAIN;
1425 
1426 	/*
1427 	 * Just continue the operation since exec or rebind worker
1428 	 * will take care of rebinding.
1429 	 */
1430 	return 0;
1431 }
1432 
1433 static int op_check_userptr(struct xe_vm *vm, struct xe_vma_op *op,
1434 			    struct xe_vm_pgtable_update_ops *pt_update)
1435 {
1436 	int err = 0;
1437 
1438 	lockdep_assert_held_read(&vm->userptr.notifier_lock);
1439 
1440 	switch (op->base.op) {
1441 	case DRM_GPUVA_OP_MAP:
1442 		if (!op->map.immediate && xe_vm_in_fault_mode(vm))
1443 			break;
1444 
1445 		err = vma_check_userptr(vm, op->map.vma, pt_update);
1446 		break;
1447 	case DRM_GPUVA_OP_REMAP:
1448 		if (op->remap.prev)
1449 			err = vma_check_userptr(vm, op->remap.prev, pt_update);
1450 		if (!err && op->remap.next)
1451 			err = vma_check_userptr(vm, op->remap.next, pt_update);
1452 		break;
1453 	case DRM_GPUVA_OP_UNMAP:
1454 		break;
1455 	case DRM_GPUVA_OP_PREFETCH:
1456 		err = vma_check_userptr(vm, gpuva_to_vma(op->base.prefetch.va),
1457 					pt_update);
1458 		break;
1459 	default:
1460 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
1461 	}
1462 
1463 	return err;
1464 }
1465 
1466 static int xe_pt_userptr_pre_commit(struct xe_migrate_pt_update *pt_update)
1467 {
1468 	struct xe_vm *vm = pt_update->vops->vm;
1469 	struct xe_vma_ops *vops = pt_update->vops;
1470 	struct xe_vm_pgtable_update_ops *pt_update_ops =
1471 		&vops->pt_update_ops[pt_update->tile_id];
1472 	struct xe_vma_op *op;
1473 	int err;
1474 
1475 	err = xe_pt_pre_commit(pt_update);
1476 	if (err)
1477 		return err;
1478 
1479 	down_read(&vm->userptr.notifier_lock);
1480 
1481 	list_for_each_entry(op, &vops->list, link) {
1482 		err = op_check_userptr(vm, op, pt_update_ops);
1483 		if (err) {
1484 			up_read(&vm->userptr.notifier_lock);
1485 			break;
1486 		}
1487 	}
1488 
1489 	return err;
1490 }
1491 
1492 #if IS_ENABLED(CONFIG_DRM_XE_GPUSVM)
1493 static int xe_pt_svm_pre_commit(struct xe_migrate_pt_update *pt_update)
1494 {
1495 	struct xe_vm *vm = pt_update->vops->vm;
1496 	struct xe_vma_ops *vops = pt_update->vops;
1497 	struct xe_vma_op *op;
1498 	unsigned long i;
1499 	int err;
1500 
1501 	err = xe_pt_pre_commit(pt_update);
1502 	if (err)
1503 		return err;
1504 
1505 	xe_svm_notifier_lock(vm);
1506 
1507 	list_for_each_entry(op, &vops->list, link) {
1508 		struct xe_svm_range *range = NULL;
1509 
1510 		if (op->subop == XE_VMA_SUBOP_UNMAP_RANGE)
1511 			continue;
1512 
1513 		if (op->base.op == DRM_GPUVA_OP_PREFETCH) {
1514 			xe_assert(vm->xe,
1515 				  xe_vma_is_cpu_addr_mirror(gpuva_to_vma(op->base.prefetch.va)));
1516 			xa_for_each(&op->prefetch_range.range, i, range) {
1517 				xe_svm_range_debug(range, "PRE-COMMIT");
1518 
1519 				if (!xe_svm_range_pages_valid(range)) {
1520 					xe_svm_range_debug(range, "PRE-COMMIT - RETRY");
1521 					xe_svm_notifier_unlock(vm);
1522 					return -ENODATA;
1523 				}
1524 			}
1525 		} else {
1526 			xe_assert(vm->xe, xe_vma_is_cpu_addr_mirror(op->map_range.vma));
1527 			xe_assert(vm->xe, op->subop == XE_VMA_SUBOP_MAP_RANGE);
1528 			range = op->map_range.range;
1529 
1530 			xe_svm_range_debug(range, "PRE-COMMIT");
1531 
1532 			if (!xe_svm_range_pages_valid(range)) {
1533 				xe_svm_range_debug(range, "PRE-COMMIT - RETRY");
1534 				xe_svm_notifier_unlock(vm);
1535 				return -EAGAIN;
1536 			}
1537 		}
1538 	}
1539 
1540 	return 0;
1541 }
1542 #endif
1543 
1544 struct xe_pt_stage_unbind_walk {
1545 	/** @base: The pagewalk base-class. */
1546 	struct xe_pt_walk base;
1547 
1548 	/* Input parameters for the walk */
1549 	/** @tile: The tile we're unbinding from. */
1550 	struct xe_tile *tile;
1551 
1552 	/**
1553 	 * @modified_start: Walk range start, modified to include any
1554 	 * shared pagetables that we're the only user of and can thus
1555 	 * treat as private.
1556 	 */
1557 	u64 modified_start;
1558 	/** @modified_end: Walk range start, modified like @modified_start. */
1559 	u64 modified_end;
1560 
1561 	/* Output */
1562 	/* @wupd: Structure to track the page-table updates we're building */
1563 	struct xe_walk_update wupd;
1564 };
1565 
1566 /*
1567  * Check whether this range is the only one populating this pagetable,
1568  * and in that case, update the walk range checks so that higher levels don't
1569  * view us as a shared pagetable.
1570  */
1571 static bool xe_pt_check_kill(u64 addr, u64 next, unsigned int level,
1572 			     const struct xe_pt *child,
1573 			     enum page_walk_action *action,
1574 			     struct xe_pt_walk *walk)
1575 {
1576 	struct xe_pt_stage_unbind_walk *xe_walk =
1577 		container_of(walk, typeof(*xe_walk), base);
1578 	unsigned int shift = walk->shifts[level];
1579 	u64 size = 1ull << shift;
1580 
1581 	if (IS_ALIGNED(addr, size) && IS_ALIGNED(next, size) &&
1582 	    ((next - addr) >> shift) == child->num_live) {
1583 		u64 size = 1ull << walk->shifts[level + 1];
1584 
1585 		*action = ACTION_CONTINUE;
1586 
1587 		if (xe_walk->modified_start >= addr)
1588 			xe_walk->modified_start = round_down(addr, size);
1589 		if (xe_walk->modified_end <= next)
1590 			xe_walk->modified_end = round_up(next, size);
1591 
1592 		return true;
1593 	}
1594 
1595 	return false;
1596 }
1597 
1598 static int xe_pt_stage_unbind_entry(struct xe_ptw *parent, pgoff_t offset,
1599 				    unsigned int level, u64 addr, u64 next,
1600 				    struct xe_ptw **child,
1601 				    enum page_walk_action *action,
1602 				    struct xe_pt_walk *walk)
1603 {
1604 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
1605 
1606 	XE_WARN_ON(!*child);
1607 	XE_WARN_ON(!level);
1608 
1609 	xe_pt_check_kill(addr, next, level - 1, xe_child, action, walk);
1610 
1611 	return 0;
1612 }
1613 
1614 static int
1615 xe_pt_stage_unbind_post_descend(struct xe_ptw *parent, pgoff_t offset,
1616 				unsigned int level, u64 addr, u64 next,
1617 				struct xe_ptw **child,
1618 				enum page_walk_action *action,
1619 				struct xe_pt_walk *walk)
1620 {
1621 	struct xe_pt_stage_unbind_walk *xe_walk =
1622 		container_of(walk, typeof(*xe_walk), base);
1623 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
1624 	pgoff_t end_offset;
1625 	u64 size = 1ull << walk->shifts[--level];
1626 	int err;
1627 
1628 	if (!IS_ALIGNED(addr, size))
1629 		addr = xe_walk->modified_start;
1630 	if (!IS_ALIGNED(next, size))
1631 		next = xe_walk->modified_end;
1632 
1633 	/* Parent == *child is the root pt. Don't kill it. */
1634 	if (parent != *child &&
1635 	    xe_pt_check_kill(addr, next, level, xe_child, action, walk))
1636 		return 0;
1637 
1638 	if (!xe_pt_nonshared_offsets(addr, next, level, walk, action, &offset,
1639 				     &end_offset))
1640 		return 0;
1641 
1642 	err = xe_pt_new_shared(&xe_walk->wupd, xe_child, offset, true);
1643 	if (err)
1644 		return err;
1645 
1646 	xe_walk->wupd.updates[level].update->qwords = end_offset - offset;
1647 
1648 	return 0;
1649 }
1650 
1651 static const struct xe_pt_walk_ops xe_pt_stage_unbind_ops = {
1652 	.pt_entry = xe_pt_stage_unbind_entry,
1653 	.pt_post_descend = xe_pt_stage_unbind_post_descend,
1654 };
1655 
1656 /**
1657  * xe_pt_stage_unbind() - Build page-table update structures for an unbind
1658  * operation
1659  * @tile: The tile we're unbinding for.
1660  * @vm: The vm
1661  * @vma: The vma we're unbinding.
1662  * @range: The range we're unbinding.
1663  * @entries: Caller-provided storage for the update structures.
1664  *
1665  * Builds page-table update structures for an unbind operation. The function
1666  * will attempt to remove all page-tables that we're the only user
1667  * of, and for that to work, the unbind operation must be committed in the
1668  * same critical section that blocks racing binds to the same page-table tree.
1669  *
1670  * Return: The number of entries used.
1671  */
1672 static unsigned int xe_pt_stage_unbind(struct xe_tile *tile,
1673 				       struct xe_vm *vm,
1674 				       struct xe_vma *vma,
1675 				       struct xe_svm_range *range,
1676 				       struct xe_vm_pgtable_update *entries)
1677 {
1678 	u64 start = range ? range->base.itree.start : xe_vma_start(vma);
1679 	u64 end = range ? range->base.itree.last + 1 : xe_vma_end(vma);
1680 	struct xe_pt_stage_unbind_walk xe_walk = {
1681 		.base = {
1682 			.ops = &xe_pt_stage_unbind_ops,
1683 			.shifts = xe_normal_pt_shifts,
1684 			.max_level = XE_PT_HIGHEST_LEVEL,
1685 			.staging = true,
1686 		},
1687 		.tile = tile,
1688 		.modified_start = start,
1689 		.modified_end = end,
1690 		.wupd.entries = entries,
1691 	};
1692 	struct xe_pt *pt = vm->pt_root[tile->id];
1693 
1694 	(void)xe_pt_walk_shared(&pt->base, pt->level, start, end,
1695 				&xe_walk.base);
1696 
1697 	return xe_walk.wupd.num_used_entries;
1698 }
1699 
1700 static void
1701 xe_migrate_clear_pgtable_callback(struct xe_migrate_pt_update *pt_update,
1702 				  struct xe_tile *tile, struct iosys_map *map,
1703 				  void *ptr, u32 qword_ofs, u32 num_qwords,
1704 				  const struct xe_vm_pgtable_update *update)
1705 {
1706 	struct xe_vm *vm = pt_update->vops->vm;
1707 	u64 empty = __xe_pt_empty_pte(tile, vm, update->pt->level);
1708 	int i;
1709 
1710 	if (map && map->is_iomem)
1711 		for (i = 0; i < num_qwords; ++i)
1712 			xe_map_wr(tile_to_xe(tile), map, (qword_ofs + i) *
1713 				  sizeof(u64), u64, empty);
1714 	else if (map)
1715 		memset64(map->vaddr + qword_ofs * sizeof(u64), empty,
1716 			 num_qwords);
1717 	else
1718 		memset64(ptr, empty, num_qwords);
1719 }
1720 
1721 static void xe_pt_abort_unbind(struct xe_vma *vma,
1722 			       struct xe_vm_pgtable_update *entries,
1723 			       u32 num_entries)
1724 {
1725 	int i, j;
1726 
1727 	xe_pt_commit_prepare_locks_assert(vma);
1728 
1729 	for (i = num_entries - 1; i >= 0; --i) {
1730 		struct xe_vm_pgtable_update *entry = &entries[i];
1731 		struct xe_pt *pt = entry->pt;
1732 		struct xe_pt_dir *pt_dir = as_xe_pt_dir(pt);
1733 
1734 		pt->num_live += entry->qwords;
1735 
1736 		if (!pt->level)
1737 			continue;
1738 
1739 		for (j = entry->ofs; j < entry->ofs + entry->qwords; j++)
1740 			pt_dir->staging[j] =
1741 				entries[i].pt_entries[j - entry->ofs].pt ?
1742 				&entries[i].pt_entries[j - entry->ofs].pt->base : NULL;
1743 	}
1744 }
1745 
1746 static void
1747 xe_pt_commit_prepare_unbind(struct xe_vma *vma,
1748 			    struct xe_vm_pgtable_update *entries,
1749 			    u32 num_entries)
1750 {
1751 	int i, j;
1752 
1753 	xe_pt_commit_prepare_locks_assert(vma);
1754 
1755 	for (i = 0; i < num_entries; ++i) {
1756 		struct xe_vm_pgtable_update *entry = &entries[i];
1757 		struct xe_pt *pt = entry->pt;
1758 		struct xe_pt_dir *pt_dir;
1759 
1760 		pt->num_live -= entry->qwords;
1761 		if (!pt->level)
1762 			continue;
1763 
1764 		pt_dir = as_xe_pt_dir(pt);
1765 		for (j = entry->ofs; j < entry->ofs + entry->qwords; j++) {
1766 			entry->pt_entries[j - entry->ofs].pt =
1767 				xe_pt_entry_staging(pt_dir, j);
1768 			pt_dir->staging[j] = NULL;
1769 		}
1770 	}
1771 }
1772 
1773 static void
1774 xe_pt_update_ops_rfence_interval(struct xe_vm_pgtable_update_ops *pt_update_ops,
1775 				 u64 start, u64 end)
1776 {
1777 	u64 last;
1778 	u32 current_op = pt_update_ops->current_op;
1779 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
1780 	int i, level = 0;
1781 
1782 	for (i = 0; i < pt_op->num_entries; i++) {
1783 		const struct xe_vm_pgtable_update *entry = &pt_op->entries[i];
1784 
1785 		if (entry->pt->level > level)
1786 			level = entry->pt->level;
1787 	}
1788 
1789 	/* Greedy (non-optimal) calculation but simple */
1790 	start = ALIGN_DOWN(start, 0x1ull << xe_pt_shift(level));
1791 	last = ALIGN(end, 0x1ull << xe_pt_shift(level)) - 1;
1792 
1793 	if (start < pt_update_ops->start)
1794 		pt_update_ops->start = start;
1795 	if (last > pt_update_ops->last)
1796 		pt_update_ops->last = last;
1797 }
1798 
1799 static int vma_reserve_fences(struct xe_device *xe, struct xe_vma *vma)
1800 {
1801 	int shift = xe_device_get_root_tile(xe)->media_gt ? 1 : 0;
1802 
1803 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm)
1804 		return dma_resv_reserve_fences(xe_vma_bo(vma)->ttm.base.resv,
1805 					       xe->info.tile_count << shift);
1806 
1807 	return 0;
1808 }
1809 
1810 static int bind_op_prepare(struct xe_vm *vm, struct xe_tile *tile,
1811 			   struct xe_vm_pgtable_update_ops *pt_update_ops,
1812 			   struct xe_vma *vma, bool invalidate_on_bind)
1813 {
1814 	u32 current_op = pt_update_ops->current_op;
1815 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
1816 	int err;
1817 
1818 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
1819 	xe_bo_assert_held(xe_vma_bo(vma));
1820 
1821 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
1822 	       "Preparing bind, with range [%llx...%llx)\n",
1823 	       xe_vma_start(vma), xe_vma_end(vma) - 1);
1824 
1825 	pt_op->vma = NULL;
1826 	pt_op->bind = true;
1827 	pt_op->rebind = BIT(tile->id) & vma->tile_present;
1828 
1829 	err = vma_reserve_fences(tile_to_xe(tile), vma);
1830 	if (err)
1831 		return err;
1832 
1833 	err = xe_pt_prepare_bind(tile, vma, NULL, pt_op->entries,
1834 				 &pt_op->num_entries, invalidate_on_bind);
1835 	if (!err) {
1836 		xe_tile_assert(tile, pt_op->num_entries <=
1837 			       ARRAY_SIZE(pt_op->entries));
1838 		xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
1839 					pt_op->num_entries, true);
1840 
1841 		xe_pt_update_ops_rfence_interval(pt_update_ops,
1842 						 xe_vma_start(vma),
1843 						 xe_vma_end(vma));
1844 		++pt_update_ops->current_op;
1845 		pt_update_ops->needs_userptr_lock |= xe_vma_is_userptr(vma);
1846 
1847 		/*
1848 		 * If rebind, we have to invalidate TLB on !LR vms to invalidate
1849 		 * cached PTEs point to freed memory. On LR vms this is done
1850 		 * automatically when the context is re-enabled by the rebind worker,
1851 		 * or in fault mode it was invalidated on PTE zapping.
1852 		 *
1853 		 * If !rebind, and scratch enabled VMs, there is a chance the scratch
1854 		 * PTE is already cached in the TLB so it needs to be invalidated.
1855 		 * On !LR VMs this is done in the ring ops preceding a batch, but on
1856 		 * LR, in particular on user-space batch buffer chaining, it needs to
1857 		 * be done here.
1858 		 */
1859 		if ((!pt_op->rebind && xe_vm_has_scratch(vm) &&
1860 		     xe_vm_in_lr_mode(vm)))
1861 			pt_update_ops->needs_invalidation = true;
1862 		else if (pt_op->rebind && !xe_vm_in_lr_mode(vm))
1863 			/* We bump also if batch_invalidate_tlb is true */
1864 			vm->tlb_flush_seqno++;
1865 
1866 		vma->tile_staged |= BIT(tile->id);
1867 		pt_op->vma = vma;
1868 		xe_pt_commit_prepare_bind(vma, pt_op->entries,
1869 					  pt_op->num_entries, pt_op->rebind);
1870 	} else {
1871 		xe_pt_cancel_bind(vma, pt_op->entries, pt_op->num_entries);
1872 	}
1873 
1874 	return err;
1875 }
1876 
1877 static int bind_range_prepare(struct xe_vm *vm, struct xe_tile *tile,
1878 			      struct xe_vm_pgtable_update_ops *pt_update_ops,
1879 			      struct xe_vma *vma, struct xe_svm_range *range)
1880 {
1881 	u32 current_op = pt_update_ops->current_op;
1882 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
1883 	int err;
1884 
1885 	xe_tile_assert(tile, xe_vma_is_cpu_addr_mirror(vma));
1886 
1887 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
1888 	       "Preparing bind, with range [%lx...%lx)\n",
1889 	       range->base.itree.start, range->base.itree.last);
1890 
1891 	pt_op->vma = NULL;
1892 	pt_op->bind = true;
1893 	pt_op->rebind = BIT(tile->id) & range->tile_present;
1894 
1895 	err = xe_pt_prepare_bind(tile, vma, range, pt_op->entries,
1896 				 &pt_op->num_entries, false);
1897 	if (!err) {
1898 		xe_tile_assert(tile, pt_op->num_entries <=
1899 			       ARRAY_SIZE(pt_op->entries));
1900 		xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
1901 					pt_op->num_entries, true);
1902 
1903 		xe_pt_update_ops_rfence_interval(pt_update_ops,
1904 						 range->base.itree.start,
1905 						 range->base.itree.last + 1);
1906 		++pt_update_ops->current_op;
1907 		pt_update_ops->needs_svm_lock = true;
1908 
1909 		pt_op->vma = vma;
1910 		xe_pt_commit_prepare_bind(vma, pt_op->entries,
1911 					  pt_op->num_entries, pt_op->rebind);
1912 	} else {
1913 		xe_pt_cancel_bind(vma, pt_op->entries, pt_op->num_entries);
1914 	}
1915 
1916 	return err;
1917 }
1918 
1919 static int unbind_op_prepare(struct xe_tile *tile,
1920 			     struct xe_vm_pgtable_update_ops *pt_update_ops,
1921 			     struct xe_vma *vma)
1922 {
1923 	u32 current_op = pt_update_ops->current_op;
1924 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
1925 	int err;
1926 
1927 	if (!((vma->tile_present | vma->tile_staged) & BIT(tile->id)))
1928 		return 0;
1929 
1930 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
1931 	xe_bo_assert_held(xe_vma_bo(vma));
1932 
1933 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
1934 	       "Preparing unbind, with range [%llx...%llx)\n",
1935 	       xe_vma_start(vma), xe_vma_end(vma) - 1);
1936 
1937 	pt_op->vma = vma;
1938 	pt_op->bind = false;
1939 	pt_op->rebind = false;
1940 
1941 	err = vma_reserve_fences(tile_to_xe(tile), vma);
1942 	if (err)
1943 		return err;
1944 
1945 	pt_op->num_entries = xe_pt_stage_unbind(tile, xe_vma_vm(vma),
1946 						vma, NULL, pt_op->entries);
1947 
1948 	xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
1949 				pt_op->num_entries, false);
1950 	xe_pt_update_ops_rfence_interval(pt_update_ops, xe_vma_start(vma),
1951 					 xe_vma_end(vma));
1952 	++pt_update_ops->current_op;
1953 	pt_update_ops->needs_userptr_lock |= xe_vma_is_userptr(vma);
1954 	pt_update_ops->needs_invalidation = true;
1955 
1956 	xe_pt_commit_prepare_unbind(vma, pt_op->entries, pt_op->num_entries);
1957 
1958 	return 0;
1959 }
1960 
1961 static bool
1962 xe_pt_op_check_range_skip_invalidation(struct xe_vm_pgtable_update_op *pt_op,
1963 				       struct xe_svm_range *range)
1964 {
1965 	struct xe_vm_pgtable_update *update = pt_op->entries;
1966 
1967 	XE_WARN_ON(!pt_op->num_entries);
1968 
1969 	/*
1970 	 * We can't skip the invalidation if we are removing PTEs that span more
1971 	 * than the range, do some checks to ensure we are removing PTEs that
1972 	 * are invalid.
1973 	 */
1974 
1975 	if (pt_op->num_entries > 1)
1976 		return false;
1977 
1978 	if (update->pt->level == 0)
1979 		return true;
1980 
1981 	if (update->pt->level == 1)
1982 		return xe_svm_range_size(range) >= SZ_2M;
1983 
1984 	return false;
1985 }
1986 
1987 static int unbind_range_prepare(struct xe_vm *vm,
1988 				struct xe_tile *tile,
1989 				struct xe_vm_pgtable_update_ops *pt_update_ops,
1990 				struct xe_svm_range *range)
1991 {
1992 	u32 current_op = pt_update_ops->current_op;
1993 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
1994 
1995 	if (!(range->tile_present & BIT(tile->id)))
1996 		return 0;
1997 
1998 	vm_dbg(&vm->xe->drm,
1999 	       "Preparing unbind, with range [%lx...%lx)\n",
2000 	       range->base.itree.start, range->base.itree.last);
2001 
2002 	pt_op->vma = XE_INVALID_VMA;
2003 	pt_op->bind = false;
2004 	pt_op->rebind = false;
2005 
2006 	pt_op->num_entries = xe_pt_stage_unbind(tile, vm, NULL, range,
2007 						pt_op->entries);
2008 
2009 	xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
2010 				pt_op->num_entries, false);
2011 	xe_pt_update_ops_rfence_interval(pt_update_ops, range->base.itree.start,
2012 					 range->base.itree.last + 1);
2013 	++pt_update_ops->current_op;
2014 	pt_update_ops->needs_svm_lock = true;
2015 	pt_update_ops->needs_invalidation |= xe_vm_has_scratch(vm) ||
2016 		xe_vm_has_valid_gpu_mapping(tile, range->tile_present,
2017 					    range->tile_invalidated) ||
2018 		!xe_pt_op_check_range_skip_invalidation(pt_op, range);
2019 
2020 	xe_pt_commit_prepare_unbind(XE_INVALID_VMA, pt_op->entries,
2021 				    pt_op->num_entries);
2022 
2023 	return 0;
2024 }
2025 
2026 static int op_prepare(struct xe_vm *vm,
2027 		      struct xe_tile *tile,
2028 		      struct xe_vm_pgtable_update_ops *pt_update_ops,
2029 		      struct xe_vma_op *op)
2030 {
2031 	int err = 0;
2032 
2033 	xe_vm_assert_held(vm);
2034 
2035 	switch (op->base.op) {
2036 	case DRM_GPUVA_OP_MAP:
2037 		if ((!op->map.immediate && xe_vm_in_fault_mode(vm) &&
2038 		     !op->map.invalidate_on_bind) ||
2039 		    op->map.is_cpu_addr_mirror)
2040 			break;
2041 
2042 		err = bind_op_prepare(vm, tile, pt_update_ops, op->map.vma,
2043 				      op->map.invalidate_on_bind);
2044 		pt_update_ops->wait_vm_kernel = true;
2045 		break;
2046 	case DRM_GPUVA_OP_REMAP:
2047 	{
2048 		struct xe_vma *old = gpuva_to_vma(op->base.remap.unmap->va);
2049 
2050 		if (xe_vma_is_cpu_addr_mirror(old))
2051 			break;
2052 
2053 		err = unbind_op_prepare(tile, pt_update_ops, old);
2054 
2055 		if (!err && op->remap.prev) {
2056 			err = bind_op_prepare(vm, tile, pt_update_ops,
2057 					      op->remap.prev, false);
2058 			pt_update_ops->wait_vm_bookkeep = true;
2059 		}
2060 		if (!err && op->remap.next) {
2061 			err = bind_op_prepare(vm, tile, pt_update_ops,
2062 					      op->remap.next, false);
2063 			pt_update_ops->wait_vm_bookkeep = true;
2064 		}
2065 		break;
2066 	}
2067 	case DRM_GPUVA_OP_UNMAP:
2068 	{
2069 		struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
2070 
2071 		if (xe_vma_is_cpu_addr_mirror(vma))
2072 			break;
2073 
2074 		err = unbind_op_prepare(tile, pt_update_ops, vma);
2075 		break;
2076 	}
2077 	case DRM_GPUVA_OP_PREFETCH:
2078 	{
2079 		struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2080 
2081 		if (xe_vma_is_cpu_addr_mirror(vma)) {
2082 			struct xe_svm_range *range;
2083 			unsigned long i;
2084 
2085 			xa_for_each(&op->prefetch_range.range, i, range) {
2086 				err = bind_range_prepare(vm, tile, pt_update_ops,
2087 							 vma, range);
2088 				if (err)
2089 					return err;
2090 			}
2091 		} else {
2092 			err = bind_op_prepare(vm, tile, pt_update_ops, vma, false);
2093 			pt_update_ops->wait_vm_kernel = true;
2094 		}
2095 		break;
2096 	}
2097 	case DRM_GPUVA_OP_DRIVER:
2098 		if (op->subop == XE_VMA_SUBOP_MAP_RANGE) {
2099 			xe_assert(vm->xe, xe_vma_is_cpu_addr_mirror(op->map_range.vma));
2100 
2101 			err = bind_range_prepare(vm, tile, pt_update_ops,
2102 						 op->map_range.vma,
2103 						 op->map_range.range);
2104 		} else if (op->subop == XE_VMA_SUBOP_UNMAP_RANGE) {
2105 			err = unbind_range_prepare(vm, tile, pt_update_ops,
2106 						   op->unmap_range.range);
2107 		}
2108 		break;
2109 	default:
2110 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2111 	}
2112 
2113 	return err;
2114 }
2115 
2116 static void
2117 xe_pt_update_ops_init(struct xe_vm_pgtable_update_ops *pt_update_ops)
2118 {
2119 	init_llist_head(&pt_update_ops->deferred);
2120 	pt_update_ops->start = ~0x0ull;
2121 	pt_update_ops->last = 0x0ull;
2122 }
2123 
2124 /**
2125  * xe_pt_update_ops_prepare() - Prepare PT update operations
2126  * @tile: Tile of PT update operations
2127  * @vops: VMA operationa
2128  *
2129  * Prepare PT update operations which includes updating internal PT state,
2130  * allocate memory for page tables, populate page table being pruned in, and
2131  * create PT update operations for leaf insertion / removal.
2132  *
2133  * Return: 0 on success, negative error code on error.
2134  */
2135 int xe_pt_update_ops_prepare(struct xe_tile *tile, struct xe_vma_ops *vops)
2136 {
2137 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2138 		&vops->pt_update_ops[tile->id];
2139 	struct xe_vma_op *op;
2140 	int shift = tile->media_gt ? 1 : 0;
2141 	int err;
2142 
2143 	lockdep_assert_held(&vops->vm->lock);
2144 	xe_vm_assert_held(vops->vm);
2145 
2146 	xe_pt_update_ops_init(pt_update_ops);
2147 
2148 	err = dma_resv_reserve_fences(xe_vm_resv(vops->vm),
2149 				      tile_to_xe(tile)->info.tile_count << shift);
2150 	if (err)
2151 		return err;
2152 
2153 	list_for_each_entry(op, &vops->list, link) {
2154 		err = op_prepare(vops->vm, tile, pt_update_ops, op);
2155 
2156 		if (err)
2157 			return err;
2158 	}
2159 
2160 	xe_tile_assert(tile, pt_update_ops->current_op <=
2161 		       pt_update_ops->num_ops);
2162 
2163 #ifdef TEST_VM_OPS_ERROR
2164 	if (vops->inject_error &&
2165 	    vops->vm->xe->vm_inject_error_position == FORCE_OP_ERROR_PREPARE)
2166 		return -ENOSPC;
2167 #endif
2168 
2169 	return 0;
2170 }
2171 ALLOW_ERROR_INJECTION(xe_pt_update_ops_prepare, ERRNO);
2172 
2173 static void bind_op_commit(struct xe_vm *vm, struct xe_tile *tile,
2174 			   struct xe_vm_pgtable_update_ops *pt_update_ops,
2175 			   struct xe_vma *vma, struct dma_fence *fence,
2176 			   struct dma_fence *fence2, bool invalidate_on_bind)
2177 {
2178 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2179 
2180 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm) {
2181 		dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence,
2182 				   pt_update_ops->wait_vm_bookkeep ?
2183 				   DMA_RESV_USAGE_KERNEL :
2184 				   DMA_RESV_USAGE_BOOKKEEP);
2185 		if (fence2)
2186 			dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence2,
2187 					   pt_update_ops->wait_vm_bookkeep ?
2188 					   DMA_RESV_USAGE_KERNEL :
2189 					   DMA_RESV_USAGE_BOOKKEEP);
2190 	}
2191 	/* All WRITE_ONCE pair with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2192 	WRITE_ONCE(vma->tile_present, vma->tile_present | BIT(tile->id));
2193 	if (invalidate_on_bind)
2194 		WRITE_ONCE(vma->tile_invalidated,
2195 			   vma->tile_invalidated | BIT(tile->id));
2196 	else
2197 		WRITE_ONCE(vma->tile_invalidated,
2198 			   vma->tile_invalidated & ~BIT(tile->id));
2199 	vma->tile_staged &= ~BIT(tile->id);
2200 	if (xe_vma_is_userptr(vma)) {
2201 		lockdep_assert_held_read(&vm->userptr.notifier_lock);
2202 		to_userptr_vma(vma)->userptr.initial_bind = true;
2203 	}
2204 
2205 	/*
2206 	 * Kick rebind worker if this bind triggers preempt fences and not in
2207 	 * the rebind worker
2208 	 */
2209 	if (pt_update_ops->wait_vm_bookkeep &&
2210 	    xe_vm_in_preempt_fence_mode(vm) &&
2211 	    !current->mm)
2212 		xe_vm_queue_rebind_worker(vm);
2213 }
2214 
2215 static void unbind_op_commit(struct xe_vm *vm, struct xe_tile *tile,
2216 			     struct xe_vm_pgtable_update_ops *pt_update_ops,
2217 			     struct xe_vma *vma, struct dma_fence *fence,
2218 			     struct dma_fence *fence2)
2219 {
2220 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2221 
2222 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm) {
2223 		dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence,
2224 				   pt_update_ops->wait_vm_bookkeep ?
2225 				   DMA_RESV_USAGE_KERNEL :
2226 				   DMA_RESV_USAGE_BOOKKEEP);
2227 		if (fence2)
2228 			dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence2,
2229 					   pt_update_ops->wait_vm_bookkeep ?
2230 					   DMA_RESV_USAGE_KERNEL :
2231 					   DMA_RESV_USAGE_BOOKKEEP);
2232 	}
2233 	vma->tile_present &= ~BIT(tile->id);
2234 	if (!vma->tile_present) {
2235 		list_del_init(&vma->combined_links.rebind);
2236 		if (xe_vma_is_userptr(vma)) {
2237 			lockdep_assert_held_read(&vm->userptr.notifier_lock);
2238 
2239 			spin_lock(&vm->userptr.invalidated_lock);
2240 			list_del_init(&to_userptr_vma(vma)->userptr.invalidate_link);
2241 			spin_unlock(&vm->userptr.invalidated_lock);
2242 		}
2243 	}
2244 }
2245 
2246 static void range_present_and_invalidated_tile(struct xe_vm *vm,
2247 					       struct xe_svm_range *range,
2248 					       u8 tile_id)
2249 {
2250 	/* All WRITE_ONCE pair with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2251 
2252 	lockdep_assert_held(&vm->svm.gpusvm.notifier_lock);
2253 
2254 	WRITE_ONCE(range->tile_present, range->tile_present | BIT(tile_id));
2255 	WRITE_ONCE(range->tile_invalidated, range->tile_invalidated & ~BIT(tile_id));
2256 }
2257 
2258 static void op_commit(struct xe_vm *vm,
2259 		      struct xe_tile *tile,
2260 		      struct xe_vm_pgtable_update_ops *pt_update_ops,
2261 		      struct xe_vma_op *op, struct dma_fence *fence,
2262 		      struct dma_fence *fence2)
2263 {
2264 	xe_vm_assert_held(vm);
2265 
2266 	switch (op->base.op) {
2267 	case DRM_GPUVA_OP_MAP:
2268 		if ((!op->map.immediate && xe_vm_in_fault_mode(vm)) ||
2269 		    op->map.is_cpu_addr_mirror)
2270 			break;
2271 
2272 		bind_op_commit(vm, tile, pt_update_ops, op->map.vma, fence,
2273 			       fence2, op->map.invalidate_on_bind);
2274 		break;
2275 	case DRM_GPUVA_OP_REMAP:
2276 	{
2277 		struct xe_vma *old = gpuva_to_vma(op->base.remap.unmap->va);
2278 
2279 		if (xe_vma_is_cpu_addr_mirror(old))
2280 			break;
2281 
2282 		unbind_op_commit(vm, tile, pt_update_ops, old, fence, fence2);
2283 
2284 		if (op->remap.prev)
2285 			bind_op_commit(vm, tile, pt_update_ops, op->remap.prev,
2286 				       fence, fence2, false);
2287 		if (op->remap.next)
2288 			bind_op_commit(vm, tile, pt_update_ops, op->remap.next,
2289 				       fence, fence2, false);
2290 		break;
2291 	}
2292 	case DRM_GPUVA_OP_UNMAP:
2293 	{
2294 		struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
2295 
2296 		if (!xe_vma_is_cpu_addr_mirror(vma))
2297 			unbind_op_commit(vm, tile, pt_update_ops, vma, fence,
2298 					 fence2);
2299 		break;
2300 	}
2301 	case DRM_GPUVA_OP_PREFETCH:
2302 	{
2303 		struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2304 
2305 		if (xe_vma_is_cpu_addr_mirror(vma)) {
2306 			struct xe_svm_range *range = NULL;
2307 			unsigned long i;
2308 
2309 			xa_for_each(&op->prefetch_range.range, i, range)
2310 				range_present_and_invalidated_tile(vm, range, tile->id);
2311 		} else {
2312 			bind_op_commit(vm, tile, pt_update_ops, vma, fence,
2313 				       fence2, false);
2314 		}
2315 		break;
2316 	}
2317 	case DRM_GPUVA_OP_DRIVER:
2318 	{
2319 		/* WRITE_ONCE pairs with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2320 		if (op->subop == XE_VMA_SUBOP_MAP_RANGE)
2321 			range_present_and_invalidated_tile(vm, op->map_range.range, tile->id);
2322 		else if (op->subop == XE_VMA_SUBOP_UNMAP_RANGE)
2323 			WRITE_ONCE(op->unmap_range.range->tile_present,
2324 				   op->unmap_range.range->tile_present &
2325 				   ~BIT(tile->id));
2326 
2327 		break;
2328 	}
2329 	default:
2330 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2331 	}
2332 }
2333 
2334 static const struct xe_migrate_pt_update_ops migrate_ops = {
2335 	.populate = xe_vm_populate_pgtable,
2336 	.clear = xe_migrate_clear_pgtable_callback,
2337 	.pre_commit = xe_pt_pre_commit,
2338 };
2339 
2340 static const struct xe_migrate_pt_update_ops userptr_migrate_ops = {
2341 	.populate = xe_vm_populate_pgtable,
2342 	.clear = xe_migrate_clear_pgtable_callback,
2343 	.pre_commit = xe_pt_userptr_pre_commit,
2344 };
2345 
2346 #if IS_ENABLED(CONFIG_DRM_XE_GPUSVM)
2347 static const struct xe_migrate_pt_update_ops svm_migrate_ops = {
2348 	.populate = xe_vm_populate_pgtable,
2349 	.clear = xe_migrate_clear_pgtable_callback,
2350 	.pre_commit = xe_pt_svm_pre_commit,
2351 };
2352 #else
2353 static const struct xe_migrate_pt_update_ops svm_migrate_ops;
2354 #endif
2355 
2356 /**
2357  * xe_pt_update_ops_run() - Run PT update operations
2358  * @tile: Tile of PT update operations
2359  * @vops: VMA operationa
2360  *
2361  * Run PT update operations which includes committing internal PT state changes,
2362  * creating job for PT update operations for leaf insertion / removal, and
2363  * installing job fence in various places.
2364  *
2365  * Return: fence on success, negative ERR_PTR on error.
2366  */
2367 struct dma_fence *
2368 xe_pt_update_ops_run(struct xe_tile *tile, struct xe_vma_ops *vops)
2369 {
2370 	struct xe_vm *vm = vops->vm;
2371 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2372 		&vops->pt_update_ops[tile->id];
2373 	struct dma_fence *fence, *ifence, *mfence;
2374 	struct xe_gt_tlb_inval_job *ijob = NULL, *mjob = NULL;
2375 	struct dma_fence **fences = NULL;
2376 	struct dma_fence_array *cf = NULL;
2377 	struct xe_range_fence *rfence;
2378 	struct xe_vma_op *op;
2379 	int err = 0, i;
2380 	struct xe_migrate_pt_update update = {
2381 		.ops = pt_update_ops->needs_svm_lock ?
2382 			&svm_migrate_ops :
2383 			pt_update_ops->needs_userptr_lock ?
2384 			&userptr_migrate_ops :
2385 			&migrate_ops,
2386 		.vops = vops,
2387 		.tile_id = tile->id,
2388 	};
2389 
2390 	lockdep_assert_held(&vm->lock);
2391 	xe_vm_assert_held(vm);
2392 
2393 	if (!pt_update_ops->current_op) {
2394 		xe_tile_assert(tile, xe_vm_in_fault_mode(vm));
2395 
2396 		return dma_fence_get_stub();
2397 	}
2398 
2399 #ifdef TEST_VM_OPS_ERROR
2400 	if (vops->inject_error &&
2401 	    vm->xe->vm_inject_error_position == FORCE_OP_ERROR_RUN)
2402 		return ERR_PTR(-ENOSPC);
2403 #endif
2404 
2405 	if (pt_update_ops->needs_invalidation) {
2406 		ijob = xe_gt_tlb_inval_job_create(pt_update_ops->q,
2407 						  tile->primary_gt,
2408 						  pt_update_ops->start,
2409 						  pt_update_ops->last,
2410 						  vm->usm.asid);
2411 		if (IS_ERR(ijob)) {
2412 			err = PTR_ERR(ijob);
2413 			goto kill_vm_tile1;
2414 		}
2415 		update.ijob = ijob;
2416 
2417 		if (tile->media_gt) {
2418 			mjob = xe_gt_tlb_inval_job_create(pt_update_ops->q,
2419 							  tile->media_gt,
2420 							  pt_update_ops->start,
2421 							  pt_update_ops->last,
2422 							  vm->usm.asid);
2423 			if (IS_ERR(mjob)) {
2424 				err = PTR_ERR(mjob);
2425 				goto free_ijob;
2426 			}
2427 			update.mjob = mjob;
2428 
2429 			fences = kmalloc_array(2, sizeof(*fences), GFP_KERNEL);
2430 			if (!fences) {
2431 				err = -ENOMEM;
2432 				goto free_ijob;
2433 			}
2434 			cf = dma_fence_array_alloc(2);
2435 			if (!cf) {
2436 				err = -ENOMEM;
2437 				goto free_ijob;
2438 			}
2439 		}
2440 	}
2441 
2442 	rfence = kzalloc(sizeof(*rfence), GFP_KERNEL);
2443 	if (!rfence) {
2444 		err = -ENOMEM;
2445 		goto free_ijob;
2446 	}
2447 
2448 	fence = xe_migrate_update_pgtables(tile->migrate, &update);
2449 	if (IS_ERR(fence)) {
2450 		err = PTR_ERR(fence);
2451 		goto free_rfence;
2452 	}
2453 
2454 	/* Point of no return - VM killed if failure after this */
2455 	for (i = 0; i < pt_update_ops->current_op; ++i) {
2456 		struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[i];
2457 
2458 		xe_pt_commit(pt_op->vma, pt_op->entries,
2459 			     pt_op->num_entries, &pt_update_ops->deferred);
2460 		pt_op->vma = NULL;	/* skip in xe_pt_update_ops_abort */
2461 	}
2462 
2463 	if (xe_range_fence_insert(&vm->rftree[tile->id], rfence,
2464 				  &xe_range_fence_kfree_ops,
2465 				  pt_update_ops->start,
2466 				  pt_update_ops->last, fence))
2467 		dma_fence_wait(fence, false);
2468 
2469 	/* tlb invalidation must be done before signaling unbind/rebind */
2470 	if (ijob) {
2471 		struct dma_fence *__fence;
2472 
2473 		ifence = xe_gt_tlb_inval_job_push(ijob, tile->migrate, fence);
2474 		__fence = ifence;
2475 
2476 		if (mjob) {
2477 			fences[0] = ifence;
2478 			mfence = xe_gt_tlb_inval_job_push(mjob, tile->migrate,
2479 							  fence);
2480 			fences[1] = mfence;
2481 
2482 			dma_fence_array_init(cf, 2, fences,
2483 					     vm->composite_fence_ctx,
2484 					     vm->composite_fence_seqno++,
2485 					     false);
2486 			__fence = &cf->base;
2487 		}
2488 
2489 		dma_fence_put(fence);
2490 		fence = __fence;
2491 	}
2492 
2493 	if (!mjob) {
2494 		dma_resv_add_fence(xe_vm_resv(vm), fence,
2495 				   pt_update_ops->wait_vm_bookkeep ?
2496 				   DMA_RESV_USAGE_KERNEL :
2497 				   DMA_RESV_USAGE_BOOKKEEP);
2498 
2499 		list_for_each_entry(op, &vops->list, link)
2500 			op_commit(vops->vm, tile, pt_update_ops, op, fence, NULL);
2501 	} else {
2502 		dma_resv_add_fence(xe_vm_resv(vm), ifence,
2503 				   pt_update_ops->wait_vm_bookkeep ?
2504 				   DMA_RESV_USAGE_KERNEL :
2505 				   DMA_RESV_USAGE_BOOKKEEP);
2506 
2507 		dma_resv_add_fence(xe_vm_resv(vm), mfence,
2508 				   pt_update_ops->wait_vm_bookkeep ?
2509 				   DMA_RESV_USAGE_KERNEL :
2510 				   DMA_RESV_USAGE_BOOKKEEP);
2511 
2512 		list_for_each_entry(op, &vops->list, link)
2513 			op_commit(vops->vm, tile, pt_update_ops, op, ifence,
2514 				  mfence);
2515 	}
2516 
2517 	if (pt_update_ops->needs_svm_lock)
2518 		xe_svm_notifier_unlock(vm);
2519 	if (pt_update_ops->needs_userptr_lock)
2520 		up_read(&vm->userptr.notifier_lock);
2521 
2522 	xe_gt_tlb_inval_job_put(mjob);
2523 	xe_gt_tlb_inval_job_put(ijob);
2524 
2525 	return fence;
2526 
2527 free_rfence:
2528 	kfree(rfence);
2529 free_ijob:
2530 	kfree(cf);
2531 	kfree(fences);
2532 	xe_gt_tlb_inval_job_put(mjob);
2533 	xe_gt_tlb_inval_job_put(ijob);
2534 kill_vm_tile1:
2535 	if (err != -EAGAIN && err != -ENODATA && tile->id)
2536 		xe_vm_kill(vops->vm, false);
2537 
2538 	return ERR_PTR(err);
2539 }
2540 ALLOW_ERROR_INJECTION(xe_pt_update_ops_run, ERRNO);
2541 
2542 /**
2543  * xe_pt_update_ops_fini() - Finish PT update operations
2544  * @tile: Tile of PT update operations
2545  * @vops: VMA operations
2546  *
2547  * Finish PT update operations by committing to destroy page table memory
2548  */
2549 void xe_pt_update_ops_fini(struct xe_tile *tile, struct xe_vma_ops *vops)
2550 {
2551 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2552 		&vops->pt_update_ops[tile->id];
2553 	int i;
2554 
2555 	lockdep_assert_held(&vops->vm->lock);
2556 	xe_vm_assert_held(vops->vm);
2557 
2558 	for (i = 0; i < pt_update_ops->current_op; ++i) {
2559 		struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[i];
2560 
2561 		xe_pt_free_bind(pt_op->entries, pt_op->num_entries);
2562 	}
2563 	xe_bo_put_commit(&vops->pt_update_ops[tile->id].deferred);
2564 }
2565 
2566 /**
2567  * xe_pt_update_ops_abort() - Abort PT update operations
2568  * @tile: Tile of PT update operations
2569  * @vops: VMA operationa
2570  *
2571  *  Abort PT update operations by unwinding internal PT state
2572  */
2573 void xe_pt_update_ops_abort(struct xe_tile *tile, struct xe_vma_ops *vops)
2574 {
2575 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2576 		&vops->pt_update_ops[tile->id];
2577 	int i;
2578 
2579 	lockdep_assert_held(&vops->vm->lock);
2580 	xe_vm_assert_held(vops->vm);
2581 
2582 	for (i = pt_update_ops->num_ops - 1; i >= 0; --i) {
2583 		struct xe_vm_pgtable_update_op *pt_op =
2584 			&pt_update_ops->ops[i];
2585 
2586 		if (!pt_op->vma || i >= pt_update_ops->current_op)
2587 			continue;
2588 
2589 		if (pt_op->bind)
2590 			xe_pt_abort_bind(pt_op->vma, pt_op->entries,
2591 					 pt_op->num_entries,
2592 					 pt_op->rebind);
2593 		else
2594 			xe_pt_abort_unbind(pt_op->vma, pt_op->entries,
2595 					   pt_op->num_entries);
2596 	}
2597 
2598 	xe_pt_update_ops_fini(tile, vops);
2599 }
2600