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