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