xref: /linux/drivers/gpu/drm/xe/xe_pt.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
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 	/* null VMA's and purged BO's do not have dma addresses */
447 	if (xe_vma_is_null(xe_walk->vma) || (bo && xe_bo_is_purged(bo)))
448 		return true;
449 
450 	/* if we are clearing page table, no dma addresses*/
451 	if (xe_walk->clear_pt)
452 		return true;
453 
454 	/* Does the DMA segment cover the whole pte? */
455 	if (next - xe_walk->va_curs_start > xe_walk->curs->size)
456 		return false;
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 		xe_assert(xe, !range);
780 		curs.size = xe_vma_size(vma);
781 		goto walk_pt;
782 	}
783 
784 	if (vma->gpuva.flags & XE_VMA_ATOMIC_PTE_BIT) {
785 		xe_walk.default_vram_pte = xe_atomic_for_vram(vm, vma) ? XE_USM_PPGTT_PTE_AE : 0;
786 		xe_walk.default_system_pte = xe_atomic_for_system(vm, vma) ?
787 			XE_USM_PPGTT_PTE_AE : 0;
788 	}
789 
790 	xe_walk.default_vram_pte |= XE_PPGTT_PTE_DM;
791 	xe_walk.dma_offset = (bo && !is_purged) ? vram_region_gpu_offset(bo->ttm.resource) : 0;
792 	if (!range)
793 		xe_bo_assert_held(bo);
794 
795 	if (!xe_vma_is_null(vma) && !range && !is_purged) {
796 		if (xe_vma_is_userptr(vma))
797 			xe_res_first_dma(to_userptr_vma(vma)->userptr.pages.dma_addr, 0,
798 					 xe_vma_size(vma), &curs);
799 		else if (xe_bo_is_vram(bo) || xe_bo_is_stolen(bo))
800 			xe_res_first(bo->ttm.resource, xe_vma_bo_offset(vma),
801 				     xe_vma_size(vma), &curs);
802 		else
803 			xe_res_first_sg(xe_bo_sg(bo), xe_vma_bo_offset(vma),
804 					xe_vma_size(vma), &curs);
805 	} else if (!range) {
806 		curs.size = xe_vma_size(vma);
807 	}
808 
809 walk_pt:
810 	ret = xe_pt_walk_range(&pt->base, pt->level,
811 			       range ? xe_svm_range_start(range) : xe_vma_start(vma),
812 			       range ? xe_svm_range_end(range) : xe_vma_end(vma),
813 			       &xe_walk.base);
814 
815 	*num_entries = xe_walk.wupd.num_used_entries;
816 	return ret;
817 }
818 
819 /**
820  * xe_pt_nonshared_offsets() - Determine the non-shared entry offsets of a
821  * shared pagetable.
822  * @addr: The start address within the non-shared pagetable.
823  * @end: The end address within the non-shared pagetable.
824  * @level: The level of the non-shared pagetable.
825  * @walk: Walk info. The function adjusts the walk action.
826  * @action: next action to perform (see enum page_walk_action)
827  * @offset: Ignored on input, First non-shared entry on output.
828  * @end_offset: Ignored on input, Last non-shared entry + 1 on output.
829  *
830  * A non-shared page-table has some entries that belong to the address range
831  * and others that don't. This function determines the entries that belong
832  * fully to the address range. Depending on level, some entries may
833  * partially belong to the address range (that can't happen at level 0).
834  * The function detects that and adjust those offsets to not include those
835  * partial entries. Iff it does detect partial entries, we know that there must
836  * be shared page tables also at lower levels, so it adjusts the walk action
837  * accordingly.
838  *
839  * Return: true if there were non-shared entries, false otherwise.
840  */
841 static bool xe_pt_nonshared_offsets(u64 addr, u64 end, unsigned int level,
842 				    struct xe_pt_walk *walk,
843 				    enum page_walk_action *action,
844 				    pgoff_t *offset, pgoff_t *end_offset)
845 {
846 	u64 size = 1ull << walk->shifts[level];
847 
848 	*offset = xe_pt_offset(addr, level, walk);
849 	*end_offset = xe_pt_num_entries(addr, end, level, walk) + *offset;
850 
851 	if (!level)
852 		return true;
853 
854 	/*
855 	 * If addr or next are not size aligned, there are shared pts at lower
856 	 * level, so in that case traverse down the subtree
857 	 */
858 	*action = ACTION_CONTINUE;
859 	if (!IS_ALIGNED(addr, size)) {
860 		*action = ACTION_SUBTREE;
861 		(*offset)++;
862 	}
863 
864 	if (!IS_ALIGNED(end, size)) {
865 		*action = ACTION_SUBTREE;
866 		(*end_offset)--;
867 	}
868 
869 	return *end_offset > *offset;
870 }
871 
872 struct xe_pt_zap_ptes_walk {
873 	/** @base: The walk base-class */
874 	struct xe_pt_walk base;
875 
876 	/* Input parameters for the walk */
877 	/** @tile: The tile we're building for */
878 	struct xe_tile *tile;
879 
880 	/* Output */
881 	/** @needs_invalidate: Whether we need to invalidate TLB*/
882 	bool needs_invalidate;
883 };
884 
885 static int xe_pt_zap_ptes_entry(struct xe_ptw *parent, pgoff_t offset,
886 				unsigned int level, u64 addr, u64 next,
887 				struct xe_ptw **child,
888 				enum page_walk_action *action,
889 				struct xe_pt_walk *walk)
890 {
891 	struct xe_pt_zap_ptes_walk *xe_walk =
892 		container_of(walk, typeof(*xe_walk), base);
893 	struct xe_pt *xe_child;
894 	pgoff_t end_offset;
895 
896 	XE_WARN_ON(!level);
897 
898 	/*
899 	 * Below would be unexpected behavior that needs to be root caused
900 	 * but better warn and bail than crash the driver.
901 	 */
902 	if (XE_WARN_ON(!*child))
903 		return 0;
904 
905 	xe_child = container_of(*child, typeof(*xe_child), base);
906 
907 	/*
908 	 * Note that we're called from an entry callback, and we're dealing
909 	 * with the child of that entry rather than the parent, so need to
910 	 * adjust level down.
911 	 */
912 	if (xe_pt_nonshared_offsets(addr, next, --level, walk, action, &offset,
913 				    &end_offset)) {
914 		xe_map_memset(tile_to_xe(xe_walk->tile), &xe_child->bo->vmap,
915 			      offset * sizeof(u64), 0,
916 			      (end_offset - offset) * sizeof(u64));
917 		xe_walk->needs_invalidate = true;
918 	}
919 
920 	return 0;
921 }
922 
923 static const struct xe_pt_walk_ops xe_pt_zap_ptes_ops = {
924 	.pt_entry = xe_pt_zap_ptes_entry,
925 };
926 
927 /**
928  * xe_pt_zap_ptes() - Zap (zero) gpu ptes of an address range
929  * @tile: The tile we're zapping for.
930  * @vma: GPU VMA detailing address range.
931  *
932  * Eviction and Userptr invalidation needs to be able to zap the
933  * gpu ptes of a given address range in pagefaulting mode.
934  * In order to be able to do that, that function needs access to the shared
935  * page-table entrieaso it can either clear the leaf PTEs or
936  * clear the pointers to lower-level page-tables. The caller is required
937  * to hold the necessary locks to ensure neither the page-table connectivity
938  * nor the page-table entries of the range is updated from under us.
939  *
940  * Return: Whether ptes were actually updated and a TLB invalidation is
941  * required.
942  */
943 bool xe_pt_zap_ptes(struct xe_tile *tile, struct xe_vma *vma)
944 {
945 	struct xe_pt_zap_ptes_walk xe_walk = {
946 		.base = {
947 			.ops = &xe_pt_zap_ptes_ops,
948 			.shifts = xe_normal_pt_shifts,
949 			.max_level = XE_PT_HIGHEST_LEVEL,
950 		},
951 		.tile = tile,
952 	};
953 	struct xe_pt *pt = xe_vma_vm(vma)->pt_root[tile->id];
954 	u8 pt_mask = (vma->tile_present & ~vma->tile_invalidated);
955 
956 	if (xe_vma_bo(vma))
957 		xe_bo_assert_held(xe_vma_bo(vma));
958 	else if (xe_vma_is_userptr(vma))
959 		lockdep_assert_held(&xe_vma_vm(vma)->svm.gpusvm.notifier_lock);
960 
961 	if (!(pt_mask & BIT(tile->id)))
962 		return false;
963 
964 	(void)xe_pt_walk_shared(&pt->base, pt->level, xe_vma_start(vma),
965 				xe_vma_end(vma), &xe_walk.base);
966 
967 	return xe_walk.needs_invalidate;
968 }
969 
970 /**
971  * xe_pt_zap_ptes_range() - Zap (zero) gpu ptes of a SVM range
972  * @tile: The tile we're zapping for.
973  * @vm: The VM we're zapping for.
974  * @range: The SVM range we're zapping for.
975  *
976  * SVM invalidation needs to be able to zap the gpu ptes of a given address
977  * range. In order to be able to do that, that function needs access to the
978  * shared page-table entries so it can either clear the leaf PTEs or
979  * clear the pointers to lower-level page-tables. The caller is required
980  * to hold the SVM notifier lock.
981  *
982  * Return: Whether ptes were actually updated and a TLB invalidation is
983  * required.
984  */
985 bool xe_pt_zap_ptes_range(struct xe_tile *tile, struct xe_vm *vm,
986 			  struct xe_svm_range *range)
987 {
988 	struct xe_pt_zap_ptes_walk xe_walk = {
989 		.base = {
990 			.ops = &xe_pt_zap_ptes_ops,
991 			.shifts = xe_normal_pt_shifts,
992 			.max_level = XE_PT_HIGHEST_LEVEL,
993 		},
994 		.tile = tile,
995 	};
996 	struct xe_pt *pt = vm->pt_root[tile->id];
997 	u8 pt_mask = (range->tile_present & ~range->tile_invalidated);
998 
999 	/*
1000 	 * Locking rules:
1001 	 *
1002 	 * - notifier_lock (write): full protection against page table changes
1003 	 *   and MMU notifier invalidations.
1004 	 *
1005 	 * - notifier_lock (read) + vm_lock (write): combined protection against
1006 	 *   invalidations and concurrent page table modifications. (e.g., madvise)
1007 	 *
1008 	 */
1009 	lockdep_assert(lockdep_is_held_type(&vm->svm.gpusvm.notifier_lock, 0) ||
1010 		       (lockdep_is_held_type(&vm->svm.gpusvm.notifier_lock, 1) &&
1011 		       lockdep_is_held_type(&vm->lock, 0)));
1012 
1013 	if (!(pt_mask & BIT(tile->id)))
1014 		return false;
1015 
1016 	(void)xe_pt_walk_shared(&pt->base, pt->level, xe_svm_range_start(range),
1017 				xe_svm_range_end(range), &xe_walk.base);
1018 
1019 	return xe_walk.needs_invalidate;
1020 }
1021 
1022 static void
1023 xe_vm_populate_pgtable(struct xe_migrate_pt_update *pt_update, struct xe_tile *tile,
1024 		       struct iosys_map *map, void *data,
1025 		       u32 qword_ofs, u32 num_qwords,
1026 		       const struct xe_vm_pgtable_update *update)
1027 {
1028 	struct xe_pt_entry *ptes = update->pt_entries;
1029 	u64 *ptr = data;
1030 	u32 i;
1031 
1032 	/*
1033 	 * @qword_ofs is the absolute entry offset within the page table, while
1034 	 * @ptes is indexed relative to @update->ofs (its first entry). The GPU
1035 	 * path (write_pgtable) splits a single update into MAX_PTE_PER_SDI-sized
1036 	 * chunks, calling this with an advancing @qword_ofs but a fresh @data
1037 	 * pointer per chunk, so translate back into a @ptes index rather than
1038 	 * assuming the chunk starts at ptes[0].
1039 	 */
1040 	for (i = 0; i < num_qwords; i++) {
1041 		u32 idx = qword_ofs - update->ofs + i;
1042 
1043 		if (map)
1044 			xe_map_wr(tile_to_xe(tile), map, (qword_ofs + i) *
1045 				  sizeof(u64), u64, ptes[idx].pte);
1046 		else
1047 			ptr[i] = ptes[idx].pte;
1048 	}
1049 }
1050 
1051 static void xe_pt_cancel_bind(struct xe_vma *vma,
1052 			      struct xe_vm_pgtable_update *entries,
1053 			      u32 num_entries)
1054 {
1055 	u32 i, j;
1056 
1057 	for (i = 0; i < num_entries; i++) {
1058 		struct xe_pt *pt = entries[i].pt;
1059 
1060 		if (!pt)
1061 			continue;
1062 
1063 		if (pt->level) {
1064 			for (j = 0; j < entries[i].qwords; j++)
1065 				xe_pt_destroy(entries[i].pt_entries[j].pt,
1066 					      xe_vma_vm(vma)->flags, NULL);
1067 		}
1068 
1069 		kfree(entries[i].pt_entries);
1070 		entries[i].pt_entries = NULL;
1071 		entries[i].qwords = 0;
1072 	}
1073 }
1074 
1075 #define XE_INVALID_VMA	((struct xe_vma *)(0xdeaddeadull))
1076 
1077 static void xe_pt_commit_prepare_locks_assert(struct xe_vma *vma)
1078 {
1079 	struct xe_vm *vm;
1080 
1081 	if (vma == XE_INVALID_VMA)
1082 		return;
1083 
1084 	vm = xe_vma_vm(vma);
1085 	lockdep_assert_held(&vm->lock);
1086 
1087 	if (!xe_vma_has_no_bo(vma))
1088 		dma_resv_assert_held(xe_vma_bo(vma)->ttm.base.resv);
1089 
1090 	xe_vm_assert_held(vm);
1091 }
1092 
1093 static void xe_pt_commit_locks_assert(struct xe_vma *vma)
1094 {
1095 	struct xe_vm *vm;
1096 
1097 	if (vma == XE_INVALID_VMA)
1098 		return;
1099 
1100 	vm = xe_vma_vm(vma);
1101 	xe_pt_commit_prepare_locks_assert(vma);
1102 
1103 	if (xe_vma_is_userptr(vma))
1104 		xe_svm_assert_held_read_or_inject_write(vm);
1105 }
1106 
1107 static void xe_pt_commit(struct xe_vma *vma,
1108 			 struct xe_vm_pgtable_update *entries,
1109 			 u32 num_entries, struct llist_head *deferred)
1110 {
1111 	u32 i, j;
1112 
1113 	xe_pt_commit_locks_assert(vma);
1114 
1115 	for (i = 0; i < num_entries; i++) {
1116 		struct xe_pt *pt = entries[i].pt;
1117 		struct xe_pt_dir *pt_dir;
1118 
1119 		if (!pt->level)
1120 			continue;
1121 
1122 		pt_dir = as_xe_pt_dir(pt);
1123 		for (j = 0; j < entries[i].qwords; j++) {
1124 			struct xe_pt *oldpte = entries[i].pt_entries[j].pt;
1125 			int j_ = j + entries[i].ofs;
1126 
1127 			pt_dir->children[j_] = pt_dir->staging[j_];
1128 			xe_pt_destroy(oldpte, (vma == XE_INVALID_VMA) ? 0 :
1129 				      xe_vma_vm(vma)->flags, deferred);
1130 		}
1131 	}
1132 }
1133 
1134 static void xe_pt_abort_bind(struct xe_vma *vma,
1135 			     struct xe_vm_pgtable_update *entries,
1136 			     u32 num_entries, bool rebind)
1137 {
1138 	int i, j;
1139 
1140 	xe_pt_commit_prepare_locks_assert(vma);
1141 
1142 	for (i = num_entries - 1; i >= 0; --i) {
1143 		struct xe_pt *pt = entries[i].pt;
1144 		struct xe_pt_dir *pt_dir;
1145 
1146 		if (!rebind)
1147 			pt->num_live -= entries[i].qwords;
1148 
1149 		if (!pt->level)
1150 			continue;
1151 
1152 		pt_dir = as_xe_pt_dir(pt);
1153 		for (j = 0; j < entries[i].qwords; j++) {
1154 			u32 j_ = j + entries[i].ofs;
1155 			struct xe_pt *newpte = xe_pt_entry_staging(pt_dir, j_);
1156 			struct xe_pt *oldpte = entries[i].pt_entries[j].pt;
1157 
1158 			pt_dir->staging[j_] = oldpte ? &oldpte->base : 0;
1159 			xe_pt_destroy(newpte, xe_vma_vm(vma)->flags, NULL);
1160 		}
1161 	}
1162 }
1163 
1164 static void xe_pt_commit_prepare_bind(struct xe_vma *vma,
1165 				      struct xe_vm_pgtable_update *entries,
1166 				      u32 num_entries, bool rebind)
1167 {
1168 	u32 i, j;
1169 
1170 	xe_pt_commit_prepare_locks_assert(vma);
1171 
1172 	for (i = 0; i < num_entries; i++) {
1173 		struct xe_pt *pt = entries[i].pt;
1174 		struct xe_pt_dir *pt_dir;
1175 
1176 		if (!rebind)
1177 			pt->num_live += entries[i].qwords;
1178 
1179 		if (!pt->level)
1180 			continue;
1181 
1182 		pt_dir = as_xe_pt_dir(pt);
1183 		for (j = 0; j < entries[i].qwords; j++) {
1184 			u32 j_ = j + entries[i].ofs;
1185 			struct xe_pt *newpte = entries[i].pt_entries[j].pt;
1186 			struct xe_pt *oldpte = NULL;
1187 
1188 			if (xe_pt_entry_staging(pt_dir, j_))
1189 				oldpte = xe_pt_entry_staging(pt_dir, j_);
1190 
1191 			pt_dir->staging[j_] = &newpte->base;
1192 			entries[i].pt_entries[j].pt = oldpte;
1193 		}
1194 	}
1195 }
1196 
1197 static void xe_pt_free_bind(struct xe_vm_pgtable_update *entries,
1198 			    u32 num_entries)
1199 {
1200 	u32 i;
1201 
1202 	for (i = 0; i < num_entries; i++)
1203 		kfree(entries[i].pt_entries);
1204 }
1205 
1206 static int
1207 xe_pt_prepare_bind(struct xe_tile *tile, struct xe_vma *vma,
1208 		   struct xe_svm_range *range,
1209 		   struct xe_vm_pgtable_update *entries,
1210 		   u32 *num_entries, bool invalidate_on_bind)
1211 {
1212 	int err;
1213 
1214 	*num_entries = 0;
1215 	err = xe_pt_stage_bind(tile, vma, range, entries, num_entries,
1216 			       invalidate_on_bind);
1217 	if (!err)
1218 		xe_tile_assert(tile, *num_entries);
1219 
1220 	return err;
1221 }
1222 
1223 static void xe_vm_dbg_print_entries(struct xe_device *xe,
1224 				    const struct xe_vm_pgtable_update *entries,
1225 				    unsigned int num_entries, bool bind)
1226 #if (IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM))
1227 {
1228 	unsigned int i;
1229 
1230 	vm_dbg(&xe->drm, "%s: %u entries to update\n", bind ? "bind" : "unbind",
1231 	       num_entries);
1232 	for (i = 0; i < num_entries; i++) {
1233 		const struct xe_vm_pgtable_update *entry = &entries[i];
1234 		struct xe_pt *xe_pt = entry->pt;
1235 		u64 page_size = 1ull << xe_pt_shift(xe_pt->level);
1236 		u64 end;
1237 		u64 start;
1238 
1239 		xe_assert(xe, !entry->pt->is_compact);
1240 		start = entry->ofs * page_size;
1241 		end = start + page_size * entry->qwords;
1242 		vm_dbg(&xe->drm,
1243 		       "\t%u: Update level %u at (%u + %u) [%llx...%llx) f:%x\n",
1244 		       i, xe_pt->level, entry->ofs, entry->qwords,
1245 		       xe_pt_addr(xe_pt) + start, xe_pt_addr(xe_pt) + end, 0);
1246 	}
1247 }
1248 #else
1249 {}
1250 #endif
1251 
1252 static bool no_in_syncs(struct xe_sync_entry *syncs, u32 num_syncs)
1253 {
1254 	int i;
1255 
1256 	for (i = 0; i < num_syncs; i++) {
1257 		struct dma_fence *fence = syncs[i].fence;
1258 
1259 		if (fence && !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
1260 				       &fence->flags))
1261 			return false;
1262 	}
1263 
1264 	return true;
1265 }
1266 
1267 static int job_test_add_deps(struct xe_sched_job *job,
1268 			     struct dma_resv *resv,
1269 			     enum dma_resv_usage usage)
1270 {
1271 	if (!job) {
1272 		if (!dma_resv_test_signaled(resv, usage))
1273 			return -ETIME;
1274 
1275 		return 0;
1276 	}
1277 
1278 	return xe_sched_job_add_deps(job, resv, usage);
1279 }
1280 
1281 static int vma_add_deps(struct xe_vma *vma, struct xe_sched_job *job)
1282 {
1283 	struct xe_bo *bo = xe_vma_bo(vma);
1284 
1285 	xe_bo_assert_held(bo);
1286 
1287 	if (bo && !bo->vm)
1288 		return job_test_add_deps(job, bo->ttm.base.resv,
1289 					 DMA_RESV_USAGE_KERNEL);
1290 
1291 	return 0;
1292 }
1293 
1294 static int op_add_deps(struct xe_vm *vm, struct xe_vma_op *op,
1295 		       struct xe_sched_job *job)
1296 {
1297 	int err = 0;
1298 
1299 	/*
1300 	 * No need to check for is_cpu_addr_mirror here as vma_add_deps is a
1301 	 * NOP if VMA is_cpu_addr_mirror
1302 	 */
1303 
1304 	switch (op->base.op) {
1305 	case DRM_GPUVA_OP_MAP:
1306 		if (!op->map.immediate && xe_vm_in_fault_mode(vm))
1307 			break;
1308 
1309 		err = vma_add_deps(op->map.vma, job);
1310 		break;
1311 	case DRM_GPUVA_OP_REMAP:
1312 		if (op->remap.prev)
1313 			err = vma_add_deps(op->remap.prev, job);
1314 		if (!err && op->remap.next)
1315 			err = vma_add_deps(op->remap.next, job);
1316 		break;
1317 	case DRM_GPUVA_OP_UNMAP:
1318 		break;
1319 	case DRM_GPUVA_OP_PREFETCH:
1320 		err = vma_add_deps(gpuva_to_vma(op->base.prefetch.va), job);
1321 		break;
1322 	case DRM_GPUVA_OP_DRIVER:
1323 		break;
1324 	default:
1325 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
1326 	}
1327 
1328 	return err;
1329 }
1330 
1331 static int xe_pt_vm_dependencies(struct xe_sched_job *job,
1332 				 struct xe_tlb_inval_job *ijob,
1333 				 struct xe_tlb_inval_job *mjob,
1334 				 struct xe_vm *vm,
1335 				 struct xe_vma_ops *vops,
1336 				 struct xe_vm_pgtable_update_ops *pt_update_ops,
1337 				 struct xe_range_fence_tree *rftree)
1338 {
1339 	struct xe_range_fence *rtfence;
1340 	struct dma_fence *fence;
1341 	struct xe_vma_op *op;
1342 	int err = 0, i;
1343 
1344 	xe_vm_assert_held(vm);
1345 
1346 	if (!job && !no_in_syncs(vops->syncs, vops->num_syncs))
1347 		return -ETIME;
1348 
1349 	if (!job && !xe_exec_queue_is_idle(pt_update_ops->q))
1350 		return -ETIME;
1351 
1352 	if (pt_update_ops->wait_vm_bookkeep || pt_update_ops->wait_vm_kernel) {
1353 		err = job_test_add_deps(job, xe_vm_resv(vm),
1354 					pt_update_ops->wait_vm_bookkeep ?
1355 					DMA_RESV_USAGE_BOOKKEEP :
1356 					DMA_RESV_USAGE_KERNEL);
1357 		if (err)
1358 			return err;
1359 	}
1360 
1361 	rtfence = xe_range_fence_tree_first(rftree, pt_update_ops->start,
1362 					    pt_update_ops->last);
1363 	while (rtfence) {
1364 		fence = rtfence->fence;
1365 
1366 		if (!dma_fence_is_signaled(fence)) {
1367 			/*
1368 			 * Is this a CPU update? GPU is busy updating, so return
1369 			 * an error
1370 			 */
1371 			if (!job)
1372 				return -ETIME;
1373 
1374 			dma_fence_get(fence);
1375 			err = drm_sched_job_add_dependency(&job->drm, fence);
1376 			if (err)
1377 				return err;
1378 		}
1379 
1380 		rtfence = xe_range_fence_tree_next(rtfence,
1381 						   pt_update_ops->start,
1382 						   pt_update_ops->last);
1383 	}
1384 
1385 	list_for_each_entry(op, &vops->list, link) {
1386 		err = op_add_deps(vm, op, job);
1387 		if (err)
1388 			return err;
1389 	}
1390 
1391 	for (i = 0; job && !err && i < vops->num_syncs; i++)
1392 		err = xe_sync_entry_add_deps(&vops->syncs[i], job);
1393 
1394 	if (job) {
1395 		if (ijob) {
1396 			err = xe_tlb_inval_job_alloc_dep(ijob);
1397 			if (err)
1398 				return err;
1399 		}
1400 
1401 		if (mjob) {
1402 			err = xe_tlb_inval_job_alloc_dep(mjob);
1403 			if (err)
1404 				return err;
1405 		}
1406 	}
1407 
1408 	return err;
1409 }
1410 
1411 static int xe_pt_pre_commit(struct xe_migrate_pt_update *pt_update)
1412 {
1413 	struct xe_vma_ops *vops = pt_update->vops;
1414 	struct xe_vm *vm = vops->vm;
1415 	struct xe_range_fence_tree *rftree = &vm->rftree[pt_update->tile_id];
1416 	struct xe_vm_pgtable_update_ops *pt_update_ops =
1417 		&vops->pt_update_ops[pt_update->tile_id];
1418 
1419 	return xe_pt_vm_dependencies(pt_update->job, pt_update->ijob,
1420 				     pt_update->mjob, vm, pt_update->vops,
1421 				     pt_update_ops, rftree);
1422 }
1423 
1424 #if IS_ENABLED(CONFIG_DRM_GPUSVM)
1425 /*
1426  * Acquire/release the svm notifier_lock around xe_pt_svm_userptr_pre_commit()
1427  * and the matching late release in xe_pt_update_ops_run(). Read mode by
1428  * default; write mode when CONFIG_DRM_XE_USERPTR_INVAL_INJECT is on,
1429  * because a userptr op in this critical section may invoke the injected
1430  * xe_vma_userptr_force_invalidate() path that calls
1431  * drm_gpusvm_unmap_pages() with ctx->in_notifier=true, which requires the
1432  * lock held for write.
1433  */
1434 static void xe_pt_svm_userptr_notifier_lock(struct xe_vm *vm)
1435 {
1436 #if IS_ENABLED(CONFIG_DRM_XE_USERPTR_INVAL_INJECT)
1437 	down_write(&vm->svm.gpusvm.notifier_lock);
1438 #else
1439 	xe_svm_notifier_lock(vm);
1440 #endif
1441 }
1442 
1443 static void xe_pt_svm_userptr_notifier_unlock(struct xe_vm *vm)
1444 {
1445 #if IS_ENABLED(CONFIG_DRM_XE_USERPTR_INVAL_INJECT)
1446 	up_write(&vm->svm.gpusvm.notifier_lock);
1447 #else
1448 	xe_svm_notifier_unlock(vm);
1449 #endif
1450 }
1451 #else
1452 static inline void xe_pt_svm_userptr_notifier_lock(struct xe_vm *vm) { }
1453 static inline void xe_pt_svm_userptr_notifier_unlock(struct xe_vm *vm) { }
1454 #endif
1455 
1456 #if IS_ENABLED(CONFIG_DRM_GPUSVM)
1457 #ifdef CONFIG_DRM_XE_USERPTR_INVAL_INJECT
1458 
1459 static bool xe_pt_userptr_inject_eagain(struct xe_userptr_vma *uvma)
1460 {
1461 	u32 divisor = uvma->userptr.divisor ? uvma->userptr.divisor : 2;
1462 	static u32 count;
1463 
1464 	if (count++ % divisor == divisor - 1) {
1465 		uvma->userptr.divisor = divisor << 1;
1466 		return true;
1467 	}
1468 
1469 	return false;
1470 }
1471 
1472 #else
1473 
1474 static bool xe_pt_userptr_inject_eagain(struct xe_userptr_vma *uvma)
1475 {
1476 	return false;
1477 }
1478 
1479 #endif
1480 
1481 static int vma_check_userptr(struct xe_vm *vm, struct xe_vma *vma,
1482 			     struct xe_vm_pgtable_update_ops *pt_update)
1483 {
1484 	struct xe_userptr_vma *uvma;
1485 	unsigned long notifier_seq;
1486 
1487 	xe_svm_assert_held_read_or_inject_write(vm);
1488 
1489 	if (!xe_vma_is_userptr(vma))
1490 		return 0;
1491 
1492 	uvma = to_userptr_vma(vma);
1493 	if (xe_pt_userptr_inject_eagain(uvma))
1494 		xe_vma_userptr_force_invalidate(uvma);
1495 
1496 	notifier_seq = uvma->userptr.pages.notifier_seq;
1497 
1498 	if (!mmu_interval_read_retry(&uvma->userptr.notifier,
1499 				     notifier_seq))
1500 		return 0;
1501 
1502 	if (xe_vm_in_fault_mode(vm))
1503 		return -EAGAIN;
1504 
1505 	/*
1506 	 * Just continue the operation since exec or rebind worker
1507 	 * will take care of rebinding.
1508 	 */
1509 	return 0;
1510 }
1511 
1512 static int op_check_svm_userptr(struct xe_vm *vm, struct xe_vma_op *op,
1513 				struct xe_vm_pgtable_update_ops *pt_update)
1514 {
1515 	int err = 0;
1516 
1517 	xe_svm_assert_held_read_or_inject_write(vm);
1518 
1519 	switch (op->base.op) {
1520 	case DRM_GPUVA_OP_MAP:
1521 		if (!op->map.immediate && xe_vm_in_fault_mode(vm))
1522 			break;
1523 
1524 		err = vma_check_userptr(vm, op->map.vma, pt_update);
1525 		break;
1526 	case DRM_GPUVA_OP_REMAP:
1527 		if (op->remap.prev && !op->remap.skip_prev)
1528 			err = vma_check_userptr(vm, op->remap.prev, pt_update);
1529 		if (!err && op->remap.next && !op->remap.skip_next)
1530 			err = vma_check_userptr(vm, op->remap.next, pt_update);
1531 		break;
1532 	case DRM_GPUVA_OP_UNMAP:
1533 		break;
1534 	case DRM_GPUVA_OP_PREFETCH:
1535 		if (xe_vma_is_cpu_addr_mirror(gpuva_to_vma(op->base.prefetch.va))) {
1536 			struct xe_svm_range *range = op->map_range.range;
1537 			unsigned long i;
1538 
1539 			xe_assert(vm->xe,
1540 				  xe_vma_is_cpu_addr_mirror(gpuva_to_vma(op->base.prefetch.va)));
1541 			xa_for_each(&op->prefetch_range.range, i, range) {
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 -ENODATA;
1547 				}
1548 			}
1549 		} else {
1550 			err = vma_check_userptr(vm, gpuva_to_vma(op->base.prefetch.va), pt_update);
1551 		}
1552 		break;
1553 #if IS_ENABLED(CONFIG_DRM_XE_GPUSVM)
1554 	case DRM_GPUVA_OP_DRIVER:
1555 		if (op->subop == XE_VMA_SUBOP_MAP_RANGE) {
1556 			struct xe_svm_range *range = op->map_range.range;
1557 
1558 			xe_assert(vm->xe, xe_vma_is_cpu_addr_mirror(op->map_range.vma));
1559 
1560 			xe_svm_range_debug(range, "PRE-COMMIT");
1561 
1562 			if (!xe_svm_range_pages_valid(range)) {
1563 				xe_svm_range_debug(range, "PRE-COMMIT - RETRY");
1564 				return -EAGAIN;
1565 			}
1566 		}
1567 		break;
1568 #endif
1569 	default:
1570 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
1571 	}
1572 
1573 	return err;
1574 }
1575 
1576 static int xe_pt_svm_userptr_pre_commit(struct xe_migrate_pt_update *pt_update)
1577 {
1578 	struct xe_vm *vm = pt_update->vops->vm;
1579 	struct xe_vma_ops *vops = pt_update->vops;
1580 	struct xe_vm_pgtable_update_ops *pt_update_ops =
1581 		&vops->pt_update_ops[pt_update->tile_id];
1582 	struct xe_vma_op *op;
1583 	int err;
1584 
1585 	err = xe_pt_pre_commit(pt_update);
1586 	if (err)
1587 		return err;
1588 
1589 	xe_pt_svm_userptr_notifier_lock(vm);
1590 
1591 	list_for_each_entry(op, &vops->list, link) {
1592 		err = op_check_svm_userptr(vm, op, pt_update_ops);
1593 		if (err) {
1594 			xe_pt_svm_userptr_notifier_unlock(vm);
1595 			break;
1596 		}
1597 	}
1598 
1599 	return err;
1600 }
1601 #endif
1602 
1603 struct xe_pt_stage_unbind_walk {
1604 	/** @base: The pagewalk base-class. */
1605 	struct xe_pt_walk base;
1606 
1607 	/* Input parameters for the walk */
1608 	/** @tile: The tile we're unbinding from. */
1609 	struct xe_tile *tile;
1610 
1611 	/**
1612 	 * @modified_start: Walk range start, modified to include any
1613 	 * shared pagetables that we're the only user of and can thus
1614 	 * treat as private.
1615 	 */
1616 	u64 modified_start;
1617 	/** @modified_end: Walk range start, modified like @modified_start. */
1618 	u64 modified_end;
1619 
1620 	/** @prl: Backing pointer to page reclaim list in pt_update_ops */
1621 	struct xe_page_reclaim_list *prl;
1622 
1623 	/* Output */
1624 	/* @wupd: Structure to track the page-table updates we're building */
1625 	struct xe_walk_update wupd;
1626 };
1627 
1628 /*
1629  * Check whether this range is the only one populating this pagetable,
1630  * and in that case, update the walk range checks so that higher levels don't
1631  * view us as a shared pagetable.
1632  */
1633 static bool xe_pt_check_kill(u64 addr, u64 next, unsigned int level,
1634 			     const struct xe_pt *child,
1635 			     enum page_walk_action *action,
1636 			     struct xe_pt_walk *walk)
1637 {
1638 	struct xe_pt_stage_unbind_walk *xe_walk =
1639 		container_of(walk, typeof(*xe_walk), base);
1640 	unsigned int shift = walk->shifts[level];
1641 	u64 size = 1ull << shift;
1642 
1643 	if (IS_ALIGNED(addr, size) && IS_ALIGNED(next, size) &&
1644 	    ((next - addr) >> shift) == child->num_live) {
1645 		u64 size = 1ull << walk->shifts[level + 1];
1646 
1647 		*action = ACTION_CONTINUE;
1648 
1649 		if (xe_walk->modified_start >= addr)
1650 			xe_walk->modified_start = round_down(addr, size);
1651 		if (xe_walk->modified_end <= next)
1652 			xe_walk->modified_end = round_up(next, size);
1653 
1654 		return true;
1655 	}
1656 
1657 	return false;
1658 }
1659 
1660 static int generate_reclaim_entry(struct xe_tile *tile,
1661 				  struct xe_page_reclaim_list *prl,
1662 				  u64 pte, struct xe_pt *xe_child)
1663 {
1664 	struct xe_gt *gt = tile->primary_gt;
1665 	struct xe_guc_page_reclaim_entry *reclaim_entries = prl->entries;
1666 	bool is_2m = xe_child->level == 1 && (pte & XE_PDE_PS_2M);
1667 	bool is_64k = xe_child->level == 0 && ((pte & XE_PTE_PS64) || xe_child->is_compact);
1668 	u32 page_shift = is_2m ? ilog2(SZ_2M) : is_64k ? ilog2(SZ_64K) : ilog2(SZ_4K);
1669 	/* Physical address bits start at page shift: 2M->[51:21], 64K->[51:16], 4K->[51:12] */
1670 	u64 phys_addr = pte & XE_PAGE_ADDR_MASK(page_shift);
1671 	/* Page address is relative to 4K page regardless of entry level */
1672 	u64 phys_page = phys_addr >> XE_PTE_SHIFT;
1673 	int num_entries = prl->num_entries;
1674 	u32 reclamation_size = page_shift - XE_PTE_SHIFT;
1675 
1676 	xe_tile_assert(tile, xe_child->level <= MAX_HUGEPTE_LEVEL);
1677 	xe_tile_assert(tile, reclaim_entries);
1678 	xe_tile_assert(tile, num_entries < XE_PAGE_RECLAIM_MAX_ENTRIES - 1);
1679 
1680 	if (!xe_page_reclaim_list_valid(prl))
1681 		return -EINVAL;
1682 
1683 	/**
1684 	 * reclamation_size indicates the size of the page to be
1685 	 * invalidated and flushed from non-coherent cache.
1686 	 * Page size is computed as 2^(reclamation_size + XE_PTE_SHIFT) bytes.
1687 	 * Only 4K, 64K (level 0), and 2M pages are supported by hardware for page reclaim
1688 	 */
1689 	if (is_2m) {
1690 		xe_gt_stats_incr(gt, XE_GT_STATS_ID_PRL_2M_ENTRY_COUNT, 1);
1691 	} else if (is_64k) {
1692 		xe_gt_stats_incr(gt, XE_GT_STATS_ID_PRL_64K_ENTRY_COUNT, 1);
1693 	} else if (xe_child->level == 0) {
1694 		xe_gt_stats_incr(gt, XE_GT_STATS_ID_PRL_4K_ENTRY_COUNT, 1);
1695 	} else {
1696 		xe_page_reclaim_list_abort(tile->primary_gt, prl,
1697 					   "unsupported PTE level=%u pte=%#llx",
1698 					   xe_child->level, pte);
1699 		return -EINVAL;
1700 	}
1701 
1702 	reclaim_entries[num_entries].qw =
1703 		FIELD_PREP(XE_PAGE_RECLAIM_VALID, 1) |
1704 		FIELD_PREP(XE_PAGE_RECLAIM_SIZE, reclamation_size) |
1705 		FIELD_PREP(XE_PAGE_RECLAIM_ADDR_LO, phys_page) |
1706 		FIELD_PREP(XE_PAGE_RECLAIM_ADDR_HI, phys_page >> 20);
1707 	prl->num_entries++;
1708 	vm_dbg(&tile_to_xe(tile)->drm,
1709 	       "PRL add entry: level=%u pte=%#llx reclamation_size=%u prl_idx=%d\n",
1710 	       xe_child->level, pte, reclamation_size, num_entries);
1711 
1712 	return 0;
1713 }
1714 
1715 static int add_pte_to_prl(struct xe_tile *tile, struct xe_page_reclaim_list *prl,
1716 			  struct xe_pt *xe_child, u64 pte, u64 addr)
1717 {
1718 	/*
1719 	 * In rare scenarios, pte may not be written yet due to racy conditions.
1720 	 * In such cases, invalidate the PRL and fallback to full PPC invalidation.
1721 	 */
1722 	if (!pte) {
1723 		xe_page_reclaim_list_abort(tile->primary_gt, prl,
1724 					   "found zero pte at addr=%#llx", addr);
1725 		return -EINVAL;
1726 	}
1727 
1728 	/* Ensure it is a defined page */
1729 	xe_tile_assert(tile, xe_child->level == 0 ||
1730 		       (pte & (XE_PDE_PS_2M | XE_PDPE_PS_1G)));
1731 
1732 	/* Account for NULL terminated entry on end (-1) */
1733 	if (prl->num_entries >= XE_PAGE_RECLAIM_MAX_ENTRIES - 1) {
1734 		xe_page_reclaim_list_abort(tile->primary_gt, prl,
1735 					   "overflow while adding pte=%#llx", pte);
1736 		return -ENOSPC;
1737 	}
1738 
1739 	return generate_reclaim_entry(tile, prl, pte, xe_child);
1740 }
1741 
1742 static bool add_compact_pt_prl(struct xe_tile *tile, struct xe_page_reclaim_list *prl,
1743 			       struct xe_device *xe, struct xe_pt *compact_pt, u64 addr)
1744 {
1745 	struct iosys_map *map = &compact_pt->bo->vmap;
1746 
1747 	for (pgoff_t i = 0; i < SZ_2M / SZ_64K && xe_page_reclaim_list_valid(prl); i++) {
1748 		u64 pte = xe_map_rd(xe, map, i * sizeof(u64), u64);
1749 
1750 		if (add_pte_to_prl(tile, prl, compact_pt, pte, addr + i * SZ_64K))
1751 			break;
1752 	}
1753 
1754 	return xe_page_reclaim_list_valid(prl);
1755 }
1756 
1757 static int xe_pt_stage_unbind_entry(struct xe_ptw *parent, pgoff_t offset,
1758 				    unsigned int level, u64 addr, u64 next,
1759 				    struct xe_ptw **child,
1760 				    enum page_walk_action *action,
1761 				    struct xe_pt_walk *walk)
1762 {
1763 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
1764 	struct xe_pt_stage_unbind_walk *xe_walk =
1765 		container_of(walk, typeof(*xe_walk), base);
1766 	struct xe_page_reclaim_list *prl = xe_walk->prl;
1767 	struct xe_tile *tile = xe_walk->tile;
1768 	struct xe_device *xe = tile_to_xe(tile);
1769 	pgoff_t first = xe_pt_offset(addr, xe_child->level, walk);
1770 	bool killed;
1771 
1772 	XE_WARN_ON(!*child);
1773 	XE_WARN_ON(!level);
1774 	/* Check for leaf node */
1775 	if (prl && xe_page_reclaim_list_valid(prl) &&
1776 	    xe_child->level <= MAX_HUGEPTE_LEVEL) {
1777 		struct iosys_map *leaf_map = &xe_child->bo->vmap;
1778 		pgoff_t count = xe_pt_num_entries(addr, next, xe_child->level, walk);
1779 
1780 		for (pgoff_t i = 0; i < count; i++) {
1781 			u64 pte;
1782 
1783 			/*
1784 			 * If not a leaf pt, skip unless non-leaf pt is interleaved between
1785 			 * leaf ptes which causes the page walk to skip over the child leaves
1786 			 */
1787 			if (xe_child->base.children && xe_child->base.children[first + i]) {
1788 				u64 pt_size = 1ULL << walk->shifts[xe_child->level];
1789 				bool edge_pt = (i == 0 && !IS_ALIGNED(addr, pt_size)) ||
1790 					       (i == count - 1 && !IS_ALIGNED(next, pt_size));
1791 				struct xe_pt *child_pt =
1792 					container_of(xe_child->base.children[first + i],
1793 						     struct xe_pt, base);
1794 
1795 				/* Compact PTs always fill a full 2M-aligned slot, never an edge. */
1796 				XE_WARN_ON(child_pt->is_compact && edge_pt);
1797 				if (edge_pt)
1798 					continue;
1799 
1800 				/* Walker never descends into compact PTs, descend now */
1801 				if (child_pt->is_compact) {
1802 					if (!add_compact_pt_prl(tile, prl, xe, child_pt,
1803 								addr + (u64)i * pt_size))
1804 						break;
1805 				} else {
1806 					xe_page_reclaim_list_abort(tile->primary_gt,
1807 								   prl,
1808 								   "PT is skipped by walk at level=%u offset=%lu",
1809 								   xe_child->level, first + i);
1810 					break;
1811 				}
1812 				continue;
1813 			}
1814 
1815 			pte = xe_map_rd(xe, leaf_map, (first + i) * sizeof(u64), u64);
1816 
1817 			if (add_pte_to_prl(tile, prl, xe_child, pte, addr))
1818 				break;
1819 
1820 			/* An entry should be added for 64KB but contigious 4K have XE_PTE_PS64 */
1821 			if (pte & XE_PTE_PS64)
1822 				i += 15; /* Skip other 15 consecutive 4K pages in the 64K page */
1823 		}
1824 	}
1825 
1826 	killed = xe_pt_check_kill(addr, next, level - 1, xe_child, action, walk);
1827 
1828 	/*
1829 	 * Verify if any PTE are potentially dropped at non-leaf levels, either from being
1830 	 * killed or the page walk covers the region.
1831 	 */
1832 	if (prl && xe_page_reclaim_list_valid(prl) &&
1833 	    xe_child->level > MAX_HUGEPTE_LEVEL && xe_child->num_live) {
1834 		bool covered = xe_pt_covers(addr, next, xe_child->level, &xe_walk->base);
1835 
1836 		/*
1837 		 * If aborting page walk early (kill) or page walk completes the full range
1838 		 * we need to invalidate the PRL.
1839 		 */
1840 		if (killed || covered)
1841 			xe_page_reclaim_list_abort(tile->primary_gt, prl,
1842 						   "kill at level=%u addr=%#llx next=%#llx num_live=%u",
1843 						   level, addr, next, xe_child->num_live);
1844 	}
1845 
1846 	return 0;
1847 }
1848 
1849 static int
1850 xe_pt_stage_unbind_post_descend(struct xe_ptw *parent, pgoff_t offset,
1851 				unsigned int level, u64 addr, u64 next,
1852 				struct xe_ptw **child,
1853 				enum page_walk_action *action,
1854 				struct xe_pt_walk *walk)
1855 {
1856 	struct xe_pt_stage_unbind_walk *xe_walk =
1857 		container_of(walk, typeof(*xe_walk), base);
1858 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
1859 	pgoff_t end_offset;
1860 	u64 size = 1ull << walk->shifts[--level];
1861 	int err;
1862 
1863 	if (!IS_ALIGNED(addr, size))
1864 		addr = xe_walk->modified_start;
1865 	if (!IS_ALIGNED(next, size))
1866 		next = xe_walk->modified_end;
1867 
1868 	/* Parent == *child is the root pt. Don't kill it. */
1869 	if (parent != *child &&
1870 	    xe_pt_check_kill(addr, next, level, xe_child, action, walk))
1871 		return 0;
1872 
1873 	if (!xe_pt_nonshared_offsets(addr, next, level, walk, action, &offset,
1874 				     &end_offset))
1875 		return 0;
1876 
1877 	err = xe_pt_new_shared(&xe_walk->wupd, xe_child, offset, true);
1878 	if (err)
1879 		return err;
1880 
1881 	xe_walk->wupd.updates[level].update->qwords = end_offset - offset;
1882 
1883 	return 0;
1884 }
1885 
1886 static const struct xe_pt_walk_ops xe_pt_stage_unbind_ops = {
1887 	.pt_entry = xe_pt_stage_unbind_entry,
1888 	.pt_post_descend = xe_pt_stage_unbind_post_descend,
1889 };
1890 
1891 /**
1892  * xe_pt_stage_unbind() - Build page-table update structures for an unbind
1893  * operation
1894  * @tile: The tile we're unbinding for.
1895  * @vm: The vm
1896  * @vma: The vma we're unbinding.
1897  * @range: The range we're unbinding.
1898  * @entries: Caller-provided storage for the update structures.
1899  *
1900  * Builds page-table update structures for an unbind operation. The function
1901  * will attempt to remove all page-tables that we're the only user
1902  * of, and for that to work, the unbind operation must be committed in the
1903  * same critical section that blocks racing binds to the same page-table tree.
1904  *
1905  * Return: The number of entries used.
1906  */
1907 static unsigned int xe_pt_stage_unbind(struct xe_tile *tile,
1908 				       struct xe_vm *vm,
1909 				       struct xe_vma *vma,
1910 				       struct xe_svm_range *range,
1911 				       struct xe_vm_pgtable_update *entries)
1912 {
1913 	u64 start = range ? xe_svm_range_start(range) : xe_vma_start(vma);
1914 	u64 end = range ? xe_svm_range_end(range) : xe_vma_end(vma);
1915 	struct xe_vm_pgtable_update_op *pt_update_op =
1916 		container_of(entries, struct xe_vm_pgtable_update_op, entries[0]);
1917 	struct xe_pt_stage_unbind_walk xe_walk = {
1918 		.base = {
1919 			.ops = &xe_pt_stage_unbind_ops,
1920 			.shifts = xe_normal_pt_shifts,
1921 			.max_level = XE_PT_HIGHEST_LEVEL,
1922 			.staging = true,
1923 		},
1924 		.tile = tile,
1925 		.modified_start = start,
1926 		.modified_end = end,
1927 		.wupd.entries = entries,
1928 		.prl = pt_update_op->prl,
1929 	};
1930 	struct xe_pt *pt = vm->pt_root[tile->id];
1931 
1932 	(void)xe_pt_walk_shared(&pt->base, pt->level, start, end,
1933 				&xe_walk.base);
1934 
1935 	return xe_walk.wupd.num_used_entries;
1936 }
1937 
1938 static void
1939 xe_migrate_clear_pgtable_callback(struct xe_migrate_pt_update *pt_update,
1940 				  struct xe_tile *tile, struct iosys_map *map,
1941 				  void *ptr, u32 qword_ofs, u32 num_qwords,
1942 				  const struct xe_vm_pgtable_update *update)
1943 {
1944 	struct xe_vm *vm = pt_update->vops->vm;
1945 	u64 empty = __xe_pt_empty_pte(tile, vm, update->pt->level);
1946 	int i;
1947 
1948 	if (map && map->is_iomem)
1949 		for (i = 0; i < num_qwords; ++i)
1950 			xe_map_wr(tile_to_xe(tile), map, (qword_ofs + i) *
1951 				  sizeof(u64), u64, empty);
1952 	else if (map)
1953 		memset64(map->vaddr + qword_ofs * sizeof(u64), empty,
1954 			 num_qwords);
1955 	else
1956 		memset64(ptr, empty, num_qwords);
1957 }
1958 
1959 static void xe_pt_abort_unbind(struct xe_vma *vma,
1960 			       struct xe_vm_pgtable_update *entries,
1961 			       u32 num_entries)
1962 {
1963 	int i, j;
1964 
1965 	xe_pt_commit_prepare_locks_assert(vma);
1966 
1967 	for (i = num_entries - 1; i >= 0; --i) {
1968 		struct xe_vm_pgtable_update *entry = &entries[i];
1969 		struct xe_pt *pt = entry->pt;
1970 		struct xe_pt_dir *pt_dir = as_xe_pt_dir(pt);
1971 
1972 		pt->num_live += entry->qwords;
1973 
1974 		if (!pt->level)
1975 			continue;
1976 
1977 		for (j = entry->ofs; j < entry->ofs + entry->qwords; j++)
1978 			pt_dir->staging[j] =
1979 				entries[i].pt_entries[j - entry->ofs].pt ?
1980 				&entries[i].pt_entries[j - entry->ofs].pt->base : NULL;
1981 	}
1982 }
1983 
1984 static void
1985 xe_pt_commit_prepare_unbind(struct xe_vma *vma,
1986 			    struct xe_vm_pgtable_update *entries,
1987 			    u32 num_entries)
1988 {
1989 	int i, j;
1990 
1991 	xe_pt_commit_prepare_locks_assert(vma);
1992 
1993 	for (i = 0; i < num_entries; ++i) {
1994 		struct xe_vm_pgtable_update *entry = &entries[i];
1995 		struct xe_pt *pt = entry->pt;
1996 		struct xe_pt_dir *pt_dir;
1997 
1998 		pt->num_live -= entry->qwords;
1999 		if (!pt->level)
2000 			continue;
2001 
2002 		pt_dir = as_xe_pt_dir(pt);
2003 		for (j = entry->ofs; j < entry->ofs + entry->qwords; j++) {
2004 			entry->pt_entries[j - entry->ofs].pt =
2005 				xe_pt_entry_staging(pt_dir, j);
2006 			pt_dir->staging[j] = NULL;
2007 		}
2008 	}
2009 }
2010 
2011 static void
2012 xe_pt_update_ops_rfence_interval(struct xe_vm_pgtable_update_ops *pt_update_ops,
2013 				 u64 start, u64 end)
2014 {
2015 	u64 last;
2016 	u32 current_op = pt_update_ops->current_op;
2017 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
2018 	int i, level = 0;
2019 
2020 	for (i = 0; i < pt_op->num_entries; i++) {
2021 		const struct xe_vm_pgtable_update *entry = &pt_op->entries[i];
2022 
2023 		if (entry->pt->level > level)
2024 			level = entry->pt->level;
2025 	}
2026 
2027 	/* Greedy (non-optimal) calculation but simple */
2028 	start = ALIGN_DOWN(start, 0x1ull << xe_pt_shift(level));
2029 	last = ALIGN(end, 0x1ull << xe_pt_shift(level)) - 1;
2030 
2031 	if (start < pt_update_ops->start)
2032 		pt_update_ops->start = start;
2033 	if (last > pt_update_ops->last)
2034 		pt_update_ops->last = last;
2035 }
2036 
2037 static int vma_reserve_fences(struct xe_device *xe, struct xe_vma *vma)
2038 {
2039 	int shift = xe_device_get_root_tile(xe)->media_gt ? 1 : 0;
2040 
2041 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm)
2042 		return dma_resv_reserve_fences(xe_vma_bo(vma)->ttm.base.resv,
2043 					       xe->info.tile_count << shift);
2044 
2045 	return 0;
2046 }
2047 
2048 static int bind_op_prepare(struct xe_vm *vm, struct xe_tile *tile,
2049 			   struct xe_vm_pgtable_update_ops *pt_update_ops,
2050 			   struct xe_vma *vma, bool invalidate_on_bind)
2051 {
2052 	u32 current_op = pt_update_ops->current_op;
2053 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
2054 	int err;
2055 
2056 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2057 	xe_bo_assert_held(xe_vma_bo(vma));
2058 
2059 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
2060 	       "Preparing bind, with range [%llx...%llx)\n",
2061 	       xe_vma_start(vma), xe_vma_end(vma) - 1);
2062 
2063 	pt_op->vma = NULL;
2064 	pt_op->bind = true;
2065 	pt_op->rebind = BIT(tile->id) & vma->tile_present;
2066 
2067 	err = vma_reserve_fences(tile_to_xe(tile), vma);
2068 	if (err)
2069 		return err;
2070 
2071 	err = xe_pt_prepare_bind(tile, vma, NULL, pt_op->entries,
2072 				 &pt_op->num_entries, invalidate_on_bind);
2073 	if (!err) {
2074 		xe_tile_assert(tile, pt_op->num_entries <=
2075 			       ARRAY_SIZE(pt_op->entries));
2076 		xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
2077 					pt_op->num_entries, true);
2078 
2079 		xe_pt_update_ops_rfence_interval(pt_update_ops,
2080 						 xe_vma_start(vma),
2081 						 xe_vma_end(vma));
2082 		++pt_update_ops->current_op;
2083 		pt_update_ops->needs_svm_lock |= xe_vma_is_userptr(vma);
2084 
2085 		/*
2086 		 * If rebind, we have to invalidate TLB on !LR vms to invalidate
2087 		 * cached PTEs point to freed memory. On LR vms this is done
2088 		 * automatically when the context is re-enabled by the rebind worker,
2089 		 * or in fault mode it was invalidated on PTE zapping.
2090 		 *
2091 		 * If !rebind, and scratch enabled VMs, there is a chance the scratch
2092 		 * PTE is already cached in the TLB so it needs to be invalidated.
2093 		 * On !LR VMs this is done in the ring ops preceding a batch, but on
2094 		 * LR, in particular on user-space batch buffer chaining, it needs to
2095 		 * be done here.
2096 		 */
2097 		if ((!pt_op->rebind && xe_vm_has_scratch(vm) &&
2098 		     xe_vm_in_lr_mode(vm)))
2099 			pt_update_ops->needs_invalidation = true;
2100 		else if (pt_op->rebind && !xe_vm_in_lr_mode(vm))
2101 			/* We bump also if batch_invalidate_tlb is true */
2102 			vm->tlb_flush_seqno++;
2103 
2104 		vma->tile_staged |= BIT(tile->id);
2105 		pt_op->vma = vma;
2106 		xe_pt_commit_prepare_bind(vma, pt_op->entries,
2107 					  pt_op->num_entries, pt_op->rebind);
2108 	} else {
2109 		xe_pt_cancel_bind(vma, pt_op->entries, pt_op->num_entries);
2110 	}
2111 
2112 	return err;
2113 }
2114 
2115 static int bind_range_prepare(struct xe_vm *vm, struct xe_tile *tile,
2116 			      struct xe_vm_pgtable_update_ops *pt_update_ops,
2117 			      struct xe_vma *vma, struct xe_svm_range *range)
2118 {
2119 	u32 current_op = pt_update_ops->current_op;
2120 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
2121 	int err;
2122 
2123 	xe_tile_assert(tile, xe_vma_is_cpu_addr_mirror(vma));
2124 
2125 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
2126 	       "Preparing bind, with range [%lx...%lx)\n",
2127 	       xe_svm_range_start(range), xe_svm_range_end(range) - 1);
2128 
2129 	pt_op->vma = NULL;
2130 	pt_op->bind = true;
2131 	pt_op->rebind = BIT(tile->id) & range->tile_present;
2132 
2133 	err = xe_pt_prepare_bind(tile, vma, range, pt_op->entries,
2134 				 &pt_op->num_entries, false);
2135 	if (!err) {
2136 		xe_tile_assert(tile, pt_op->num_entries <=
2137 			       ARRAY_SIZE(pt_op->entries));
2138 		xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
2139 					pt_op->num_entries, true);
2140 
2141 		xe_pt_update_ops_rfence_interval(pt_update_ops,
2142 						 xe_svm_range_start(range),
2143 						 xe_svm_range_end(range));
2144 		++pt_update_ops->current_op;
2145 		pt_update_ops->needs_svm_lock = true;
2146 
2147 		pt_op->vma = vma;
2148 		xe_pt_commit_prepare_bind(vma, pt_op->entries,
2149 					  pt_op->num_entries, pt_op->rebind);
2150 	} else {
2151 		xe_pt_cancel_bind(vma, pt_op->entries, pt_op->num_entries);
2152 	}
2153 
2154 	return err;
2155 }
2156 
2157 static int unbind_op_prepare(struct xe_tile *tile,
2158 			     struct xe_vm_pgtable_update_ops *pt_update_ops,
2159 			     struct xe_vma *vma)
2160 {
2161 	struct xe_device *xe = tile_to_xe(tile);
2162 	u32 current_op = pt_update_ops->current_op;
2163 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
2164 	int err;
2165 
2166 	if (!((vma->tile_present | vma->tile_staged) & BIT(tile->id)))
2167 		return 0;
2168 
2169 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2170 	xe_bo_assert_held(xe_vma_bo(vma));
2171 
2172 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
2173 	       "Preparing unbind, with range [%llx...%llx)\n",
2174 	       xe_vma_start(vma), xe_vma_end(vma) - 1);
2175 
2176 	pt_op->vma = vma;
2177 	pt_op->bind = false;
2178 	pt_op->rebind = false;
2179 	/*
2180 	 * Maintain one PRL located in pt_update_ops that all others in unbind op reference.
2181 	 * Ensure that PRL is allocated only once, and if invalidated, remains an invalidated PRL.
2182 	 */
2183 	if (xe->info.has_page_reclaim_hw_assist &&
2184 	    xe_page_reclaim_list_is_new(&pt_update_ops->prl))
2185 		xe_page_reclaim_list_alloc_entries(&pt_update_ops->prl);
2186 
2187 	/* Page reclaim may not be needed due to other features, so skip the corresponding VMA */
2188 	pt_op->prl = (xe_page_reclaim_list_valid(&pt_update_ops->prl) &&
2189 		     !xe_page_reclaim_skip(tile, vma)) ? &pt_update_ops->prl : NULL;
2190 
2191 	err = vma_reserve_fences(tile_to_xe(tile), vma);
2192 	if (err)
2193 		return err;
2194 
2195 	pt_op->num_entries = xe_pt_stage_unbind(tile, xe_vma_vm(vma),
2196 						vma, NULL, pt_op->entries);
2197 
2198 	xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
2199 				pt_op->num_entries, false);
2200 	xe_pt_update_ops_rfence_interval(pt_update_ops, xe_vma_start(vma),
2201 					 xe_vma_end(vma));
2202 	++pt_update_ops->current_op;
2203 	pt_update_ops->needs_svm_lock |= xe_vma_is_userptr(vma);
2204 	pt_update_ops->needs_invalidation = true;
2205 
2206 	xe_pt_commit_prepare_unbind(vma, pt_op->entries, pt_op->num_entries);
2207 
2208 	return 0;
2209 }
2210 
2211 static bool
2212 xe_pt_op_check_range_skip_invalidation(struct xe_vm_pgtable_update_op *pt_op,
2213 				       struct xe_svm_range *range)
2214 {
2215 	struct xe_vm_pgtable_update *update = pt_op->entries;
2216 
2217 	XE_WARN_ON(!pt_op->num_entries);
2218 
2219 	/*
2220 	 * We can't skip the invalidation if we are removing PTEs that span more
2221 	 * than the range, do some checks to ensure we are removing PTEs that
2222 	 * are invalid.
2223 	 */
2224 
2225 	if (pt_op->num_entries > 1)
2226 		return false;
2227 
2228 	if (update->pt->level == 0)
2229 		return true;
2230 
2231 	if (update->pt->level == 1)
2232 		return xe_svm_range_size(range) >= SZ_2M;
2233 
2234 	return false;
2235 }
2236 
2237 static int unbind_range_prepare(struct xe_vm *vm,
2238 				struct xe_tile *tile,
2239 				struct xe_vm_pgtable_update_ops *pt_update_ops,
2240 				struct xe_svm_range *range)
2241 {
2242 	u32 current_op = pt_update_ops->current_op;
2243 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
2244 
2245 	if (!(range->tile_present & BIT(tile->id)))
2246 		return 0;
2247 
2248 	vm_dbg(&vm->xe->drm,
2249 	       "Preparing unbind, with range [%lx...%lx)\n",
2250 	       xe_svm_range_start(range), xe_svm_range_end(range) - 1);
2251 
2252 	pt_op->vma = XE_INVALID_VMA;
2253 	pt_op->bind = false;
2254 	pt_op->rebind = false;
2255 	pt_op->prl = NULL;
2256 
2257 	pt_op->num_entries = xe_pt_stage_unbind(tile, vm, NULL, range,
2258 						pt_op->entries);
2259 
2260 	xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
2261 				pt_op->num_entries, false);
2262 	xe_pt_update_ops_rfence_interval(pt_update_ops, xe_svm_range_start(range),
2263 					 xe_svm_range_end(range));
2264 	++pt_update_ops->current_op;
2265 	pt_update_ops->needs_svm_lock = true;
2266 	pt_update_ops->needs_invalidation |= xe_vm_has_scratch(vm) ||
2267 		xe_vm_has_valid_gpu_mapping(tile, range->tile_present,
2268 					    range->tile_invalidated) ||
2269 		!xe_pt_op_check_range_skip_invalidation(pt_op, range);
2270 
2271 	xe_pt_commit_prepare_unbind(XE_INVALID_VMA, pt_op->entries,
2272 				    pt_op->num_entries);
2273 
2274 	return 0;
2275 }
2276 
2277 static int op_prepare(struct xe_vm *vm,
2278 		      struct xe_tile *tile,
2279 		      struct xe_vm_pgtable_update_ops *pt_update_ops,
2280 		      struct xe_vma_op *op)
2281 {
2282 	int err = 0;
2283 
2284 	xe_vm_assert_held(vm);
2285 
2286 	switch (op->base.op) {
2287 	case DRM_GPUVA_OP_MAP:
2288 		if ((!op->map.immediate && xe_vm_in_fault_mode(vm) &&
2289 		     !op->map.invalidate_on_bind) ||
2290 		    (op->map.vma_flags & XE_VMA_SYSTEM_ALLOCATOR))
2291 			break;
2292 
2293 		err = bind_op_prepare(vm, tile, pt_update_ops, op->map.vma,
2294 				      op->map.invalidate_on_bind);
2295 		pt_update_ops->wait_vm_kernel = true;
2296 		break;
2297 	case DRM_GPUVA_OP_REMAP:
2298 	{
2299 		struct xe_vma *old = gpuva_to_vma(op->base.remap.unmap->va);
2300 
2301 		if (xe_vma_is_cpu_addr_mirror(old))
2302 			break;
2303 
2304 		err = unbind_op_prepare(tile, pt_update_ops, old);
2305 
2306 		if (!err && op->remap.prev && !op->remap.skip_prev) {
2307 			err = bind_op_prepare(vm, tile, pt_update_ops,
2308 					      op->remap.prev, false);
2309 			pt_update_ops->wait_vm_bookkeep = true;
2310 		}
2311 		if (!err && op->remap.next && !op->remap.skip_next) {
2312 			err = bind_op_prepare(vm, tile, pt_update_ops,
2313 					      op->remap.next, false);
2314 			pt_update_ops->wait_vm_bookkeep = true;
2315 		}
2316 		break;
2317 	}
2318 	case DRM_GPUVA_OP_UNMAP:
2319 	{
2320 		struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
2321 
2322 		if (xe_vma_is_cpu_addr_mirror(vma))
2323 			break;
2324 
2325 		err = unbind_op_prepare(tile, pt_update_ops, vma);
2326 		break;
2327 	}
2328 	case DRM_GPUVA_OP_PREFETCH:
2329 	{
2330 		struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2331 
2332 		if (xe_vma_is_cpu_addr_mirror(vma)) {
2333 			struct xe_svm_range *range;
2334 			unsigned long i;
2335 
2336 			xa_for_each(&op->prefetch_range.range, i, range) {
2337 				err = bind_range_prepare(vm, tile, pt_update_ops,
2338 							 vma, range);
2339 				if (err)
2340 					return err;
2341 			}
2342 		} else {
2343 			err = bind_op_prepare(vm, tile, pt_update_ops, vma, false);
2344 			pt_update_ops->wait_vm_kernel = true;
2345 		}
2346 		break;
2347 	}
2348 	case DRM_GPUVA_OP_DRIVER:
2349 		if (op->subop == XE_VMA_SUBOP_MAP_RANGE) {
2350 			xe_assert(vm->xe, xe_vma_is_cpu_addr_mirror(op->map_range.vma));
2351 
2352 			err = bind_range_prepare(vm, tile, pt_update_ops,
2353 						 op->map_range.vma,
2354 						 op->map_range.range);
2355 		} else if (op->subop == XE_VMA_SUBOP_UNMAP_RANGE) {
2356 			err = unbind_range_prepare(vm, tile, pt_update_ops,
2357 						   op->unmap_range.range);
2358 		}
2359 		break;
2360 	default:
2361 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2362 	}
2363 
2364 	return err;
2365 }
2366 
2367 static void
2368 xe_pt_update_ops_init(struct xe_vm_pgtable_update_ops *pt_update_ops)
2369 {
2370 	init_llist_head(&pt_update_ops->deferred);
2371 	pt_update_ops->current_op = 0;
2372 	pt_update_ops->start = ~0x0ull;
2373 	pt_update_ops->last = 0x0ull;
2374 	pt_update_ops->needs_svm_lock = false;
2375 	pt_update_ops->needs_invalidation = false;
2376 	xe_page_reclaim_list_init(&pt_update_ops->prl);
2377 }
2378 
2379 /**
2380  * xe_pt_update_ops_prepare() - Prepare PT update operations
2381  * @tile: Tile of PT update operations
2382  * @vops: VMA operationa
2383  *
2384  * Prepare PT update operations which includes updating internal PT state,
2385  * allocate memory for page tables, populate page table being pruned in, and
2386  * create PT update operations for leaf insertion / removal.
2387  *
2388  * Return: 0 on success, negative error code on error.
2389  */
2390 int xe_pt_update_ops_prepare(struct xe_tile *tile, struct xe_vma_ops *vops)
2391 {
2392 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2393 		&vops->pt_update_ops[tile->id];
2394 	struct xe_vma_op *op;
2395 	int shift = tile->media_gt ? 1 : 0;
2396 	int err;
2397 
2398 	lockdep_assert_held(&vops->vm->lock);
2399 	xe_vm_assert_held(vops->vm);
2400 
2401 	xe_pt_update_ops_init(pt_update_ops);
2402 
2403 	err = dma_resv_reserve_fences(xe_vm_resv(vops->vm),
2404 				      tile_to_xe(tile)->info.tile_count << shift);
2405 	if (err)
2406 		return err;
2407 
2408 	list_for_each_entry(op, &vops->list, link) {
2409 		err = op_prepare(vops->vm, tile, pt_update_ops, op);
2410 
2411 		if (err)
2412 			return err;
2413 	}
2414 
2415 	xe_tile_assert(tile, pt_update_ops->current_op <=
2416 		       pt_update_ops->num_ops);
2417 
2418 #ifdef TEST_VM_OPS_ERROR
2419 	if (vops->inject_error &&
2420 	    vops->vm->xe->vm_inject_error_position == FORCE_OP_ERROR_PREPARE)
2421 		return -ENOSPC;
2422 #endif
2423 
2424 	return 0;
2425 }
2426 ALLOW_ERROR_INJECTION(xe_pt_update_ops_prepare, ERRNO);
2427 
2428 static void bind_op_commit(struct xe_vm *vm, struct xe_tile *tile,
2429 			   struct xe_vm_pgtable_update_ops *pt_update_ops,
2430 			   struct xe_vma *vma, struct dma_fence *fence,
2431 			   struct dma_fence *fence2, bool invalidate_on_bind)
2432 {
2433 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2434 
2435 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm) {
2436 		dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence,
2437 				   pt_update_ops->wait_vm_bookkeep ?
2438 				   DMA_RESV_USAGE_KERNEL :
2439 				   DMA_RESV_USAGE_BOOKKEEP);
2440 		if (fence2)
2441 			dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence2,
2442 					   pt_update_ops->wait_vm_bookkeep ?
2443 					   DMA_RESV_USAGE_KERNEL :
2444 					   DMA_RESV_USAGE_BOOKKEEP);
2445 	}
2446 	/* All WRITE_ONCE pair with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2447 	WRITE_ONCE(vma->tile_present, vma->tile_present | BIT(tile->id));
2448 	if (invalidate_on_bind)
2449 		WRITE_ONCE(vma->tile_invalidated,
2450 			   vma->tile_invalidated | BIT(tile->id));
2451 	else
2452 		WRITE_ONCE(vma->tile_invalidated,
2453 			   vma->tile_invalidated & ~BIT(tile->id));
2454 	vma->tile_staged &= ~BIT(tile->id);
2455 	if (xe_vma_is_userptr(vma)) {
2456 		xe_svm_assert_held_read_or_inject_write(vm);
2457 		to_userptr_vma(vma)->userptr.initial_bind = true;
2458 	}
2459 
2460 	/*
2461 	 * Kick rebind worker if this bind triggers preempt fences and not in
2462 	 * the rebind worker
2463 	 */
2464 	if (pt_update_ops->wait_vm_bookkeep &&
2465 	    xe_vm_in_preempt_fence_mode(vm) &&
2466 	    !current->mm)
2467 		xe_vm_queue_rebind_worker(vm);
2468 }
2469 
2470 static void unbind_op_commit(struct xe_vm *vm, struct xe_tile *tile,
2471 			     struct xe_vm_pgtable_update_ops *pt_update_ops,
2472 			     struct xe_vma *vma, struct dma_fence *fence,
2473 			     struct dma_fence *fence2)
2474 {
2475 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2476 
2477 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm) {
2478 		dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence,
2479 				   pt_update_ops->wait_vm_bookkeep ?
2480 				   DMA_RESV_USAGE_KERNEL :
2481 				   DMA_RESV_USAGE_BOOKKEEP);
2482 		if (fence2)
2483 			dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence2,
2484 					   pt_update_ops->wait_vm_bookkeep ?
2485 					   DMA_RESV_USAGE_KERNEL :
2486 					   DMA_RESV_USAGE_BOOKKEEP);
2487 	}
2488 	vma->tile_present &= ~BIT(tile->id);
2489 	if (!vma->tile_present) {
2490 		list_del_init(&vma->combined_links.rebind);
2491 		if (xe_vma_is_userptr(vma)) {
2492 			xe_svm_assert_held_read_or_inject_write(vm);
2493 
2494 			spin_lock(&vm->userptr.invalidated_lock);
2495 			list_del_init(&to_userptr_vma(vma)->userptr.invalidate_link);
2496 			spin_unlock(&vm->userptr.invalidated_lock);
2497 		}
2498 	}
2499 }
2500 
2501 static void range_present_and_invalidated_tile(struct xe_vm *vm,
2502 					       struct xe_svm_range *range,
2503 					       u8 tile_id)
2504 {
2505 	/* All WRITE_ONCE pair with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2506 
2507 	lockdep_assert_held(&vm->svm.gpusvm.notifier_lock);
2508 
2509 	WRITE_ONCE(range->tile_present, range->tile_present | BIT(tile_id));
2510 	WRITE_ONCE(range->tile_invalidated, range->tile_invalidated & ~BIT(tile_id));
2511 }
2512 
2513 static void op_commit(struct xe_vm *vm,
2514 		      struct xe_tile *tile,
2515 		      struct xe_vm_pgtable_update_ops *pt_update_ops,
2516 		      struct xe_vma_op *op, struct dma_fence *fence,
2517 		      struct dma_fence *fence2)
2518 {
2519 	xe_vm_assert_held(vm);
2520 
2521 	switch (op->base.op) {
2522 	case DRM_GPUVA_OP_MAP:
2523 		if ((!op->map.immediate && xe_vm_in_fault_mode(vm)) ||
2524 		    (op->map.vma_flags & XE_VMA_SYSTEM_ALLOCATOR))
2525 			break;
2526 
2527 		bind_op_commit(vm, tile, pt_update_ops, op->map.vma, fence,
2528 			       fence2, op->map.invalidate_on_bind);
2529 		break;
2530 	case DRM_GPUVA_OP_REMAP:
2531 	{
2532 		struct xe_vma *old = gpuva_to_vma(op->base.remap.unmap->va);
2533 
2534 		if (xe_vma_is_cpu_addr_mirror(old))
2535 			break;
2536 
2537 		unbind_op_commit(vm, tile, pt_update_ops, old, fence, fence2);
2538 
2539 		if (op->remap.prev && !op->remap.skip_prev)
2540 			bind_op_commit(vm, tile, pt_update_ops, op->remap.prev,
2541 				       fence, fence2, false);
2542 		if (op->remap.next && !op->remap.skip_next)
2543 			bind_op_commit(vm, tile, pt_update_ops, op->remap.next,
2544 				       fence, fence2, false);
2545 		break;
2546 	}
2547 	case DRM_GPUVA_OP_UNMAP:
2548 	{
2549 		struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
2550 
2551 		if (!xe_vma_is_cpu_addr_mirror(vma))
2552 			unbind_op_commit(vm, tile, pt_update_ops, vma, fence,
2553 					 fence2);
2554 		break;
2555 	}
2556 	case DRM_GPUVA_OP_PREFETCH:
2557 	{
2558 		struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2559 
2560 		if (xe_vma_is_cpu_addr_mirror(vma)) {
2561 			struct xe_svm_range *range = NULL;
2562 			unsigned long i;
2563 
2564 			xa_for_each(&op->prefetch_range.range, i, range)
2565 				range_present_and_invalidated_tile(vm, range, tile->id);
2566 		} else {
2567 			bind_op_commit(vm, tile, pt_update_ops, vma, fence,
2568 				       fence2, false);
2569 		}
2570 		break;
2571 	}
2572 	case DRM_GPUVA_OP_DRIVER:
2573 	{
2574 		/* WRITE_ONCE pairs with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2575 		if (op->subop == XE_VMA_SUBOP_MAP_RANGE)
2576 			range_present_and_invalidated_tile(vm, op->map_range.range, tile->id);
2577 		else if (op->subop == XE_VMA_SUBOP_UNMAP_RANGE)
2578 			WRITE_ONCE(op->unmap_range.range->tile_present,
2579 				   op->unmap_range.range->tile_present &
2580 				   ~BIT(tile->id));
2581 
2582 		break;
2583 	}
2584 	default:
2585 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2586 	}
2587 }
2588 
2589 static const struct xe_migrate_pt_update_ops migrate_ops = {
2590 	.populate = xe_vm_populate_pgtable,
2591 	.clear = xe_migrate_clear_pgtable_callback,
2592 	.pre_commit = xe_pt_pre_commit,
2593 };
2594 
2595 #if IS_ENABLED(CONFIG_DRM_GPUSVM)
2596 static const struct xe_migrate_pt_update_ops svm_userptr_migrate_ops = {
2597 	.populate = xe_vm_populate_pgtable,
2598 	.clear = xe_migrate_clear_pgtable_callback,
2599 	.pre_commit = xe_pt_svm_userptr_pre_commit,
2600 };
2601 #else
2602 static const struct xe_migrate_pt_update_ops svm_userptr_migrate_ops;
2603 #endif
2604 
2605 static struct xe_dep_scheduler *to_dep_scheduler(struct xe_exec_queue *q,
2606 						 struct xe_gt *gt)
2607 {
2608 	if (xe_gt_is_media_type(gt))
2609 		return q->tlb_inval[XE_EXEC_QUEUE_TLB_INVAL_MEDIA_GT].dep_scheduler;
2610 
2611 	return q->tlb_inval[XE_EXEC_QUEUE_TLB_INVAL_PRIMARY_GT].dep_scheduler;
2612 }
2613 
2614 /**
2615  * xe_pt_update_ops_run() - Run PT update operations
2616  * @tile: Tile of PT update operations
2617  * @vops: VMA operationa
2618  *
2619  * Run PT update operations which includes committing internal PT state changes,
2620  * creating job for PT update operations for leaf insertion / removal, and
2621  * installing job fence in various places.
2622  *
2623  * Return: fence on success, negative ERR_PTR on error.
2624  */
2625 struct dma_fence *
2626 xe_pt_update_ops_run(struct xe_tile *tile, struct xe_vma_ops *vops)
2627 {
2628 	struct xe_vm *vm = vops->vm;
2629 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2630 		&vops->pt_update_ops[tile->id];
2631 	struct xe_exec_queue *q = pt_update_ops->q;
2632 	struct dma_fence *fence, *ifence = NULL, *mfence = NULL;
2633 	struct xe_tlb_inval_job *ijob = NULL, *mjob = NULL;
2634 	struct xe_range_fence *rfence;
2635 	struct xe_vma_op *op;
2636 	int err = 0, i;
2637 	struct xe_migrate_pt_update update = {
2638 		.ops = pt_update_ops->needs_svm_lock ?
2639 			&svm_userptr_migrate_ops :
2640 			&migrate_ops,
2641 		.vops = vops,
2642 		.tile_id = tile->id,
2643 	};
2644 
2645 	lockdep_assert_held(&vm->lock);
2646 	xe_vm_assert_held(vm);
2647 
2648 	if (!pt_update_ops->current_op) {
2649 		xe_tile_assert(tile, xe_vm_in_fault_mode(vm));
2650 
2651 		return dma_fence_get_stub();
2652 	}
2653 
2654 #ifdef TEST_VM_OPS_ERROR
2655 	if (vops->inject_error &&
2656 	    vm->xe->vm_inject_error_position == FORCE_OP_ERROR_RUN)
2657 		return ERR_PTR(-ENOSPC);
2658 #endif
2659 
2660 	if (pt_update_ops->needs_invalidation) {
2661 		struct xe_dep_scheduler *dep_scheduler =
2662 			to_dep_scheduler(q, tile->primary_gt);
2663 
2664 		ijob = xe_tlb_inval_job_create(q, &tile->primary_gt->tlb_inval,
2665 					       dep_scheduler, vm,
2666 					       pt_update_ops->start,
2667 					       pt_update_ops->last,
2668 					       XE_EXEC_QUEUE_TLB_INVAL_PRIMARY_GT);
2669 		if (IS_ERR(ijob)) {
2670 			err = PTR_ERR(ijob);
2671 			goto kill_vm_tile1;
2672 		}
2673 		update.ijob = ijob;
2674 		/*
2675 		 * Only add page reclaim for the primary GT. Media GT does not have
2676 		 * any PPC to flush, so enabling the PPC flush bit for media is
2677 		 * effectively a NOP and provides no performance benefit nor
2678 		 * interfere with primary GT.
2679 		 */
2680 		if (xe_page_reclaim_list_valid(&pt_update_ops->prl)) {
2681 			xe_tlb_inval_job_add_page_reclaim(ijob, &pt_update_ops->prl);
2682 			/* Release ref from alloc, job will now handle it */
2683 			xe_page_reclaim_list_invalidate(&pt_update_ops->prl);
2684 		}
2685 
2686 		if (tile->media_gt) {
2687 			dep_scheduler = to_dep_scheduler(q, tile->media_gt);
2688 
2689 			mjob = xe_tlb_inval_job_create(q,
2690 						       &tile->media_gt->tlb_inval,
2691 						       dep_scheduler, vm,
2692 						       pt_update_ops->start,
2693 						       pt_update_ops->last,
2694 						       XE_EXEC_QUEUE_TLB_INVAL_MEDIA_GT);
2695 			if (IS_ERR(mjob)) {
2696 				err = PTR_ERR(mjob);
2697 				goto free_ijob;
2698 			}
2699 			update.mjob = mjob;
2700 		}
2701 	}
2702 
2703 	rfence = kzalloc_obj(*rfence);
2704 	if (!rfence) {
2705 		err = -ENOMEM;
2706 		goto free_ijob;
2707 	}
2708 
2709 	fence = xe_migrate_update_pgtables(tile->migrate, &update);
2710 	if (IS_ERR(fence)) {
2711 		err = PTR_ERR(fence);
2712 		goto free_rfence;
2713 	}
2714 
2715 	/* Point of no return - VM killed if failure after this */
2716 	for (i = 0; i < pt_update_ops->current_op; ++i) {
2717 		struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[i];
2718 
2719 		xe_pt_commit(pt_op->vma, pt_op->entries,
2720 			     pt_op->num_entries, &pt_update_ops->deferred);
2721 		pt_op->vma = NULL;	/* skip in xe_pt_update_ops_abort */
2722 	}
2723 
2724 	if (xe_range_fence_insert(&vm->rftree[tile->id], rfence,
2725 				  &xe_range_fence_kfree_ops,
2726 				  pt_update_ops->start,
2727 				  pt_update_ops->last, fence))
2728 		dma_fence_wait(fence, false);
2729 
2730 	if (ijob)
2731 		ifence = xe_tlb_inval_job_push(ijob, tile->migrate, fence);
2732 	if (mjob)
2733 		mfence = xe_tlb_inval_job_push(mjob, tile->migrate, fence);
2734 
2735 	if (!mjob && !ijob) {
2736 		dma_resv_add_fence(xe_vm_resv(vm), fence,
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, fence, NULL);
2743 	} else if (ijob && !mjob) {
2744 		dma_resv_add_fence(xe_vm_resv(vm), ifence,
2745 				   pt_update_ops->wait_vm_bookkeep ?
2746 				   DMA_RESV_USAGE_KERNEL :
2747 				   DMA_RESV_USAGE_BOOKKEEP);
2748 
2749 		list_for_each_entry(op, &vops->list, link)
2750 			op_commit(vops->vm, tile, pt_update_ops, op, ifence, NULL);
2751 	} else {
2752 		dma_resv_add_fence(xe_vm_resv(vm), ifence,
2753 				   pt_update_ops->wait_vm_bookkeep ?
2754 				   DMA_RESV_USAGE_KERNEL :
2755 				   DMA_RESV_USAGE_BOOKKEEP);
2756 
2757 		dma_resv_add_fence(xe_vm_resv(vm), mfence,
2758 				   pt_update_ops->wait_vm_bookkeep ?
2759 				   DMA_RESV_USAGE_KERNEL :
2760 				   DMA_RESV_USAGE_BOOKKEEP);
2761 
2762 		list_for_each_entry(op, &vops->list, link)
2763 			op_commit(vops->vm, tile, pt_update_ops, op, ifence,
2764 				  mfence);
2765 	}
2766 
2767 	if (pt_update_ops->needs_svm_lock)
2768 		xe_pt_svm_userptr_notifier_unlock(vm);
2769 
2770 	/*
2771 	 * The last fence is only used for zero bind queue idling; migrate
2772 	 * queues are not exposed to user space.
2773 	 */
2774 	if (!(q->flags & EXEC_QUEUE_FLAG_MIGRATE))
2775 		xe_exec_queue_last_fence_set(q, vm, fence);
2776 
2777 	xe_tlb_inval_job_put(mjob);
2778 	xe_tlb_inval_job_put(ijob);
2779 	dma_fence_put(ifence);
2780 	dma_fence_put(mfence);
2781 
2782 	return fence;
2783 
2784 free_rfence:
2785 	kfree(rfence);
2786 free_ijob:
2787 	xe_tlb_inval_job_put(mjob);
2788 	xe_tlb_inval_job_put(ijob);
2789 kill_vm_tile1:
2790 	if (err != -EAGAIN && err != -ENODATA && tile->id)
2791 		xe_vm_kill(vops->vm, false);
2792 
2793 	return ERR_PTR(err);
2794 }
2795 ALLOW_ERROR_INJECTION(xe_pt_update_ops_run, ERRNO);
2796 
2797 /**
2798  * xe_pt_update_ops_fini() - Finish PT update operations
2799  * @tile: Tile of PT update operations
2800  * @vops: VMA operations
2801  *
2802  * Finish PT update operations by committing to destroy page table memory
2803  */
2804 void xe_pt_update_ops_fini(struct xe_tile *tile, struct xe_vma_ops *vops)
2805 {
2806 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2807 		&vops->pt_update_ops[tile->id];
2808 	int i;
2809 
2810 	xe_page_reclaim_entries_put(pt_update_ops->prl.entries);
2811 
2812 	lockdep_assert_held(&vops->vm->lock);
2813 	xe_vm_assert_held(vops->vm);
2814 
2815 	for (i = 0; i < pt_update_ops->current_op; ++i) {
2816 		struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[i];
2817 
2818 		xe_pt_free_bind(pt_op->entries, pt_op->num_entries);
2819 	}
2820 	xe_bo_put_commit(&vops->pt_update_ops[tile->id].deferred);
2821 }
2822 
2823 /**
2824  * xe_pt_update_ops_abort() - Abort PT update operations
2825  * @tile: Tile of PT update operations
2826  * @vops: VMA operationa
2827  *
2828  *  Abort PT update operations by unwinding internal PT state
2829  */
2830 void xe_pt_update_ops_abort(struct xe_tile *tile, struct xe_vma_ops *vops)
2831 {
2832 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2833 		&vops->pt_update_ops[tile->id];
2834 	int i;
2835 
2836 	lockdep_assert_held(&vops->vm->lock);
2837 	xe_vm_assert_held(vops->vm);
2838 
2839 	for (i = pt_update_ops->num_ops - 1; i >= 0; --i) {
2840 		struct xe_vm_pgtable_update_op *pt_op =
2841 			&pt_update_ops->ops[i];
2842 
2843 		if (!pt_op->vma || i >= pt_update_ops->current_op)
2844 			continue;
2845 
2846 		if (pt_op->bind)
2847 			xe_pt_abort_bind(pt_op->vma, pt_op->entries,
2848 					 pt_op->num_entries,
2849 					 pt_op->rebind);
2850 		else
2851 			xe_pt_abort_unbind(pt_op->vma, pt_op->entries,
2852 					   pt_op->num_entries);
2853 	}
2854 
2855 	xe_pt_update_ops_fini(tile, vops);
2856 }
2857