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