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