xref: /linux/drivers/gpu/drm/xe/xe_pt.c (revision dc9ccf14dc2ad44e3df4928015923735f0101bfd)
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 /* page_size = 2^(reclamation_size + XE_PTE_SHIFT) */
1606 #define COMPUTE_RECLAIM_ADDRESS_MASK(page_size)				\
1607 ({									\
1608 	BUILD_BUG_ON(!__builtin_constant_p(page_size));			\
1609 	ilog2(page_size) - XE_PTE_SHIFT;				\
1610 })
1611 
1612 static int generate_reclaim_entry(struct xe_tile *tile,
1613 				  struct xe_page_reclaim_list *prl,
1614 				  u64 pte, struct xe_pt *xe_child)
1615 {
1616 	struct xe_gt *gt = tile->primary_gt;
1617 	struct xe_guc_page_reclaim_entry *reclaim_entries = prl->entries;
1618 	u64 phys_addr = pte & XE_PTE_ADDR_MASK;
1619 	u64 phys_page = phys_addr >> XE_PTE_SHIFT;
1620 	int num_entries = prl->num_entries;
1621 	u32 reclamation_size;
1622 
1623 	xe_tile_assert(tile, xe_child->level <= MAX_HUGEPTE_LEVEL);
1624 	xe_tile_assert(tile, reclaim_entries);
1625 	xe_tile_assert(tile, num_entries < XE_PAGE_RECLAIM_MAX_ENTRIES - 1);
1626 
1627 	if (!xe_page_reclaim_list_valid(prl))
1628 		return -EINVAL;
1629 
1630 	/**
1631 	 * reclamation_size indicates the size of the page to be
1632 	 * invalidated and flushed from non-coherent cache.
1633 	 * Page size is computed as 2^(reclamation_size + XE_PTE_SHIFT) bytes.
1634 	 * Only 4K, 64K (level 0), and 2M pages are supported by hardware for page reclaim
1635 	 */
1636 	if (xe_child->level == 0 && !(pte & XE_PTE_PS64)) {
1637 		xe_gt_stats_incr(gt, XE_GT_STATS_ID_PRL_4K_ENTRY_COUNT, 1);
1638 		reclamation_size = COMPUTE_RECLAIM_ADDRESS_MASK(SZ_4K);  /* reclamation_size = 0 */
1639 		xe_tile_assert(tile, phys_addr % SZ_4K == 0);
1640 	} else if (xe_child->level == 0) {
1641 		xe_gt_stats_incr(gt, XE_GT_STATS_ID_PRL_64K_ENTRY_COUNT, 1);
1642 		reclamation_size = COMPUTE_RECLAIM_ADDRESS_MASK(SZ_64K); /* reclamation_size = 4 */
1643 		xe_tile_assert(tile, phys_addr % SZ_64K == 0);
1644 	} else if (xe_child->level == 1 && pte & XE_PDE_PS_2M) {
1645 		xe_gt_stats_incr(gt, XE_GT_STATS_ID_PRL_2M_ENTRY_COUNT, 1);
1646 		reclamation_size = COMPUTE_RECLAIM_ADDRESS_MASK(SZ_2M);  /* reclamation_size = 9 */
1647 		xe_tile_assert(tile, phys_addr % SZ_2M == 0);
1648 	} else {
1649 		xe_page_reclaim_list_abort(tile->primary_gt, prl,
1650 					   "unsupported PTE level=%u pte=%#llx",
1651 					   xe_child->level, pte);
1652 		return -EINVAL;
1653 	}
1654 
1655 	reclaim_entries[num_entries].qw =
1656 		FIELD_PREP(XE_PAGE_RECLAIM_VALID, 1) |
1657 		FIELD_PREP(XE_PAGE_RECLAIM_SIZE, reclamation_size) |
1658 		FIELD_PREP(XE_PAGE_RECLAIM_ADDR_LO, phys_page) |
1659 		FIELD_PREP(XE_PAGE_RECLAIM_ADDR_HI, phys_page >> 20);
1660 	prl->num_entries++;
1661 	vm_dbg(&tile_to_xe(tile)->drm,
1662 	       "PRL add entry: level=%u pte=%#llx reclamation_size=%u prl_idx=%d\n",
1663 	       xe_child->level, pte, reclamation_size, num_entries);
1664 
1665 	return 0;
1666 }
1667 
1668 static int xe_pt_stage_unbind_entry(struct xe_ptw *parent, pgoff_t offset,
1669 				    unsigned int level, u64 addr, u64 next,
1670 				    struct xe_ptw **child,
1671 				    enum page_walk_action *action,
1672 				    struct xe_pt_walk *walk)
1673 {
1674 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
1675 	struct xe_pt_stage_unbind_walk *xe_walk =
1676 		container_of(walk, typeof(*xe_walk), base);
1677 	struct xe_device *xe = tile_to_xe(xe_walk->tile);
1678 	pgoff_t first = xe_pt_offset(addr, xe_child->level, walk);
1679 	bool killed;
1680 
1681 	XE_WARN_ON(!*child);
1682 	XE_WARN_ON(!level);
1683 	/* Check for leaf node */
1684 	if (xe_walk->prl && xe_page_reclaim_list_valid(xe_walk->prl) &&
1685 	    xe_child->level <= MAX_HUGEPTE_LEVEL) {
1686 		struct iosys_map *leaf_map = &xe_child->bo->vmap;
1687 		pgoff_t count = xe_pt_num_entries(addr, next, xe_child->level, walk);
1688 
1689 		for (pgoff_t i = 0; i < count; i++) {
1690 			u64 pte;
1691 			int ret;
1692 
1693 			/*
1694 			 * If not a leaf pt, skip unless non-leaf pt is interleaved between
1695 			 * leaf ptes which causes the page walk to skip over the child leaves
1696 			 */
1697 			if (xe_child->base.children && xe_child->base.children[first + i]) {
1698 				u64 pt_size = 1ULL << walk->shifts[xe_child->level];
1699 				bool edge_pt = (i == 0 && !IS_ALIGNED(addr, pt_size)) ||
1700 					       (i == count - 1 && !IS_ALIGNED(next, pt_size));
1701 
1702 				if (!edge_pt) {
1703 					xe_page_reclaim_list_abort(xe_walk->tile->primary_gt,
1704 								   xe_walk->prl,
1705 								   "PT is skipped by walk at level=%u offset=%lu",
1706 								   xe_child->level, first + i);
1707 					break;
1708 				}
1709 				continue;
1710 			}
1711 
1712 			pte = xe_map_rd(xe, leaf_map, (first + i) * sizeof(u64), u64);
1713 
1714 			/*
1715 			 * In rare scenarios, pte may not be written yet due to racy conditions.
1716 			 * In such cases, invalidate the PRL and fallback to full PPC invalidation.
1717 			 */
1718 			if (!pte) {
1719 				xe_page_reclaim_list_abort(xe_walk->tile->primary_gt, xe_walk->prl,
1720 							   "found zero pte at addr=%#llx", addr);
1721 				break;
1722 			}
1723 
1724 			/* Ensure it is a defined page */
1725 			xe_tile_assert(xe_walk->tile, xe_child->level == 0 ||
1726 				       (pte & (XE_PDE_PS_2M | XE_PDPE_PS_1G)));
1727 
1728 			/* An entry should be added for 64KB but contigious 4K have XE_PTE_PS64 */
1729 			if (pte & XE_PTE_PS64)
1730 				i += 15; /* Skip other 15 consecutive 4K pages in the 64K page */
1731 
1732 			/* Account for NULL terminated entry on end (-1) */
1733 			if (xe_walk->prl->num_entries < XE_PAGE_RECLAIM_MAX_ENTRIES - 1) {
1734 				ret = generate_reclaim_entry(xe_walk->tile, xe_walk->prl,
1735 							     pte, xe_child);
1736 				if (ret)
1737 					break;
1738 			} else {
1739 				/* overflow, mark as invalid */
1740 				xe_page_reclaim_list_abort(xe_walk->tile->primary_gt, xe_walk->prl,
1741 							   "overflow while adding pte=%#llx",
1742 							   pte);
1743 				break;
1744 			}
1745 		}
1746 	}
1747 
1748 	killed = xe_pt_check_kill(addr, next, level - 1, xe_child, action, walk);
1749 
1750 	/*
1751 	 * Verify if any PTE are potentially dropped at non-leaf levels, either from being
1752 	 * killed or the page walk covers the region.
1753 	 */
1754 	if (xe_walk->prl && xe_page_reclaim_list_valid(xe_walk->prl) &&
1755 	    xe_child->level > MAX_HUGEPTE_LEVEL && xe_child->num_live) {
1756 		bool covered = xe_pt_covers(addr, next, xe_child->level, &xe_walk->base);
1757 
1758 		/*
1759 		 * If aborting page walk early (kill) or page walk completes the full range
1760 		 * we need to invalidate the PRL.
1761 		 */
1762 		if (killed || covered)
1763 			xe_page_reclaim_list_abort(xe_walk->tile->primary_gt, xe_walk->prl,
1764 						   "kill at level=%u addr=%#llx next=%#llx num_live=%u",
1765 						   level, addr, next, xe_child->num_live);
1766 	}
1767 
1768 	return 0;
1769 }
1770 
1771 static int
1772 xe_pt_stage_unbind_post_descend(struct xe_ptw *parent, pgoff_t offset,
1773 				unsigned int level, u64 addr, u64 next,
1774 				struct xe_ptw **child,
1775 				enum page_walk_action *action,
1776 				struct xe_pt_walk *walk)
1777 {
1778 	struct xe_pt_stage_unbind_walk *xe_walk =
1779 		container_of(walk, typeof(*xe_walk), base);
1780 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
1781 	pgoff_t end_offset;
1782 	u64 size = 1ull << walk->shifts[--level];
1783 	int err;
1784 
1785 	if (!IS_ALIGNED(addr, size))
1786 		addr = xe_walk->modified_start;
1787 	if (!IS_ALIGNED(next, size))
1788 		next = xe_walk->modified_end;
1789 
1790 	/* Parent == *child is the root pt. Don't kill it. */
1791 	if (parent != *child &&
1792 	    xe_pt_check_kill(addr, next, level, xe_child, action, walk))
1793 		return 0;
1794 
1795 	if (!xe_pt_nonshared_offsets(addr, next, level, walk, action, &offset,
1796 				     &end_offset))
1797 		return 0;
1798 
1799 	err = xe_pt_new_shared(&xe_walk->wupd, xe_child, offset, true);
1800 	if (err)
1801 		return err;
1802 
1803 	xe_walk->wupd.updates[level].update->qwords = end_offset - offset;
1804 
1805 	return 0;
1806 }
1807 
1808 static const struct xe_pt_walk_ops xe_pt_stage_unbind_ops = {
1809 	.pt_entry = xe_pt_stage_unbind_entry,
1810 	.pt_post_descend = xe_pt_stage_unbind_post_descend,
1811 };
1812 
1813 /**
1814  * xe_pt_stage_unbind() - Build page-table update structures for an unbind
1815  * operation
1816  * @tile: The tile we're unbinding for.
1817  * @vm: The vm
1818  * @vma: The vma we're unbinding.
1819  * @range: The range we're unbinding.
1820  * @entries: Caller-provided storage for the update structures.
1821  *
1822  * Builds page-table update structures for an unbind operation. The function
1823  * will attempt to remove all page-tables that we're the only user
1824  * of, and for that to work, the unbind operation must be committed in the
1825  * same critical section that blocks racing binds to the same page-table tree.
1826  *
1827  * Return: The number of entries used.
1828  */
1829 static unsigned int xe_pt_stage_unbind(struct xe_tile *tile,
1830 				       struct xe_vm *vm,
1831 				       struct xe_vma *vma,
1832 				       struct xe_svm_range *range,
1833 				       struct xe_vm_pgtable_update *entries)
1834 {
1835 	u64 start = range ? xe_svm_range_start(range) : xe_vma_start(vma);
1836 	u64 end = range ? xe_svm_range_end(range) : xe_vma_end(vma);
1837 	struct xe_vm_pgtable_update_op *pt_update_op =
1838 		container_of(entries, struct xe_vm_pgtable_update_op, entries[0]);
1839 	struct xe_pt_stage_unbind_walk xe_walk = {
1840 		.base = {
1841 			.ops = &xe_pt_stage_unbind_ops,
1842 			.shifts = xe_normal_pt_shifts,
1843 			.max_level = XE_PT_HIGHEST_LEVEL,
1844 			.staging = true,
1845 		},
1846 		.tile = tile,
1847 		.modified_start = start,
1848 		.modified_end = end,
1849 		.wupd.entries = entries,
1850 		.prl = pt_update_op->prl,
1851 	};
1852 	struct xe_pt *pt = vm->pt_root[tile->id];
1853 
1854 	(void)xe_pt_walk_shared(&pt->base, pt->level, start, end,
1855 				&xe_walk.base);
1856 
1857 	return xe_walk.wupd.num_used_entries;
1858 }
1859 
1860 static void
1861 xe_migrate_clear_pgtable_callback(struct xe_migrate_pt_update *pt_update,
1862 				  struct xe_tile *tile, struct iosys_map *map,
1863 				  void *ptr, u32 qword_ofs, u32 num_qwords,
1864 				  const struct xe_vm_pgtable_update *update)
1865 {
1866 	struct xe_vm *vm = pt_update->vops->vm;
1867 	u64 empty = __xe_pt_empty_pte(tile, vm, update->pt->level);
1868 	int i;
1869 
1870 	if (map && map->is_iomem)
1871 		for (i = 0; i < num_qwords; ++i)
1872 			xe_map_wr(tile_to_xe(tile), map, (qword_ofs + i) *
1873 				  sizeof(u64), u64, empty);
1874 	else if (map)
1875 		memset64(map->vaddr + qword_ofs * sizeof(u64), empty,
1876 			 num_qwords);
1877 	else
1878 		memset64(ptr, empty, num_qwords);
1879 }
1880 
1881 static void xe_pt_abort_unbind(struct xe_vma *vma,
1882 			       struct xe_vm_pgtable_update *entries,
1883 			       u32 num_entries)
1884 {
1885 	int i, j;
1886 
1887 	xe_pt_commit_prepare_locks_assert(vma);
1888 
1889 	for (i = num_entries - 1; i >= 0; --i) {
1890 		struct xe_vm_pgtable_update *entry = &entries[i];
1891 		struct xe_pt *pt = entry->pt;
1892 		struct xe_pt_dir *pt_dir = as_xe_pt_dir(pt);
1893 
1894 		pt->num_live += entry->qwords;
1895 
1896 		if (!pt->level)
1897 			continue;
1898 
1899 		for (j = entry->ofs; j < entry->ofs + entry->qwords; j++)
1900 			pt_dir->staging[j] =
1901 				entries[i].pt_entries[j - entry->ofs].pt ?
1902 				&entries[i].pt_entries[j - entry->ofs].pt->base : NULL;
1903 	}
1904 }
1905 
1906 static void
1907 xe_pt_commit_prepare_unbind(struct xe_vma *vma,
1908 			    struct xe_vm_pgtable_update *entries,
1909 			    u32 num_entries)
1910 {
1911 	int i, j;
1912 
1913 	xe_pt_commit_prepare_locks_assert(vma);
1914 
1915 	for (i = 0; i < num_entries; ++i) {
1916 		struct xe_vm_pgtable_update *entry = &entries[i];
1917 		struct xe_pt *pt = entry->pt;
1918 		struct xe_pt_dir *pt_dir;
1919 
1920 		pt->num_live -= entry->qwords;
1921 		if (!pt->level)
1922 			continue;
1923 
1924 		pt_dir = as_xe_pt_dir(pt);
1925 		for (j = entry->ofs; j < entry->ofs + entry->qwords; j++) {
1926 			entry->pt_entries[j - entry->ofs].pt =
1927 				xe_pt_entry_staging(pt_dir, j);
1928 			pt_dir->staging[j] = NULL;
1929 		}
1930 	}
1931 }
1932 
1933 static void
1934 xe_pt_update_ops_rfence_interval(struct xe_vm_pgtable_update_ops *pt_update_ops,
1935 				 u64 start, u64 end)
1936 {
1937 	u64 last;
1938 	u32 current_op = pt_update_ops->current_op;
1939 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
1940 	int i, level = 0;
1941 
1942 	for (i = 0; i < pt_op->num_entries; i++) {
1943 		const struct xe_vm_pgtable_update *entry = &pt_op->entries[i];
1944 
1945 		if (entry->pt->level > level)
1946 			level = entry->pt->level;
1947 	}
1948 
1949 	/* Greedy (non-optimal) calculation but simple */
1950 	start = ALIGN_DOWN(start, 0x1ull << xe_pt_shift(level));
1951 	last = ALIGN(end, 0x1ull << xe_pt_shift(level)) - 1;
1952 
1953 	if (start < pt_update_ops->start)
1954 		pt_update_ops->start = start;
1955 	if (last > pt_update_ops->last)
1956 		pt_update_ops->last = last;
1957 }
1958 
1959 static int vma_reserve_fences(struct xe_device *xe, struct xe_vma *vma)
1960 {
1961 	int shift = xe_device_get_root_tile(xe)->media_gt ? 1 : 0;
1962 
1963 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm)
1964 		return dma_resv_reserve_fences(xe_vma_bo(vma)->ttm.base.resv,
1965 					       xe->info.tile_count << shift);
1966 
1967 	return 0;
1968 }
1969 
1970 static int bind_op_prepare(struct xe_vm *vm, struct xe_tile *tile,
1971 			   struct xe_vm_pgtable_update_ops *pt_update_ops,
1972 			   struct xe_vma *vma, bool invalidate_on_bind)
1973 {
1974 	u32 current_op = pt_update_ops->current_op;
1975 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
1976 	int err;
1977 
1978 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
1979 	xe_bo_assert_held(xe_vma_bo(vma));
1980 
1981 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
1982 	       "Preparing bind, with range [%llx...%llx)\n",
1983 	       xe_vma_start(vma), xe_vma_end(vma) - 1);
1984 
1985 	pt_op->vma = NULL;
1986 	pt_op->bind = true;
1987 	pt_op->rebind = BIT(tile->id) & vma->tile_present;
1988 
1989 	err = vma_reserve_fences(tile_to_xe(tile), vma);
1990 	if (err)
1991 		return err;
1992 
1993 	err = xe_pt_prepare_bind(tile, vma, NULL, pt_op->entries,
1994 				 &pt_op->num_entries, invalidate_on_bind);
1995 	if (!err) {
1996 		xe_tile_assert(tile, pt_op->num_entries <=
1997 			       ARRAY_SIZE(pt_op->entries));
1998 		xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
1999 					pt_op->num_entries, true);
2000 
2001 		xe_pt_update_ops_rfence_interval(pt_update_ops,
2002 						 xe_vma_start(vma),
2003 						 xe_vma_end(vma));
2004 		++pt_update_ops->current_op;
2005 		pt_update_ops->needs_svm_lock |= xe_vma_is_userptr(vma);
2006 
2007 		/*
2008 		 * If rebind, we have to invalidate TLB on !LR vms to invalidate
2009 		 * cached PTEs point to freed memory. On LR vms this is done
2010 		 * automatically when the context is re-enabled by the rebind worker,
2011 		 * or in fault mode it was invalidated on PTE zapping.
2012 		 *
2013 		 * If !rebind, and scratch enabled VMs, there is a chance the scratch
2014 		 * PTE is already cached in the TLB so it needs to be invalidated.
2015 		 * On !LR VMs this is done in the ring ops preceding a batch, but on
2016 		 * LR, in particular on user-space batch buffer chaining, it needs to
2017 		 * be done here.
2018 		 */
2019 		if ((!pt_op->rebind && xe_vm_has_scratch(vm) &&
2020 		     xe_vm_in_lr_mode(vm)))
2021 			pt_update_ops->needs_invalidation = true;
2022 		else if (pt_op->rebind && !xe_vm_in_lr_mode(vm))
2023 			/* We bump also if batch_invalidate_tlb is true */
2024 			vm->tlb_flush_seqno++;
2025 
2026 		vma->tile_staged |= BIT(tile->id);
2027 		pt_op->vma = vma;
2028 		xe_pt_commit_prepare_bind(vma, pt_op->entries,
2029 					  pt_op->num_entries, pt_op->rebind);
2030 	} else {
2031 		xe_pt_cancel_bind(vma, pt_op->entries, pt_op->num_entries);
2032 	}
2033 
2034 	return err;
2035 }
2036 
2037 static int bind_range_prepare(struct xe_vm *vm, struct xe_tile *tile,
2038 			      struct xe_vm_pgtable_update_ops *pt_update_ops,
2039 			      struct xe_vma *vma, struct xe_svm_range *range)
2040 {
2041 	u32 current_op = pt_update_ops->current_op;
2042 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
2043 	int err;
2044 
2045 	xe_tile_assert(tile, xe_vma_is_cpu_addr_mirror(vma));
2046 
2047 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
2048 	       "Preparing bind, with range [%lx...%lx)\n",
2049 	       xe_svm_range_start(range), xe_svm_range_end(range) - 1);
2050 
2051 	pt_op->vma = NULL;
2052 	pt_op->bind = true;
2053 	pt_op->rebind = BIT(tile->id) & range->tile_present;
2054 
2055 	err = xe_pt_prepare_bind(tile, vma, range, pt_op->entries,
2056 				 &pt_op->num_entries, false);
2057 	if (!err) {
2058 		xe_tile_assert(tile, pt_op->num_entries <=
2059 			       ARRAY_SIZE(pt_op->entries));
2060 		xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
2061 					pt_op->num_entries, true);
2062 
2063 		xe_pt_update_ops_rfence_interval(pt_update_ops,
2064 						 xe_svm_range_start(range),
2065 						 xe_svm_range_end(range));
2066 		++pt_update_ops->current_op;
2067 		pt_update_ops->needs_svm_lock = true;
2068 
2069 		pt_op->vma = vma;
2070 		xe_pt_commit_prepare_bind(vma, pt_op->entries,
2071 					  pt_op->num_entries, pt_op->rebind);
2072 	} else {
2073 		xe_pt_cancel_bind(vma, pt_op->entries, pt_op->num_entries);
2074 	}
2075 
2076 	return err;
2077 }
2078 
2079 static int unbind_op_prepare(struct xe_tile *tile,
2080 			     struct xe_vm_pgtable_update_ops *pt_update_ops,
2081 			     struct xe_vma *vma)
2082 {
2083 	struct xe_device *xe = tile_to_xe(tile);
2084 	u32 current_op = pt_update_ops->current_op;
2085 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
2086 	int err;
2087 
2088 	if (!((vma->tile_present | vma->tile_staged) & BIT(tile->id)))
2089 		return 0;
2090 
2091 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2092 	xe_bo_assert_held(xe_vma_bo(vma));
2093 
2094 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
2095 	       "Preparing unbind, with range [%llx...%llx)\n",
2096 	       xe_vma_start(vma), xe_vma_end(vma) - 1);
2097 
2098 	pt_op->vma = vma;
2099 	pt_op->bind = false;
2100 	pt_op->rebind = false;
2101 	/*
2102 	 * Maintain one PRL located in pt_update_ops that all others in unbind op reference.
2103 	 * Ensure that PRL is allocated only once, and if invalidated, remains an invalidated PRL.
2104 	 */
2105 	if (xe->info.has_page_reclaim_hw_assist &&
2106 	    xe_page_reclaim_list_is_new(&pt_update_ops->prl))
2107 		xe_page_reclaim_list_alloc_entries(&pt_update_ops->prl);
2108 
2109 	/* Page reclaim may not be needed due to other features, so skip the corresponding VMA */
2110 	pt_op->prl = (xe_page_reclaim_list_valid(&pt_update_ops->prl) &&
2111 		     !xe_page_reclaim_skip(tile, vma)) ? &pt_update_ops->prl : NULL;
2112 
2113 	err = vma_reserve_fences(tile_to_xe(tile), vma);
2114 	if (err)
2115 		return err;
2116 
2117 	pt_op->num_entries = xe_pt_stage_unbind(tile, xe_vma_vm(vma),
2118 						vma, NULL, pt_op->entries);
2119 
2120 	xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
2121 				pt_op->num_entries, false);
2122 	xe_pt_update_ops_rfence_interval(pt_update_ops, xe_vma_start(vma),
2123 					 xe_vma_end(vma));
2124 	++pt_update_ops->current_op;
2125 	pt_update_ops->needs_svm_lock |= xe_vma_is_userptr(vma);
2126 	pt_update_ops->needs_invalidation = true;
2127 
2128 	xe_pt_commit_prepare_unbind(vma, pt_op->entries, pt_op->num_entries);
2129 
2130 	return 0;
2131 }
2132 
2133 static bool
2134 xe_pt_op_check_range_skip_invalidation(struct xe_vm_pgtable_update_op *pt_op,
2135 				       struct xe_svm_range *range)
2136 {
2137 	struct xe_vm_pgtable_update *update = pt_op->entries;
2138 
2139 	XE_WARN_ON(!pt_op->num_entries);
2140 
2141 	/*
2142 	 * We can't skip the invalidation if we are removing PTEs that span more
2143 	 * than the range, do some checks to ensure we are removing PTEs that
2144 	 * are invalid.
2145 	 */
2146 
2147 	if (pt_op->num_entries > 1)
2148 		return false;
2149 
2150 	if (update->pt->level == 0)
2151 		return true;
2152 
2153 	if (update->pt->level == 1)
2154 		return xe_svm_range_size(range) >= SZ_2M;
2155 
2156 	return false;
2157 }
2158 
2159 static int unbind_range_prepare(struct xe_vm *vm,
2160 				struct xe_tile *tile,
2161 				struct xe_vm_pgtable_update_ops *pt_update_ops,
2162 				struct xe_svm_range *range)
2163 {
2164 	u32 current_op = pt_update_ops->current_op;
2165 	struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[current_op];
2166 
2167 	if (!(range->tile_present & BIT(tile->id)))
2168 		return 0;
2169 
2170 	vm_dbg(&vm->xe->drm,
2171 	       "Preparing unbind, with range [%lx...%lx)\n",
2172 	       xe_svm_range_start(range), xe_svm_range_end(range) - 1);
2173 
2174 	pt_op->vma = XE_INVALID_VMA;
2175 	pt_op->bind = false;
2176 	pt_op->rebind = false;
2177 	pt_op->prl = NULL;
2178 
2179 	pt_op->num_entries = xe_pt_stage_unbind(tile, vm, NULL, range,
2180 						pt_op->entries);
2181 
2182 	xe_vm_dbg_print_entries(tile_to_xe(tile), pt_op->entries,
2183 				pt_op->num_entries, false);
2184 	xe_pt_update_ops_rfence_interval(pt_update_ops, xe_svm_range_start(range),
2185 					 xe_svm_range_end(range));
2186 	++pt_update_ops->current_op;
2187 	pt_update_ops->needs_svm_lock = true;
2188 	pt_update_ops->needs_invalidation |= xe_vm_has_scratch(vm) ||
2189 		xe_vm_has_valid_gpu_mapping(tile, range->tile_present,
2190 					    range->tile_invalidated) ||
2191 		!xe_pt_op_check_range_skip_invalidation(pt_op, range);
2192 
2193 	xe_pt_commit_prepare_unbind(XE_INVALID_VMA, pt_op->entries,
2194 				    pt_op->num_entries);
2195 
2196 	return 0;
2197 }
2198 
2199 static int op_prepare(struct xe_vm *vm,
2200 		      struct xe_tile *tile,
2201 		      struct xe_vm_pgtable_update_ops *pt_update_ops,
2202 		      struct xe_vma_op *op)
2203 {
2204 	int err = 0;
2205 
2206 	xe_vm_assert_held(vm);
2207 
2208 	switch (op->base.op) {
2209 	case DRM_GPUVA_OP_MAP:
2210 		if ((!op->map.immediate && xe_vm_in_fault_mode(vm) &&
2211 		     !op->map.invalidate_on_bind) ||
2212 		    (op->map.vma_flags & XE_VMA_SYSTEM_ALLOCATOR))
2213 			break;
2214 
2215 		err = bind_op_prepare(vm, tile, pt_update_ops, op->map.vma,
2216 				      op->map.invalidate_on_bind);
2217 		pt_update_ops->wait_vm_kernel = true;
2218 		break;
2219 	case DRM_GPUVA_OP_REMAP:
2220 	{
2221 		struct xe_vma *old = gpuva_to_vma(op->base.remap.unmap->va);
2222 
2223 		if (xe_vma_is_cpu_addr_mirror(old))
2224 			break;
2225 
2226 		err = unbind_op_prepare(tile, pt_update_ops, old);
2227 
2228 		if (!err && op->remap.prev && !op->remap.skip_prev) {
2229 			err = bind_op_prepare(vm, tile, pt_update_ops,
2230 					      op->remap.prev, false);
2231 			pt_update_ops->wait_vm_bookkeep = true;
2232 		}
2233 		if (!err && op->remap.next && !op->remap.skip_next) {
2234 			err = bind_op_prepare(vm, tile, pt_update_ops,
2235 					      op->remap.next, false);
2236 			pt_update_ops->wait_vm_bookkeep = true;
2237 		}
2238 		break;
2239 	}
2240 	case DRM_GPUVA_OP_UNMAP:
2241 	{
2242 		struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
2243 
2244 		if (xe_vma_is_cpu_addr_mirror(vma))
2245 			break;
2246 
2247 		err = unbind_op_prepare(tile, pt_update_ops, vma);
2248 		break;
2249 	}
2250 	case DRM_GPUVA_OP_PREFETCH:
2251 	{
2252 		struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2253 
2254 		if (xe_vma_is_cpu_addr_mirror(vma)) {
2255 			struct xe_svm_range *range;
2256 			unsigned long i;
2257 
2258 			xa_for_each(&op->prefetch_range.range, i, range) {
2259 				err = bind_range_prepare(vm, tile, pt_update_ops,
2260 							 vma, range);
2261 				if (err)
2262 					return err;
2263 			}
2264 		} else {
2265 			err = bind_op_prepare(vm, tile, pt_update_ops, vma, false);
2266 			pt_update_ops->wait_vm_kernel = true;
2267 		}
2268 		break;
2269 	}
2270 	case DRM_GPUVA_OP_DRIVER:
2271 		if (op->subop == XE_VMA_SUBOP_MAP_RANGE) {
2272 			xe_assert(vm->xe, xe_vma_is_cpu_addr_mirror(op->map_range.vma));
2273 
2274 			err = bind_range_prepare(vm, tile, pt_update_ops,
2275 						 op->map_range.vma,
2276 						 op->map_range.range);
2277 		} else if (op->subop == XE_VMA_SUBOP_UNMAP_RANGE) {
2278 			err = unbind_range_prepare(vm, tile, pt_update_ops,
2279 						   op->unmap_range.range);
2280 		}
2281 		break;
2282 	default:
2283 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2284 	}
2285 
2286 	return err;
2287 }
2288 
2289 static void
2290 xe_pt_update_ops_init(struct xe_vm_pgtable_update_ops *pt_update_ops)
2291 {
2292 	init_llist_head(&pt_update_ops->deferred);
2293 	pt_update_ops->start = ~0x0ull;
2294 	pt_update_ops->last = 0x0ull;
2295 	xe_page_reclaim_list_init(&pt_update_ops->prl);
2296 }
2297 
2298 /**
2299  * xe_pt_update_ops_prepare() - Prepare PT update operations
2300  * @tile: Tile of PT update operations
2301  * @vops: VMA operationa
2302  *
2303  * Prepare PT update operations which includes updating internal PT state,
2304  * allocate memory for page tables, populate page table being pruned in, and
2305  * create PT update operations for leaf insertion / removal.
2306  *
2307  * Return: 0 on success, negative error code on error.
2308  */
2309 int xe_pt_update_ops_prepare(struct xe_tile *tile, struct xe_vma_ops *vops)
2310 {
2311 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2312 		&vops->pt_update_ops[tile->id];
2313 	struct xe_vma_op *op;
2314 	int shift = tile->media_gt ? 1 : 0;
2315 	int err;
2316 
2317 	lockdep_assert_held(&vops->vm->lock);
2318 	xe_vm_assert_held(vops->vm);
2319 
2320 	xe_pt_update_ops_init(pt_update_ops);
2321 
2322 	err = dma_resv_reserve_fences(xe_vm_resv(vops->vm),
2323 				      tile_to_xe(tile)->info.tile_count << shift);
2324 	if (err)
2325 		return err;
2326 
2327 	list_for_each_entry(op, &vops->list, link) {
2328 		err = op_prepare(vops->vm, tile, pt_update_ops, op);
2329 
2330 		if (err)
2331 			return err;
2332 	}
2333 
2334 	xe_tile_assert(tile, pt_update_ops->current_op <=
2335 		       pt_update_ops->num_ops);
2336 
2337 #ifdef TEST_VM_OPS_ERROR
2338 	if (vops->inject_error &&
2339 	    vops->vm->xe->vm_inject_error_position == FORCE_OP_ERROR_PREPARE)
2340 		return -ENOSPC;
2341 #endif
2342 
2343 	return 0;
2344 }
2345 ALLOW_ERROR_INJECTION(xe_pt_update_ops_prepare, ERRNO);
2346 
2347 static void bind_op_commit(struct xe_vm *vm, struct xe_tile *tile,
2348 			   struct xe_vm_pgtable_update_ops *pt_update_ops,
2349 			   struct xe_vma *vma, struct dma_fence *fence,
2350 			   struct dma_fence *fence2, bool invalidate_on_bind)
2351 {
2352 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2353 
2354 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm) {
2355 		dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence,
2356 				   pt_update_ops->wait_vm_bookkeep ?
2357 				   DMA_RESV_USAGE_KERNEL :
2358 				   DMA_RESV_USAGE_BOOKKEEP);
2359 		if (fence2)
2360 			dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence2,
2361 					   pt_update_ops->wait_vm_bookkeep ?
2362 					   DMA_RESV_USAGE_KERNEL :
2363 					   DMA_RESV_USAGE_BOOKKEEP);
2364 	}
2365 	/* All WRITE_ONCE pair with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2366 	WRITE_ONCE(vma->tile_present, vma->tile_present | BIT(tile->id));
2367 	if (invalidate_on_bind)
2368 		WRITE_ONCE(vma->tile_invalidated,
2369 			   vma->tile_invalidated | BIT(tile->id));
2370 	else
2371 		WRITE_ONCE(vma->tile_invalidated,
2372 			   vma->tile_invalidated & ~BIT(tile->id));
2373 	vma->tile_staged &= ~BIT(tile->id);
2374 	if (xe_vma_is_userptr(vma)) {
2375 		xe_svm_assert_held_read(vm);
2376 		to_userptr_vma(vma)->userptr.initial_bind = true;
2377 	}
2378 
2379 	/*
2380 	 * Kick rebind worker if this bind triggers preempt fences and not in
2381 	 * the rebind worker
2382 	 */
2383 	if (pt_update_ops->wait_vm_bookkeep &&
2384 	    xe_vm_in_preempt_fence_mode(vm) &&
2385 	    !current->mm)
2386 		xe_vm_queue_rebind_worker(vm);
2387 }
2388 
2389 static void unbind_op_commit(struct xe_vm *vm, struct xe_tile *tile,
2390 			     struct xe_vm_pgtable_update_ops *pt_update_ops,
2391 			     struct xe_vma *vma, struct dma_fence *fence,
2392 			     struct dma_fence *fence2)
2393 {
2394 	xe_tile_assert(tile, !xe_vma_is_cpu_addr_mirror(vma));
2395 
2396 	if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm) {
2397 		dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence,
2398 				   pt_update_ops->wait_vm_bookkeep ?
2399 				   DMA_RESV_USAGE_KERNEL :
2400 				   DMA_RESV_USAGE_BOOKKEEP);
2401 		if (fence2)
2402 			dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence2,
2403 					   pt_update_ops->wait_vm_bookkeep ?
2404 					   DMA_RESV_USAGE_KERNEL :
2405 					   DMA_RESV_USAGE_BOOKKEEP);
2406 	}
2407 	vma->tile_present &= ~BIT(tile->id);
2408 	if (!vma->tile_present) {
2409 		list_del_init(&vma->combined_links.rebind);
2410 		if (xe_vma_is_userptr(vma)) {
2411 			xe_svm_assert_held_read(vm);
2412 
2413 			spin_lock(&vm->userptr.invalidated_lock);
2414 			list_del_init(&to_userptr_vma(vma)->userptr.invalidate_link);
2415 			spin_unlock(&vm->userptr.invalidated_lock);
2416 		}
2417 	}
2418 }
2419 
2420 static void range_present_and_invalidated_tile(struct xe_vm *vm,
2421 					       struct xe_svm_range *range,
2422 					       u8 tile_id)
2423 {
2424 	/* All WRITE_ONCE pair with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2425 
2426 	lockdep_assert_held(&vm->svm.gpusvm.notifier_lock);
2427 
2428 	WRITE_ONCE(range->tile_present, range->tile_present | BIT(tile_id));
2429 	WRITE_ONCE(range->tile_invalidated, range->tile_invalidated & ~BIT(tile_id));
2430 }
2431 
2432 static void op_commit(struct xe_vm *vm,
2433 		      struct xe_tile *tile,
2434 		      struct xe_vm_pgtable_update_ops *pt_update_ops,
2435 		      struct xe_vma_op *op, struct dma_fence *fence,
2436 		      struct dma_fence *fence2)
2437 {
2438 	xe_vm_assert_held(vm);
2439 
2440 	switch (op->base.op) {
2441 	case DRM_GPUVA_OP_MAP:
2442 		if ((!op->map.immediate && xe_vm_in_fault_mode(vm)) ||
2443 		    (op->map.vma_flags & XE_VMA_SYSTEM_ALLOCATOR))
2444 			break;
2445 
2446 		bind_op_commit(vm, tile, pt_update_ops, op->map.vma, fence,
2447 			       fence2, op->map.invalidate_on_bind);
2448 		break;
2449 	case DRM_GPUVA_OP_REMAP:
2450 	{
2451 		struct xe_vma *old = gpuva_to_vma(op->base.remap.unmap->va);
2452 
2453 		if (xe_vma_is_cpu_addr_mirror(old))
2454 			break;
2455 
2456 		unbind_op_commit(vm, tile, pt_update_ops, old, fence, fence2);
2457 
2458 		if (op->remap.prev && !op->remap.skip_prev)
2459 			bind_op_commit(vm, tile, pt_update_ops, op->remap.prev,
2460 				       fence, fence2, false);
2461 		if (op->remap.next && !op->remap.skip_next)
2462 			bind_op_commit(vm, tile, pt_update_ops, op->remap.next,
2463 				       fence, fence2, false);
2464 		break;
2465 	}
2466 	case DRM_GPUVA_OP_UNMAP:
2467 	{
2468 		struct xe_vma *vma = gpuva_to_vma(op->base.unmap.va);
2469 
2470 		if (!xe_vma_is_cpu_addr_mirror(vma))
2471 			unbind_op_commit(vm, tile, pt_update_ops, vma, fence,
2472 					 fence2);
2473 		break;
2474 	}
2475 	case DRM_GPUVA_OP_PREFETCH:
2476 	{
2477 		struct xe_vma *vma = gpuva_to_vma(op->base.prefetch.va);
2478 
2479 		if (xe_vma_is_cpu_addr_mirror(vma)) {
2480 			struct xe_svm_range *range = NULL;
2481 			unsigned long i;
2482 
2483 			xa_for_each(&op->prefetch_range.range, i, range)
2484 				range_present_and_invalidated_tile(vm, range, tile->id);
2485 		} else {
2486 			bind_op_commit(vm, tile, pt_update_ops, vma, fence,
2487 				       fence2, false);
2488 		}
2489 		break;
2490 	}
2491 	case DRM_GPUVA_OP_DRIVER:
2492 	{
2493 		/* WRITE_ONCE pairs with READ_ONCE in xe_vm_has_valid_gpu_mapping() */
2494 		if (op->subop == XE_VMA_SUBOP_MAP_RANGE)
2495 			range_present_and_invalidated_tile(vm, op->map_range.range, tile->id);
2496 		else if (op->subop == XE_VMA_SUBOP_UNMAP_RANGE)
2497 			WRITE_ONCE(op->unmap_range.range->tile_present,
2498 				   op->unmap_range.range->tile_present &
2499 				   ~BIT(tile->id));
2500 
2501 		break;
2502 	}
2503 	default:
2504 		drm_warn(&vm->xe->drm, "NOT POSSIBLE");
2505 	}
2506 }
2507 
2508 static const struct xe_migrate_pt_update_ops migrate_ops = {
2509 	.populate = xe_vm_populate_pgtable,
2510 	.clear = xe_migrate_clear_pgtable_callback,
2511 	.pre_commit = xe_pt_pre_commit,
2512 };
2513 
2514 #if IS_ENABLED(CONFIG_DRM_GPUSVM)
2515 static const struct xe_migrate_pt_update_ops svm_userptr_migrate_ops = {
2516 	.populate = xe_vm_populate_pgtable,
2517 	.clear = xe_migrate_clear_pgtable_callback,
2518 	.pre_commit = xe_pt_svm_userptr_pre_commit,
2519 };
2520 #else
2521 static const struct xe_migrate_pt_update_ops svm_userptr_migrate_ops;
2522 #endif
2523 
2524 static struct xe_dep_scheduler *to_dep_scheduler(struct xe_exec_queue *q,
2525 						 struct xe_gt *gt)
2526 {
2527 	if (xe_gt_is_media_type(gt))
2528 		return q->tlb_inval[XE_EXEC_QUEUE_TLB_INVAL_MEDIA_GT].dep_scheduler;
2529 
2530 	return q->tlb_inval[XE_EXEC_QUEUE_TLB_INVAL_PRIMARY_GT].dep_scheduler;
2531 }
2532 
2533 /**
2534  * xe_pt_update_ops_run() - Run PT update operations
2535  * @tile: Tile of PT update operations
2536  * @vops: VMA operationa
2537  *
2538  * Run PT update operations which includes committing internal PT state changes,
2539  * creating job for PT update operations for leaf insertion / removal, and
2540  * installing job fence in various places.
2541  *
2542  * Return: fence on success, negative ERR_PTR on error.
2543  */
2544 struct dma_fence *
2545 xe_pt_update_ops_run(struct xe_tile *tile, struct xe_vma_ops *vops)
2546 {
2547 	struct xe_vm *vm = vops->vm;
2548 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2549 		&vops->pt_update_ops[tile->id];
2550 	struct xe_exec_queue *q = pt_update_ops->q;
2551 	struct dma_fence *fence, *ifence = NULL, *mfence = NULL;
2552 	struct xe_tlb_inval_job *ijob = NULL, *mjob = NULL;
2553 	struct xe_range_fence *rfence;
2554 	struct xe_vma_op *op;
2555 	int err = 0, i;
2556 	struct xe_migrate_pt_update update = {
2557 		.ops = pt_update_ops->needs_svm_lock ?
2558 			&svm_userptr_migrate_ops :
2559 			&migrate_ops,
2560 		.vops = vops,
2561 		.tile_id = tile->id,
2562 	};
2563 
2564 	lockdep_assert_held(&vm->lock);
2565 	xe_vm_assert_held(vm);
2566 
2567 	if (!pt_update_ops->current_op) {
2568 		xe_tile_assert(tile, xe_vm_in_fault_mode(vm));
2569 
2570 		return dma_fence_get_stub();
2571 	}
2572 
2573 #ifdef TEST_VM_OPS_ERROR
2574 	if (vops->inject_error &&
2575 	    vm->xe->vm_inject_error_position == FORCE_OP_ERROR_RUN)
2576 		return ERR_PTR(-ENOSPC);
2577 #endif
2578 
2579 	if (pt_update_ops->needs_invalidation) {
2580 		struct xe_dep_scheduler *dep_scheduler =
2581 			to_dep_scheduler(q, tile->primary_gt);
2582 
2583 		ijob = xe_tlb_inval_job_create(q, &tile->primary_gt->tlb_inval,
2584 					       dep_scheduler, vm,
2585 					       pt_update_ops->start,
2586 					       pt_update_ops->last,
2587 					       XE_EXEC_QUEUE_TLB_INVAL_PRIMARY_GT);
2588 		if (IS_ERR(ijob)) {
2589 			err = PTR_ERR(ijob);
2590 			goto kill_vm_tile1;
2591 		}
2592 		update.ijob = ijob;
2593 		/*
2594 		 * Only add page reclaim for the primary GT. Media GT does not have
2595 		 * any PPC to flush, so enabling the PPC flush bit for media is
2596 		 * effectively a NOP and provides no performance benefit nor
2597 		 * interfere with primary GT.
2598 		 */
2599 		if (xe_page_reclaim_list_valid(&pt_update_ops->prl)) {
2600 			xe_tlb_inval_job_add_page_reclaim(ijob, &pt_update_ops->prl);
2601 			/* Release ref from alloc, job will now handle it */
2602 			xe_page_reclaim_list_invalidate(&pt_update_ops->prl);
2603 		}
2604 
2605 		if (tile->media_gt) {
2606 			dep_scheduler = to_dep_scheduler(q, tile->media_gt);
2607 
2608 			mjob = xe_tlb_inval_job_create(q,
2609 						       &tile->media_gt->tlb_inval,
2610 						       dep_scheduler, vm,
2611 						       pt_update_ops->start,
2612 						       pt_update_ops->last,
2613 						       XE_EXEC_QUEUE_TLB_INVAL_MEDIA_GT);
2614 			if (IS_ERR(mjob)) {
2615 				err = PTR_ERR(mjob);
2616 				goto free_ijob;
2617 			}
2618 			update.mjob = mjob;
2619 		}
2620 	}
2621 
2622 	rfence = kzalloc_obj(*rfence);
2623 	if (!rfence) {
2624 		err = -ENOMEM;
2625 		goto free_ijob;
2626 	}
2627 
2628 	fence = xe_migrate_update_pgtables(tile->migrate, &update);
2629 	if (IS_ERR(fence)) {
2630 		err = PTR_ERR(fence);
2631 		goto free_rfence;
2632 	}
2633 
2634 	/* Point of no return - VM killed if failure after this */
2635 	for (i = 0; i < pt_update_ops->current_op; ++i) {
2636 		struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[i];
2637 
2638 		xe_pt_commit(pt_op->vma, pt_op->entries,
2639 			     pt_op->num_entries, &pt_update_ops->deferred);
2640 		pt_op->vma = NULL;	/* skip in xe_pt_update_ops_abort */
2641 	}
2642 
2643 	if (xe_range_fence_insert(&vm->rftree[tile->id], rfence,
2644 				  &xe_range_fence_kfree_ops,
2645 				  pt_update_ops->start,
2646 				  pt_update_ops->last, fence))
2647 		dma_fence_wait(fence, false);
2648 
2649 	if (ijob)
2650 		ifence = xe_tlb_inval_job_push(ijob, tile->migrate, fence);
2651 	if (mjob)
2652 		mfence = xe_tlb_inval_job_push(mjob, tile->migrate, fence);
2653 
2654 	if (!mjob && !ijob) {
2655 		dma_resv_add_fence(xe_vm_resv(vm), fence,
2656 				   pt_update_ops->wait_vm_bookkeep ?
2657 				   DMA_RESV_USAGE_KERNEL :
2658 				   DMA_RESV_USAGE_BOOKKEEP);
2659 
2660 		list_for_each_entry(op, &vops->list, link)
2661 			op_commit(vops->vm, tile, pt_update_ops, op, fence, NULL);
2662 	} else if (ijob && !mjob) {
2663 		dma_resv_add_fence(xe_vm_resv(vm), ifence,
2664 				   pt_update_ops->wait_vm_bookkeep ?
2665 				   DMA_RESV_USAGE_KERNEL :
2666 				   DMA_RESV_USAGE_BOOKKEEP);
2667 
2668 		list_for_each_entry(op, &vops->list, link)
2669 			op_commit(vops->vm, tile, pt_update_ops, op, ifence, NULL);
2670 	} else {
2671 		dma_resv_add_fence(xe_vm_resv(vm), ifence,
2672 				   pt_update_ops->wait_vm_bookkeep ?
2673 				   DMA_RESV_USAGE_KERNEL :
2674 				   DMA_RESV_USAGE_BOOKKEEP);
2675 
2676 		dma_resv_add_fence(xe_vm_resv(vm), mfence,
2677 				   pt_update_ops->wait_vm_bookkeep ?
2678 				   DMA_RESV_USAGE_KERNEL :
2679 				   DMA_RESV_USAGE_BOOKKEEP);
2680 
2681 		list_for_each_entry(op, &vops->list, link)
2682 			op_commit(vops->vm, tile, pt_update_ops, op, ifence,
2683 				  mfence);
2684 	}
2685 
2686 	if (pt_update_ops->needs_svm_lock)
2687 		xe_svm_notifier_unlock(vm);
2688 
2689 	/*
2690 	 * The last fence is only used for zero bind queue idling; migrate
2691 	 * queues are not exposed to user space.
2692 	 */
2693 	if (!(q->flags & EXEC_QUEUE_FLAG_MIGRATE))
2694 		xe_exec_queue_last_fence_set(q, vm, fence);
2695 
2696 	xe_tlb_inval_job_put(mjob);
2697 	xe_tlb_inval_job_put(ijob);
2698 	dma_fence_put(ifence);
2699 	dma_fence_put(mfence);
2700 
2701 	return fence;
2702 
2703 free_rfence:
2704 	kfree(rfence);
2705 free_ijob:
2706 	xe_tlb_inval_job_put(mjob);
2707 	xe_tlb_inval_job_put(ijob);
2708 kill_vm_tile1:
2709 	if (err != -EAGAIN && err != -ENODATA && tile->id)
2710 		xe_vm_kill(vops->vm, false);
2711 
2712 	return ERR_PTR(err);
2713 }
2714 ALLOW_ERROR_INJECTION(xe_pt_update_ops_run, ERRNO);
2715 
2716 /**
2717  * xe_pt_update_ops_fini() - Finish PT update operations
2718  * @tile: Tile of PT update operations
2719  * @vops: VMA operations
2720  *
2721  * Finish PT update operations by committing to destroy page table memory
2722  */
2723 void xe_pt_update_ops_fini(struct xe_tile *tile, struct xe_vma_ops *vops)
2724 {
2725 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2726 		&vops->pt_update_ops[tile->id];
2727 	int i;
2728 
2729 	xe_page_reclaim_entries_put(pt_update_ops->prl.entries);
2730 
2731 	lockdep_assert_held(&vops->vm->lock);
2732 	xe_vm_assert_held(vops->vm);
2733 
2734 	for (i = 0; i < pt_update_ops->current_op; ++i) {
2735 		struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[i];
2736 
2737 		xe_pt_free_bind(pt_op->entries, pt_op->num_entries);
2738 	}
2739 	xe_bo_put_commit(&vops->pt_update_ops[tile->id].deferred);
2740 }
2741 
2742 /**
2743  * xe_pt_update_ops_abort() - Abort PT update operations
2744  * @tile: Tile of PT update operations
2745  * @vops: VMA operationa
2746  *
2747  *  Abort PT update operations by unwinding internal PT state
2748  */
2749 void xe_pt_update_ops_abort(struct xe_tile *tile, struct xe_vma_ops *vops)
2750 {
2751 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2752 		&vops->pt_update_ops[tile->id];
2753 	int i;
2754 
2755 	lockdep_assert_held(&vops->vm->lock);
2756 	xe_vm_assert_held(vops->vm);
2757 
2758 	for (i = pt_update_ops->num_ops - 1; i >= 0; --i) {
2759 		struct xe_vm_pgtable_update_op *pt_op =
2760 			&pt_update_ops->ops[i];
2761 
2762 		if (!pt_op->vma || i >= pt_update_ops->current_op)
2763 			continue;
2764 
2765 		if (pt_op->bind)
2766 			xe_pt_abort_bind(pt_op->vma, pt_op->entries,
2767 					 pt_op->num_entries,
2768 					 pt_op->rebind);
2769 		else
2770 			xe_pt_abort_unbind(pt_op->vma, pt_op->entries,
2771 					   pt_op->num_entries);
2772 	}
2773 
2774 	xe_pt_update_ops_fini(tile, vops);
2775 }
2776