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