xref: /linux/drivers/gpu/drm/xe/xe_pt.c (revision a3a02a52bcfcbcc4a637d4b68bf1bc391c9fad02)
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_gt.h"
13 #include "xe_gt_tlb_invalidation.h"
14 #include "xe_migrate.h"
15 #include "xe_pt_types.h"
16 #include "xe_pt_walk.h"
17 #include "xe_res_cursor.h"
18 #include "xe_trace.h"
19 #include "xe_ttm_stolen_mgr.h"
20 #include "xe_vm.h"
21 
22 struct xe_pt_dir {
23 	struct xe_pt pt;
24 	/** @children: Array of page-table child nodes */
25 	struct xe_ptw *children[XE_PDES];
26 };
27 
28 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM)
29 #define xe_pt_set_addr(__xe_pt, __addr) ((__xe_pt)->addr = (__addr))
30 #define xe_pt_addr(__xe_pt) ((__xe_pt)->addr)
31 #else
32 #define xe_pt_set_addr(__xe_pt, __addr)
33 #define xe_pt_addr(__xe_pt) 0ull
34 #endif
35 
36 static const u64 xe_normal_pt_shifts[] = {12, 21, 30, 39, 48};
37 static const u64 xe_compact_pt_shifts[] = {16, 21, 30, 39, 48};
38 
39 #define XE_PT_HIGHEST_LEVEL (ARRAY_SIZE(xe_normal_pt_shifts) - 1)
40 
41 static struct xe_pt_dir *as_xe_pt_dir(struct xe_pt *pt)
42 {
43 	return container_of(pt, struct xe_pt_dir, pt);
44 }
45 
46 static struct xe_pt *xe_pt_entry(struct xe_pt_dir *pt_dir, unsigned int index)
47 {
48 	return container_of(pt_dir->children[index], struct xe_pt, base);
49 }
50 
51 static u64 __xe_pt_empty_pte(struct xe_tile *tile, struct xe_vm *vm,
52 			     unsigned int level)
53 {
54 	struct xe_device *xe = tile_to_xe(tile);
55 	u16 pat_index = xe->pat.idx[XE_CACHE_WB];
56 	u8 id = tile->id;
57 
58 	if (!xe_vm_has_scratch(vm))
59 		return 0;
60 
61 	if (level > MAX_HUGEPTE_LEVEL)
62 		return vm->pt_ops->pde_encode_bo(vm->scratch_pt[id][level - 1]->bo,
63 						 0, pat_index);
64 
65 	return vm->pt_ops->pte_encode_addr(xe, 0, pat_index, level, IS_DGFX(xe), 0) |
66 		XE_PTE_NULL;
67 }
68 
69 static void xe_pt_free(struct xe_pt *pt)
70 {
71 	if (pt->level)
72 		kfree(as_xe_pt_dir(pt));
73 	else
74 		kfree(pt);
75 }
76 
77 /**
78  * xe_pt_create() - Create a page-table.
79  * @vm: The vm to create for.
80  * @tile: The tile to create for.
81  * @level: The page-table level.
82  *
83  * Allocate and initialize a single struct xe_pt metadata structure. Also
84  * create the corresponding page-table bo, but don't initialize it. If the
85  * level is grater than zero, then it's assumed to be a directory page-
86  * table and the directory structure is also allocated and initialized to
87  * NULL pointers.
88  *
89  * Return: A valid struct xe_pt pointer on success, Pointer error code on
90  * error.
91  */
92 struct xe_pt *xe_pt_create(struct xe_vm *vm, struct xe_tile *tile,
93 			   unsigned int level)
94 {
95 	struct xe_pt *pt;
96 	struct xe_bo *bo;
97 	int err;
98 
99 	if (level) {
100 		struct xe_pt_dir *dir = kzalloc(sizeof(*dir), GFP_KERNEL);
101 
102 		pt = (dir) ? &dir->pt : NULL;
103 	} else {
104 		pt = kzalloc(sizeof(*pt), GFP_KERNEL);
105 	}
106 	if (!pt)
107 		return ERR_PTR(-ENOMEM);
108 
109 	pt->level = level;
110 	bo = xe_bo_create_pin_map(vm->xe, tile, vm, SZ_4K,
111 				  ttm_bo_type_kernel,
112 				  XE_BO_FLAG_VRAM_IF_DGFX(tile) |
113 				  XE_BO_FLAG_IGNORE_MIN_PAGE_SIZE |
114 				  XE_BO_FLAG_PINNED |
115 				  XE_BO_FLAG_NO_RESV_EVICT |
116 				  XE_BO_FLAG_PAGETABLE);
117 	if (IS_ERR(bo)) {
118 		err = PTR_ERR(bo);
119 		goto err_kfree;
120 	}
121 	pt->bo = bo;
122 	pt->base.children = level ? as_xe_pt_dir(pt)->children : NULL;
123 
124 	if (vm->xef)
125 		xe_drm_client_add_bo(vm->xef->client, pt->bo);
126 	xe_tile_assert(tile, level <= XE_VM_MAX_LEVEL);
127 
128 	return pt;
129 
130 err_kfree:
131 	xe_pt_free(pt);
132 	return ERR_PTR(err);
133 }
134 
135 /**
136  * xe_pt_populate_empty() - Populate a page-table bo with scratch- or zero
137  * entries.
138  * @tile: The tile the scratch pagetable of which to use.
139  * @vm: The vm we populate for.
140  * @pt: The pagetable the bo of which to initialize.
141  *
142  * Populate the page-table bo of @pt with entries pointing into the tile's
143  * scratch page-table tree if any. Otherwise populate with zeros.
144  */
145 void xe_pt_populate_empty(struct xe_tile *tile, struct xe_vm *vm,
146 			  struct xe_pt *pt)
147 {
148 	struct iosys_map *map = &pt->bo->vmap;
149 	u64 empty;
150 	int i;
151 
152 	if (!xe_vm_has_scratch(vm)) {
153 		/*
154 		 * FIXME: Some memory is allocated already allocated to zero?
155 		 * Find out which memory that is and avoid this memset...
156 		 */
157 		xe_map_memset(vm->xe, map, 0, 0, SZ_4K);
158 	} else {
159 		empty = __xe_pt_empty_pte(tile, vm, pt->level);
160 		for (i = 0; i < XE_PDES; i++)
161 			xe_pt_write(vm->xe, map, i, empty);
162 	}
163 }
164 
165 /**
166  * xe_pt_shift() - Return the ilog2 value of the size of the address range of
167  * a page-table at a certain level.
168  * @level: The level.
169  *
170  * Return: The ilog2 value of the size of the address range of a page-table
171  * at level @level.
172  */
173 unsigned int xe_pt_shift(unsigned int level)
174 {
175 	return XE_PTE_SHIFT + XE_PDE_SHIFT * level;
176 }
177 
178 /**
179  * xe_pt_destroy() - Destroy a page-table tree.
180  * @pt: The root of the page-table tree to destroy.
181  * @flags: vm flags. Currently unused.
182  * @deferred: List head of lockless list for deferred putting. NULL for
183  *            immediate putting.
184  *
185  * Puts the page-table bo, recursively calls xe_pt_destroy on all children
186  * and finally frees @pt. TODO: Can we remove the @flags argument?
187  */
188 void xe_pt_destroy(struct xe_pt *pt, u32 flags, struct llist_head *deferred)
189 {
190 	int i;
191 
192 	if (!pt)
193 		return;
194 
195 	XE_WARN_ON(!list_empty(&pt->bo->ttm.base.gpuva.list));
196 	xe_bo_unpin(pt->bo);
197 	xe_bo_put_deferred(pt->bo, deferred);
198 
199 	if (pt->level > 0 && pt->num_live) {
200 		struct xe_pt_dir *pt_dir = as_xe_pt_dir(pt);
201 
202 		for (i = 0; i < XE_PDES; i++) {
203 			if (xe_pt_entry(pt_dir, i))
204 				xe_pt_destroy(xe_pt_entry(pt_dir, i), flags,
205 					      deferred);
206 		}
207 	}
208 	xe_pt_free(pt);
209 }
210 
211 /**
212  * DOC: Pagetable building
213  *
214  * Below we use the term "page-table" for both page-directories, containing
215  * pointers to lower level page-directories or page-tables, and level 0
216  * page-tables that contain only page-table-entries pointing to memory pages.
217  *
218  * When inserting an address range in an already existing page-table tree
219  * there will typically be a set of page-tables that are shared with other
220  * address ranges, and a set that are private to this address range.
221  * The set of shared page-tables can be at most two per level,
222  * and those can't be updated immediately because the entries of those
223  * page-tables may still be in use by the gpu for other mappings. Therefore
224  * when inserting entries into those, we instead stage those insertions by
225  * adding insertion data into struct xe_vm_pgtable_update structures. This
226  * data, (subtrees for the cpu and page-table-entries for the gpu) is then
227  * added in a separate commit step. CPU-data is committed while still under the
228  * vm lock, the object lock and for userptr, the notifier lock in read mode.
229  * The GPU async data is committed either by the GPU or CPU after fulfilling
230  * relevant dependencies.
231  * For non-shared page-tables (and, in fact, for shared ones that aren't
232  * existing at the time of staging), we add the data in-place without the
233  * special update structures. This private part of the page-table tree will
234  * remain disconnected from the vm page-table tree until data is committed to
235  * the shared page tables of the vm tree in the commit phase.
236  */
237 
238 struct xe_pt_update {
239 	/** @update: The update structure we're building for this parent. */
240 	struct xe_vm_pgtable_update *update;
241 	/** @parent: The parent. Used to detect a parent change. */
242 	struct xe_pt *parent;
243 	/** @preexisting: Whether the parent was pre-existing or allocated */
244 	bool preexisting;
245 };
246 
247 struct xe_pt_stage_bind_walk {
248 	/** base: The base class. */
249 	struct xe_pt_walk base;
250 
251 	/* Input parameters for the walk */
252 	/** @vm: The vm we're building for. */
253 	struct xe_vm *vm;
254 	/** @tile: The tile we're building for. */
255 	struct xe_tile *tile;
256 	/** @default_pte: PTE flag only template. No address is associated */
257 	u64 default_pte;
258 	/** @dma_offset: DMA offset to add to the PTE. */
259 	u64 dma_offset;
260 	/**
261 	 * @needs_64k: This address range enforces 64K alignment and
262 	 * granularity.
263 	 */
264 	bool needs_64K;
265 	/**
266 	 * @vma: VMA being mapped
267 	 */
268 	struct xe_vma *vma;
269 
270 	/* Also input, but is updated during the walk*/
271 	/** @curs: The DMA address cursor. */
272 	struct xe_res_cursor *curs;
273 	/** @va_curs_start: The Virtual address coresponding to @curs->start */
274 	u64 va_curs_start;
275 
276 	/* Output */
277 	struct xe_walk_update {
278 		/** @wupd.entries: Caller provided storage. */
279 		struct xe_vm_pgtable_update *entries;
280 		/** @wupd.num_used_entries: Number of update @entries used. */
281 		unsigned int num_used_entries;
282 		/** @wupd.updates: Tracks the update entry at a given level */
283 		struct xe_pt_update updates[XE_VM_MAX_LEVEL + 1];
284 	} wupd;
285 
286 	/* Walk state */
287 	/**
288 	 * @l0_end_addr: The end address of the current l0 leaf. Used for
289 	 * 64K granularity detection.
290 	 */
291 	u64 l0_end_addr;
292 	/** @addr_64K: The start address of the current 64K chunk. */
293 	u64 addr_64K;
294 	/** @found_64: Whether @add_64K actually points to a 64K chunk. */
295 	bool found_64K;
296 };
297 
298 static int
299 xe_pt_new_shared(struct xe_walk_update *wupd, struct xe_pt *parent,
300 		 pgoff_t offset, bool alloc_entries)
301 {
302 	struct xe_pt_update *upd = &wupd->updates[parent->level];
303 	struct xe_vm_pgtable_update *entry;
304 
305 	/*
306 	 * For *each level*, we could only have one active
307 	 * struct xt_pt_update at any one time. Once we move on to a
308 	 * new parent and page-directory, the old one is complete, and
309 	 * updates are either already stored in the build tree or in
310 	 * @wupd->entries
311 	 */
312 	if (likely(upd->parent == parent))
313 		return 0;
314 
315 	upd->parent = parent;
316 	upd->preexisting = true;
317 
318 	if (wupd->num_used_entries == XE_VM_MAX_LEVEL * 2 + 1)
319 		return -EINVAL;
320 
321 	entry = wupd->entries + wupd->num_used_entries++;
322 	upd->update = entry;
323 	entry->ofs = offset;
324 	entry->pt_bo = parent->bo;
325 	entry->pt = parent;
326 	entry->flags = 0;
327 	entry->qwords = 0;
328 
329 	if (alloc_entries) {
330 		entry->pt_entries = kmalloc_array(XE_PDES,
331 						  sizeof(*entry->pt_entries),
332 						  GFP_KERNEL);
333 		if (!entry->pt_entries)
334 			return -ENOMEM;
335 	}
336 
337 	return 0;
338 }
339 
340 /*
341  * NOTE: This is a very frequently called function so we allow ourselves
342  * to annotate (using branch prediction hints) the fastpath of updating a
343  * non-pre-existing pagetable with leaf ptes.
344  */
345 static int
346 xe_pt_insert_entry(struct xe_pt_stage_bind_walk *xe_walk, struct xe_pt *parent,
347 		   pgoff_t offset, struct xe_pt *xe_child, u64 pte)
348 {
349 	struct xe_pt_update *upd = &xe_walk->wupd.updates[parent->level];
350 	struct xe_pt_update *child_upd = xe_child ?
351 		&xe_walk->wupd.updates[xe_child->level] : NULL;
352 	int ret;
353 
354 	ret = xe_pt_new_shared(&xe_walk->wupd, parent, offset, true);
355 	if (unlikely(ret))
356 		return ret;
357 
358 	/*
359 	 * Register this new pagetable so that it won't be recognized as
360 	 * a shared pagetable by a subsequent insertion.
361 	 */
362 	if (unlikely(child_upd)) {
363 		child_upd->update = NULL;
364 		child_upd->parent = xe_child;
365 		child_upd->preexisting = false;
366 	}
367 
368 	if (likely(!upd->preexisting)) {
369 		/* Continue building a non-connected subtree. */
370 		struct iosys_map *map = &parent->bo->vmap;
371 
372 		if (unlikely(xe_child))
373 			parent->base.children[offset] = &xe_child->base;
374 
375 		xe_pt_write(xe_walk->vm->xe, map, offset, pte);
376 		parent->num_live++;
377 	} else {
378 		/* Shared pt. Stage update. */
379 		unsigned int idx;
380 		struct xe_vm_pgtable_update *entry = upd->update;
381 
382 		idx = offset - entry->ofs;
383 		entry->pt_entries[idx].pt = xe_child;
384 		entry->pt_entries[idx].pte = pte;
385 		entry->qwords++;
386 	}
387 
388 	return 0;
389 }
390 
391 static bool xe_pt_hugepte_possible(u64 addr, u64 next, unsigned int level,
392 				   struct xe_pt_stage_bind_walk *xe_walk)
393 {
394 	u64 size, dma;
395 
396 	if (level > MAX_HUGEPTE_LEVEL)
397 		return false;
398 
399 	/* Does the virtual range requested cover a huge pte? */
400 	if (!xe_pt_covers(addr, next, level, &xe_walk->base))
401 		return false;
402 
403 	/* Does the DMA segment cover the whole pte? */
404 	if (next - xe_walk->va_curs_start > xe_walk->curs->size)
405 		return false;
406 
407 	/* null VMA's do not have dma addresses */
408 	if (xe_vma_is_null(xe_walk->vma))
409 		return true;
410 
411 	/* Is the DMA address huge PTE size aligned? */
412 	size = next - addr;
413 	dma = addr - xe_walk->va_curs_start + xe_res_dma(xe_walk->curs);
414 
415 	return IS_ALIGNED(dma, size);
416 }
417 
418 /*
419  * Scan the requested mapping to check whether it can be done entirely
420  * with 64K PTEs.
421  */
422 static bool
423 xe_pt_scan_64K(u64 addr, u64 next, struct xe_pt_stage_bind_walk *xe_walk)
424 {
425 	struct xe_res_cursor curs = *xe_walk->curs;
426 
427 	if (!IS_ALIGNED(addr, SZ_64K))
428 		return false;
429 
430 	if (next > xe_walk->l0_end_addr)
431 		return false;
432 
433 	/* null VMA's do not have dma addresses */
434 	if (xe_vma_is_null(xe_walk->vma))
435 		return true;
436 
437 	xe_res_next(&curs, addr - xe_walk->va_curs_start);
438 	for (; addr < next; addr += SZ_64K) {
439 		if (!IS_ALIGNED(xe_res_dma(&curs), SZ_64K) || curs.size < SZ_64K)
440 			return false;
441 
442 		xe_res_next(&curs, SZ_64K);
443 	}
444 
445 	return addr == next;
446 }
447 
448 /*
449  * For non-compact "normal" 4K level-0 pagetables, we want to try to group
450  * addresses together in 64K-contigous regions to add a 64K TLB hint for the
451  * device to the PTE.
452  * This function determines whether the address is part of such a
453  * segment. For VRAM in normal pagetables, this is strictly necessary on
454  * some devices.
455  */
456 static bool
457 xe_pt_is_pte_ps64K(u64 addr, u64 next, struct xe_pt_stage_bind_walk *xe_walk)
458 {
459 	/* Address is within an already found 64k region */
460 	if (xe_walk->found_64K && addr - xe_walk->addr_64K < SZ_64K)
461 		return true;
462 
463 	xe_walk->found_64K = xe_pt_scan_64K(addr, addr + SZ_64K, xe_walk);
464 	xe_walk->addr_64K = addr;
465 
466 	return xe_walk->found_64K;
467 }
468 
469 static int
470 xe_pt_stage_bind_entry(struct xe_ptw *parent, pgoff_t offset,
471 		       unsigned int level, u64 addr, u64 next,
472 		       struct xe_ptw **child,
473 		       enum page_walk_action *action,
474 		       struct xe_pt_walk *walk)
475 {
476 	struct xe_pt_stage_bind_walk *xe_walk =
477 		container_of(walk, typeof(*xe_walk), base);
478 	u16 pat_index = xe_walk->vma->pat_index;
479 	struct xe_pt *xe_parent = container_of(parent, typeof(*xe_parent), base);
480 	struct xe_vm *vm = xe_walk->vm;
481 	struct xe_pt *xe_child;
482 	bool covers;
483 	int ret = 0;
484 	u64 pte;
485 
486 	/* Is this a leaf entry ?*/
487 	if (level == 0 || xe_pt_hugepte_possible(addr, next, level, xe_walk)) {
488 		struct xe_res_cursor *curs = xe_walk->curs;
489 		bool is_null = xe_vma_is_null(xe_walk->vma);
490 
491 		XE_WARN_ON(xe_walk->va_curs_start != addr);
492 
493 		pte = vm->pt_ops->pte_encode_vma(is_null ? 0 :
494 						 xe_res_dma(curs) + xe_walk->dma_offset,
495 						 xe_walk->vma, pat_index, level);
496 		pte |= xe_walk->default_pte;
497 
498 		/*
499 		 * Set the XE_PTE_PS64 hint if possible, otherwise if
500 		 * this device *requires* 64K PTE size for VRAM, fail.
501 		 */
502 		if (level == 0 && !xe_parent->is_compact) {
503 			if (xe_pt_is_pte_ps64K(addr, next, xe_walk)) {
504 				xe_walk->vma->gpuva.flags |= XE_VMA_PTE_64K;
505 				pte |= XE_PTE_PS64;
506 			} else if (XE_WARN_ON(xe_walk->needs_64K)) {
507 				return -EINVAL;
508 			}
509 		}
510 
511 		ret = xe_pt_insert_entry(xe_walk, xe_parent, offset, NULL, pte);
512 		if (unlikely(ret))
513 			return ret;
514 
515 		if (!is_null)
516 			xe_res_next(curs, next - addr);
517 		xe_walk->va_curs_start = next;
518 		xe_walk->vma->gpuva.flags |= (XE_VMA_PTE_4K << level);
519 		*action = ACTION_CONTINUE;
520 
521 		return ret;
522 	}
523 
524 	/*
525 	 * Descending to lower level. Determine if we need to allocate a
526 	 * new page table or -directory, which we do if there is no
527 	 * previous one or there is one we can completely replace.
528 	 */
529 	if (level == 1) {
530 		walk->shifts = xe_normal_pt_shifts;
531 		xe_walk->l0_end_addr = next;
532 	}
533 
534 	covers = xe_pt_covers(addr, next, level, &xe_walk->base);
535 	if (covers || !*child) {
536 		u64 flags = 0;
537 
538 		xe_child = xe_pt_create(xe_walk->vm, xe_walk->tile, level - 1);
539 		if (IS_ERR(xe_child))
540 			return PTR_ERR(xe_child);
541 
542 		xe_pt_set_addr(xe_child,
543 			       round_down(addr, 1ull << walk->shifts[level]));
544 
545 		if (!covers)
546 			xe_pt_populate_empty(xe_walk->tile, xe_walk->vm, xe_child);
547 
548 		*child = &xe_child->base;
549 
550 		/*
551 		 * Prefer the compact pagetable layout for L0 if possible. Only
552 		 * possible if VMA covers entire 2MB region as compact 64k and
553 		 * 4k pages cannot be mixed within a 2MB region.
554 		 * TODO: Suballocate the pt bo to avoid wasting a lot of
555 		 * memory.
556 		 */
557 		if (GRAPHICS_VERx100(tile_to_xe(xe_walk->tile)) >= 1250 && level == 1 &&
558 		    covers && xe_pt_scan_64K(addr, next, xe_walk)) {
559 			walk->shifts = xe_compact_pt_shifts;
560 			xe_walk->vma->gpuva.flags |= XE_VMA_PTE_COMPACT;
561 			flags |= XE_PDE_64K;
562 			xe_child->is_compact = true;
563 		}
564 
565 		pte = vm->pt_ops->pde_encode_bo(xe_child->bo, 0, pat_index) | flags;
566 		ret = xe_pt_insert_entry(xe_walk, xe_parent, offset, xe_child,
567 					 pte);
568 	}
569 
570 	*action = ACTION_SUBTREE;
571 	return ret;
572 }
573 
574 static const struct xe_pt_walk_ops xe_pt_stage_bind_ops = {
575 	.pt_entry = xe_pt_stage_bind_entry,
576 };
577 
578 /**
579  * xe_pt_stage_bind() - Build a disconnected page-table tree for a given address
580  * range.
581  * @tile: The tile we're building for.
582  * @vma: The vma indicating the address range.
583  * @entries: Storage for the update entries used for connecting the tree to
584  * the main tree at commit time.
585  * @num_entries: On output contains the number of @entries used.
586  *
587  * This function builds a disconnected page-table tree for a given address
588  * range. The tree is connected to the main vm tree for the gpu using
589  * xe_migrate_update_pgtables() and for the cpu using xe_pt_commit_bind().
590  * The function builds xe_vm_pgtable_update structures for already existing
591  * shared page-tables, and non-existing shared and non-shared page-tables
592  * are built and populated directly.
593  *
594  * Return 0 on success, negative error code on error.
595  */
596 static int
597 xe_pt_stage_bind(struct xe_tile *tile, struct xe_vma *vma,
598 		 struct xe_vm_pgtable_update *entries, u32 *num_entries)
599 {
600 	struct xe_device *xe = tile_to_xe(tile);
601 	struct xe_bo *bo = xe_vma_bo(vma);
602 	bool is_devmem = !xe_vma_is_userptr(vma) && bo &&
603 		(xe_bo_is_vram(bo) || xe_bo_is_stolen_devmem(bo));
604 	struct xe_res_cursor curs;
605 	struct xe_pt_stage_bind_walk xe_walk = {
606 		.base = {
607 			.ops = &xe_pt_stage_bind_ops,
608 			.shifts = xe_normal_pt_shifts,
609 			.max_level = XE_PT_HIGHEST_LEVEL,
610 		},
611 		.vm = xe_vma_vm(vma),
612 		.tile = tile,
613 		.curs = &curs,
614 		.va_curs_start = xe_vma_start(vma),
615 		.vma = vma,
616 		.wupd.entries = entries,
617 		.needs_64K = (xe_vma_vm(vma)->flags & XE_VM_FLAG_64K) && is_devmem,
618 	};
619 	struct xe_pt *pt = xe_vma_vm(vma)->pt_root[tile->id];
620 	int ret;
621 
622 	/**
623 	 * Default atomic expectations for different allocation scenarios are as follows:
624 	 *
625 	 * 1. Traditional API: When the VM is not in LR mode:
626 	 *    - Device atomics are expected to function with all allocations.
627 	 *
628 	 * 2. Compute/SVM API: When the VM is in LR mode:
629 	 *    - Device atomics are the default behavior when the bo is placed in a single region.
630 	 *    - In all other cases device atomics will be disabled with AE=0 until an application
631 	 *      request differently using a ioctl like madvise.
632 	 */
633 	if (vma->gpuva.flags & XE_VMA_ATOMIC_PTE_BIT) {
634 		if (xe_vm_in_lr_mode(xe_vma_vm(vma))) {
635 			if (bo && xe_bo_has_single_placement(bo))
636 				xe_walk.default_pte |= XE_USM_PPGTT_PTE_AE;
637 			/**
638 			 * If a SMEM+LMEM allocation is backed by SMEM, a device
639 			 * atomics will cause a gpu page fault and which then
640 			 * gets migrated to LMEM, bind such allocations with
641 			 * device atomics enabled.
642 			 */
643 			else if (is_devmem && !xe_bo_has_single_placement(bo))
644 				xe_walk.default_pte |= XE_USM_PPGTT_PTE_AE;
645 		} else {
646 			xe_walk.default_pte |= XE_USM_PPGTT_PTE_AE;
647 		}
648 
649 		/**
650 		 * Unset AE if the platform(PVC) doesn't support it on an
651 		 * allocation
652 		 */
653 		if (!xe->info.has_device_atomics_on_smem && !is_devmem)
654 			xe_walk.default_pte &= ~XE_USM_PPGTT_PTE_AE;
655 	}
656 
657 	if (is_devmem) {
658 		xe_walk.default_pte |= XE_PPGTT_PTE_DM;
659 		xe_walk.dma_offset = vram_region_gpu_offset(bo->ttm.resource);
660 	}
661 
662 	if (!xe_vma_has_no_bo(vma) && xe_bo_is_stolen(bo))
663 		xe_walk.dma_offset = xe_ttm_stolen_gpu_offset(xe_bo_device(bo));
664 
665 	xe_bo_assert_held(bo);
666 
667 	if (!xe_vma_is_null(vma)) {
668 		if (xe_vma_is_userptr(vma))
669 			xe_res_first_sg(to_userptr_vma(vma)->userptr.sg, 0,
670 					xe_vma_size(vma), &curs);
671 		else if (xe_bo_is_vram(bo) || xe_bo_is_stolen(bo))
672 			xe_res_first(bo->ttm.resource, xe_vma_bo_offset(vma),
673 				     xe_vma_size(vma), &curs);
674 		else
675 			xe_res_first_sg(xe_bo_sg(bo), xe_vma_bo_offset(vma),
676 					xe_vma_size(vma), &curs);
677 	} else {
678 		curs.size = xe_vma_size(vma);
679 	}
680 
681 	ret = xe_pt_walk_range(&pt->base, pt->level, xe_vma_start(vma),
682 			       xe_vma_end(vma), &xe_walk.base);
683 
684 	*num_entries = xe_walk.wupd.num_used_entries;
685 	return ret;
686 }
687 
688 /**
689  * xe_pt_nonshared_offsets() - Determine the non-shared entry offsets of a
690  * shared pagetable.
691  * @addr: The start address within the non-shared pagetable.
692  * @end: The end address within the non-shared pagetable.
693  * @level: The level of the non-shared pagetable.
694  * @walk: Walk info. The function adjusts the walk action.
695  * @action: next action to perform (see enum page_walk_action)
696  * @offset: Ignored on input, First non-shared entry on output.
697  * @end_offset: Ignored on input, Last non-shared entry + 1 on output.
698  *
699  * A non-shared page-table has some entries that belong to the address range
700  * and others that don't. This function determines the entries that belong
701  * fully to the address range. Depending on level, some entries may
702  * partially belong to the address range (that can't happen at level 0).
703  * The function detects that and adjust those offsets to not include those
704  * partial entries. Iff it does detect partial entries, we know that there must
705  * be shared page tables also at lower levels, so it adjusts the walk action
706  * accordingly.
707  *
708  * Return: true if there were non-shared entries, false otherwise.
709  */
710 static bool xe_pt_nonshared_offsets(u64 addr, u64 end, unsigned int level,
711 				    struct xe_pt_walk *walk,
712 				    enum page_walk_action *action,
713 				    pgoff_t *offset, pgoff_t *end_offset)
714 {
715 	u64 size = 1ull << walk->shifts[level];
716 
717 	*offset = xe_pt_offset(addr, level, walk);
718 	*end_offset = xe_pt_num_entries(addr, end, level, walk) + *offset;
719 
720 	if (!level)
721 		return true;
722 
723 	/*
724 	 * If addr or next are not size aligned, there are shared pts at lower
725 	 * level, so in that case traverse down the subtree
726 	 */
727 	*action = ACTION_CONTINUE;
728 	if (!IS_ALIGNED(addr, size)) {
729 		*action = ACTION_SUBTREE;
730 		(*offset)++;
731 	}
732 
733 	if (!IS_ALIGNED(end, size)) {
734 		*action = ACTION_SUBTREE;
735 		(*end_offset)--;
736 	}
737 
738 	return *end_offset > *offset;
739 }
740 
741 struct xe_pt_zap_ptes_walk {
742 	/** @base: The walk base-class */
743 	struct xe_pt_walk base;
744 
745 	/* Input parameters for the walk */
746 	/** @tile: The tile we're building for */
747 	struct xe_tile *tile;
748 
749 	/* Output */
750 	/** @needs_invalidate: Whether we need to invalidate TLB*/
751 	bool needs_invalidate;
752 };
753 
754 static int xe_pt_zap_ptes_entry(struct xe_ptw *parent, pgoff_t offset,
755 				unsigned int level, u64 addr, u64 next,
756 				struct xe_ptw **child,
757 				enum page_walk_action *action,
758 				struct xe_pt_walk *walk)
759 {
760 	struct xe_pt_zap_ptes_walk *xe_walk =
761 		container_of(walk, typeof(*xe_walk), base);
762 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
763 	pgoff_t end_offset;
764 
765 	XE_WARN_ON(!*child);
766 	XE_WARN_ON(!level);
767 
768 	/*
769 	 * Note that we're called from an entry callback, and we're dealing
770 	 * with the child of that entry rather than the parent, so need to
771 	 * adjust level down.
772 	 */
773 	if (xe_pt_nonshared_offsets(addr, next, --level, walk, action, &offset,
774 				    &end_offset)) {
775 		xe_map_memset(tile_to_xe(xe_walk->tile), &xe_child->bo->vmap,
776 			      offset * sizeof(u64), 0,
777 			      (end_offset - offset) * sizeof(u64));
778 		xe_walk->needs_invalidate = true;
779 	}
780 
781 	return 0;
782 }
783 
784 static const struct xe_pt_walk_ops xe_pt_zap_ptes_ops = {
785 	.pt_entry = xe_pt_zap_ptes_entry,
786 };
787 
788 /**
789  * xe_pt_zap_ptes() - Zap (zero) gpu ptes of an address range
790  * @tile: The tile we're zapping for.
791  * @vma: GPU VMA detailing address range.
792  *
793  * Eviction and Userptr invalidation needs to be able to zap the
794  * gpu ptes of a given address range in pagefaulting mode.
795  * In order to be able to do that, that function needs access to the shared
796  * page-table entrieaso it can either clear the leaf PTEs or
797  * clear the pointers to lower-level page-tables. The caller is required
798  * to hold the necessary locks to ensure neither the page-table connectivity
799  * nor the page-table entries of the range is updated from under us.
800  *
801  * Return: Whether ptes were actually updated and a TLB invalidation is
802  * required.
803  */
804 bool xe_pt_zap_ptes(struct xe_tile *tile, struct xe_vma *vma)
805 {
806 	struct xe_pt_zap_ptes_walk xe_walk = {
807 		.base = {
808 			.ops = &xe_pt_zap_ptes_ops,
809 			.shifts = xe_normal_pt_shifts,
810 			.max_level = XE_PT_HIGHEST_LEVEL,
811 		},
812 		.tile = tile,
813 	};
814 	struct xe_pt *pt = xe_vma_vm(vma)->pt_root[tile->id];
815 	u8 pt_mask = (vma->tile_present & ~vma->tile_invalidated);
816 
817 	if (!(pt_mask & BIT(tile->id)))
818 		return false;
819 
820 	(void)xe_pt_walk_shared(&pt->base, pt->level, xe_vma_start(vma),
821 				xe_vma_end(vma), &xe_walk.base);
822 
823 	return xe_walk.needs_invalidate;
824 }
825 
826 static void
827 xe_vm_populate_pgtable(struct xe_migrate_pt_update *pt_update, struct xe_tile *tile,
828 		       struct iosys_map *map, void *data,
829 		       u32 qword_ofs, u32 num_qwords,
830 		       const struct xe_vm_pgtable_update *update)
831 {
832 	struct xe_pt_entry *ptes = update->pt_entries;
833 	u64 *ptr = data;
834 	u32 i;
835 
836 	for (i = 0; i < num_qwords; i++) {
837 		if (map)
838 			xe_map_wr(tile_to_xe(tile), map, (qword_ofs + i) *
839 				  sizeof(u64), u64, ptes[i].pte);
840 		else
841 			ptr[i] = ptes[i].pte;
842 	}
843 }
844 
845 static void xe_pt_abort_bind(struct xe_vma *vma,
846 			     struct xe_vm_pgtable_update *entries,
847 			     u32 num_entries)
848 {
849 	u32 i, j;
850 
851 	for (i = 0; i < num_entries; i++) {
852 		if (!entries[i].pt_entries)
853 			continue;
854 
855 		for (j = 0; j < entries[i].qwords; j++)
856 			xe_pt_destroy(entries[i].pt_entries[j].pt, xe_vma_vm(vma)->flags, NULL);
857 		kfree(entries[i].pt_entries);
858 	}
859 }
860 
861 static void xe_pt_commit_locks_assert(struct xe_vma *vma)
862 {
863 	struct xe_vm *vm = xe_vma_vm(vma);
864 
865 	lockdep_assert_held(&vm->lock);
866 
867 	if (xe_vma_is_userptr(vma))
868 		lockdep_assert_held_read(&vm->userptr.notifier_lock);
869 	else if (!xe_vma_is_null(vma))
870 		dma_resv_assert_held(xe_vma_bo(vma)->ttm.base.resv);
871 
872 	xe_vm_assert_held(vm);
873 }
874 
875 static void xe_pt_commit_bind(struct xe_vma *vma,
876 			      struct xe_vm_pgtable_update *entries,
877 			      u32 num_entries, bool rebind,
878 			      struct llist_head *deferred)
879 {
880 	u32 i, j;
881 
882 	xe_pt_commit_locks_assert(vma);
883 
884 	for (i = 0; i < num_entries; i++) {
885 		struct xe_pt *pt = entries[i].pt;
886 		struct xe_pt_dir *pt_dir;
887 
888 		if (!rebind)
889 			pt->num_live += entries[i].qwords;
890 
891 		if (!pt->level) {
892 			kfree(entries[i].pt_entries);
893 			continue;
894 		}
895 
896 		pt_dir = as_xe_pt_dir(pt);
897 		for (j = 0; j < entries[i].qwords; j++) {
898 			u32 j_ = j + entries[i].ofs;
899 			struct xe_pt *newpte = entries[i].pt_entries[j].pt;
900 
901 			if (xe_pt_entry(pt_dir, j_))
902 				xe_pt_destroy(xe_pt_entry(pt_dir, j_),
903 					      xe_vma_vm(vma)->flags, deferred);
904 
905 			pt_dir->children[j_] = &newpte->base;
906 		}
907 		kfree(entries[i].pt_entries);
908 	}
909 }
910 
911 static int
912 xe_pt_prepare_bind(struct xe_tile *tile, struct xe_vma *vma,
913 		   struct xe_vm_pgtable_update *entries, u32 *num_entries)
914 {
915 	int err;
916 
917 	*num_entries = 0;
918 	err = xe_pt_stage_bind(tile, vma, entries, num_entries);
919 	if (!err)
920 		xe_tile_assert(tile, *num_entries);
921 	else /* abort! */
922 		xe_pt_abort_bind(vma, entries, *num_entries);
923 
924 	return err;
925 }
926 
927 static void xe_vm_dbg_print_entries(struct xe_device *xe,
928 				    const struct xe_vm_pgtable_update *entries,
929 				    unsigned int num_entries)
930 #if (IS_ENABLED(CONFIG_DRM_XE_DEBUG_VM))
931 {
932 	unsigned int i;
933 
934 	vm_dbg(&xe->drm, "%u entries to update\n", num_entries);
935 	for (i = 0; i < num_entries; i++) {
936 		const struct xe_vm_pgtable_update *entry = &entries[i];
937 		struct xe_pt *xe_pt = entry->pt;
938 		u64 page_size = 1ull << xe_pt_shift(xe_pt->level);
939 		u64 end;
940 		u64 start;
941 
942 		xe_assert(xe, !entry->pt->is_compact);
943 		start = entry->ofs * page_size;
944 		end = start + page_size * entry->qwords;
945 		vm_dbg(&xe->drm,
946 		       "\t%u: Update level %u at (%u + %u) [%llx...%llx) f:%x\n",
947 		       i, xe_pt->level, entry->ofs, entry->qwords,
948 		       xe_pt_addr(xe_pt) + start, xe_pt_addr(xe_pt) + end, 0);
949 	}
950 }
951 #else
952 {}
953 #endif
954 
955 #ifdef CONFIG_DRM_XE_USERPTR_INVAL_INJECT
956 
957 static int xe_pt_userptr_inject_eagain(struct xe_userptr_vma *uvma)
958 {
959 	u32 divisor = uvma->userptr.divisor ? uvma->userptr.divisor : 2;
960 	static u32 count;
961 
962 	if (count++ % divisor == divisor - 1) {
963 		struct xe_vm *vm = xe_vma_vm(&uvma->vma);
964 
965 		uvma->userptr.divisor = divisor << 1;
966 		spin_lock(&vm->userptr.invalidated_lock);
967 		list_move_tail(&uvma->userptr.invalidate_link,
968 			       &vm->userptr.invalidated);
969 		spin_unlock(&vm->userptr.invalidated_lock);
970 		return true;
971 	}
972 
973 	return false;
974 }
975 
976 #else
977 
978 static bool xe_pt_userptr_inject_eagain(struct xe_userptr_vma *uvma)
979 {
980 	return false;
981 }
982 
983 #endif
984 
985 /**
986  * struct xe_pt_migrate_pt_update - Callback argument for pre-commit callbacks
987  * @base: Base we derive from.
988  * @bind: Whether this is a bind or an unbind operation. A bind operation
989  *        makes the pre-commit callback error with -EAGAIN if it detects a
990  *        pending invalidation.
991  * @locked: Whether the pre-commit callback locked the userptr notifier lock
992  *          and it needs unlocking.
993  */
994 struct xe_pt_migrate_pt_update {
995 	struct xe_migrate_pt_update base;
996 	bool bind;
997 	bool locked;
998 };
999 
1000 /*
1001  * This function adds the needed dependencies to a page-table update job
1002  * to make sure racing jobs for separate bind engines don't race writing
1003  * to the same page-table range, wreaking havoc. Initially use a single
1004  * fence for the entire VM. An optimization would use smaller granularity.
1005  */
1006 static int xe_pt_vm_dependencies(struct xe_sched_job *job,
1007 				 struct xe_range_fence_tree *rftree,
1008 				 u64 start, u64 last)
1009 {
1010 	struct xe_range_fence *rtfence;
1011 	struct dma_fence *fence;
1012 	int err;
1013 
1014 	rtfence = xe_range_fence_tree_first(rftree, start, last);
1015 	while (rtfence) {
1016 		fence = rtfence->fence;
1017 
1018 		if (!dma_fence_is_signaled(fence)) {
1019 			/*
1020 			 * Is this a CPU update? GPU is busy updating, so return
1021 			 * an error
1022 			 */
1023 			if (!job)
1024 				return -ETIME;
1025 
1026 			dma_fence_get(fence);
1027 			err = drm_sched_job_add_dependency(&job->drm, fence);
1028 			if (err)
1029 				return err;
1030 		}
1031 
1032 		rtfence = xe_range_fence_tree_next(rtfence, start, last);
1033 	}
1034 
1035 	return 0;
1036 }
1037 
1038 static int xe_pt_pre_commit(struct xe_migrate_pt_update *pt_update)
1039 {
1040 	struct xe_range_fence_tree *rftree =
1041 		&xe_vma_vm(pt_update->vma)->rftree[pt_update->tile_id];
1042 
1043 	return xe_pt_vm_dependencies(pt_update->job, rftree,
1044 				     pt_update->start, pt_update->last);
1045 }
1046 
1047 static int xe_pt_userptr_pre_commit(struct xe_migrate_pt_update *pt_update)
1048 {
1049 	struct xe_pt_migrate_pt_update *userptr_update =
1050 		container_of(pt_update, typeof(*userptr_update), base);
1051 	struct xe_userptr_vma *uvma = to_userptr_vma(pt_update->vma);
1052 	unsigned long notifier_seq = uvma->userptr.notifier_seq;
1053 	struct xe_vm *vm = xe_vma_vm(&uvma->vma);
1054 	int err = xe_pt_vm_dependencies(pt_update->job,
1055 					&vm->rftree[pt_update->tile_id],
1056 					pt_update->start,
1057 					pt_update->last);
1058 
1059 	if (err)
1060 		return err;
1061 
1062 	userptr_update->locked = false;
1063 
1064 	/*
1065 	 * Wait until nobody is running the invalidation notifier, and
1066 	 * since we're exiting the loop holding the notifier lock,
1067 	 * nobody can proceed invalidating either.
1068 	 *
1069 	 * Note that we don't update the vma->userptr.notifier_seq since
1070 	 * we don't update the userptr pages.
1071 	 */
1072 	do {
1073 		down_read(&vm->userptr.notifier_lock);
1074 		if (!mmu_interval_read_retry(&uvma->userptr.notifier,
1075 					     notifier_seq))
1076 			break;
1077 
1078 		up_read(&vm->userptr.notifier_lock);
1079 
1080 		if (userptr_update->bind)
1081 			return -EAGAIN;
1082 
1083 		notifier_seq = mmu_interval_read_begin(&uvma->userptr.notifier);
1084 	} while (true);
1085 
1086 	/* Inject errors to test_whether they are handled correctly */
1087 	if (userptr_update->bind && xe_pt_userptr_inject_eagain(uvma)) {
1088 		up_read(&vm->userptr.notifier_lock);
1089 		return -EAGAIN;
1090 	}
1091 
1092 	userptr_update->locked = true;
1093 
1094 	return 0;
1095 }
1096 
1097 static const struct xe_migrate_pt_update_ops bind_ops = {
1098 	.populate = xe_vm_populate_pgtable,
1099 	.pre_commit = xe_pt_pre_commit,
1100 };
1101 
1102 static const struct xe_migrate_pt_update_ops userptr_bind_ops = {
1103 	.populate = xe_vm_populate_pgtable,
1104 	.pre_commit = xe_pt_userptr_pre_commit,
1105 };
1106 
1107 struct invalidation_fence {
1108 	struct xe_gt_tlb_invalidation_fence base;
1109 	struct xe_gt *gt;
1110 	struct dma_fence *fence;
1111 	struct dma_fence_cb cb;
1112 	struct work_struct work;
1113 	u64 start;
1114 	u64 end;
1115 	u32 asid;
1116 };
1117 
1118 static void invalidation_fence_cb(struct dma_fence *fence,
1119 				  struct dma_fence_cb *cb)
1120 {
1121 	struct invalidation_fence *ifence =
1122 		container_of(cb, struct invalidation_fence, cb);
1123 	struct xe_device *xe = gt_to_xe(ifence->gt);
1124 
1125 	trace_xe_gt_tlb_invalidation_fence_cb(xe, &ifence->base);
1126 	if (!ifence->fence->error) {
1127 		queue_work(system_wq, &ifence->work);
1128 	} else {
1129 		ifence->base.base.error = ifence->fence->error;
1130 		dma_fence_signal(&ifence->base.base);
1131 		dma_fence_put(&ifence->base.base);
1132 	}
1133 	dma_fence_put(ifence->fence);
1134 }
1135 
1136 static void invalidation_fence_work_func(struct work_struct *w)
1137 {
1138 	struct invalidation_fence *ifence =
1139 		container_of(w, struct invalidation_fence, work);
1140 	struct xe_device *xe = gt_to_xe(ifence->gt);
1141 
1142 	trace_xe_gt_tlb_invalidation_fence_work_func(xe, &ifence->base);
1143 	xe_gt_tlb_invalidation_range(ifence->gt, &ifence->base, ifence->start,
1144 				     ifence->end, ifence->asid);
1145 }
1146 
1147 static int invalidation_fence_init(struct xe_gt *gt,
1148 				   struct invalidation_fence *ifence,
1149 				   struct dma_fence *fence,
1150 				   u64 start, u64 end, u32 asid)
1151 {
1152 	int ret;
1153 
1154 	trace_xe_gt_tlb_invalidation_fence_create(gt_to_xe(gt), &ifence->base);
1155 
1156 	xe_gt_tlb_invalidation_fence_init(gt, &ifence->base, false);
1157 
1158 	ifence->fence = fence;
1159 	ifence->gt = gt;
1160 	ifence->start = start;
1161 	ifence->end = end;
1162 	ifence->asid = asid;
1163 
1164 	INIT_WORK(&ifence->work, invalidation_fence_work_func);
1165 	ret = dma_fence_add_callback(fence, &ifence->cb, invalidation_fence_cb);
1166 	if (ret == -ENOENT) {
1167 		dma_fence_put(ifence->fence);	/* Usually dropped in CB */
1168 		invalidation_fence_work_func(&ifence->work);
1169 	} else if (ret) {
1170 		dma_fence_put(&ifence->base.base);	/* Caller ref */
1171 		dma_fence_put(&ifence->base.base);	/* Creation ref */
1172 	}
1173 
1174 	xe_gt_assert(gt, !ret || ret == -ENOENT);
1175 
1176 	return ret && ret != -ENOENT ? ret : 0;
1177 }
1178 
1179 static void xe_pt_calc_rfence_interval(struct xe_vma *vma,
1180 				       struct xe_pt_migrate_pt_update *update,
1181 				       struct xe_vm_pgtable_update *entries,
1182 				       u32 num_entries)
1183 {
1184 	int i, level = 0;
1185 
1186 	for (i = 0; i < num_entries; i++) {
1187 		const struct xe_vm_pgtable_update *entry = &entries[i];
1188 
1189 		if (entry->pt->level > level)
1190 			level = entry->pt->level;
1191 	}
1192 
1193 	/* Greedy (non-optimal) calculation but simple */
1194 	update->base.start = ALIGN_DOWN(xe_vma_start(vma),
1195 					0x1ull << xe_pt_shift(level));
1196 	update->base.last = ALIGN(xe_vma_end(vma),
1197 				  0x1ull << xe_pt_shift(level)) - 1;
1198 }
1199 
1200 /**
1201  * __xe_pt_bind_vma() - Build and connect a page-table tree for the vma
1202  * address range.
1203  * @tile: The tile to bind for.
1204  * @vma: The vma to bind.
1205  * @q: The exec_queue with which to do pipelined page-table updates.
1206  * @syncs: Entries to sync on before binding the built tree to the live vm tree.
1207  * @num_syncs: Number of @sync entries.
1208  * @rebind: Whether we're rebinding this vma to the same address range without
1209  * an unbind in-between.
1210  *
1211  * This function builds a page-table tree (see xe_pt_stage_bind() for more
1212  * information on page-table building), and the xe_vm_pgtable_update entries
1213  * abstracting the operations needed to attach it to the main vm tree. It
1214  * then takes the relevant locks and updates the metadata side of the main
1215  * vm tree and submits the operations for pipelined attachment of the
1216  * gpu page-table to the vm main tree, (which can be done either by the
1217  * cpu and the GPU).
1218  *
1219  * Return: A valid dma-fence representing the pipelined attachment operation
1220  * on success, an error pointer on error.
1221  */
1222 struct dma_fence *
1223 __xe_pt_bind_vma(struct xe_tile *tile, struct xe_vma *vma, struct xe_exec_queue *q,
1224 		 struct xe_sync_entry *syncs, u32 num_syncs,
1225 		 bool rebind)
1226 {
1227 	struct xe_vm_pgtable_update entries[XE_VM_MAX_LEVEL * 2 + 1];
1228 	struct xe_pt_migrate_pt_update bind_pt_update = {
1229 		.base = {
1230 			.ops = xe_vma_is_userptr(vma) ? &userptr_bind_ops : &bind_ops,
1231 			.vma = vma,
1232 			.tile_id = tile->id,
1233 		},
1234 		.bind = true,
1235 	};
1236 	struct xe_vm *vm = xe_vma_vm(vma);
1237 	u32 num_entries;
1238 	struct dma_fence *fence;
1239 	struct invalidation_fence *ifence = NULL;
1240 	struct xe_range_fence *rfence;
1241 	int err;
1242 
1243 	bind_pt_update.locked = false;
1244 	xe_bo_assert_held(xe_vma_bo(vma));
1245 	xe_vm_assert_held(vm);
1246 
1247 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
1248 	       "Preparing bind, with range [%llx...%llx) engine %p.\n",
1249 	       xe_vma_start(vma), xe_vma_end(vma), q);
1250 
1251 	err = xe_pt_prepare_bind(tile, vma, entries, &num_entries);
1252 	if (err)
1253 		goto err;
1254 
1255 	err = dma_resv_reserve_fences(xe_vm_resv(vm), 1);
1256 	if (!err && !xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm)
1257 		err = dma_resv_reserve_fences(xe_vma_bo(vma)->ttm.base.resv, 1);
1258 	if (err)
1259 		goto err;
1260 
1261 	xe_tile_assert(tile, num_entries <= ARRAY_SIZE(entries));
1262 
1263 	xe_vm_dbg_print_entries(tile_to_xe(tile), entries, num_entries);
1264 	xe_pt_calc_rfence_interval(vma, &bind_pt_update, entries,
1265 				   num_entries);
1266 
1267 	/*
1268 	 * If rebind, we have to invalidate TLB on !LR vms to invalidate
1269 	 * cached PTEs point to freed memory. on LR vms this is done
1270 	 * automatically when the context is re-enabled by the rebind worker,
1271 	 * or in fault mode it was invalidated on PTE zapping.
1272 	 *
1273 	 * If !rebind, and scratch enabled VMs, there is a chance the scratch
1274 	 * PTE is already cached in the TLB so it needs to be invalidated.
1275 	 * on !LR VMs this is done in the ring ops preceding a batch, but on
1276 	 * non-faulting LR, in particular on user-space batch buffer chaining,
1277 	 * it needs to be done here.
1278 	 */
1279 	if ((!rebind && xe_vm_has_scratch(vm) && xe_vm_in_preempt_fence_mode(vm))) {
1280 		ifence = kzalloc(sizeof(*ifence), GFP_KERNEL);
1281 		if (!ifence)
1282 			return ERR_PTR(-ENOMEM);
1283 	} else if (rebind && !xe_vm_in_lr_mode(vm)) {
1284 		/* We bump also if batch_invalidate_tlb is true */
1285 		vm->tlb_flush_seqno++;
1286 	}
1287 
1288 	rfence = kzalloc(sizeof(*rfence), GFP_KERNEL);
1289 	if (!rfence) {
1290 		kfree(ifence);
1291 		return ERR_PTR(-ENOMEM);
1292 	}
1293 
1294 	fence = xe_migrate_update_pgtables(tile->migrate,
1295 					   vm, xe_vma_bo(vma), q,
1296 					   entries, num_entries,
1297 					   syncs, num_syncs,
1298 					   &bind_pt_update.base);
1299 	if (!IS_ERR(fence)) {
1300 		bool last_munmap_rebind = vma->gpuva.flags & XE_VMA_LAST_REBIND;
1301 		LLIST_HEAD(deferred);
1302 		int err;
1303 
1304 		err = xe_range_fence_insert(&vm->rftree[tile->id], rfence,
1305 					    &xe_range_fence_kfree_ops,
1306 					    bind_pt_update.base.start,
1307 					    bind_pt_update.base.last, fence);
1308 		if (err)
1309 			dma_fence_wait(fence, false);
1310 
1311 		/* TLB invalidation must be done before signaling rebind */
1312 		if (ifence) {
1313 			int err = invalidation_fence_init(tile->primary_gt,
1314 							  ifence, fence,
1315 							  xe_vma_start(vma),
1316 							  xe_vma_end(vma),
1317 							  xe_vma_vm(vma)->usm.asid);
1318 			if (err) {
1319 				dma_fence_put(fence);
1320 				kfree(ifence);
1321 				return ERR_PTR(err);
1322 			}
1323 			fence = &ifence->base.base;
1324 		}
1325 
1326 		/* add shared fence now for pagetable delayed destroy */
1327 		dma_resv_add_fence(xe_vm_resv(vm), fence, rebind ||
1328 				   last_munmap_rebind ?
1329 				   DMA_RESV_USAGE_KERNEL :
1330 				   DMA_RESV_USAGE_BOOKKEEP);
1331 
1332 		if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm)
1333 			dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence,
1334 					   DMA_RESV_USAGE_BOOKKEEP);
1335 		xe_pt_commit_bind(vma, entries, num_entries, rebind,
1336 				  bind_pt_update.locked ? &deferred : NULL);
1337 
1338 		/* This vma is live (again?) now */
1339 		vma->tile_present |= BIT(tile->id);
1340 
1341 		if (bind_pt_update.locked) {
1342 			to_userptr_vma(vma)->userptr.initial_bind = true;
1343 			up_read(&vm->userptr.notifier_lock);
1344 			xe_bo_put_commit(&deferred);
1345 		}
1346 		if (!rebind && last_munmap_rebind &&
1347 		    xe_vm_in_preempt_fence_mode(vm))
1348 			xe_vm_queue_rebind_worker(vm);
1349 	} else {
1350 		kfree(rfence);
1351 		kfree(ifence);
1352 		if (bind_pt_update.locked)
1353 			up_read(&vm->userptr.notifier_lock);
1354 		xe_pt_abort_bind(vma, entries, num_entries);
1355 	}
1356 
1357 	return fence;
1358 
1359 err:
1360 	return ERR_PTR(err);
1361 }
1362 
1363 struct xe_pt_stage_unbind_walk {
1364 	/** @base: The pagewalk base-class. */
1365 	struct xe_pt_walk base;
1366 
1367 	/* Input parameters for the walk */
1368 	/** @tile: The tile we're unbinding from. */
1369 	struct xe_tile *tile;
1370 
1371 	/**
1372 	 * @modified_start: Walk range start, modified to include any
1373 	 * shared pagetables that we're the only user of and can thus
1374 	 * treat as private.
1375 	 */
1376 	u64 modified_start;
1377 	/** @modified_end: Walk range start, modified like @modified_start. */
1378 	u64 modified_end;
1379 
1380 	/* Output */
1381 	/* @wupd: Structure to track the page-table updates we're building */
1382 	struct xe_walk_update wupd;
1383 };
1384 
1385 /*
1386  * Check whether this range is the only one populating this pagetable,
1387  * and in that case, update the walk range checks so that higher levels don't
1388  * view us as a shared pagetable.
1389  */
1390 static bool xe_pt_check_kill(u64 addr, u64 next, unsigned int level,
1391 			     const struct xe_pt *child,
1392 			     enum page_walk_action *action,
1393 			     struct xe_pt_walk *walk)
1394 {
1395 	struct xe_pt_stage_unbind_walk *xe_walk =
1396 		container_of(walk, typeof(*xe_walk), base);
1397 	unsigned int shift = walk->shifts[level];
1398 	u64 size = 1ull << shift;
1399 
1400 	if (IS_ALIGNED(addr, size) && IS_ALIGNED(next, size) &&
1401 	    ((next - addr) >> shift) == child->num_live) {
1402 		u64 size = 1ull << walk->shifts[level + 1];
1403 
1404 		*action = ACTION_CONTINUE;
1405 
1406 		if (xe_walk->modified_start >= addr)
1407 			xe_walk->modified_start = round_down(addr, size);
1408 		if (xe_walk->modified_end <= next)
1409 			xe_walk->modified_end = round_up(next, size);
1410 
1411 		return true;
1412 	}
1413 
1414 	return false;
1415 }
1416 
1417 static int xe_pt_stage_unbind_entry(struct xe_ptw *parent, pgoff_t offset,
1418 				    unsigned int level, u64 addr, u64 next,
1419 				    struct xe_ptw **child,
1420 				    enum page_walk_action *action,
1421 				    struct xe_pt_walk *walk)
1422 {
1423 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
1424 
1425 	XE_WARN_ON(!*child);
1426 	XE_WARN_ON(!level);
1427 
1428 	xe_pt_check_kill(addr, next, level - 1, xe_child, action, walk);
1429 
1430 	return 0;
1431 }
1432 
1433 static int
1434 xe_pt_stage_unbind_post_descend(struct xe_ptw *parent, pgoff_t offset,
1435 				unsigned int level, u64 addr, u64 next,
1436 				struct xe_ptw **child,
1437 				enum page_walk_action *action,
1438 				struct xe_pt_walk *walk)
1439 {
1440 	struct xe_pt_stage_unbind_walk *xe_walk =
1441 		container_of(walk, typeof(*xe_walk), base);
1442 	struct xe_pt *xe_child = container_of(*child, typeof(*xe_child), base);
1443 	pgoff_t end_offset;
1444 	u64 size = 1ull << walk->shifts[--level];
1445 
1446 	if (!IS_ALIGNED(addr, size))
1447 		addr = xe_walk->modified_start;
1448 	if (!IS_ALIGNED(next, size))
1449 		next = xe_walk->modified_end;
1450 
1451 	/* Parent == *child is the root pt. Don't kill it. */
1452 	if (parent != *child &&
1453 	    xe_pt_check_kill(addr, next, level, xe_child, action, walk))
1454 		return 0;
1455 
1456 	if (!xe_pt_nonshared_offsets(addr, next, level, walk, action, &offset,
1457 				     &end_offset))
1458 		return 0;
1459 
1460 	(void)xe_pt_new_shared(&xe_walk->wupd, xe_child, offset, false);
1461 	xe_walk->wupd.updates[level].update->qwords = end_offset - offset;
1462 
1463 	return 0;
1464 }
1465 
1466 static const struct xe_pt_walk_ops xe_pt_stage_unbind_ops = {
1467 	.pt_entry = xe_pt_stage_unbind_entry,
1468 	.pt_post_descend = xe_pt_stage_unbind_post_descend,
1469 };
1470 
1471 /**
1472  * xe_pt_stage_unbind() - Build page-table update structures for an unbind
1473  * operation
1474  * @tile: The tile we're unbinding for.
1475  * @vma: The vma we're unbinding.
1476  * @entries: Caller-provided storage for the update structures.
1477  *
1478  * Builds page-table update structures for an unbind operation. The function
1479  * will attempt to remove all page-tables that we're the only user
1480  * of, and for that to work, the unbind operation must be committed in the
1481  * same critical section that blocks racing binds to the same page-table tree.
1482  *
1483  * Return: The number of entries used.
1484  */
1485 static unsigned int xe_pt_stage_unbind(struct xe_tile *tile, struct xe_vma *vma,
1486 				       struct xe_vm_pgtable_update *entries)
1487 {
1488 	struct xe_pt_stage_unbind_walk xe_walk = {
1489 		.base = {
1490 			.ops = &xe_pt_stage_unbind_ops,
1491 			.shifts = xe_normal_pt_shifts,
1492 			.max_level = XE_PT_HIGHEST_LEVEL,
1493 		},
1494 		.tile = tile,
1495 		.modified_start = xe_vma_start(vma),
1496 		.modified_end = xe_vma_end(vma),
1497 		.wupd.entries = entries,
1498 	};
1499 	struct xe_pt *pt = xe_vma_vm(vma)->pt_root[tile->id];
1500 
1501 	(void)xe_pt_walk_shared(&pt->base, pt->level, xe_vma_start(vma),
1502 				xe_vma_end(vma), &xe_walk.base);
1503 
1504 	return xe_walk.wupd.num_used_entries;
1505 }
1506 
1507 static void
1508 xe_migrate_clear_pgtable_callback(struct xe_migrate_pt_update *pt_update,
1509 				  struct xe_tile *tile, struct iosys_map *map,
1510 				  void *ptr, u32 qword_ofs, u32 num_qwords,
1511 				  const struct xe_vm_pgtable_update *update)
1512 {
1513 	struct xe_vma *vma = pt_update->vma;
1514 	u64 empty = __xe_pt_empty_pte(tile, xe_vma_vm(vma), update->pt->level);
1515 	int i;
1516 
1517 	if (map && map->is_iomem)
1518 		for (i = 0; i < num_qwords; ++i)
1519 			xe_map_wr(tile_to_xe(tile), map, (qword_ofs + i) *
1520 				  sizeof(u64), u64, empty);
1521 	else if (map)
1522 		memset64(map->vaddr + qword_ofs * sizeof(u64), empty,
1523 			 num_qwords);
1524 	else
1525 		memset64(ptr, empty, num_qwords);
1526 }
1527 
1528 static void
1529 xe_pt_commit_unbind(struct xe_vma *vma,
1530 		    struct xe_vm_pgtable_update *entries, u32 num_entries,
1531 		    struct llist_head *deferred)
1532 {
1533 	u32 j;
1534 
1535 	xe_pt_commit_locks_assert(vma);
1536 
1537 	for (j = 0; j < num_entries; ++j) {
1538 		struct xe_vm_pgtable_update *entry = &entries[j];
1539 		struct xe_pt *pt = entry->pt;
1540 
1541 		pt->num_live -= entry->qwords;
1542 		if (pt->level) {
1543 			struct xe_pt_dir *pt_dir = as_xe_pt_dir(pt);
1544 			u32 i;
1545 
1546 			for (i = entry->ofs; i < entry->ofs + entry->qwords;
1547 			     i++) {
1548 				if (xe_pt_entry(pt_dir, i))
1549 					xe_pt_destroy(xe_pt_entry(pt_dir, i),
1550 						      xe_vma_vm(vma)->flags, deferred);
1551 
1552 				pt_dir->children[i] = NULL;
1553 			}
1554 		}
1555 	}
1556 }
1557 
1558 static const struct xe_migrate_pt_update_ops unbind_ops = {
1559 	.populate = xe_migrate_clear_pgtable_callback,
1560 	.pre_commit = xe_pt_pre_commit,
1561 };
1562 
1563 static const struct xe_migrate_pt_update_ops userptr_unbind_ops = {
1564 	.populate = xe_migrate_clear_pgtable_callback,
1565 	.pre_commit = xe_pt_userptr_pre_commit,
1566 };
1567 
1568 /**
1569  * __xe_pt_unbind_vma() - Disconnect and free a page-table tree for the vma
1570  * address range.
1571  * @tile: The tile to unbind for.
1572  * @vma: The vma to unbind.
1573  * @q: The exec_queue with which to do pipelined page-table updates.
1574  * @syncs: Entries to sync on before disconnecting the tree to be destroyed.
1575  * @num_syncs: Number of @sync entries.
1576  *
1577  * This function builds a the xe_vm_pgtable_update entries abstracting the
1578  * operations needed to detach the page-table tree to be destroyed from the
1579  * man vm tree.
1580  * It then takes the relevant locks and submits the operations for
1581  * pipelined detachment of the gpu page-table from  the vm main tree,
1582  * (which can be done either by the cpu and the GPU), Finally it frees the
1583  * detached page-table tree.
1584  *
1585  * Return: A valid dma-fence representing the pipelined detachment operation
1586  * on success, an error pointer on error.
1587  */
1588 struct dma_fence *
1589 __xe_pt_unbind_vma(struct xe_tile *tile, struct xe_vma *vma, struct xe_exec_queue *q,
1590 		   struct xe_sync_entry *syncs, u32 num_syncs)
1591 {
1592 	struct xe_vm_pgtable_update entries[XE_VM_MAX_LEVEL * 2 + 1];
1593 	struct xe_pt_migrate_pt_update unbind_pt_update = {
1594 		.base = {
1595 			.ops = xe_vma_is_userptr(vma) ? &userptr_unbind_ops :
1596 			&unbind_ops,
1597 			.vma = vma,
1598 			.tile_id = tile->id,
1599 		},
1600 	};
1601 	struct xe_vm *vm = xe_vma_vm(vma);
1602 	u32 num_entries;
1603 	struct dma_fence *fence = NULL;
1604 	struct invalidation_fence *ifence;
1605 	struct xe_range_fence *rfence;
1606 	int err;
1607 
1608 	LLIST_HEAD(deferred);
1609 
1610 	xe_bo_assert_held(xe_vma_bo(vma));
1611 	xe_vm_assert_held(vm);
1612 
1613 	vm_dbg(&xe_vma_vm(vma)->xe->drm,
1614 	       "Preparing unbind, with range [%llx...%llx) engine %p.\n",
1615 	       xe_vma_start(vma), xe_vma_end(vma), q);
1616 
1617 	num_entries = xe_pt_stage_unbind(tile, vma, entries);
1618 	xe_tile_assert(tile, num_entries <= ARRAY_SIZE(entries));
1619 
1620 	xe_vm_dbg_print_entries(tile_to_xe(tile), entries, num_entries);
1621 	xe_pt_calc_rfence_interval(vma, &unbind_pt_update, entries,
1622 				   num_entries);
1623 
1624 	err = dma_resv_reserve_fences(xe_vm_resv(vm), 1);
1625 	if (!err && !xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm)
1626 		err = dma_resv_reserve_fences(xe_vma_bo(vma)->ttm.base.resv, 1);
1627 	if (err)
1628 		return ERR_PTR(err);
1629 
1630 	ifence = kzalloc(sizeof(*ifence), GFP_KERNEL);
1631 	if (!ifence)
1632 		return ERR_PTR(-ENOMEM);
1633 
1634 	rfence = kzalloc(sizeof(*rfence), GFP_KERNEL);
1635 	if (!rfence) {
1636 		kfree(ifence);
1637 		return ERR_PTR(-ENOMEM);
1638 	}
1639 
1640 	/*
1641 	 * Even if we were already evicted and unbind to destroy, we need to
1642 	 * clear again here. The eviction may have updated pagetables at a
1643 	 * lower level, because it needs to be more conservative.
1644 	 */
1645 	fence = xe_migrate_update_pgtables(tile->migrate,
1646 					   vm, NULL, q ? q :
1647 					   vm->q[tile->id],
1648 					   entries, num_entries,
1649 					   syncs, num_syncs,
1650 					   &unbind_pt_update.base);
1651 	if (!IS_ERR(fence)) {
1652 		int err;
1653 
1654 		err = xe_range_fence_insert(&vm->rftree[tile->id], rfence,
1655 					    &xe_range_fence_kfree_ops,
1656 					    unbind_pt_update.base.start,
1657 					    unbind_pt_update.base.last, fence);
1658 		if (err)
1659 			dma_fence_wait(fence, false);
1660 
1661 		/* TLB invalidation must be done before signaling unbind */
1662 		err = invalidation_fence_init(tile->primary_gt, ifence, fence,
1663 					      xe_vma_start(vma),
1664 					      xe_vma_end(vma),
1665 					      xe_vma_vm(vma)->usm.asid);
1666 		if (err) {
1667 			dma_fence_put(fence);
1668 			kfree(ifence);
1669 			return ERR_PTR(err);
1670 		}
1671 		fence = &ifence->base.base;
1672 
1673 		/* add shared fence now for pagetable delayed destroy */
1674 		dma_resv_add_fence(xe_vm_resv(vm), fence,
1675 				   DMA_RESV_USAGE_BOOKKEEP);
1676 
1677 		/* This fence will be installed by caller when doing eviction */
1678 		if (!xe_vma_has_no_bo(vma) && !xe_vma_bo(vma)->vm)
1679 			dma_resv_add_fence(xe_vma_bo(vma)->ttm.base.resv, fence,
1680 					   DMA_RESV_USAGE_BOOKKEEP);
1681 		xe_pt_commit_unbind(vma, entries, num_entries,
1682 				    unbind_pt_update.locked ? &deferred : NULL);
1683 		vma->tile_present &= ~BIT(tile->id);
1684 	} else {
1685 		kfree(rfence);
1686 		kfree(ifence);
1687 	}
1688 
1689 	if (!vma->tile_present)
1690 		list_del_init(&vma->combined_links.rebind);
1691 
1692 	if (unbind_pt_update.locked) {
1693 		xe_tile_assert(tile, xe_vma_is_userptr(vma));
1694 
1695 		if (!vma->tile_present) {
1696 			spin_lock(&vm->userptr.invalidated_lock);
1697 			list_del_init(&to_userptr_vma(vma)->userptr.invalidate_link);
1698 			spin_unlock(&vm->userptr.invalidated_lock);
1699 		}
1700 		up_read(&vm->userptr.notifier_lock);
1701 		xe_bo_put_commit(&deferred);
1702 	}
1703 
1704 	return fence;
1705 }
1706