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