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