xref: /linux/drivers/gpu/drm/xe/xe_bo.c (revision 570f7e331f5febb30f1384817463c7e42b65ca7d)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2021 Intel Corporation
4  */
5 
6 #include "xe_bo.h"
7 
8 #include <linux/dma-buf.h>
9 #include <linux/nospec.h>
10 
11 #include <drm/drm_drv.h>
12 #include <drm/drm_dumb_buffers.h>
13 #include <drm/drm_gem_ttm_helper.h>
14 #include <drm/drm_managed.h>
15 #include <drm/ttm/ttm_backup.h>
16 #include <drm/ttm/ttm_device.h>
17 #include <drm/ttm/ttm_placement.h>
18 #include <drm/ttm/ttm_tt.h>
19 #include <uapi/drm/xe_drm.h>
20 
21 #include <kunit/static_stub.h>
22 
23 #include <trace/events/gpu_mem.h>
24 
25 #include "xe_device.h"
26 #include "xe_dma_buf.h"
27 #include "xe_drm_client.h"
28 #include "xe_ggtt.h"
29 #include "xe_map.h"
30 #include "xe_migrate.h"
31 #include "xe_pat.h"
32 #include "xe_pm.h"
33 #include "xe_preempt_fence.h"
34 #include "xe_pxp.h"
35 #include "xe_res_cursor.h"
36 #include "xe_shrinker.h"
37 #include "xe_sriov_vf_ccs.h"
38 #include "xe_tile.h"
39 #include "xe_trace_bo.h"
40 #include "xe_ttm_stolen_mgr.h"
41 #include "xe_vm.h"
42 #include "xe_vram_types.h"
43 
44 const char *const xe_mem_type_to_name[TTM_NUM_MEM_TYPES]  = {
45 	[XE_PL_SYSTEM] = "system",
46 	[XE_PL_TT] = "gtt",
47 	[XE_PL_VRAM0] = "vram0",
48 	[XE_PL_VRAM1] = "vram1",
49 	[XE_PL_STOLEN] = "stolen"
50 };
51 
52 static const struct ttm_place sys_placement_flags = {
53 	.fpfn = 0,
54 	.lpfn = 0,
55 	.mem_type = XE_PL_SYSTEM,
56 	.flags = 0,
57 };
58 
59 static struct ttm_placement sys_placement = {
60 	.num_placement = 1,
61 	.placement = &sys_placement_flags,
62 };
63 
64 static struct ttm_placement purge_placement;
65 
66 static const struct ttm_place tt_placement_flags[] = {
67 	{
68 		.fpfn = 0,
69 		.lpfn = 0,
70 		.mem_type = XE_PL_TT,
71 		.flags = TTM_PL_FLAG_DESIRED,
72 	},
73 	{
74 		.fpfn = 0,
75 		.lpfn = 0,
76 		.mem_type = XE_PL_SYSTEM,
77 		.flags = TTM_PL_FLAG_FALLBACK,
78 	}
79 };
80 
81 static struct ttm_placement tt_placement = {
82 	.num_placement = 2,
83 	.placement = tt_placement_flags,
84 };
85 
86 #define for_each_set_bo_vram_flag(bit__, bo_flags__) \
87 	for (unsigned int __bit_tmp = BIT(0); __bit_tmp <= XE_BO_FLAG_VRAM_MASK; __bit_tmp <<= 1) \
88 		for_each_if(((bit__) = __bit_tmp) & (bo_flags__) & XE_BO_FLAG_VRAM_MASK)
89 
90 bool mem_type_is_vram(u32 mem_type)
91 {
92 	return mem_type >= XE_PL_VRAM0 && mem_type != XE_PL_STOLEN;
93 }
94 
95 static bool resource_is_stolen_vram(struct xe_device *xe, struct ttm_resource *res)
96 {
97 	return res->mem_type == XE_PL_STOLEN && IS_DGFX(xe);
98 }
99 
100 static bool resource_is_vram(struct ttm_resource *res)
101 {
102 	return mem_type_is_vram(res->mem_type);
103 }
104 
105 bool xe_bo_is_vram(struct xe_bo *bo)
106 {
107 	return resource_is_vram(bo->ttm.resource) ||
108 		resource_is_stolen_vram(xe_bo_device(bo), bo->ttm.resource);
109 }
110 
111 bool xe_bo_is_stolen(struct xe_bo *bo)
112 {
113 	return bo->ttm.resource->mem_type == XE_PL_STOLEN;
114 }
115 
116 /**
117  * xe_bo_has_single_placement - check if BO is placed only in one memory location
118  * @bo: The BO
119  *
120  * This function checks whether a given BO is placed in only one memory location.
121  *
122  * Returns: true if the BO is placed in a single memory location, false otherwise.
123  *
124  */
125 bool xe_bo_has_single_placement(struct xe_bo *bo)
126 {
127 	return bo->placement.num_placement == 1;
128 }
129 
130 /**
131  * xe_bo_is_stolen_devmem - check if BO is of stolen type accessed via PCI BAR
132  * @bo: The BO
133  *
134  * The stolen memory is accessed through the PCI BAR for both DGFX and some
135  * integrated platforms that have a dedicated bit in the PTE for devmem (DM).
136  *
137  * Returns: true if it's stolen memory accessed via PCI BAR, false otherwise.
138  */
139 bool xe_bo_is_stolen_devmem(struct xe_bo *bo)
140 {
141 	return xe_bo_is_stolen(bo) &&
142 		GRAPHICS_VERx100(xe_bo_device(bo)) >= 1270;
143 }
144 
145 /**
146  * xe_bo_is_vm_bound - check if BO has any mappings through VM_BIND
147  * @bo: The BO
148  *
149  * Check if a given bo is bound through VM_BIND. This requires the
150  * reservation lock for the BO to be held.
151  *
152  * Returns: boolean
153  */
154 bool xe_bo_is_vm_bound(struct xe_bo *bo)
155 {
156 	xe_bo_assert_held(bo);
157 
158 	return !list_empty(&bo->ttm.base.gpuva.list);
159 }
160 
161 static bool xe_bo_is_user(struct xe_bo *bo)
162 {
163 	return bo->flags & XE_BO_FLAG_USER;
164 }
165 
166 static struct xe_migrate *
167 mem_type_to_migrate(struct xe_device *xe, u32 mem_type)
168 {
169 	struct xe_tile *tile;
170 
171 	xe_assert(xe, mem_type == XE_PL_STOLEN || mem_type_is_vram(mem_type));
172 	tile = &xe->tiles[mem_type == XE_PL_STOLEN ? 0 : (mem_type - XE_PL_VRAM0)];
173 	return tile->migrate;
174 }
175 
176 static void try_add_system(struct xe_device *xe, struct xe_bo *bo,
177 			   u32 bo_flags, u32 *c)
178 {
179 	if (bo_flags & XE_BO_FLAG_SYSTEM) {
180 		xe_assert(xe, *c < ARRAY_SIZE(bo->placements));
181 
182 		bo->placements[*c] = (struct ttm_place) {
183 			.mem_type = XE_PL_TT,
184 			.flags = (bo_flags & XE_BO_FLAG_VRAM_MASK) ?
185 			TTM_PL_FLAG_FALLBACK : 0,
186 		};
187 		*c += 1;
188 	}
189 }
190 
191 static bool force_contiguous(u32 bo_flags)
192 {
193 	if (bo_flags & XE_BO_FLAG_STOLEN)
194 		return true; /* users expect this */
195 	else if (bo_flags & XE_BO_FLAG_PINNED &&
196 		 !(bo_flags & XE_BO_FLAG_PINNED_LATE_RESTORE))
197 		return true; /* needs vmap */
198 	else if (bo_flags & XE_BO_FLAG_CPU_ADDR_MIRROR)
199 		return true;
200 
201 	/*
202 	 * For eviction / restore on suspend / resume objects pinned in VRAM
203 	 * must be contiguous, also only contiguous BOs support xe_bo_vmap.
204 	 */
205 	return bo_flags & XE_BO_FLAG_NEEDS_CPU_ACCESS &&
206 	       bo_flags & XE_BO_FLAG_PINNED;
207 }
208 
209 static u8 vram_bo_flag_to_tile_id(struct xe_device *xe, u32 vram_bo_flag)
210 {
211 	xe_assert(xe, vram_bo_flag & XE_BO_FLAG_VRAM_MASK);
212 	xe_assert(xe, (vram_bo_flag & (vram_bo_flag - 1)) == 0);
213 
214 	return __ffs(vram_bo_flag >> (__ffs(XE_BO_FLAG_VRAM0) - 1)) - 1;
215 }
216 
217 static u32 bo_vram_flags_to_vram_placement(struct xe_device *xe, u32 bo_flags, u32 vram_flag,
218 					   enum ttm_bo_type type)
219 {
220 	u8 tile_id = vram_bo_flag_to_tile_id(xe, vram_flag);
221 
222 	xe_assert(xe, tile_id < xe->info.tile_count);
223 
224 	if (type == ttm_bo_type_kernel && !(bo_flags & XE_BO_FLAG_FORCE_USER_VRAM))
225 		return xe->tiles[tile_id].mem.kernel_vram->placement;
226 	else
227 		return xe->tiles[tile_id].mem.vram->placement;
228 }
229 
230 static void add_vram(struct xe_device *xe, struct xe_bo *bo,
231 		     struct ttm_place *places, u32 bo_flags, u32 mem_type, u32 *c)
232 {
233 	struct ttm_place place = { .mem_type = mem_type };
234 	struct ttm_resource_manager *mgr = ttm_manager_type(&xe->ttm, mem_type);
235 	struct xe_ttm_vram_mgr *vram_mgr = to_xe_ttm_vram_mgr(mgr);
236 
237 	struct xe_vram_region *vram;
238 	u64 io_size;
239 
240 	xe_assert(xe, *c < ARRAY_SIZE(bo->placements));
241 
242 	vram = container_of(vram_mgr, struct xe_vram_region, ttm);
243 	xe_assert(xe, vram && vram->usable_size);
244 	io_size = vram->io_size;
245 
246 	if (force_contiguous(bo_flags))
247 		place.flags |= TTM_PL_FLAG_CONTIGUOUS;
248 
249 	if (io_size < vram->usable_size) {
250 		if (bo_flags & XE_BO_FLAG_NEEDS_CPU_ACCESS) {
251 			place.fpfn = 0;
252 			place.lpfn = io_size >> PAGE_SHIFT;
253 		} else {
254 			place.flags |= TTM_PL_FLAG_TOPDOWN;
255 		}
256 	}
257 	places[*c] = place;
258 	*c += 1;
259 }
260 
261 static void try_add_vram(struct xe_device *xe, struct xe_bo *bo,
262 			 u32 bo_flags, enum ttm_bo_type type, u32 *c)
263 {
264 	u32 vram_flag;
265 
266 	for_each_set_bo_vram_flag(vram_flag, bo_flags) {
267 		u32 pl = bo_vram_flags_to_vram_placement(xe, bo_flags, vram_flag, type);
268 
269 		add_vram(xe, bo, bo->placements, bo_flags, pl, c);
270 	}
271 }
272 
273 static void try_add_stolen(struct xe_device *xe, struct xe_bo *bo,
274 			   u32 bo_flags, u32 *c)
275 {
276 	if (bo_flags & XE_BO_FLAG_STOLEN) {
277 		xe_assert(xe, *c < ARRAY_SIZE(bo->placements));
278 
279 		bo->placements[*c] = (struct ttm_place) {
280 			.mem_type = XE_PL_STOLEN,
281 			.flags = force_contiguous(bo_flags) ?
282 				TTM_PL_FLAG_CONTIGUOUS : 0,
283 		};
284 		*c += 1;
285 	}
286 }
287 
288 static int __xe_bo_placement_for_flags(struct xe_device *xe, struct xe_bo *bo,
289 				       u32 bo_flags, enum ttm_bo_type type)
290 {
291 	u32 c = 0;
292 
293 	try_add_vram(xe, bo, bo_flags, type, &c);
294 	try_add_system(xe, bo, bo_flags, &c);
295 	try_add_stolen(xe, bo, bo_flags, &c);
296 
297 	if (!c)
298 		return -EINVAL;
299 
300 	bo->placement = (struct ttm_placement) {
301 		.num_placement = c,
302 		.placement = bo->placements,
303 	};
304 
305 	return 0;
306 }
307 
308 int xe_bo_placement_for_flags(struct xe_device *xe, struct xe_bo *bo,
309 			      u32 bo_flags, enum ttm_bo_type type)
310 {
311 	xe_bo_assert_held(bo);
312 	return __xe_bo_placement_for_flags(xe, bo, bo_flags, type);
313 }
314 
315 static void xe_evict_flags(struct ttm_buffer_object *tbo,
316 			   struct ttm_placement *placement)
317 {
318 	struct xe_device *xe = container_of(tbo->bdev, typeof(*xe), ttm);
319 	bool device_unplugged = drm_dev_is_unplugged(&xe->drm);
320 	struct xe_bo *bo;
321 
322 	if (!xe_bo_is_xe_bo(tbo)) {
323 		/* Don't handle scatter gather BOs */
324 		if (tbo->type == ttm_bo_type_sg) {
325 			placement->num_placement = 0;
326 			return;
327 		}
328 
329 		*placement = device_unplugged ? purge_placement : sys_placement;
330 		return;
331 	}
332 
333 	bo = ttm_to_xe_bo(tbo);
334 	if (bo->flags & XE_BO_FLAG_CPU_ADDR_MIRROR) {
335 		*placement = sys_placement;
336 		return;
337 	}
338 
339 	if (device_unplugged && !tbo->base.dma_buf) {
340 		*placement = purge_placement;
341 		return;
342 	}
343 
344 	if (xe_bo_madv_is_dontneed(bo)) {
345 		/*
346 		 * We can't use purge_placement here, since we need to trigger
347 		 * our own purge procedure at the start of xe_bo_move(), which
348 		 * would otherwise be skipped. At the same time we don't want
349 		 * ttm to then populate the tt with dst pages, before the move
350 		 * callback, hence use sys_placement here.
351 		 */
352 		*placement = sys_placement;
353 		return;
354 	}
355 
356 	/*
357 	 * For xe, sg bos that are evicted to system just triggers a
358 	 * rebind of the sg list upon subsequent validation to XE_PL_TT.
359 	 */
360 	switch (tbo->resource->mem_type) {
361 	case XE_PL_VRAM0:
362 	case XE_PL_VRAM1:
363 	case XE_PL_STOLEN:
364 		*placement = tt_placement;
365 		break;
366 	case XE_PL_TT:
367 	default:
368 		*placement = sys_placement;
369 		break;
370 	}
371 }
372 
373 /* struct xe_ttm_tt - Subclassed ttm_tt for xe */
374 struct xe_ttm_tt {
375 	struct ttm_tt ttm;
376 	struct sg_table sgt;
377 	struct sg_table *sg;
378 	/** @purgeable: Whether the content of the pages of @ttm is purgeable. */
379 	bool purgeable;
380 };
381 
382 static int xe_tt_map_sg(struct xe_device *xe, struct ttm_tt *tt)
383 {
384 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
385 	unsigned long num_pages = tt->num_pages;
386 	int ret;
387 
388 	XE_WARN_ON((tt->page_flags & TTM_TT_FLAG_EXTERNAL) &&
389 		   !(tt->page_flags & TTM_TT_FLAG_EXTERNAL_MAPPABLE));
390 
391 	if (xe_tt->sg)
392 		return 0;
393 
394 	ret = sg_alloc_table_from_pages_segment(&xe_tt->sgt, tt->pages,
395 						num_pages, 0,
396 						(u64)num_pages << PAGE_SHIFT,
397 						xe_sg_segment_size(xe->drm.dev),
398 						GFP_KERNEL);
399 	if (ret)
400 		return ret;
401 
402 	xe_tt->sg = &xe_tt->sgt;
403 	ret = dma_map_sgtable(xe->drm.dev, xe_tt->sg, DMA_BIDIRECTIONAL,
404 			      DMA_ATTR_SKIP_CPU_SYNC);
405 	if (ret) {
406 		sg_free_table(xe_tt->sg);
407 		xe_tt->sg = NULL;
408 		return ret;
409 	}
410 
411 	return 0;
412 }
413 
414 static void xe_tt_unmap_sg(struct xe_device *xe, struct ttm_tt *tt)
415 {
416 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
417 
418 	if (xe_tt->sg) {
419 		dma_unmap_sgtable(xe->drm.dev, xe_tt->sg,
420 				  DMA_BIDIRECTIONAL, 0);
421 		sg_free_table(xe_tt->sg);
422 		xe_tt->sg = NULL;
423 	}
424 }
425 
426 struct sg_table *xe_bo_sg(struct xe_bo *bo)
427 {
428 	struct ttm_tt *tt = bo->ttm.ttm;
429 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
430 
431 	return xe_tt->sg;
432 }
433 
434 /*
435  * Account ttm pages against the device shrinker's shrinkable and
436  * purgeable counts.
437  */
438 static void xe_ttm_tt_account_add(struct xe_device *xe, struct ttm_tt *tt)
439 {
440 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
441 
442 	if (xe_tt->purgeable)
443 		xe_shrinker_mod_pages(xe->mem.shrinker, 0, tt->num_pages);
444 	else
445 		xe_shrinker_mod_pages(xe->mem.shrinker, tt->num_pages, 0);
446 }
447 
448 static void xe_ttm_tt_account_subtract(struct xe_device *xe, struct ttm_tt *tt)
449 {
450 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
451 
452 	if (xe_tt->purgeable)
453 		xe_shrinker_mod_pages(xe->mem.shrinker, 0, -(long)tt->num_pages);
454 	else
455 		xe_shrinker_mod_pages(xe->mem.shrinker, -(long)tt->num_pages, 0);
456 }
457 
458 static void update_global_total_pages(struct ttm_device *ttm_dev,
459 				      long num_pages)
460 {
461 #if IS_ENABLED(CONFIG_TRACE_GPU_MEM)
462 	struct xe_device *xe = ttm_to_xe_device(ttm_dev);
463 	u64 global_total_pages =
464 		atomic64_add_return(num_pages, &xe->global_total_pages);
465 
466 	trace_gpu_mem_total(xe->drm.primary->index, 0,
467 			    global_total_pages << PAGE_SHIFT);
468 #endif
469 }
470 
471 static struct ttm_tt *xe_ttm_tt_create(struct ttm_buffer_object *ttm_bo,
472 				       u32 page_flags)
473 {
474 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
475 	struct xe_device *xe = xe_bo_device(bo);
476 	struct xe_ttm_tt *xe_tt;
477 	struct ttm_tt *tt;
478 	unsigned long extra_pages;
479 	enum ttm_caching caching = ttm_cached;
480 	int err;
481 
482 	xe_tt = kzalloc_obj(*xe_tt);
483 	if (!xe_tt)
484 		return NULL;
485 
486 	tt = &xe_tt->ttm;
487 
488 	extra_pages = 0;
489 	if (xe_bo_needs_ccs_pages(bo))
490 		extra_pages = DIV_ROUND_UP(xe_device_ccs_bytes(xe, xe_bo_size(bo)),
491 					   PAGE_SIZE);
492 
493 	/*
494 	 * DGFX system memory is always WB / ttm_cached, since
495 	 * other caching modes are only supported on x86. DGFX
496 	 * GPU system memory accesses are always coherent with the
497 	 * CPU.
498 	 */
499 	if (!IS_DGFX(xe)) {
500 		switch (bo->cpu_caching) {
501 		case DRM_XE_GEM_CPU_CACHING_WC:
502 			caching = ttm_write_combined;
503 			break;
504 		default:
505 			caching = ttm_cached;
506 			break;
507 		}
508 
509 		WARN_ON((bo->flags & XE_BO_FLAG_USER) && !bo->cpu_caching);
510 
511 		/*
512 		 * For Xe_LPG and beyond up to NVL-P (excluding), PPGTT PTE
513 		 * lookups are also non-coherent and require a CPU:WC mapping.
514 		 */
515 		if ((!bo->cpu_caching && bo->flags & XE_BO_FLAG_FORCE_WC) ||
516 		    (!xe->info.has_cached_pt && bo->flags & XE_BO_FLAG_PAGETABLE))
517 			caching = ttm_write_combined;
518 	}
519 
520 	if (bo->flags & XE_BO_FLAG_NEEDS_UC) {
521 		/*
522 		 * Valid only for internally-created buffers only, for
523 		 * which cpu_caching is never initialized.
524 		 */
525 		xe_assert(xe, bo->cpu_caching == 0);
526 		caching = ttm_uncached;
527 	}
528 
529 	if (ttm_bo->type != ttm_bo_type_sg)
530 		page_flags |= TTM_TT_FLAG_EXTERNAL | TTM_TT_FLAG_EXTERNAL_MAPPABLE;
531 
532 	err = ttm_tt_init(tt, &bo->ttm, page_flags, caching, extra_pages);
533 	if (err) {
534 		kfree(xe_tt);
535 		return NULL;
536 	}
537 
538 	if (ttm_bo->type != ttm_bo_type_sg) {
539 		err = ttm_tt_setup_backup(tt);
540 		if (err) {
541 			ttm_tt_fini(tt);
542 			kfree(xe_tt);
543 			return NULL;
544 		}
545 	}
546 
547 	return tt;
548 }
549 
550 static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
551 			      struct ttm_operation_ctx *ctx)
552 {
553 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
554 	int err;
555 
556 	/*
557 	 * dma-bufs are not populated with pages, and the dma-
558 	 * addresses are set up when moved to XE_PL_TT.
559 	 */
560 	if ((tt->page_flags & TTM_TT_FLAG_EXTERNAL) &&
561 	    !(tt->page_flags & TTM_TT_FLAG_EXTERNAL_MAPPABLE))
562 		return 0;
563 
564 	if (ttm_tt_is_backed_up(tt) && !xe_tt->purgeable) {
565 		err = ttm_tt_restore(ttm_dev, tt, ctx);
566 	} else {
567 		ttm_tt_clear_backed_up(tt);
568 		err = ttm_pool_alloc(&ttm_dev->pool, tt, ctx);
569 	}
570 	if (err)
571 		return err;
572 
573 	xe_tt->purgeable = false;
574 	xe_ttm_tt_account_add(ttm_to_xe_device(ttm_dev), tt);
575 	update_global_total_pages(ttm_dev, tt->num_pages);
576 
577 	return 0;
578 }
579 
580 static void xe_ttm_tt_unpopulate(struct ttm_device *ttm_dev, struct ttm_tt *tt)
581 {
582 	struct xe_device *xe = ttm_to_xe_device(ttm_dev);
583 
584 	if ((tt->page_flags & TTM_TT_FLAG_EXTERNAL) &&
585 	    !(tt->page_flags & TTM_TT_FLAG_EXTERNAL_MAPPABLE))
586 		return;
587 
588 	xe_tt_unmap_sg(xe, tt);
589 
590 	ttm_pool_free(&ttm_dev->pool, tt);
591 	xe_ttm_tt_account_subtract(xe, tt);
592 	update_global_total_pages(ttm_dev, -(long)tt->num_pages);
593 }
594 
595 static void xe_ttm_tt_destroy(struct ttm_device *ttm_dev, struct ttm_tt *tt)
596 {
597 	ttm_tt_fini(tt);
598 	kfree(tt);
599 }
600 
601 static bool xe_ttm_resource_visible(struct xe_device *xe, struct ttm_resource *mem)
602 {
603 	struct xe_ttm_vram_mgr_resource *vres;
604 
605 	if (mem->mem_type == XE_PL_STOLEN) {
606 		struct xe_ttm_stolen_mgr *mgr = xe->mem.stolen_mgr;
607 
608 		return mgr->io_base && !xe_ttm_stolen_cpu_access_needs_ggtt(xe);
609 	}
610 
611 	vres = to_xe_ttm_vram_mgr_resource(mem);
612 	return vres->used_visible_size == mem->size;
613 }
614 
615 /**
616  * xe_bo_is_visible_vram - check if BO is placed entirely in visible VRAM.
617  * @bo: The BO
618  *
619  * This function checks whether a given BO resides entirely in memory visible from the CPU
620  *
621  * Returns: true if the BO is entirely visible, false otherwise.
622  *
623  */
624 bool xe_bo_is_visible_vram(struct xe_bo *bo)
625 {
626 	if (drm_WARN_ON(bo->ttm.base.dev, !xe_bo_is_vram(bo)))
627 		return false;
628 
629 	return xe_ttm_resource_visible(xe_bo_device(bo), bo->ttm.resource);
630 }
631 
632 static int xe_ttm_io_mem_reserve(struct ttm_device *bdev,
633 				 struct ttm_resource *mem)
634 {
635 	struct xe_device *xe = ttm_to_xe_device(bdev);
636 
637 	switch (mem->mem_type) {
638 	case XE_PL_SYSTEM:
639 	case XE_PL_TT:
640 		return 0;
641 	case XE_PL_VRAM0:
642 	case XE_PL_VRAM1: {
643 		struct xe_vram_region *vram = xe_map_resource_to_region(mem);
644 
645 		if (!xe_ttm_resource_visible(xe, mem))
646 			return -EINVAL;
647 
648 		mem->bus.offset = mem->start << PAGE_SHIFT;
649 
650 		if (vram->mapping &&
651 		    mem->placement & TTM_PL_FLAG_CONTIGUOUS)
652 			mem->bus.addr = (u8 __force *)vram->mapping +
653 				mem->bus.offset;
654 
655 		mem->bus.offset += vram->io_start;
656 		mem->bus.is_iomem = true;
657 
658 #if  !IS_ENABLED(CONFIG_X86)
659 		mem->bus.caching = ttm_write_combined;
660 #endif
661 		return 0;
662 	} case XE_PL_STOLEN:
663 		return xe_ttm_stolen_io_mem_reserve(xe, mem);
664 	default:
665 		return -EINVAL;
666 	}
667 }
668 
669 static int xe_bo_trigger_rebind(struct xe_device *xe, struct xe_bo *bo,
670 				const struct ttm_operation_ctx *ctx)
671 {
672 	struct dma_resv_iter cursor;
673 	struct dma_fence *fence;
674 	struct drm_gem_object *obj = &bo->ttm.base;
675 	struct drm_gpuvm_bo *vm_bo;
676 	bool idle = false;
677 	int ret = 0;
678 
679 	dma_resv_assert_held(bo->ttm.base.resv);
680 
681 	if (!list_empty(&bo->ttm.base.gpuva.list)) {
682 		dma_resv_iter_begin(&cursor, bo->ttm.base.resv,
683 				    DMA_RESV_USAGE_BOOKKEEP);
684 		dma_resv_for_each_fence_unlocked(&cursor, fence)
685 			dma_fence_enable_signaling(fence);
686 		dma_resv_iter_end(&cursor);
687 	}
688 
689 	drm_gem_for_each_gpuvm_bo(vm_bo, obj) {
690 		struct xe_vm *vm = gpuvm_to_vm(vm_bo->vm);
691 		struct drm_gpuva *gpuva;
692 
693 		if (!xe_vm_in_fault_mode(vm)) {
694 			drm_gpuvm_bo_evict(vm_bo, true);
695 			/*
696 			 * L2 cache may not be flushed, so ensure that is done in
697 			 * xe_vm_invalidate_vma() below
698 			 */
699 			if (!xe_device_is_l2_flush_optimized(xe))
700 				continue;
701 		}
702 
703 		if (!idle) {
704 			long timeout;
705 
706 			if (ctx->no_wait_gpu &&
707 			    !dma_resv_test_signaled(bo->ttm.base.resv,
708 						    DMA_RESV_USAGE_BOOKKEEP))
709 				return -EBUSY;
710 
711 			timeout = dma_resv_wait_timeout(bo->ttm.base.resv,
712 							DMA_RESV_USAGE_BOOKKEEP,
713 							ctx->interruptible,
714 							MAX_SCHEDULE_TIMEOUT);
715 			if (!timeout)
716 				return -ETIME;
717 			if (timeout < 0)
718 				return timeout;
719 
720 			idle = true;
721 		}
722 
723 		drm_gpuvm_bo_for_each_va(gpuva, vm_bo) {
724 			struct xe_vma *vma = gpuva_to_vma(gpuva);
725 
726 			trace_xe_vma_evict(vma);
727 			ret = xe_vm_invalidate_vma(vma);
728 			if (XE_WARN_ON(ret))
729 				return ret;
730 		}
731 	}
732 
733 	return ret;
734 }
735 
736 /*
737  * The dma-buf map_attachment() / unmap_attachment() is hooked up here.
738  * Note that unmapping the attachment is deferred to the next
739  * map_attachment time, or to bo destroy (after idling) whichever comes first.
740  * This is to avoid syncing before unmap_attachment(), assuming that the
741  * caller relies on idling the reservation object before moving the
742  * backing store out. Should that assumption not hold, then we will be able
743  * to unconditionally call unmap_attachment() when moving out to system.
744  */
745 static int xe_bo_move_dmabuf(struct ttm_buffer_object *ttm_bo,
746 			     struct ttm_resource *new_res)
747 {
748 	struct dma_buf_attachment *attach = ttm_bo->base.import_attach;
749 	struct xe_ttm_tt *xe_tt = container_of(ttm_bo->ttm, struct xe_ttm_tt,
750 					       ttm);
751 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
752 	bool device_unplugged = drm_dev_is_unplugged(&xe->drm);
753 	struct sg_table *sg;
754 
755 	xe_assert(xe, attach);
756 	xe_assert(xe, ttm_bo->ttm);
757 
758 	if (device_unplugged && new_res->mem_type == XE_PL_SYSTEM &&
759 	    ttm_bo->sg) {
760 		dma_resv_wait_timeout(ttm_bo->base.resv, DMA_RESV_USAGE_BOOKKEEP,
761 				      false, MAX_SCHEDULE_TIMEOUT);
762 		dma_buf_unmap_attachment(attach, ttm_bo->sg, DMA_BIDIRECTIONAL);
763 		ttm_bo->sg = NULL;
764 	}
765 
766 	if (new_res->mem_type == XE_PL_SYSTEM)
767 		goto out;
768 
769 	if (ttm_bo->sg) {
770 		dma_buf_unmap_attachment(attach, ttm_bo->sg, DMA_BIDIRECTIONAL);
771 		ttm_bo->sg = NULL;
772 	}
773 
774 	sg = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
775 	if (IS_ERR(sg))
776 		return PTR_ERR(sg);
777 
778 	ttm_bo->sg = sg;
779 	xe_tt->sg = sg;
780 
781 out:
782 	ttm_bo_move_null(ttm_bo, new_res);
783 
784 	return 0;
785 }
786 
787 /**
788  * xe_bo_move_notify - Notify subsystems of a pending move
789  * @bo: The buffer object
790  * @ctx: The struct ttm_operation_ctx controlling locking and waits.
791  *
792  * This function notifies subsystems of an upcoming buffer move.
793  * Upon receiving such a notification, subsystems should schedule
794  * halting access to the underlying pages and optionally add a fence
795  * to the buffer object's dma_resv object, that signals when access is
796  * stopped. The caller will wait on all dma_resv fences before
797  * starting the move.
798  *
799  * A subsystem may commence access to the object after obtaining
800  * bindings to the new backing memory under the object lock.
801  *
802  * Return: 0 on success, -EINTR or -ERESTARTSYS if interrupted in fault mode,
803  * negative error code on error.
804  */
805 static int xe_bo_move_notify(struct xe_bo *bo,
806 			     const struct ttm_operation_ctx *ctx)
807 {
808 	struct ttm_buffer_object *ttm_bo = &bo->ttm;
809 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
810 	struct ttm_resource *old_mem = ttm_bo->resource;
811 	u32 old_mem_type = old_mem ? old_mem->mem_type : XE_PL_SYSTEM;
812 	int ret;
813 
814 	/*
815 	 * If this starts to call into many components, consider
816 	 * using a notification chain here.
817 	 */
818 
819 	if (xe_bo_is_pinned(bo))
820 		return -EINVAL;
821 
822 	xe_bo_vunmap(bo);
823 	ret = xe_bo_trigger_rebind(xe, bo, ctx);
824 	if (ret)
825 		return ret;
826 
827 	/* Don't call move_notify() for imported dma-bufs. */
828 	if (ttm_bo->base.dma_buf && !ttm_bo->base.import_attach)
829 		dma_buf_invalidate_mappings(ttm_bo->base.dma_buf);
830 
831 	/*
832 	 * TTM has already nuked the mmap for us (see ttm_bo_unmap_virtual),
833 	 * so if we moved from VRAM make sure to unlink this from the userfault
834 	 * tracking.
835 	 */
836 	if (mem_type_is_vram(old_mem_type)) {
837 		mutex_lock(&xe->mem_access.vram_userfault.lock);
838 		if (!list_empty(&bo->vram_userfault_link))
839 			list_del_init(&bo->vram_userfault_link);
840 		mutex_unlock(&xe->mem_access.vram_userfault.lock);
841 	}
842 
843 	return 0;
844 }
845 
846 /**
847  * xe_bo_set_purgeable_shrinker() - Update shrinker accounting for purgeable state
848  * @bo: Buffer object
849  * @new_state: New purgeable state being set
850  *
851  * Transfers pages between shrinkable and purgeable buckets when the BO
852  * purgeable state changes. Called automatically from xe_bo_set_purgeable_state().
853  */
854 static void xe_bo_set_purgeable_shrinker(struct xe_bo *bo,
855 					 enum xe_madv_purgeable_state new_state)
856 {
857 	struct ttm_buffer_object *ttm_bo = &bo->ttm;
858 	struct ttm_tt *tt = ttm_bo->ttm;
859 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
860 	struct xe_ttm_tt *xe_tt;
861 	long tt_pages;
862 
863 	xe_bo_assert_held(bo);
864 
865 	if (!tt || !ttm_tt_is_populated(tt))
866 		return;
867 
868 	xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
869 	tt_pages = tt->num_pages;
870 
871 	if (!xe_tt->purgeable && new_state == XE_MADV_PURGEABLE_DONTNEED) {
872 		xe_tt->purgeable = true;
873 		/* Transfer pages from shrinkable to purgeable count */
874 		xe_shrinker_mod_pages(xe->mem.shrinker, -tt_pages, tt_pages);
875 	} else if (xe_tt->purgeable && new_state == XE_MADV_PURGEABLE_WILLNEED) {
876 		xe_tt->purgeable = false;
877 		/* Transfer pages from purgeable to shrinkable count */
878 		xe_shrinker_mod_pages(xe->mem.shrinker, tt_pages, -tt_pages);
879 	}
880 }
881 
882 /**
883  * xe_bo_set_purgeable_state() - Set BO purgeable state with validation
884  * @bo: Buffer object
885  * @new_state: New purgeable state
886  *
887  * Sets the purgeable state with lockdep assertions and validates state
888  * transitions. Once a BO is PURGED, it cannot transition to any other state.
889  * Invalid transitions are caught with xe_assert(). Shrinker page accounting
890  * is updated automatically.
891  */
892 void xe_bo_set_purgeable_state(struct xe_bo *bo,
893 			       enum xe_madv_purgeable_state new_state)
894 {
895 	struct xe_device *xe = xe_bo_device(bo);
896 
897 	xe_bo_assert_held(bo);
898 
899 	/* Validate state is one of the known values */
900 	xe_assert(xe, new_state == XE_MADV_PURGEABLE_WILLNEED ||
901 		  new_state == XE_MADV_PURGEABLE_DONTNEED ||
902 		  new_state == XE_MADV_PURGEABLE_PURGED);
903 
904 	/* Once purged, always purged - cannot transition out */
905 	xe_assert(xe, !(bo->purgeable.state == XE_MADV_PURGEABLE_PURGED &&
906 			new_state != XE_MADV_PURGEABLE_PURGED));
907 
908 	bo->purgeable.state = new_state;
909 	xe_bo_set_purgeable_shrinker(bo, new_state);
910 }
911 
912 /**
913  * xe_ttm_bo_purge() - Purge buffer object backing store
914  * @ttm_bo: The TTM buffer object to purge
915  * @ctx: TTM operation context
916  *
917  * This function purges the backing store of a BO marked as DONTNEED and
918  * triggers rebind to invalidate stale GPU mappings. For fault-mode VMs,
919  * this zaps the PTEs. The next GPU access will trigger a page fault and
920  * perform NULL rebind (scratch pages or clear PTEs based on VM config).
921  *
922  * Return: 0 on success, negative error code on failure
923  */
924 static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operation_ctx *ctx)
925 {
926 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
927 	struct ttm_placement place = {};
928 	int ret;
929 
930 	xe_bo_assert_held(bo);
931 
932 	if (!ttm_bo->ttm)
933 		return 0;
934 
935 	if (!xe_bo_madv_is_dontneed(bo))
936 		return 0;
937 
938 	/*
939 	 * Use the standard pre-move hook so we share the same cleanup/invalidate
940 	 * path as migrations: drop any CPU vmap and schedule the necessary GPU
941 	 * unbind/rebind work.
942 	 *
943 	 * This must be called before ttm_bo_validate() frees the pages.
944 	 * May fail in no-wait contexts (fault/shrinker) or if the BO is
945 	 * pinned. Keep state unchanged on failure so we don't end up "PURGED"
946 	 * with stale mappings.
947 	 */
948 	ret = xe_bo_move_notify(bo, ctx);
949 	if (ret)
950 		return ret;
951 
952 	ret = ttm_bo_validate(ttm_bo, &place, ctx);
953 	if (ret)
954 		return ret;
955 
956 	/* Commit the state transition only once invalidation was queued */
957 	xe_bo_set_purgeable_state(bo, XE_MADV_PURGEABLE_PURGED);
958 
959 	return 0;
960 }
961 
962 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
963 		      struct ttm_operation_ctx *ctx,
964 		      struct ttm_resource *new_mem,
965 		      struct ttm_place *hop)
966 {
967 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
968 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
969 	struct ttm_resource *old_mem = ttm_bo->resource;
970 	u32 old_mem_type = old_mem ? old_mem->mem_type : XE_PL_SYSTEM;
971 	struct ttm_tt *ttm = ttm_bo->ttm;
972 	struct xe_migrate *migrate = NULL;
973 	struct dma_fence *fence;
974 	bool move_lacks_source;
975 	bool tt_has_data;
976 	bool needs_clear;
977 	bool handle_system_ccs = (!IS_DGFX(xe) && xe_bo_needs_ccs_pages(bo) &&
978 				  ttm && ttm_tt_is_populated(ttm)) ? true : false;
979 	int ret = 0;
980 
981 	/*
982 	 * Purge only non-shared BOs explicitly marked DONTNEED by userspace.
983 	 * The move_notify callback will handle invalidation asynchronously.
984 	 */
985 	if (evict && xe_bo_madv_is_dontneed(bo)) {
986 		ret = xe_ttm_bo_purge(ttm_bo, ctx);
987 		if (ret)
988 			return ret;
989 
990 		/* Free the unused eviction destination resource */
991 		ttm_resource_free(ttm_bo, &new_mem);
992 		return 0;
993 	}
994 
995 	/* Bo creation path, moving to system or TT. */
996 	if ((!old_mem && ttm) && !handle_system_ccs) {
997 		if (new_mem->mem_type == XE_PL_TT)
998 			ret = xe_tt_map_sg(xe, ttm);
999 		if (!ret)
1000 			ttm_bo_move_null(ttm_bo, new_mem);
1001 		goto out;
1002 	}
1003 
1004 	if (ttm_bo->type == ttm_bo_type_sg) {
1005 		if (new_mem->mem_type == XE_PL_SYSTEM)
1006 			ret = xe_bo_move_notify(bo, ctx);
1007 		if (!ret)
1008 			ret = xe_bo_move_dmabuf(ttm_bo, new_mem);
1009 		return ret;
1010 	}
1011 
1012 	tt_has_data = ttm && (ttm_tt_is_populated(ttm) || ttm_tt_is_swapped(ttm));
1013 
1014 	move_lacks_source = !old_mem || (handle_system_ccs ? (!bo->ccs_cleared) :
1015 					 (!mem_type_is_vram(old_mem_type) && !tt_has_data));
1016 
1017 	needs_clear = (ttm && ttm->page_flags & TTM_TT_FLAG_ZERO_ALLOC) ||
1018 		(!ttm && ttm_bo->type == ttm_bo_type_device);
1019 
1020 	if (new_mem->mem_type == XE_PL_TT) {
1021 		ret = xe_tt_map_sg(xe, ttm);
1022 		if (ret)
1023 			goto out;
1024 	}
1025 
1026 	if ((move_lacks_source && !needs_clear)) {
1027 		ttm_bo_move_null(ttm_bo, new_mem);
1028 		goto out;
1029 	}
1030 
1031 	if (!move_lacks_source && (bo->flags & XE_BO_FLAG_CPU_ADDR_MIRROR) &&
1032 	    new_mem->mem_type == XE_PL_SYSTEM) {
1033 		ret = xe_svm_bo_evict(bo);
1034 		if (!ret) {
1035 			drm_dbg(&xe->drm, "Evict system allocator BO success\n");
1036 			ttm_bo_move_null(ttm_bo, new_mem);
1037 		} else {
1038 			drm_dbg(&xe->drm, "Evict system allocator BO failed=%pe\n",
1039 				ERR_PTR(ret));
1040 		}
1041 
1042 		goto out;
1043 	}
1044 
1045 	if (old_mem_type == XE_PL_SYSTEM && new_mem->mem_type == XE_PL_TT && !handle_system_ccs) {
1046 		ttm_bo_move_null(ttm_bo, new_mem);
1047 		goto out;
1048 	}
1049 
1050 	/*
1051 	 * Failed multi-hop where the old_mem is still marked as
1052 	 * TTM_PL_FLAG_TEMPORARY, should just be a dummy move.
1053 	 */
1054 	if (old_mem_type == XE_PL_TT &&
1055 	    new_mem->mem_type == XE_PL_TT) {
1056 		ttm_bo_move_null(ttm_bo, new_mem);
1057 		goto out;
1058 	}
1059 
1060 	if (!move_lacks_source && !xe_bo_is_pinned(bo)) {
1061 		ret = xe_bo_move_notify(bo, ctx);
1062 		if (ret)
1063 			goto out;
1064 	}
1065 
1066 	if (old_mem_type == XE_PL_TT &&
1067 	    new_mem->mem_type == XE_PL_SYSTEM) {
1068 		long timeout = dma_resv_wait_timeout(ttm_bo->base.resv,
1069 						     DMA_RESV_USAGE_BOOKKEEP,
1070 						     false,
1071 						     MAX_SCHEDULE_TIMEOUT);
1072 		if (timeout < 0) {
1073 			ret = timeout;
1074 			goto out;
1075 		}
1076 
1077 		if (!handle_system_ccs) {
1078 			ttm_bo_move_null(ttm_bo, new_mem);
1079 			goto out;
1080 		}
1081 	}
1082 
1083 	if (!move_lacks_source &&
1084 	    ((old_mem_type == XE_PL_SYSTEM && resource_is_vram(new_mem)) ||
1085 	     (mem_type_is_vram(old_mem_type) &&
1086 	      new_mem->mem_type == XE_PL_SYSTEM))) {
1087 		hop->fpfn = 0;
1088 		hop->lpfn = 0;
1089 		hop->mem_type = XE_PL_TT;
1090 		hop->flags = TTM_PL_FLAG_TEMPORARY;
1091 		ret = -EMULTIHOP;
1092 		goto out;
1093 	}
1094 
1095 	if (bo->tile)
1096 		migrate = bo->tile->migrate;
1097 	else if (resource_is_vram(new_mem))
1098 		migrate = mem_type_to_migrate(xe, new_mem->mem_type);
1099 	else if (mem_type_is_vram(old_mem_type))
1100 		migrate = mem_type_to_migrate(xe, old_mem_type);
1101 	else
1102 		migrate = xe->tiles[0].migrate;
1103 
1104 	xe_assert(xe, migrate);
1105 	trace_xe_bo_move(bo, new_mem->mem_type, old_mem_type, move_lacks_source);
1106 	if (xe_rpm_reclaim_safe(xe)) {
1107 		/*
1108 		 * We might be called through swapout in the validation path of
1109 		 * another TTM device, so acquire rpm here.
1110 		 */
1111 		xe_pm_runtime_get(xe);
1112 	} else {
1113 		drm_WARN_ON(&xe->drm, handle_system_ccs);
1114 		xe_pm_runtime_get_noresume(xe);
1115 	}
1116 
1117 	/*
1118 	 * Attach CCS BBs before submitting the copy job below so a VF
1119 	 * migration racing the copy sees valid, up to date attach state.
1120 	 */
1121 	if (IS_VF_CCS_READY(xe) &&
1122 	    ((move_lacks_source && new_mem->mem_type == XE_PL_TT) ||
1123 	     (old_mem_type == XE_PL_SYSTEM && new_mem->mem_type == XE_PL_TT)) &&
1124 	    handle_system_ccs) {
1125 		ret = xe_sriov_vf_ccs_attach_bo(bo, new_mem);
1126 		if (ret) {
1127 			xe_pm_runtime_put(xe);
1128 			goto out;
1129 		}
1130 	}
1131 
1132 	if (move_lacks_source) {
1133 		u32 flags = 0;
1134 
1135 		if (mem_type_is_vram(new_mem->mem_type))
1136 			flags |= XE_MIGRATE_CLEAR_FLAG_FULL;
1137 		else if (handle_system_ccs)
1138 			flags |= XE_MIGRATE_CLEAR_FLAG_CCS_DATA;
1139 
1140 		fence = xe_migrate_clear(migrate, bo, new_mem, flags);
1141 	} else {
1142 		fence = xe_migrate_copy(migrate, bo, bo, old_mem, new_mem,
1143 					handle_system_ccs);
1144 	}
1145 	if (IS_ERR(fence)) {
1146 		ret = PTR_ERR(fence);
1147 		xe_pm_runtime_put(xe);
1148 		goto out;
1149 	}
1150 	if (!move_lacks_source) {
1151 		ret = ttm_bo_move_accel_cleanup(ttm_bo, fence, evict, true,
1152 						new_mem);
1153 		if (ret) {
1154 			dma_fence_wait(fence, false);
1155 			ttm_bo_move_null(ttm_bo, new_mem);
1156 			ret = 0;
1157 		}
1158 	} else {
1159 		/*
1160 		 * ttm_bo_move_accel_cleanup() may blow up if
1161 		 * bo->resource == NULL, so just attach the
1162 		 * fence and set the new resource.
1163 		 */
1164 		dma_resv_add_fence(ttm_bo->base.resv, fence,
1165 				   DMA_RESV_USAGE_KERNEL);
1166 		ttm_bo_move_null(ttm_bo, new_mem);
1167 	}
1168 
1169 	/*
1170 	 * Detach must wait for the copy above to complete: a VF migration
1171 	 * racing an in-flight copy must still see valid CCS BBs, so don't
1172 	 * tear them down until the copy fence has signaled.
1173 	 */
1174 	if (IS_VF_CCS_READY(xe) && old_mem_type == XE_PL_TT &&
1175 	    new_mem->mem_type == XE_PL_SYSTEM) {
1176 		dma_fence_wait(fence, false);
1177 		xe_sriov_vf_ccs_detach_bo(bo);
1178 	}
1179 
1180 	dma_fence_put(fence);
1181 	xe_pm_runtime_put(xe);
1182 
1183 out:
1184 	if ((!ttm_bo->resource || ttm_bo->resource->mem_type == XE_PL_SYSTEM) &&
1185 	    ttm_bo->ttm) {
1186 		long timeout = dma_resv_wait_timeout(ttm_bo->base.resv,
1187 						     DMA_RESV_USAGE_KERNEL,
1188 						     false,
1189 						     MAX_SCHEDULE_TIMEOUT);
1190 		if (timeout < 0)
1191 			ret = timeout;
1192 
1193 		if (IS_VF_CCS_READY(xe))
1194 			xe_sriov_vf_ccs_detach_bo(bo);
1195 
1196 		xe_tt_unmap_sg(xe, ttm_bo->ttm);
1197 	}
1198 
1199 	return ret;
1200 }
1201 
1202 static long xe_bo_shrink_purge(struct ttm_operation_ctx *ctx,
1203 			       struct ttm_buffer_object *bo,
1204 			       unsigned long *scanned)
1205 {
1206 	struct xe_device *xe = ttm_to_xe_device(bo->bdev);
1207 	struct ttm_tt *tt = bo->ttm;
1208 	long lret;
1209 
1210 	/* Fake move to system, without copying data. */
1211 	if (bo->resource->mem_type != XE_PL_SYSTEM) {
1212 		struct ttm_resource *new_resource;
1213 
1214 		lret = ttm_bo_wait_ctx(bo, ctx);
1215 		if (lret)
1216 			return lret;
1217 
1218 		lret = ttm_bo_mem_space(bo, &sys_placement, &new_resource, ctx);
1219 		if (lret)
1220 			return lret;
1221 
1222 		xe_tt_unmap_sg(xe, bo->ttm);
1223 		ttm_bo_move_null(bo, new_resource);
1224 	}
1225 
1226 	*scanned += bo->ttm->num_pages;
1227 	lret = ttm_bo_shrink(ctx, bo, (struct ttm_bo_shrink_flags)
1228 			     {.purge = true,
1229 			      .writeback = false,
1230 			      .allow_move = false});
1231 
1232 	if (lret > 0) {
1233 		xe_ttm_tt_account_subtract(xe, bo->ttm);
1234 		update_global_total_pages(bo->bdev, -(long)tt->num_pages);
1235 	}
1236 
1237 	return lret;
1238 }
1239 
1240 static bool
1241 xe_bo_eviction_valuable(struct ttm_buffer_object *bo, const struct ttm_place *place)
1242 {
1243 	struct drm_gpuvm_bo *vm_bo;
1244 
1245 	if (!ttm_bo_eviction_valuable(bo, place))
1246 		return false;
1247 
1248 	if (!xe_bo_is_xe_bo(bo))
1249 		return true;
1250 
1251 	drm_gem_for_each_gpuvm_bo(vm_bo, &bo->base) {
1252 		if (xe_vm_is_validating(gpuvm_to_vm(vm_bo->vm)))
1253 			return false;
1254 	}
1255 
1256 	return true;
1257 }
1258 
1259 /**
1260  * xe_bo_shrink() - Try to shrink an xe bo.
1261  * @ctx: The struct ttm_operation_ctx used for shrinking.
1262  * @bo: The TTM buffer object whose pages to shrink.
1263  * @flags: Flags governing the shrink behaviour.
1264  * @scanned: Pointer to a counter of the number of pages
1265  * attempted to shrink.
1266  *
1267  * Try to shrink- or purge a bo, and if it succeeds, unmap dma.
1268  * Note that we need to be able to handle also non xe bos
1269  * (ghost bos), but only if the struct ttm_tt is embedded in
1270  * a struct xe_ttm_tt. When the function attempts to shrink
1271  * the pages of a buffer object, The value pointed to by @scanned
1272  * is updated.
1273  *
1274  * Return: The number of pages shrunken or purged, or negative error
1275  * code on failure.
1276  */
1277 long xe_bo_shrink(struct ttm_operation_ctx *ctx, struct ttm_buffer_object *bo,
1278 		  const struct xe_bo_shrink_flags flags,
1279 		  unsigned long *scanned)
1280 {
1281 	struct ttm_tt *tt = bo->ttm;
1282 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
1283 	struct ttm_place place = {.mem_type = bo->resource->mem_type};
1284 	struct xe_bo *xe_bo = ttm_to_xe_bo(bo);
1285 	struct xe_device *xe = ttm_to_xe_device(bo->bdev);
1286 	bool needs_rpm;
1287 	long lret = 0L;
1288 
1289 	if (!(tt->page_flags & TTM_TT_FLAG_EXTERNAL_MAPPABLE) ||
1290 	    (flags.purge && !xe_tt->purgeable))
1291 		return -EBUSY;
1292 
1293 	if (!xe_bo_eviction_valuable(bo, &place))
1294 		return -EBUSY;
1295 
1296 	if (!xe_bo_is_xe_bo(bo) || !xe_bo_get_unless_zero(xe_bo))
1297 		return xe_bo_shrink_purge(ctx, bo, scanned);
1298 
1299 	if (xe_tt->purgeable) {
1300 		if (bo->resource->mem_type != XE_PL_SYSTEM)
1301 			lret = xe_bo_move_notify(xe_bo, ctx);
1302 		if (!lret)
1303 			lret = xe_bo_shrink_purge(ctx, bo, scanned);
1304 		if (lret > 0 && xe_bo_madv_is_dontneed(xe_bo))
1305 			xe_bo_set_purgeable_state(xe_bo,
1306 						  XE_MADV_PURGEABLE_PURGED);
1307 		goto out_unref;
1308 	}
1309 
1310 	/* System CCS needs gpu copy when moving PL_TT -> PL_SYSTEM */
1311 	needs_rpm = (!IS_DGFX(xe) && bo->resource->mem_type != XE_PL_SYSTEM &&
1312 		     xe_bo_needs_ccs_pages(xe_bo));
1313 	if (needs_rpm && !xe_pm_runtime_get_if_active(xe))
1314 		goto out_unref;
1315 
1316 	*scanned += tt->num_pages;
1317 	lret = ttm_bo_shrink(ctx, bo, (struct ttm_bo_shrink_flags)
1318 			     {.purge = false,
1319 			      .writeback = flags.writeback,
1320 			      .allow_move = true});
1321 	if (needs_rpm)
1322 		xe_pm_runtime_put(xe);
1323 
1324 	if (lret > 0) {
1325 		xe_ttm_tt_account_subtract(xe, tt);
1326 		update_global_total_pages(bo->bdev, -(long)tt->num_pages);
1327 	}
1328 
1329 out_unref:
1330 	xe_bo_put(xe_bo);
1331 
1332 	return lret;
1333 }
1334 
1335 /**
1336  * xe_bo_notifier_prepare_pinned() - Prepare a pinned VRAM object to be backed
1337  * up in system memory.
1338  * @bo: The buffer object to prepare.
1339  *
1340  * On successful completion, the object backup pages are allocated. Expectation
1341  * is that this is called from the PM notifier, prior to suspend/hibernation.
1342  *
1343  * Return: 0 on success. Negative error code on failure.
1344  */
1345 int xe_bo_notifier_prepare_pinned(struct xe_bo *bo)
1346 {
1347 	struct xe_device *xe = ttm_to_xe_device(bo->ttm.bdev);
1348 	struct xe_validation_ctx ctx;
1349 	struct drm_exec exec;
1350 	struct xe_bo *backup;
1351 	int ret = 0;
1352 
1353 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.exclusive = true}, ret) {
1354 		ret = drm_exec_lock_obj(&exec, &bo->ttm.base);
1355 		drm_exec_retry_on_contention(&exec);
1356 		xe_assert(xe, !ret);
1357 		xe_assert(xe, !bo->backup_obj);
1358 
1359 		/*
1360 		 * Since this is called from the PM notifier we might have raced with
1361 		 * someone unpinning this after we dropped the pinned list lock and
1362 		 * grabbing the above bo lock.
1363 		 */
1364 		if (!xe_bo_is_pinned(bo))
1365 			break;
1366 
1367 		if (!xe_bo_is_vram(bo))
1368 			break;
1369 
1370 		if (bo->flags & XE_BO_FLAG_PINNED_NORESTORE)
1371 			break;
1372 
1373 		backup = xe_bo_init_locked(xe, NULL, NULL, bo->ttm.base.resv, NULL, xe_bo_size(bo),
1374 					   DRM_XE_GEM_CPU_CACHING_WB, ttm_bo_type_kernel,
1375 					   XE_BO_FLAG_SYSTEM | XE_BO_FLAG_NEEDS_CPU_ACCESS |
1376 					   XE_BO_FLAG_PINNED, NULL, &exec);
1377 		if (IS_ERR(backup)) {
1378 			drm_exec_retry_on_contention(&exec);
1379 			ret = PTR_ERR(backup);
1380 			xe_validation_retry_on_oom(&ctx, &ret);
1381 			break;
1382 		}
1383 
1384 		backup->parent_obj = xe_bo_get(bo); /* Released by bo_destroy */
1385 		ttm_bo_pin(&backup->ttm);
1386 		bo->backup_obj = backup;
1387 	}
1388 
1389 	return ret;
1390 }
1391 
1392 /**
1393  * xe_bo_notifier_unprepare_pinned() - Undo the previous prepare operation.
1394  * @bo: The buffer object to undo the prepare for.
1395  *
1396  * Always returns 0. The backup object is removed, if still present. Expectation
1397  * it that this called from the PM notifier when undoing the prepare step.
1398  *
1399  * Return: Always returns 0.
1400  */
1401 int xe_bo_notifier_unprepare_pinned(struct xe_bo *bo)
1402 {
1403 	xe_bo_lock(bo, false);
1404 	if (bo->backup_obj) {
1405 		ttm_bo_unpin(&bo->backup_obj->ttm);
1406 		xe_bo_put(bo->backup_obj);
1407 		bo->backup_obj = NULL;
1408 	}
1409 	xe_bo_unlock(bo);
1410 
1411 	return 0;
1412 }
1413 
1414 static int xe_bo_evict_pinned_copy(struct xe_bo *bo, struct xe_bo *backup)
1415 {
1416 	struct xe_device *xe = xe_bo_device(bo);
1417 	bool unmap = false;
1418 	int ret = 0;
1419 
1420 	if (xe_bo_is_user(bo) || (bo->flags & XE_BO_FLAG_PINNED_LATE_RESTORE)) {
1421 		struct xe_migrate *migrate;
1422 		struct dma_fence *fence;
1423 
1424 		if (bo->tile)
1425 			migrate = bo->tile->migrate;
1426 		else
1427 			migrate = mem_type_to_migrate(xe, bo->ttm.resource->mem_type);
1428 
1429 		xe_assert(xe, bo->ttm.base.resv == backup->ttm.base.resv);
1430 		ret = dma_resv_reserve_fences(bo->ttm.base.resv, 1);
1431 		if (ret)
1432 			goto out_backup;
1433 
1434 		fence = xe_migrate_copy(migrate, bo, backup, bo->ttm.resource,
1435 					backup->ttm.resource, false);
1436 		if (IS_ERR(fence)) {
1437 			ret = PTR_ERR(fence);
1438 			goto out_backup;
1439 		}
1440 
1441 		dma_resv_add_fence(bo->ttm.base.resv, fence,
1442 				   DMA_RESV_USAGE_KERNEL);
1443 		dma_fence_put(fence);
1444 	} else {
1445 		ret = xe_bo_vmap(backup);
1446 		if (ret)
1447 			goto out_backup;
1448 
1449 		if (iosys_map_is_null(&bo->vmap)) {
1450 			ret = xe_bo_vmap(bo);
1451 			if (ret)
1452 				goto out_vunmap;
1453 			unmap = true;
1454 		}
1455 
1456 		xe_map_memcpy_from(xe, backup->vmap.vaddr, &bo->vmap, 0,
1457 				   xe_bo_size(bo));
1458 	}
1459 
1460 	if (!bo->backup_obj)
1461 		bo->backup_obj = backup;
1462 out_vunmap:
1463 	xe_bo_vunmap(backup);
1464 out_backup:
1465 	if (unmap)
1466 		xe_bo_vunmap(bo);
1467 
1468 	return ret;
1469 }
1470 
1471 /**
1472  * xe_bo_evict_pinned() - Evict a pinned VRAM object to system memory
1473  * @bo: The buffer object to move.
1474  *
1475  * On successful completion, the object memory will be moved to system memory.
1476  *
1477  * This is needed to for special handling of pinned VRAM object during
1478  * suspend-resume.
1479  *
1480  * Return: 0 on success. Negative error code on failure.
1481  */
1482 int xe_bo_evict_pinned(struct xe_bo *bo)
1483 {
1484 	struct xe_device *xe = ttm_to_xe_device(bo->ttm.bdev);
1485 	struct xe_validation_ctx ctx;
1486 	struct drm_exec exec;
1487 	struct xe_bo *backup = bo->backup_obj;
1488 	bool backup_created = false;
1489 	int ret = 0;
1490 
1491 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.exclusive = true}, ret) {
1492 		ret = drm_exec_lock_obj(&exec, &bo->ttm.base);
1493 		drm_exec_retry_on_contention(&exec);
1494 		xe_assert(xe, !ret);
1495 
1496 		if (WARN_ON(!bo->ttm.resource)) {
1497 			ret = -EINVAL;
1498 			break;
1499 		}
1500 
1501 		if (WARN_ON(!xe_bo_is_pinned(bo))) {
1502 			ret = -EINVAL;
1503 			break;
1504 		}
1505 
1506 		if (!xe_bo_is_vram(bo))
1507 			break;
1508 
1509 		if (bo->flags & XE_BO_FLAG_PINNED_NORESTORE)
1510 			break;
1511 
1512 		if (!backup) {
1513 			backup = xe_bo_init_locked(xe, NULL, NULL, bo->ttm.base.resv, NULL,
1514 						   xe_bo_size(bo),
1515 						   DRM_XE_GEM_CPU_CACHING_WB, ttm_bo_type_kernel,
1516 						   XE_BO_FLAG_SYSTEM | XE_BO_FLAG_NEEDS_CPU_ACCESS |
1517 						   XE_BO_FLAG_PINNED, NULL, &exec);
1518 			if (IS_ERR(backup)) {
1519 				drm_exec_retry_on_contention(&exec);
1520 				ret = PTR_ERR(backup);
1521 				xe_validation_retry_on_oom(&ctx, &ret);
1522 				break;
1523 			}
1524 			backup->parent_obj = xe_bo_get(bo); /* Released by bo_destroy */
1525 			backup_created = true;
1526 		}
1527 
1528 		ret = xe_bo_evict_pinned_copy(bo, backup);
1529 	}
1530 
1531 	if (ret && backup_created)
1532 		xe_bo_put(backup);
1533 
1534 	return ret;
1535 }
1536 
1537 /**
1538  * xe_bo_restore_pinned() - Restore a pinned VRAM object
1539  * @bo: The buffer object to move.
1540  *
1541  * On successful completion, the object memory will be moved back to VRAM.
1542  *
1543  * This is needed to for special handling of pinned VRAM object during
1544  * suspend-resume.
1545  *
1546  * Return: 0 on success. Negative error code on failure.
1547  */
1548 int xe_bo_restore_pinned(struct xe_bo *bo)
1549 {
1550 	struct ttm_operation_ctx ctx = {
1551 		.interruptible = false,
1552 		.gfp_retry_mayfail = false,
1553 	};
1554 	struct xe_device *xe = ttm_to_xe_device(bo->ttm.bdev);
1555 	struct xe_bo *backup = bo->backup_obj;
1556 	bool unmap = false;
1557 	int ret;
1558 
1559 	if (!backup)
1560 		return 0;
1561 
1562 	xe_bo_lock(bo, false);
1563 
1564 	if (!xe_bo_is_pinned(backup)) {
1565 		ret = ttm_bo_validate(&backup->ttm, &backup->placement, &ctx);
1566 		if (ret)
1567 			goto out_unlock_bo;
1568 	}
1569 
1570 	if (xe_bo_is_user(bo) || (bo->flags & XE_BO_FLAG_PINNED_LATE_RESTORE)) {
1571 		struct xe_migrate *migrate;
1572 		struct dma_fence *fence;
1573 
1574 		if (bo->tile)
1575 			migrate = bo->tile->migrate;
1576 		else
1577 			migrate = mem_type_to_migrate(xe, bo->ttm.resource->mem_type);
1578 
1579 		ret = dma_resv_reserve_fences(bo->ttm.base.resv, 1);
1580 		if (ret)
1581 			goto out_unlock_bo;
1582 
1583 		fence = xe_migrate_copy(migrate, backup, bo,
1584 					backup->ttm.resource, bo->ttm.resource,
1585 					false);
1586 		if (IS_ERR(fence)) {
1587 			ret = PTR_ERR(fence);
1588 			goto out_unlock_bo;
1589 		}
1590 
1591 		dma_resv_add_fence(bo->ttm.base.resv, fence,
1592 				   DMA_RESV_USAGE_KERNEL);
1593 		dma_fence_put(fence);
1594 	} else {
1595 		ret = xe_bo_vmap(backup);
1596 		if (ret)
1597 			goto out_unlock_bo;
1598 
1599 		if (iosys_map_is_null(&bo->vmap)) {
1600 			ret = xe_bo_vmap(bo);
1601 			if (ret)
1602 				goto out_backup;
1603 			unmap = true;
1604 		}
1605 
1606 		xe_map_memcpy_to(xe, &bo->vmap, 0, backup->vmap.vaddr,
1607 				 xe_bo_size(bo));
1608 	}
1609 
1610 	bo->backup_obj = NULL;
1611 
1612 out_backup:
1613 	xe_bo_vunmap(backup);
1614 	if (!bo->backup_obj) {
1615 		if (xe_bo_is_pinned(backup))
1616 			ttm_bo_unpin(&backup->ttm);
1617 		xe_bo_put(backup);
1618 	}
1619 out_unlock_bo:
1620 	if (unmap)
1621 		xe_bo_vunmap(bo);
1622 	xe_bo_unlock(bo);
1623 	return ret;
1624 }
1625 
1626 int xe_bo_dma_unmap_pinned(struct xe_bo *bo)
1627 {
1628 	struct ttm_buffer_object *ttm_bo = &bo->ttm;
1629 	struct ttm_tt *tt = ttm_bo->ttm;
1630 
1631 	if (tt) {
1632 		struct xe_ttm_tt *xe_tt = container_of(tt, typeof(*xe_tt), ttm);
1633 
1634 		if (ttm_bo->type == ttm_bo_type_sg && ttm_bo->sg) {
1635 			dma_buf_unmap_attachment(ttm_bo->base.import_attach,
1636 						 ttm_bo->sg,
1637 						 DMA_BIDIRECTIONAL);
1638 			ttm_bo->sg = NULL;
1639 			xe_tt->sg = NULL;
1640 		} else if (xe_tt->sg) {
1641 			dma_unmap_sgtable(ttm_to_xe_device(ttm_bo->bdev)->drm.dev,
1642 					  xe_tt->sg,
1643 					  DMA_BIDIRECTIONAL, 0);
1644 			sg_free_table(xe_tt->sg);
1645 			xe_tt->sg = NULL;
1646 		}
1647 	}
1648 
1649 	return 0;
1650 }
1651 
1652 static unsigned long xe_ttm_io_mem_pfn(struct ttm_buffer_object *ttm_bo,
1653 				       unsigned long page_offset)
1654 {
1655 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
1656 	struct xe_res_cursor cursor;
1657 	struct xe_vram_region *vram;
1658 
1659 	if (ttm_bo->resource->mem_type == XE_PL_STOLEN)
1660 		return xe_ttm_stolen_io_offset(bo, page_offset << PAGE_SHIFT) >> PAGE_SHIFT;
1661 
1662 	vram = xe_map_resource_to_region(ttm_bo->resource);
1663 	xe_res_first(ttm_bo->resource, (u64)page_offset << PAGE_SHIFT, 0, &cursor);
1664 	return (vram->io_start + cursor.start) >> PAGE_SHIFT;
1665 }
1666 
1667 static void __xe_bo_vunmap(struct xe_bo *bo);
1668 
1669 /*
1670  * TODO: Move this function to TTM so we don't rely on how TTM does its
1671  * locking, thereby abusing TTM internals.
1672  */
1673 static bool xe_ttm_bo_lock_in_destructor(struct ttm_buffer_object *ttm_bo)
1674 {
1675 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
1676 	bool locked;
1677 
1678 	xe_assert(xe, !kref_read(&ttm_bo->kref));
1679 
1680 	/*
1681 	 * We can typically only race with TTM trylocking under the
1682 	 * lru_lock, which will immediately be unlocked again since
1683 	 * the ttm_bo refcount is zero at this point. So trylocking *should*
1684 	 * always succeed here, as long as we hold the lru lock.
1685 	 */
1686 	spin_lock(&ttm_bo->bdev->lru_lock);
1687 	locked = dma_resv_trylock(&ttm_bo->base._resv);
1688 	spin_unlock(&ttm_bo->bdev->lru_lock);
1689 	xe_assert(xe, locked);
1690 
1691 	return locked;
1692 }
1693 
1694 static void xe_ttm_bo_release_notify(struct ttm_buffer_object *ttm_bo)
1695 {
1696 	struct dma_resv_iter cursor;
1697 	struct dma_fence *fence;
1698 	struct dma_fence *replacement = NULL;
1699 	struct xe_bo *bo;
1700 
1701 	if (!xe_bo_is_xe_bo(ttm_bo))
1702 		return;
1703 
1704 	bo = ttm_to_xe_bo(ttm_bo);
1705 	xe_assert(xe_bo_device(bo), !(bo->created && kref_read(&ttm_bo->base.refcount)));
1706 
1707 	if (!xe_ttm_bo_lock_in_destructor(ttm_bo))
1708 		return;
1709 
1710 	/*
1711 	 * Scrub the preempt fences if any. The unbind fence is already
1712 	 * attached to the resv.
1713 	 * TODO: Don't do this for external bos once we scrub them after
1714 	 * unbind.
1715 	 */
1716 	dma_resv_for_each_fence(&cursor, &ttm_bo->base._resv,
1717 				DMA_RESV_USAGE_BOOKKEEP, fence) {
1718 		if (xe_fence_is_xe_preempt(fence) &&
1719 		    !dma_fence_is_signaled(fence)) {
1720 			if (!replacement)
1721 				replacement = dma_fence_get_stub();
1722 
1723 			dma_resv_replace_fences(&ttm_bo->base._resv,
1724 						fence->context,
1725 						replacement,
1726 						DMA_RESV_USAGE_BOOKKEEP);
1727 		}
1728 	}
1729 	dma_fence_put(replacement);
1730 
1731 	dma_resv_unlock(&ttm_bo->base._resv);
1732 }
1733 
1734 static void xe_ttm_bo_delete_mem_notify(struct ttm_buffer_object *ttm_bo)
1735 {
1736 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
1737 
1738 	if (!xe_bo_is_xe_bo(ttm_bo))
1739 		return;
1740 
1741 	if (IS_VF_CCS_READY(ttm_to_xe_device(ttm_bo->bdev)))
1742 		xe_sriov_vf_ccs_detach_bo(bo);
1743 
1744 	/*
1745 	 * Object is idle and about to be destroyed. Release the
1746 	 * dma-buf attachment.
1747 	 */
1748 	if (ttm_bo->type == ttm_bo_type_sg && ttm_bo->sg) {
1749 		struct xe_ttm_tt *xe_tt = container_of(ttm_bo->ttm,
1750 						       struct xe_ttm_tt, ttm);
1751 
1752 		dma_buf_unmap_attachment(ttm_bo->base.import_attach, ttm_bo->sg,
1753 					 DMA_BIDIRECTIONAL);
1754 		ttm_bo->sg = NULL;
1755 		xe_tt->sg = NULL;
1756 	}
1757 }
1758 
1759 static void xe_ttm_bo_swap_notify(struct ttm_buffer_object *ttm_bo)
1760 {
1761 	struct ttm_operation_ctx ctx = {
1762 		.interruptible = false,
1763 		.gfp_retry_mayfail = false,
1764 	};
1765 
1766 	if (ttm_bo->ttm) {
1767 		struct xe_ttm_tt *xe_tt =
1768 			container_of(ttm_bo->ttm, struct xe_ttm_tt, ttm);
1769 
1770 		if (xe_tt->purgeable)
1771 			xe_ttm_bo_purge(ttm_bo, &ctx);
1772 	}
1773 }
1774 
1775 static int xe_ttm_access_memory(struct ttm_buffer_object *ttm_bo,
1776 				unsigned long offset, void *buf, int len,
1777 				int write)
1778 {
1779 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
1780 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
1781 	struct iosys_map vmap;
1782 	struct xe_res_cursor cursor;
1783 	struct xe_vram_region *vram;
1784 	int bytes_left = len;
1785 	int err = 0;
1786 
1787 	xe_bo_assert_held(bo);
1788 	xe_device_assert_mem_access(xe);
1789 
1790 	if (!mem_type_is_vram(ttm_bo->resource->mem_type))
1791 		return -EIO;
1792 
1793 	if (!xe_bo_is_visible_vram(bo) || len >= SZ_16K) {
1794 		struct xe_migrate *migrate =
1795 			mem_type_to_migrate(xe, ttm_bo->resource->mem_type);
1796 
1797 		err = xe_migrate_access_memory(migrate, bo, offset, buf, len,
1798 					       write);
1799 		goto out;
1800 	}
1801 
1802 	vram = xe_map_resource_to_region(ttm_bo->resource);
1803 	xe_res_first(ttm_bo->resource, offset & PAGE_MASK,
1804 		     xe_bo_size(bo) - (offset & PAGE_MASK), &cursor);
1805 
1806 	do {
1807 		unsigned long page_offset = (offset & ~PAGE_MASK);
1808 		int byte_count = min((int)(PAGE_SIZE - page_offset), bytes_left);
1809 
1810 		iosys_map_set_vaddr_iomem(&vmap, (u8 __iomem *)vram->mapping +
1811 					  cursor.start);
1812 		if (write)
1813 			xe_map_memcpy_to(xe, &vmap, page_offset, buf, byte_count);
1814 		else
1815 			xe_map_memcpy_from(xe, buf, &vmap, page_offset, byte_count);
1816 
1817 		buf += byte_count;
1818 		offset += byte_count;
1819 		bytes_left -= byte_count;
1820 		if (bytes_left)
1821 			xe_res_next(&cursor, PAGE_SIZE);
1822 	} while (bytes_left);
1823 
1824 out:
1825 	return err ?: len;
1826 }
1827 
1828 const struct ttm_device_funcs xe_ttm_funcs = {
1829 	.ttm_tt_create = xe_ttm_tt_create,
1830 	.ttm_tt_populate = xe_ttm_tt_populate,
1831 	.ttm_tt_unpopulate = xe_ttm_tt_unpopulate,
1832 	.ttm_tt_destroy = xe_ttm_tt_destroy,
1833 	.evict_flags = xe_evict_flags,
1834 	.move = xe_bo_move,
1835 	.io_mem_reserve = xe_ttm_io_mem_reserve,
1836 	.io_mem_pfn = xe_ttm_io_mem_pfn,
1837 	.access_memory = xe_ttm_access_memory,
1838 	.release_notify = xe_ttm_bo_release_notify,
1839 	.eviction_valuable = xe_bo_eviction_valuable,
1840 	.delete_mem_notify = xe_ttm_bo_delete_mem_notify,
1841 	.swap_notify = xe_ttm_bo_swap_notify,
1842 };
1843 
1844 static void xe_ttm_bo_destroy(struct ttm_buffer_object *ttm_bo)
1845 {
1846 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
1847 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
1848 	struct xe_tile *tile;
1849 	u8 id;
1850 
1851 	if (bo->ttm.base.import_attach)
1852 		drm_prime_gem_destroy(&bo->ttm.base, NULL);
1853 	if (bo->dma_buf)
1854 		dma_buf_put(bo->dma_buf);
1855 	drm_gem_object_release(&bo->ttm.base);
1856 
1857 	xe_assert(xe, list_empty(&ttm_bo->base.gpuva.list));
1858 
1859 	for_each_tile(tile, xe, id)
1860 		if (bo->ggtt_node[id])
1861 			xe_ggtt_remove_bo(tile->mem.ggtt, bo);
1862 
1863 #ifdef CONFIG_PROC_FS
1864 	if (bo->client)
1865 		xe_drm_client_remove_bo(bo);
1866 #endif
1867 
1868 	if (bo->vm && xe_bo_is_user(bo))
1869 		xe_vm_put(bo->vm);
1870 
1871 	if (bo->parent_obj)
1872 		xe_bo_put(bo->parent_obj);
1873 
1874 	mutex_lock(&xe->mem_access.vram_userfault.lock);
1875 	if (!list_empty(&bo->vram_userfault_link))
1876 		list_del(&bo->vram_userfault_link);
1877 	mutex_unlock(&xe->mem_access.vram_userfault.lock);
1878 
1879 	kfree(bo);
1880 }
1881 
1882 static void xe_gem_object_free(struct drm_gem_object *obj)
1883 {
1884 	/* Our BO reference counting scheme works as follows:
1885 	 *
1886 	 * The gem object kref is typically used throughout the driver,
1887 	 * and the gem object holds a ttm_buffer_object refcount, so
1888 	 * that when the last gem object reference is put, which is when
1889 	 * we end up in this function, we put also that ttm_buffer_object
1890 	 * refcount. Anything using gem interfaces is then no longer
1891 	 * allowed to access the object in a way that requires a gem
1892 	 * refcount, including locking the object.
1893 	 *
1894 	 * driver ttm callbacks is allowed to use the ttm_buffer_object
1895 	 * refcount directly if needed.
1896 	 */
1897 	__xe_bo_vunmap(gem_to_xe_bo(obj));
1898 	ttm_bo_fini(container_of(obj, struct ttm_buffer_object, base));
1899 }
1900 
1901 static void xe_gem_object_close(struct drm_gem_object *obj,
1902 				struct drm_file *file_priv)
1903 {
1904 	struct xe_bo *bo = gem_to_xe_bo(obj);
1905 
1906 	if (bo->vm && !xe_vm_in_fault_mode(bo->vm)) {
1907 		xe_assert(xe_bo_device(bo), xe_bo_is_user(bo));
1908 
1909 		xe_bo_lock(bo, false);
1910 		ttm_bo_set_bulk_move(&bo->ttm, NULL);
1911 		xe_bo_unlock(bo);
1912 	}
1913 }
1914 
1915 static bool should_migrate_to_smem(struct xe_bo *bo)
1916 {
1917 	/*
1918 	 * NOTE: The following atomic checks are platform-specific. For example,
1919 	 * if a device supports CXL atomics, these may not be necessary or
1920 	 * may behave differently.
1921 	 */
1922 
1923 	return bo->attr.atomic_access == DRM_XE_ATOMIC_GLOBAL ||
1924 	       bo->attr.atomic_access == DRM_XE_ATOMIC_CPU;
1925 }
1926 
1927 static int xe_bo_wait_usage_kernel(struct xe_bo *bo, struct ttm_operation_ctx *ctx)
1928 {
1929 	long lerr;
1930 
1931 	if (ctx->no_wait_gpu)
1932 		return dma_resv_test_signaled(bo->ttm.base.resv, DMA_RESV_USAGE_KERNEL) ?
1933 			0 : -EBUSY;
1934 
1935 	lerr = dma_resv_wait_timeout(bo->ttm.base.resv, DMA_RESV_USAGE_KERNEL,
1936 				     ctx->interruptible, MAX_SCHEDULE_TIMEOUT);
1937 	if (lerr < 0)
1938 		return lerr;
1939 	if (lerr == 0)
1940 		return -EBUSY;
1941 
1942 	return 0;
1943 }
1944 
1945 /* Populate the bo if swapped out, or migrate if the access mode requires that. */
1946 static int xe_bo_fault_migrate(struct xe_bo *bo, struct ttm_operation_ctx *ctx,
1947 			       struct drm_exec *exec)
1948 {
1949 	struct ttm_buffer_object *tbo = &bo->ttm;
1950 	int err = 0;
1951 
1952 	if (ttm_manager_type(tbo->bdev, tbo->resource->mem_type)->use_tt) {
1953 		err = xe_bo_wait_usage_kernel(bo, ctx);
1954 		if (!err)
1955 			err = ttm_bo_populate(&bo->ttm, ctx);
1956 	} else if (should_migrate_to_smem(bo)) {
1957 		xe_assert(xe_bo_device(bo), bo->flags & XE_BO_FLAG_SYSTEM);
1958 		err = xe_bo_migrate(bo, XE_PL_TT, ctx, exec);
1959 	}
1960 
1961 	return err;
1962 }
1963 
1964 /* Call into TTM to populate PTEs, and register bo for PTE removal on runtime suspend. */
1965 static vm_fault_t __xe_bo_cpu_fault(struct vm_fault *vmf, struct xe_device *xe, struct xe_bo *bo)
1966 {
1967 	vm_fault_t ret;
1968 
1969 	trace_xe_bo_cpu_fault(bo);
1970 
1971 	ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
1972 				       TTM_BO_VM_NUM_PREFAULT);
1973 	/*
1974 	 * When TTM is actually called to insert PTEs, ensure no blocking conditions
1975 	 * remain, in which case TTM may drop locks and return VM_FAULT_RETRY.
1976 	 */
1977 	xe_assert(xe, ret != VM_FAULT_RETRY);
1978 
1979 	if (ret == VM_FAULT_NOPAGE &&
1980 	    mem_type_is_vram(bo->ttm.resource->mem_type)) {
1981 		mutex_lock(&xe->mem_access.vram_userfault.lock);
1982 		if (list_empty(&bo->vram_userfault_link))
1983 			list_add(&bo->vram_userfault_link,
1984 				 &xe->mem_access.vram_userfault.list);
1985 		mutex_unlock(&xe->mem_access.vram_userfault.lock);
1986 	}
1987 
1988 	return ret;
1989 }
1990 
1991 static vm_fault_t xe_err_to_fault_t(int err)
1992 {
1993 	switch (err) {
1994 	case 0:
1995 	case -EINTR:
1996 	case -ERESTARTSYS:
1997 	case -EAGAIN:
1998 		return VM_FAULT_NOPAGE;
1999 	case -ENOMEM:
2000 	case -ENOSPC:
2001 		return VM_FAULT_OOM;
2002 	default:
2003 		break;
2004 	}
2005 	return VM_FAULT_SIGBUS;
2006 }
2007 
2008 static bool xe_ttm_bo_is_imported(struct ttm_buffer_object *tbo)
2009 {
2010 	dma_resv_assert_held(tbo->base.resv);
2011 
2012 	return tbo->ttm &&
2013 		(tbo->ttm->page_flags & (TTM_TT_FLAG_EXTERNAL | TTM_TT_FLAG_EXTERNAL_MAPPABLE)) ==
2014 		TTM_TT_FLAG_EXTERNAL;
2015 }
2016 
2017 static vm_fault_t xe_bo_cpu_fault_fastpath(struct vm_fault *vmf, struct xe_device *xe,
2018 					   struct xe_bo *bo, bool needs_rpm)
2019 {
2020 	struct ttm_buffer_object *tbo = &bo->ttm;
2021 	vm_fault_t ret = VM_FAULT_RETRY;
2022 	struct xe_validation_ctx ctx;
2023 	struct ttm_operation_ctx tctx = {
2024 		.interruptible = true,
2025 		.no_wait_gpu = true,
2026 		.gfp_retry_mayfail = true,
2027 
2028 	};
2029 	int err;
2030 
2031 	if (needs_rpm && !xe_pm_runtime_get_if_active(xe))
2032 		return VM_FAULT_RETRY;
2033 
2034 	err = xe_validation_ctx_init(&ctx, &xe->val, NULL,
2035 				     (struct xe_val_flags) {
2036 					     .interruptible = true,
2037 					     .no_block = true
2038 				     });
2039 	if (err)
2040 		goto out_pm;
2041 
2042 	if (!dma_resv_trylock(tbo->base.resv))
2043 		goto out_validation;
2044 
2045 	/*
2046 	 * Reject CPU faults to purgeable BOs. DONTNEED BOs can be purged
2047 	 * at any time, and purged BOs have no backing store. Either case
2048 	 * is undefined behavior for CPU access.
2049 	 */
2050 	if (xe_bo_madv_is_dontneed(bo) || xe_bo_is_purged(bo)) {
2051 		ret = VM_FAULT_SIGBUS;
2052 		goto out_unlock;
2053 	}
2054 
2055 	if (xe_ttm_bo_is_imported(tbo)) {
2056 		ret = VM_FAULT_SIGBUS;
2057 		drm_dbg(&xe->drm, "CPU trying to access an imported buffer object.\n");
2058 		goto out_unlock;
2059 	}
2060 
2061 	err = xe_bo_fault_migrate(bo, &tctx, NULL);
2062 	if (err) {
2063 		/* Return VM_FAULT_RETRY on these errors. */
2064 		if (err != -ENOMEM && err != -ENOSPC && err != -EBUSY)
2065 			ret = xe_err_to_fault_t(err);
2066 		goto out_unlock;
2067 	}
2068 
2069 	if (dma_resv_test_signaled(bo->ttm.base.resv, DMA_RESV_USAGE_KERNEL))
2070 		ret = __xe_bo_cpu_fault(vmf, xe, bo);
2071 
2072 out_unlock:
2073 	dma_resv_unlock(tbo->base.resv);
2074 out_validation:
2075 	xe_validation_ctx_fini(&ctx);
2076 out_pm:
2077 	if (needs_rpm)
2078 		xe_pm_runtime_put(xe);
2079 
2080 	return ret;
2081 }
2082 
2083 static vm_fault_t xe_bo_cpu_fault(struct vm_fault *vmf)
2084 {
2085 	struct ttm_buffer_object *tbo = vmf->vma->vm_private_data;
2086 	struct drm_device *ddev = tbo->base.dev;
2087 	struct xe_device *xe = to_xe_device(ddev);
2088 	struct xe_bo *bo = ttm_to_xe_bo(tbo);
2089 	bool needs_rpm = bo->flags & XE_BO_FLAG_VRAM_MASK;
2090 	bool retry_after_wait = false;
2091 	struct xe_validation_ctx ctx;
2092 	struct drm_exec exec;
2093 	vm_fault_t ret;
2094 	int err = 0;
2095 	int idx;
2096 
2097 	if (xe_device_wedged(xe) || !drm_dev_enter(&xe->drm, &idx))
2098 		return ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
2099 
2100 	ret = xe_bo_cpu_fault_fastpath(vmf, xe, bo, needs_rpm);
2101 	if (ret != VM_FAULT_RETRY)
2102 		goto out;
2103 
2104 	if (fault_flag_allow_retry_first(vmf->flags)) {
2105 		if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2106 			goto out;
2107 		retry_after_wait = true;
2108 		xe_bo_get(bo);
2109 		mmap_read_unlock(vmf->vma->vm_mm);
2110 	} else {
2111 		ret = VM_FAULT_NOPAGE;
2112 	}
2113 
2114 	/*
2115 	 * The fastpath failed and we were not required to return and retry immediately.
2116 	 * We're now running in one of two modes:
2117 	 *
2118 	 * 1) retry_after_wait == true: The mmap_read_lock() is dropped, and we're trying
2119 	 * to resolve blocking waits. But we can't resolve the fault since the
2120 	 * mmap_read_lock() is dropped. After retrying the fault, the aim is that the fastpath
2121 	 * should succeed. But it may fail since we drop the bo lock.
2122 	 *
2123 	 * 2) retry_after_wait == false: The fastpath failed, typically even after
2124 	 * a retry. Do whatever's necessary to resolve the fault.
2125 	 *
2126 	 * This construct is recommended to avoid excessive waits under the mmap_lock.
2127 	 */
2128 
2129 	if (needs_rpm)
2130 		xe_pm_runtime_get(xe);
2131 
2132 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = true},
2133 			    err) {
2134 		struct ttm_operation_ctx tctx = {
2135 			.interruptible = true,
2136 			.no_wait_gpu = false,
2137 			.gfp_retry_mayfail = retry_after_wait,
2138 		};
2139 
2140 		err = drm_exec_lock_obj(&exec, &tbo->base);
2141 		drm_exec_retry_on_contention(&exec);
2142 		if (err)
2143 			break;
2144 
2145 		/*
2146 		 * Reject CPU faults to purgeable BOs. DONTNEED BOs can be
2147 		 * purged at any time, and purged BOs have no backing store.
2148 		 */
2149 		if (xe_bo_madv_is_dontneed(bo) || xe_bo_is_purged(bo)) {
2150 			err = -EFAULT;
2151 			break;
2152 		}
2153 
2154 		if (xe_ttm_bo_is_imported(tbo)) {
2155 			err = -EFAULT;
2156 			drm_dbg(&xe->drm, "CPU trying to access an imported buffer object.\n");
2157 			break;
2158 		}
2159 
2160 		err = xe_bo_fault_migrate(bo, &tctx, &exec);
2161 		if (err) {
2162 			drm_exec_retry_on_contention(&exec);
2163 			xe_validation_retry_on_oom(&ctx, &err);
2164 			break;
2165 		}
2166 
2167 		err = xe_bo_wait_usage_kernel(bo, &tctx);
2168 		if (err)
2169 			break;
2170 
2171 		if (!retry_after_wait)
2172 			ret = __xe_bo_cpu_fault(vmf, xe, bo);
2173 	}
2174 	/* if retry_after_wait == true, we *must* return VM_FAULT_RETRY. */
2175 	if (err && !retry_after_wait)
2176 		ret = xe_err_to_fault_t(err);
2177 
2178 	if (needs_rpm)
2179 		xe_pm_runtime_put(xe);
2180 
2181 	if (retry_after_wait)
2182 		xe_bo_put(bo);
2183 out:
2184 	drm_dev_exit(idx);
2185 
2186 	return ret;
2187 }
2188 
2189 static int xe_bo_vm_access(struct vm_area_struct *vma, unsigned long addr,
2190 			   void *buf, int len, int write)
2191 {
2192 	struct ttm_buffer_object *ttm_bo = vma->vm_private_data;
2193 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
2194 	struct xe_device *xe = xe_bo_device(bo);
2195 
2196 	guard(xe_pm_runtime)(xe);
2197 	return ttm_bo_vm_access(vma, addr, buf, len, write);
2198 }
2199 
2200 /**
2201  * xe_bo_read() - Read from an xe_bo
2202  * @bo: The buffer object to read from.
2203  * @offset: The byte offset to start reading from.
2204  * @dst: Location to store the read.
2205  * @size: Size in bytes for the read.
2206  *
2207  * Read @size bytes from the @bo, starting from @offset, storing into @dst.
2208  *
2209  * Return: Zero on success, or negative error.
2210  */
2211 int xe_bo_read(struct xe_bo *bo, u64 offset, void *dst, int size)
2212 {
2213 	int ret;
2214 
2215 	ret = ttm_bo_access(&bo->ttm, offset, dst, size, 0);
2216 	if (ret >= 0 && ret != size)
2217 		ret = -EIO;
2218 	else if (ret == size)
2219 		ret = 0;
2220 
2221 	return ret;
2222 }
2223 
2224 static const struct vm_operations_struct xe_gem_vm_ops = {
2225 	.fault = xe_bo_cpu_fault,
2226 	.open = ttm_bo_vm_open,
2227 	.close = ttm_bo_vm_close,
2228 	.access = xe_bo_vm_access,
2229 };
2230 
2231 static int xe_gem_object_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
2232 {
2233 	struct xe_bo *bo = gem_to_xe_bo(obj);
2234 	int err = 0;
2235 
2236 	/*
2237 	 * Reject mmap of purgeable BOs. DONTNEED BOs can be purged
2238 	 * at any time, making CPU access undefined behavior. Purged BOs have
2239 	 * no backing store and are permanently invalid.
2240 	 */
2241 	err = xe_bo_lock(bo, true);
2242 	if (err)
2243 		return err;
2244 
2245 	if (xe_bo_madv_is_dontneed(bo))
2246 		err = -EBUSY;
2247 	else if (xe_bo_is_purged(bo))
2248 		err = -EINVAL;
2249 	xe_bo_unlock(bo);
2250 	if (err)
2251 		return err;
2252 
2253 	return drm_gem_ttm_mmap(obj, vma);
2254 }
2255 
2256 static const struct drm_gem_object_funcs xe_gem_object_funcs = {
2257 	.free = xe_gem_object_free,
2258 	.close = xe_gem_object_close,
2259 	.mmap = xe_gem_object_mmap,
2260 	.export = xe_gem_prime_export,
2261 	.vm_ops = &xe_gem_vm_ops,
2262 };
2263 
2264 /**
2265  * xe_bo_alloc - Allocate storage for a struct xe_bo
2266  *
2267  * This function is intended to allocate storage to be used for input
2268  * to __xe_bo_create_locked(), in the case a pointer to the bo to be
2269  * created is needed before the call to __xe_bo_create_locked().
2270  * If __xe_bo_create_locked ends up never to be called, then the
2271  * storage allocated with this function needs to be freed using
2272  * xe_bo_free().
2273  *
2274  * Return: A pointer to an uninitialized struct xe_bo on success,
2275  * ERR_PTR(-ENOMEM) on error.
2276  */
2277 struct xe_bo *xe_bo_alloc(void)
2278 {
2279 	struct xe_bo *bo = kzalloc_obj(*bo);
2280 
2281 	if (!bo)
2282 		return ERR_PTR(-ENOMEM);
2283 
2284 	return bo;
2285 }
2286 
2287 /**
2288  * xe_bo_free - Free storage allocated using xe_bo_alloc()
2289  * @bo: The buffer object storage.
2290  *
2291  * Refer to xe_bo_alloc() documentation for valid use-cases.
2292  */
2293 void xe_bo_free(struct xe_bo *bo)
2294 {
2295 	kfree(bo);
2296 }
2297 
2298 /**
2299  * xe_bo_init_locked() - Initialize or create an xe_bo.
2300  * @xe: The xe device.
2301  * @bo: An already allocated buffer object or NULL
2302  * if the function should allocate a new one.
2303  * @tile: The tile to select for migration of this bo, and the tile used for
2304  * GGTT binding if any. Only to be non-NULL for ttm_bo_type_kernel bos.
2305  * @resv: Pointer to a locked shared reservation object to use for this bo,
2306  * or NULL for the xe_bo to use its own.
2307  * @bulk: The bulk move to use for LRU bumping, or NULL for external bos.
2308  * @size: The storage size to use for the bo.
2309  * @cpu_caching: The cpu caching used for system memory backing store.
2310  * @type: The TTM buffer object type.
2311  * @flags: XE_BO_FLAG_ flags.
2312  * @dma_buf: The dma-buf to reference for the BO lifetime (imported BOs),
2313  * or NULL.
2314  * @exec: The drm_exec transaction to use for exhaustive eviction.
2315  *
2316  * Initialize or create an xe buffer object. On failure, any allocated buffer
2317  * object passed in @bo will have been unreferenced.
2318  *
2319  * Return: The buffer object on success. Negative error pointer on failure.
2320  */
2321 struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
2322 				struct xe_tile *tile, struct dma_resv *resv,
2323 				struct ttm_lru_bulk_move *bulk, size_t size,
2324 				u16 cpu_caching, enum ttm_bo_type type,
2325 				u32 flags, struct dma_buf *dma_buf,
2326 				struct drm_exec *exec)
2327 {
2328 	struct ttm_operation_ctx ctx = {
2329 		.interruptible = true,
2330 		.no_wait_gpu = false,
2331 		.gfp_retry_mayfail = true,
2332 	};
2333 	struct ttm_placement *placement;
2334 	uint32_t alignment;
2335 	size_t aligned_size;
2336 	int err;
2337 
2338 	/* Only kernel objects should set GT */
2339 	xe_assert(xe, !tile || type == ttm_bo_type_kernel);
2340 
2341 	if (XE_WARN_ON(!size)) {
2342 		xe_bo_free(bo);
2343 		return ERR_PTR(-EINVAL);
2344 	}
2345 
2346 	/* XE_BO_FLAG_GGTTx requires XE_BO_FLAG_GGTT also be set */
2347 	if ((flags & XE_BO_FLAG_GGTT_ALL) && !(flags & XE_BO_FLAG_GGTT)) {
2348 		xe_bo_free(bo);
2349 		return ERR_PTR(-EINVAL);
2350 	}
2351 
2352 	if (flags & (XE_BO_FLAG_VRAM_MASK | XE_BO_FLAG_STOLEN) &&
2353 	    !(flags & XE_BO_FLAG_IGNORE_MIN_PAGE_SIZE) &&
2354 	    ((xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K) ||
2355 	     (flags & (XE_BO_FLAG_NEEDS_64K | XE_BO_FLAG_NEEDS_2M |
2356 		       XE_BO_FLAG_NEEDS_1G)))) {
2357 		size_t align;
2358 
2359 		if (flags & XE_BO_FLAG_NEEDS_1G)
2360 			align = SZ_1G;
2361 		else if (flags & XE_BO_FLAG_NEEDS_2M)
2362 			align = SZ_2M;
2363 		else
2364 			align = SZ_64K;
2365 
2366 		aligned_size = ALIGN(size, align);
2367 		if (type != ttm_bo_type_device)
2368 			size = ALIGN(size, align);
2369 		flags |= XE_BO_FLAG_INTERNAL_64K;
2370 		alignment = align >> PAGE_SHIFT;
2371 	} else {
2372 		aligned_size = ALIGN(size, SZ_4K);
2373 		flags &= ~XE_BO_FLAG_INTERNAL_64K;
2374 		alignment = SZ_4K >> PAGE_SHIFT;
2375 	}
2376 
2377 	if (type == ttm_bo_type_device && aligned_size != size) {
2378 		xe_bo_free(bo);
2379 		return ERR_PTR(-EINVAL);
2380 	}
2381 
2382 	if (!bo) {
2383 		bo = xe_bo_alloc();
2384 		if (IS_ERR(bo))
2385 			return bo;
2386 	}
2387 
2388 	bo->ccs_cleared = false;
2389 	bo->tile = tile;
2390 	bo->flags = flags;
2391 	bo->cpu_caching = cpu_caching;
2392 	bo->ttm.base.funcs = &xe_gem_object_funcs;
2393 	bo->ttm.priority = XE_BO_PRIORITY_NORMAL;
2394 	INIT_LIST_HEAD(&bo->pinned_link);
2395 #ifdef CONFIG_PROC_FS
2396 	INIT_LIST_HEAD(&bo->client_link);
2397 #endif
2398 	INIT_LIST_HEAD(&bo->vram_userfault_link);
2399 
2400 	/* Initialize purge advisory state */
2401 	bo->purgeable.state = XE_MADV_PURGEABLE_WILLNEED;
2402 
2403 	drm_gem_private_object_init(&xe->drm, &bo->ttm.base, size);
2404 
2405 	if (resv) {
2406 		ctx.allow_res_evict = !(flags & XE_BO_FLAG_NO_RESV_EVICT);
2407 		ctx.resv = resv;
2408 	}
2409 
2410 	xe_validation_assert_exec(xe, exec, &bo->ttm.base);
2411 	if (!(flags & XE_BO_FLAG_FIXED_PLACEMENT)) {
2412 		err = __xe_bo_placement_for_flags(xe, bo, bo->flags, type);
2413 		if (WARN_ON(err)) {
2414 			xe_ttm_bo_destroy(&bo->ttm);
2415 			return ERR_PTR(err);
2416 		}
2417 	}
2418 
2419 	/* Defer populating type_sg bos */
2420 	placement = (type == ttm_bo_type_sg ||
2421 		     bo->flags & XE_BO_FLAG_DEFER_BACKING) ? &sys_placement :
2422 		&bo->placement;
2423 
2424 	/*
2425 	 * For imported BOs, keep the exporter dma-buf alive for the BO
2426 	 * lifetime. Taken before ttm_bo_init_reserved() to also cover a
2427 	 * creation failure there. Released in xe_ttm_bo_destroy().
2428 	 */
2429 	if (dma_buf) {
2430 		get_dma_buf(dma_buf);
2431 		bo->dma_buf = dma_buf;
2432 	}
2433 
2434 	err = ttm_bo_init_reserved(&xe->ttm, &bo->ttm, type,
2435 				   placement, alignment,
2436 				   &ctx, NULL, resv, xe_ttm_bo_destroy);
2437 	if (err)
2438 		return ERR_PTR(err);
2439 
2440 	/*
2441 	 * The VRAM pages underneath are potentially still being accessed by the
2442 	 * GPU, as per async GPU clearing and async evictions. However TTM makes
2443 	 * sure to add any corresponding move/clear fences into the objects
2444 	 * dma-resv using the DMA_RESV_USAGE_KERNEL slot.
2445 	 *
2446 	 * For KMD internal buffers we don't care about GPU clearing, however we
2447 	 * still need to handle async evictions, where the VRAM is still being
2448 	 * accessed by the GPU. Most internal callers are not expecting this,
2449 	 * since they are missing the required synchronisation before accessing
2450 	 * the memory. To keep things simple just sync wait any kernel fences
2451 	 * here, if the buffer is designated KMD internal.
2452 	 *
2453 	 * For normal userspace objects we should already have the required
2454 	 * pipelining or sync waiting elsewhere, since we already have to deal
2455 	 * with things like async GPU clearing.
2456 	 */
2457 	if (type == ttm_bo_type_kernel) {
2458 		long timeout = dma_resv_wait_timeout(bo->ttm.base.resv,
2459 						     DMA_RESV_USAGE_KERNEL,
2460 						     ctx.interruptible,
2461 						     MAX_SCHEDULE_TIMEOUT);
2462 
2463 		if (timeout < 0) {
2464 			if (!resv)
2465 				dma_resv_unlock(bo->ttm.base.resv);
2466 			xe_bo_put(bo);
2467 			return ERR_PTR(timeout);
2468 		}
2469 	}
2470 
2471 	bo->created = true;
2472 	if (bulk)
2473 		ttm_bo_set_bulk_move(&bo->ttm, bulk);
2474 	else
2475 		ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
2476 
2477 	return bo;
2478 }
2479 
2480 static int __xe_bo_fixed_placement(struct xe_device *xe,
2481 				   struct xe_bo *bo, enum ttm_bo_type type,
2482 				   u32 flags,
2483 				   u64 start, u64 end, u64 size)
2484 {
2485 	struct ttm_place *place = bo->placements;
2486 	u32 vram_flag, vram_stolen_flags;
2487 
2488 	/*
2489 	 * to allow fixed placement in GGTT of a VF, post-migration fixups would have to
2490 	 * include selecting a new fixed offset and shifting the page ranges for it
2491 	 */
2492 	xe_assert(xe, !IS_SRIOV_VF(xe) || !(bo->flags & XE_BO_FLAG_GGTT));
2493 
2494 	if (flags & (XE_BO_FLAG_USER | XE_BO_FLAG_SYSTEM))
2495 		return -EINVAL;
2496 
2497 	vram_flag = flags & XE_BO_FLAG_VRAM_MASK;
2498 	vram_stolen_flags = (flags & (XE_BO_FLAG_STOLEN)) | vram_flag;
2499 
2500 	/* check if more than one VRAM/STOLEN flag is set */
2501 	if (hweight32(vram_stolen_flags) > 1)
2502 		return -EINVAL;
2503 
2504 	place->flags = TTM_PL_FLAG_CONTIGUOUS;
2505 	place->fpfn = start >> PAGE_SHIFT;
2506 	place->lpfn = end >> PAGE_SHIFT;
2507 
2508 	if (flags & XE_BO_FLAG_STOLEN)
2509 		place->mem_type = XE_PL_STOLEN;
2510 	else
2511 		place->mem_type = bo_vram_flags_to_vram_placement(xe, flags, vram_flag, type);
2512 
2513 	bo->placement = (struct ttm_placement) {
2514 		.num_placement = 1,
2515 		.placement = place,
2516 	};
2517 
2518 	return 0;
2519 }
2520 
2521 static struct xe_bo *
2522 __xe_bo_create_locked(struct xe_device *xe,
2523 		      struct xe_tile *tile, struct xe_vm *vm,
2524 		      size_t size, u64 start, u64 end,
2525 		      u16 cpu_caching, enum ttm_bo_type type, u32 flags,
2526 		      u64 alignment, struct drm_exec *exec)
2527 {
2528 	struct xe_bo *bo = NULL;
2529 	int err;
2530 
2531 	if (vm)
2532 		xe_vm_assert_held(vm);
2533 
2534 	if (start || end != ~0ULL) {
2535 		bo = xe_bo_alloc();
2536 		if (IS_ERR(bo))
2537 			return bo;
2538 
2539 		flags |= XE_BO_FLAG_FIXED_PLACEMENT;
2540 		err = __xe_bo_fixed_placement(xe, bo, type, flags, start, end, size);
2541 		if (err) {
2542 			xe_bo_free(bo);
2543 			return ERR_PTR(err);
2544 		}
2545 	}
2546 
2547 	bo = xe_bo_init_locked(xe, bo, tile, vm ? xe_vm_resv(vm) : NULL,
2548 			       vm && !xe_vm_in_fault_mode(vm) &&
2549 			       flags & XE_BO_FLAG_USER ?
2550 			       &vm->lru_bulk_move : NULL, size,
2551 			       cpu_caching, type, flags, NULL, exec);
2552 	if (IS_ERR(bo))
2553 		return bo;
2554 
2555 	bo->min_align = alignment;
2556 
2557 	/*
2558 	 * Note that instead of taking a reference no the drm_gpuvm_resv_bo(),
2559 	 * to ensure the shared resv doesn't disappear under the bo, the bo
2560 	 * will keep a reference to the vm, and avoid circular references
2561 	 * by having all the vm's bo refereferences released at vm close
2562 	 * time.
2563 	 */
2564 	if (vm && xe_bo_is_user(bo))
2565 		xe_vm_get(vm);
2566 	bo->vm = vm;
2567 
2568 	if (bo->flags & XE_BO_FLAG_GGTT) {
2569 		struct xe_tile *t;
2570 		u8 id;
2571 
2572 		if (!(bo->flags & XE_BO_FLAG_GGTT_ALL)) {
2573 			if (!tile && flags & XE_BO_FLAG_STOLEN)
2574 				tile = xe_device_get_root_tile(xe);
2575 
2576 			xe_assert(xe, tile);
2577 		}
2578 
2579 		for_each_tile(t, xe, id) {
2580 			if (t != tile && !(bo->flags & XE_BO_FLAG_GGTTx(t)))
2581 				continue;
2582 
2583 			if (flags & XE_BO_FLAG_FIXED_PLACEMENT) {
2584 				err = xe_ggtt_insert_bo_at(t->mem.ggtt, bo,
2585 							   start + xe_bo_size(bo), U64_MAX,
2586 							   exec);
2587 			} else {
2588 				err = xe_ggtt_insert_bo(t->mem.ggtt, bo, exec);
2589 			}
2590 			if (err)
2591 				goto err_unlock_put_bo;
2592 		}
2593 	}
2594 
2595 	trace_xe_bo_create(bo);
2596 	return bo;
2597 
2598 err_unlock_put_bo:
2599 	__xe_bo_unset_bulk_move(bo);
2600 	xe_bo_unlock_vm_held(bo);
2601 	xe_bo_put(bo);
2602 	return ERR_PTR(err);
2603 }
2604 
2605 /**
2606  * xe_bo_create_locked() - Create a BO
2607  * @xe: The xe device.
2608  * @tile: The tile to select for migration of this bo, and the tile used for
2609  * GGTT binding if any. Only to be non-NULL for ttm_bo_type_kernel bos.
2610  * @vm: The local vm or NULL for external objects.
2611  * @size: The storage size to use for the bo.
2612  * @type: The TTM buffer object type.
2613  * @flags: XE_BO_FLAG_ flags.
2614  * @exec: The drm_exec transaction to use for exhaustive eviction.
2615  *
2616  * Create a locked xe BO with no range- nor alignment restrictions.
2617  *
2618  * Return: The buffer object on success. Negative error pointer on failure.
2619  */
2620 struct xe_bo *xe_bo_create_locked(struct xe_device *xe, struct xe_tile *tile,
2621 				  struct xe_vm *vm, size_t size,
2622 				  enum ttm_bo_type type, u32 flags,
2623 				  struct drm_exec *exec)
2624 {
2625 	return __xe_bo_create_locked(xe, tile, vm, size, 0, ~0ULL, 0, type,
2626 				     flags, 0, exec);
2627 }
2628 
2629 static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *tile,
2630 				       size_t size, u16 cpu_caching,
2631 				       enum ttm_bo_type type, u32 flags,
2632 				       u64 alignment, bool intr)
2633 {
2634 	struct xe_validation_ctx ctx;
2635 	struct drm_exec exec;
2636 	struct xe_bo *bo;
2637 	int ret = 0;
2638 
2639 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = intr},
2640 			    ret) {
2641 		bo = __xe_bo_create_locked(xe, tile, NULL, size, 0, ~0ULL,
2642 					   cpu_caching, type, flags, alignment, &exec);
2643 		drm_exec_retry_on_contention(&exec);
2644 		if (IS_ERR(bo)) {
2645 			ret = PTR_ERR(bo);
2646 			xe_validation_retry_on_oom(&ctx, &ret);
2647 		} else {
2648 			xe_bo_unlock(bo);
2649 		}
2650 	}
2651 
2652 	return ret ? ERR_PTR(ret) : bo;
2653 }
2654 
2655 #ifdef CONFIG_DRM_XE_DEBUG_PAGE_SIZE
2656 static void xe_bo_debug_mixed_mode_cur_index_advance(struct xe_device *xe, struct xe_bo *bo)
2657 {
2658 	if (!xe_debug_page_size_mode_is_mixed(xe))
2659 		return;
2660 
2661 	if (!(bo->flags & XE_BO_FLAG_VRAM_MASK) ||
2662 	    !(bo->flags & XE_BO_FLAG_USER))
2663 		return;
2664 
2665 	mutex_lock(&xe->page_size_alloc_ctrl.lock);
2666 	if (xe->page_size_alloc_ctrl.mode == XE_PAGE_SIZE_ALLOC_CTRL_MODE_MIXED)
2667 		xe->page_size_alloc_ctrl.cur_index++;
2668 	mutex_unlock(&xe->page_size_alloc_ctrl.lock);
2669 }
2670 
2671 static bool xe_size_align_overflows(size_t size, size_t align)
2672 {
2673 	return size > SIZE_MAX - (align - 1);
2674 }
2675 
2676 static u32 get_flag_from_cur_index_in_mixed_mode(struct xe_device *xe, size_t *align_size,
2677 						 int *err)
2678 {
2679 	static const struct {
2680 		u32    flag;
2681 		size_t align;
2682 	} map[] = {
2683 		{ 0,                     SZ_4K  }, /* default: 4K, no flag */
2684 		{ XE_BO_FLAG_NEEDS_64K,  SZ_64K },
2685 		{ XE_BO_FLAG_NEEDS_2M,   SZ_2M  },
2686 		{ XE_BO_FLAG_NEEDS_1G,   SZ_1G  },
2687 	};
2688 	u32 idx;
2689 	const typeof(*map) *entry;
2690 
2691 	lockdep_assert_held(&xe->page_size_alloc_ctrl.lock);
2692 
2693 	*err = 0;
2694 	idx = xe->page_size_alloc_ctrl.cur_index % ARRAY_SIZE(map);
2695 
2696 	entry = &map[idx];
2697 
2698 	if (!entry->flag)
2699 		return 0;
2700 
2701 	if (xe_size_align_overflows(*align_size, entry->align)) {
2702 		*err = -EINVAL;
2703 		return 0;
2704 	}
2705 	*align_size = ALIGN(*align_size, entry->align);
2706 
2707 	return entry->flag;
2708 }
2709 
2710 static int xe_bo_apply_debug_page_size_policy(struct xe_device *xe,
2711 					      u32 *bo_flags,
2712 					      size_t *size)
2713 {
2714 	enum xe_page_size_alloc_ctrl_mode mode;
2715 	u32 want = 0;
2716 	size_t align_size = *size;
2717 	int err = 0;
2718 
2719 	/*
2720 	 * The debug page-size policy is only meaningful for BOs placed in
2721 	 * VRAM, where the downstream BO init path can
2722 	 * actually honor the corresponding minimum page-size requirement.
2723 	 */
2724 	if (!(*bo_flags & XE_BO_FLAG_VRAM_MASK))
2725 		return 0;
2726 
2727 	/*
2728 	 * Do not override existing page-size requirement flags, since they
2729 	 * may reflect functional requirements for specific BO types.
2730 	 */
2731 	if (*bo_flags & (XE_BO_FLAG_NEEDS_64K |
2732 			 XE_BO_FLAG_NEEDS_2M |
2733 			 XE_BO_FLAG_NEEDS_1G))
2734 		return 0;
2735 
2736 	if (!READ_ONCE(xe->page_size_alloc_ctrl.mode))
2737 		return 0;
2738 
2739 	mutex_lock(&xe->page_size_alloc_ctrl.lock);
2740 
2741 	mode = xe->page_size_alloc_ctrl.mode;
2742 	if (mode == XE_PAGE_SIZE_ALLOC_CTRL_MODE_NONE) {
2743 		goto out_unlock;
2744 	} else if (mode == XE_PAGE_SIZE_ALLOC_CTRL_MODE_ONLY_2M) {
2745 		if (xe_size_align_overflows(align_size, SZ_2M)) {
2746 			err = -EINVAL;
2747 			goto out_unlock;
2748 		}
2749 		want = XE_BO_FLAG_NEEDS_2M;
2750 		align_size = ALIGN(align_size, SZ_2M);
2751 	} else if (mode == XE_PAGE_SIZE_ALLOC_CTRL_MODE_ONLY_1G) {
2752 		if (xe_size_align_overflows(align_size, SZ_1G)) {
2753 			err = -EINVAL;
2754 			goto out_unlock;
2755 		}
2756 		want = XE_BO_FLAG_NEEDS_1G;
2757 		align_size = ALIGN(align_size, SZ_1G);
2758 	} else if (mode == XE_PAGE_SIZE_ALLOC_CTRL_MODE_MIXED) {
2759 		want = get_flag_from_cur_index_in_mixed_mode(xe, &align_size, &err);
2760 		if (err)
2761 			goto out_unlock;
2762 	} else {
2763 		goto out_unlock;
2764 	}
2765 
2766 	mutex_unlock(&xe->page_size_alloc_ctrl.lock);
2767 
2768 	*bo_flags |= want;
2769 	/*
2770 	 * Apply the debug page-size policy by rounding the user BO size up to
2771 	 * the selected granularity.
2772 	 */
2773 	*size = align_size;
2774 	return err;
2775 
2776 out_unlock:
2777 	mutex_unlock(&xe->page_size_alloc_ctrl.lock);
2778 	return err;
2779 }
2780 #else
2781 static int xe_bo_apply_debug_page_size_policy(struct xe_device *xe,
2782 					      u32 *bo_flags,
2783 					      size_t *size)
2784 {
2785 	return 0;
2786 }
2787 
2788 static void xe_bo_debug_mixed_mode_cur_index_advance(struct xe_device *xe,
2789 						     struct xe_bo *bo)
2790 {
2791 }
2792 #endif
2793 
2794 /**
2795  * xe_bo_create_user() - Create a user BO
2796  * @xe: The xe device.
2797  * @vm: The local vm or NULL for external objects.
2798  * @size: The storage size to use for the bo.
2799  * @cpu_caching: The caching mode to be used for system backing store.
2800  * @flags: XE_BO_FLAG_ flags.
2801  * @exec: The drm_exec transaction to use for exhaustive eviction, or NULL
2802  * if such a transaction should be initiated by the call.
2803  *
2804  * Create a bo on behalf of user-space.
2805  *
2806  * Return: The buffer object on success. Negative error pointer on failure.
2807  */
2808 struct xe_bo *xe_bo_create_user(struct xe_device *xe,
2809 				struct xe_vm *vm, size_t size,
2810 				u16 cpu_caching,
2811 				u32 flags, struct drm_exec *exec)
2812 {
2813 	struct xe_bo *bo;
2814 	int err = 0;
2815 
2816 	flags |= XE_BO_FLAG_USER;
2817 
2818 	if (xe_debug_page_size_mode_not_none(xe)) {
2819 		err = xe_bo_apply_debug_page_size_policy(xe, &flags, &size);
2820 		if (err)
2821 			return ERR_PTR(err);
2822 	}
2823 
2824 	if (vm || exec) {
2825 		xe_assert(xe, exec);
2826 		bo = __xe_bo_create_locked(xe, NULL, vm, size, 0, ~0ULL,
2827 					   cpu_caching, ttm_bo_type_device,
2828 					   flags, 0, exec);
2829 		if (!IS_ERR(bo))
2830 			xe_bo_unlock_vm_held(bo);
2831 	} else {
2832 		bo = xe_bo_create_novm(xe, NULL, size, cpu_caching,
2833 				       ttm_bo_type_device, flags, 0, true);
2834 	}
2835 
2836 	return bo;
2837 }
2838 
2839 /**
2840  * xe_bo_create_pin_range_novm() - Create and pin a BO with range options.
2841  * @xe: The xe device.
2842  * @tile: The tile to select for migration of this bo, and the tile used for
2843  * GGTT binding if any. Only to be non-NULL for ttm_bo_type_kernel bos.
2844  * @size: The storage size to use for the bo.
2845  * @start: Start of fixed VRAM range or 0.
2846  * @end: End of fixed VRAM range or ~0ULL.
2847  * @type: The TTM buffer object type.
2848  * @flags: XE_BO_FLAG_ flags.
2849  *
2850  * Create an Xe BO with range- and options. If @start and @end indicate
2851  * a fixed VRAM range, this must be a ttm_bo_type_kernel bo with VRAM placement
2852  * only.
2853  *
2854  * Return: The buffer object on success. Negative error pointer on failure.
2855  */
2856 struct xe_bo *xe_bo_create_pin_range_novm(struct xe_device *xe, struct xe_tile *tile,
2857 					  size_t size, u64 start, u64 end,
2858 					  enum ttm_bo_type type, u32 flags)
2859 {
2860 	struct xe_validation_ctx ctx;
2861 	struct drm_exec exec;
2862 	struct xe_bo *bo;
2863 	int err = 0;
2864 
2865 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {}, err) {
2866 		bo = __xe_bo_create_locked(xe, tile, NULL, size, start, end,
2867 					   0, type, flags, 0, &exec);
2868 		if (IS_ERR(bo)) {
2869 			drm_exec_retry_on_contention(&exec);
2870 			err = PTR_ERR(bo);
2871 			xe_validation_retry_on_oom(&ctx, &err);
2872 			break;
2873 		}
2874 
2875 		err = xe_bo_pin(bo, &exec);
2876 		xe_bo_unlock(bo);
2877 		if (err) {
2878 			xe_bo_put(bo);
2879 			drm_exec_retry_on_contention(&exec);
2880 			xe_validation_retry_on_oom(&ctx, &err);
2881 			break;
2882 		}
2883 	}
2884 
2885 	return err ? ERR_PTR(err) : bo;
2886 }
2887 
2888 static struct xe_bo *xe_bo_create_pin_map_at_aligned(struct xe_device *xe,
2889 						     struct xe_tile *tile,
2890 						     struct xe_vm *vm,
2891 						     size_t size, u64 offset,
2892 						     enum ttm_bo_type type, u32 flags,
2893 						     u64 alignment, struct drm_exec *exec)
2894 {
2895 	struct xe_bo *bo;
2896 	int err;
2897 	u64 start = offset == ~0ull ? 0 : offset;
2898 	u64 end = offset == ~0ull ? ~0ull : start + size;
2899 
2900 	if (flags & XE_BO_FLAG_STOLEN &&
2901 	    xe_ttm_stolen_cpu_access_needs_ggtt(xe))
2902 		flags |= XE_BO_FLAG_GGTT;
2903 
2904 	bo = __xe_bo_create_locked(xe, tile, vm, size, start, end, 0, type,
2905 				   flags | XE_BO_FLAG_NEEDS_CPU_ACCESS | XE_BO_FLAG_PINNED,
2906 				   alignment, exec);
2907 	if (IS_ERR(bo))
2908 		return bo;
2909 
2910 	err = xe_bo_pin(bo, exec);
2911 	if (err)
2912 		goto err_put;
2913 
2914 	err = xe_bo_vmap(bo);
2915 	if (err)
2916 		goto err_unpin;
2917 
2918 	xe_bo_unlock_vm_held(bo);
2919 
2920 	return bo;
2921 
2922 err_unpin:
2923 	xe_bo_unpin(bo);
2924 err_put:
2925 	xe_bo_unlock_vm_held(bo);
2926 	xe_bo_put(bo);
2927 	return ERR_PTR(err);
2928 }
2929 
2930 /**
2931  * xe_bo_create_pin_map_at_novm() - Create pinned and mapped bo at optional VRAM offset
2932  * @xe: The xe device.
2933  * @tile: The tile to select for migration of this bo, and the tile used for
2934  * GGTT binding if any. Only to be non-NULL for ttm_bo_type_kernel bos.
2935  * @size: The storage size to use for the bo.
2936  * @offset: Optional VRAM offset or %~0ull for don't care.
2937  * @type: The TTM buffer object type.
2938  * @flags: XE_BO_FLAG_ flags.
2939  * @alignment: GGTT alignment.
2940  * @intr: Whether to execute any waits for backing store interruptible.
2941  *
2942  * Create a pinned and optionally mapped bo with VRAM offset and GGTT alignment
2943  * options. The bo will be external and not associated with a VM.
2944  *
2945  * Return: The buffer object on success. Negative error pointer on failure.
2946  * In particular, the function may return ERR_PTR(%-EINTR) if @intr was set
2947  * to true on entry.
2948  */
2949 struct xe_bo *
2950 xe_bo_create_pin_map_at_novm(struct xe_device *xe, struct xe_tile *tile,
2951 			     size_t size, u64 offset, enum ttm_bo_type type, u32 flags,
2952 			     u64 alignment, bool intr)
2953 {
2954 	struct xe_validation_ctx ctx;
2955 	struct drm_exec exec;
2956 	struct xe_bo *bo;
2957 	int ret = 0;
2958 
2959 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = intr},
2960 			    ret) {
2961 		bo = xe_bo_create_pin_map_at_aligned(xe, tile, NULL, size, offset,
2962 						     type, flags, alignment, &exec);
2963 		if (IS_ERR(bo)) {
2964 			drm_exec_retry_on_contention(&exec);
2965 			ret = PTR_ERR(bo);
2966 			xe_validation_retry_on_oom(&ctx, &ret);
2967 		}
2968 	}
2969 
2970 	return ret ? ERR_PTR(ret) : bo;
2971 }
2972 
2973 /**
2974  * xe_bo_create_pin_map() - Create pinned and mapped bo
2975  * @xe: The xe device.
2976  * @tile: The tile to select for migration of this bo, and the tile used for
2977  * @vm: The vm to associate the buffer object with. The vm's resv must be locked
2978  * with the transaction represented by @exec.
2979  * GGTT binding if any. Only to be non-NULL for ttm_bo_type_kernel bos.
2980  * @size: The storage size to use for the bo.
2981  * @type: The TTM buffer object type.
2982  * @flags: XE_BO_FLAG_ flags.
2983  * @exec: The drm_exec transaction to use for exhaustive eviction, and
2984  * previously used for locking @vm's resv.
2985  *
2986  * Create a pinned and mapped bo. The bo will be external and not associated
2987  * with a VM.
2988  *
2989  * Return: The buffer object on success. Negative error pointer on failure.
2990  * In particular, the function may return ERR_PTR(%-EINTR) if @exec was
2991  * configured for interruptible locking.
2992  */
2993 struct xe_bo *xe_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
2994 				   struct xe_vm *vm, size_t size,
2995 				   enum ttm_bo_type type, u32 flags,
2996 				   struct drm_exec *exec)
2997 {
2998 	return xe_bo_create_pin_map_at_aligned(xe, tile, vm, size, ~0ull, type, flags,
2999 					       0, exec);
3000 }
3001 
3002 /**
3003  * xe_bo_create_pin_map_novm() - Create pinned and mapped bo
3004  * @xe: The xe device.
3005  * @tile: The tile to select for migration of this bo, and the tile used for
3006  * GGTT binding if any. Only to be non-NULL for ttm_bo_type_kernel bos.
3007  * @size: The storage size to use for the bo.
3008  * @type: The TTM buffer object type.
3009  * @flags: XE_BO_FLAG_ flags.
3010  * @intr: Whether to execute any waits for backing store interruptible.
3011  *
3012  * Create a pinned and mapped bo. The bo will be external and not associated
3013  * with a VM.
3014  *
3015  * Return: The buffer object on success. Negative error pointer on failure.
3016  * In particular, the function may return ERR_PTR(%-EINTR) if @intr was set
3017  * to true on entry.
3018  */
3019 struct xe_bo *xe_bo_create_pin_map_novm(struct xe_device *xe, struct xe_tile *tile,
3020 					size_t size, enum ttm_bo_type type, u32 flags,
3021 					bool intr)
3022 {
3023 	return xe_bo_create_pin_map_at_novm(xe, tile, size, ~0ull, type, flags, 0, intr);
3024 }
3025 
3026 static void __xe_bo_unpin_map_no_vm(void *arg)
3027 {
3028 	xe_bo_unpin_map_no_vm(arg);
3029 }
3030 
3031 struct xe_bo *xe_managed_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
3032 					   size_t size, u32 flags)
3033 {
3034 	struct xe_bo *bo;
3035 	int ret;
3036 
3037 	KUNIT_STATIC_STUB_REDIRECT(xe_managed_bo_create_pin_map, xe, tile, size, flags);
3038 	bo = xe_bo_create_pin_map_novm(xe, tile, size, ttm_bo_type_kernel, flags, true);
3039 	if (IS_ERR(bo))
3040 		return bo;
3041 
3042 	ret = devm_add_action_or_reset(xe->drm.dev, __xe_bo_unpin_map_no_vm, bo);
3043 	if (ret)
3044 		return ERR_PTR(ret);
3045 
3046 	return bo;
3047 }
3048 
3049 void xe_managed_bo_unpin_map_no_vm(struct xe_bo *bo)
3050 {
3051 	devm_release_action(xe_bo_device(bo)->drm.dev, __xe_bo_unpin_map_no_vm, bo);
3052 }
3053 
3054 struct xe_bo *xe_managed_bo_create_from_data(struct xe_device *xe, struct xe_tile *tile,
3055 					     const void *data, size_t size, u32 flags)
3056 {
3057 	struct xe_bo *bo = xe_managed_bo_create_pin_map(xe, tile, ALIGN(size, PAGE_SIZE), flags);
3058 
3059 	if (IS_ERR(bo))
3060 		return bo;
3061 
3062 	xe_map_memcpy_to(xe, &bo->vmap, 0, data, size);
3063 
3064 	return bo;
3065 }
3066 
3067 /**
3068  * xe_managed_bo_reinit_in_vram
3069  * @xe: xe device
3070  * @tile: Tile where the new buffer will be created
3071  * @src: Managed buffer object allocated in system memory
3072  *
3073  * Replace a managed src buffer object allocated in system memory with a new
3074  * one allocated in vram, copying the data between them.
3075  * Buffer object in VRAM is not going to have the same GGTT address, the caller
3076  * is responsible for making sure that any old references to it are updated.
3077  *
3078  * Returns 0 for success, negative error code otherwise.
3079  */
3080 int xe_managed_bo_reinit_in_vram(struct xe_device *xe, struct xe_tile *tile, struct xe_bo **src)
3081 {
3082 	struct xe_bo *bo;
3083 	u32 dst_flags = XE_BO_FLAG_VRAM_IF_DGFX(tile) | XE_BO_FLAG_GGTT;
3084 
3085 	dst_flags |= (*src)->flags & (XE_BO_FLAG_GGTT_INVALIDATE |
3086 				      XE_BO_FLAG_PINNED_NORESTORE);
3087 
3088 	xe_assert(xe, IS_DGFX(xe));
3089 	xe_assert(xe, !(*src)->vmap.is_iomem);
3090 
3091 	bo = xe_managed_bo_create_from_data(xe, tile, (*src)->vmap.vaddr,
3092 					    xe_bo_size(*src), dst_flags);
3093 	if (IS_ERR(bo))
3094 		return PTR_ERR(bo);
3095 
3096 	devm_release_action(xe->drm.dev, __xe_bo_unpin_map_no_vm, *src);
3097 	*src = bo;
3098 
3099 	return 0;
3100 }
3101 
3102 /*
3103  * XXX: This is in the VM bind data path, likely should calculate this once and
3104  * store, with a recalculation if the BO is moved.
3105  */
3106 uint64_t vram_region_gpu_offset(struct ttm_resource *res)
3107 {
3108 	struct xe_device *xe = ttm_to_xe_device(res->bo->bdev);
3109 
3110 	switch (res->mem_type) {
3111 	case XE_PL_STOLEN:
3112 		return xe_ttm_stolen_gpu_offset(xe);
3113 	case XE_PL_TT:
3114 	case XE_PL_SYSTEM:
3115 		return 0;
3116 	default:
3117 		return xe_map_resource_to_region(res)->dpa_base;
3118 	}
3119 	return 0;
3120 }
3121 
3122 /**
3123  * xe_bo_pin_external - pin an external BO
3124  * @bo: buffer object to be pinned
3125  * @in_place: Pin in current placement, don't attempt to migrate.
3126  * @exec: The drm_exec transaction to use for exhaustive eviction.
3127  *
3128  * Pin an external (not tied to a VM, can be exported via dma-buf / prime FD)
3129  * BO. Unique call compared to xe_bo_pin as this function has it own set of
3130  * asserts and code to ensure evict / restore on suspend / resume.
3131  *
3132  * Returns 0 for success, negative error code otherwise.
3133  */
3134 int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec)
3135 {
3136 	struct xe_device *xe = xe_bo_device(bo);
3137 	int err;
3138 
3139 	xe_assert(xe, !bo->vm);
3140 	xe_assert(xe, xe_bo_is_user(bo));
3141 
3142 	if (!xe_bo_is_pinned(bo)) {
3143 		if (!in_place) {
3144 			err = xe_bo_validate(bo, NULL, false, exec);
3145 			if (err)
3146 				return err;
3147 		}
3148 
3149 		spin_lock(&xe->pinned.lock);
3150 		list_add_tail(&bo->pinned_link, &xe->pinned.late.external);
3151 		spin_unlock(&xe->pinned.lock);
3152 	}
3153 
3154 	ttm_bo_pin(&bo->ttm);
3155 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
3156 		xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
3157 
3158 	/*
3159 	 * FIXME: If we always use the reserve / unreserve functions for locking
3160 	 * we do not need this.
3161 	 */
3162 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
3163 
3164 	return 0;
3165 }
3166 
3167 /**
3168  * xe_bo_pin() - Pin a kernel bo after potentially migrating it
3169  * @bo: The kernel bo to pin.
3170  * @exec: The drm_exec transaction to use for exhaustive eviction.
3171  *
3172  * Attempts to migrate a bo to @bo->placement. If that succeeds,
3173  * pins the bo.
3174  *
3175  * Return: %0 on success, negative error code on migration failure.
3176  */
3177 int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec)
3178 {
3179 	struct ttm_place *place = &bo->placements[0];
3180 	struct xe_device *xe = xe_bo_device(bo);
3181 	int err;
3182 
3183 	/* We currently don't expect user BO to be pinned */
3184 	xe_assert(xe, !xe_bo_is_user(bo));
3185 
3186 	/* Pinned object must be in GGTT or have pinned flag */
3187 	xe_assert(xe, bo->flags & (XE_BO_FLAG_PINNED |
3188 				   XE_BO_FLAG_GGTT));
3189 
3190 	/*
3191 	 * No reason we can't support pinning imported dma-bufs we just don't
3192 	 * expect to pin an imported dma-buf.
3193 	 */
3194 	xe_assert(xe, !bo->ttm.base.import_attach);
3195 
3196 	/* We only expect at most 1 pin */
3197 	xe_assert(xe, !xe_bo_is_pinned(bo));
3198 
3199 	err = xe_bo_validate(bo, NULL, false, exec);
3200 	if (err)
3201 		return err;
3202 
3203 	if (mem_type_is_vram(place->mem_type) || bo->flags & XE_BO_FLAG_GGTT) {
3204 		spin_lock(&xe->pinned.lock);
3205 		if (bo->flags & XE_BO_FLAG_PINNED_LATE_RESTORE)
3206 			list_add_tail(&bo->pinned_link, &xe->pinned.late.kernel_bo_present);
3207 		else
3208 			list_add_tail(&bo->pinned_link, &xe->pinned.early.kernel_bo_present);
3209 		spin_unlock(&xe->pinned.lock);
3210 	}
3211 
3212 	ttm_bo_pin(&bo->ttm);
3213 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
3214 		xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
3215 
3216 	/*
3217 	 * FIXME: If we always use the reserve / unreserve functions for locking
3218 	 * we do not need this.
3219 	 */
3220 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
3221 
3222 	return 0;
3223 }
3224 
3225 /**
3226  * xe_bo_unpin_external - unpin an external BO
3227  * @bo: buffer object to be unpinned
3228  *
3229  * Unpin an external (not tied to a VM, can be exported via dma-buf / prime FD)
3230  * BO. Unique call compared to xe_bo_unpin as this function has it own set of
3231  * asserts and code to ensure evict / restore on suspend / resume.
3232  *
3233  * Returns 0 for success, negative error code otherwise.
3234  */
3235 void xe_bo_unpin_external(struct xe_bo *bo)
3236 {
3237 	struct xe_device *xe = xe_bo_device(bo);
3238 
3239 	xe_assert(xe, !bo->vm);
3240 	xe_assert(xe, xe_bo_is_pinned(bo));
3241 	xe_assert(xe, xe_bo_is_user(bo));
3242 
3243 	spin_lock(&xe->pinned.lock);
3244 	if (bo->ttm.pin_count == 1 && !list_empty(&bo->pinned_link))
3245 		list_del_init(&bo->pinned_link);
3246 	spin_unlock(&xe->pinned.lock);
3247 
3248 	ttm_bo_unpin(&bo->ttm);
3249 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
3250 		xe_ttm_tt_account_add(xe, bo->ttm.ttm);
3251 
3252 	/*
3253 	 * FIXME: If we always use the reserve / unreserve functions for locking
3254 	 * we do not need this.
3255 	 */
3256 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
3257 }
3258 
3259 void xe_bo_unpin(struct xe_bo *bo)
3260 {
3261 	struct ttm_place *place = &bo->placements[0];
3262 	struct xe_device *xe = xe_bo_device(bo);
3263 
3264 	xe_assert(xe, !bo->ttm.base.import_attach);
3265 	xe_assert(xe, xe_bo_is_pinned(bo));
3266 
3267 	if (mem_type_is_vram(place->mem_type) || bo->flags & XE_BO_FLAG_GGTT) {
3268 		spin_lock(&xe->pinned.lock);
3269 		xe_assert(xe, !list_empty(&bo->pinned_link));
3270 		list_del_init(&bo->pinned_link);
3271 		spin_unlock(&xe->pinned.lock);
3272 
3273 		if (bo->backup_obj) {
3274 			if (xe_bo_is_pinned(bo->backup_obj))
3275 				ttm_bo_unpin(&bo->backup_obj->ttm);
3276 			xe_bo_put(bo->backup_obj);
3277 			bo->backup_obj = NULL;
3278 		}
3279 	}
3280 	ttm_bo_unpin(&bo->ttm);
3281 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
3282 		xe_ttm_tt_account_add(xe, bo->ttm.ttm);
3283 }
3284 
3285 /**
3286  * xe_bo_validate() - Make sure the bo is in an allowed placement
3287  * @bo: The bo,
3288  * @vm: Pointer to a the vm the bo shares a locked dma_resv object with, or
3289  *      NULL. Used together with @allow_res_evict.
3290  * @allow_res_evict: Whether it's allowed to evict bos sharing @vm's
3291  *                   reservation object.
3292  * @exec: The drm_exec transaction to use for exhaustive eviction.
3293  *
3294  * Make sure the bo is in allowed placement, migrating it if necessary. If
3295  * needed, other bos will be evicted. If bos selected for eviction shares
3296  * the @vm's reservation object, they can be evicted iff @allow_res_evict is
3297  * set to true, otherwise they will be bypassed.
3298  *
3299  * Return: 0 on success, negative error code on failure. May return
3300  * -EINTR or -ERESTARTSYS if internal waits are interrupted by a signal.
3301  */
3302 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict,
3303 		   struct drm_exec *exec)
3304 {
3305 	struct ttm_operation_ctx ctx = {
3306 		.interruptible = true,
3307 		.no_wait_gpu = false,
3308 		.gfp_retry_mayfail = true,
3309 	};
3310 	int ret;
3311 
3312 	if (xe_bo_is_pinned(bo))
3313 		return 0;
3314 
3315 	if (vm) {
3316 		lockdep_assert_held(&vm->lock);
3317 		xe_vm_assert_held(vm);
3318 
3319 		ctx.allow_res_evict = allow_res_evict;
3320 		ctx.resv = xe_vm_resv(vm);
3321 	}
3322 
3323 	xe_vm_set_validating(vm, allow_res_evict);
3324 	trace_xe_bo_validate(bo);
3325 	xe_validation_assert_exec(xe_bo_device(bo), exec, &bo->ttm.base);
3326 	ret = ttm_bo_validate(&bo->ttm, &bo->placement, &ctx);
3327 	xe_vm_clear_validating(vm, allow_res_evict);
3328 
3329 	return ret;
3330 }
3331 
3332 bool xe_bo_is_xe_bo(struct ttm_buffer_object *bo)
3333 {
3334 	if (bo->destroy == &xe_ttm_bo_destroy)
3335 		return true;
3336 
3337 	return false;
3338 }
3339 
3340 /*
3341  * Resolve a BO address. There is no assert to check if the proper lock is held
3342  * so it should only be used in cases where it is not fatal to get the wrong
3343  * address, such as printing debug information, but not in cases where memory is
3344  * written based on this result.
3345  */
3346 dma_addr_t __xe_bo_addr(struct xe_bo *bo, u64 offset, size_t page_size)
3347 {
3348 	struct xe_device *xe = xe_bo_device(bo);
3349 	struct xe_res_cursor cur;
3350 	u64 page;
3351 
3352 	xe_assert(xe, page_size <= PAGE_SIZE);
3353 	page = offset >> PAGE_SHIFT;
3354 	offset &= (PAGE_SIZE - 1);
3355 
3356 	if (!xe_bo_is_vram(bo) && !xe_bo_is_stolen(bo)) {
3357 		xe_assert(xe, bo->ttm.ttm);
3358 
3359 		xe_res_first_sg(xe_bo_sg(bo), page << PAGE_SHIFT,
3360 				page_size, &cur);
3361 		return xe_res_dma(&cur) + offset;
3362 	} else {
3363 		struct xe_res_cursor cur;
3364 
3365 		xe_res_first(bo->ttm.resource, page << PAGE_SHIFT,
3366 			     page_size, &cur);
3367 		return cur.start + offset + vram_region_gpu_offset(bo->ttm.resource);
3368 	}
3369 }
3370 
3371 dma_addr_t xe_bo_addr(struct xe_bo *bo, u64 offset, size_t page_size)
3372 {
3373 	if (!READ_ONCE(bo->ttm.pin_count))
3374 		xe_bo_assert_held(bo);
3375 	return __xe_bo_addr(bo, offset, page_size);
3376 }
3377 
3378 int xe_bo_vmap(struct xe_bo *bo)
3379 {
3380 	struct xe_device *xe = ttm_to_xe_device(bo->ttm.bdev);
3381 	void *virtual;
3382 	bool is_iomem;
3383 	int ret;
3384 
3385 	xe_bo_assert_held(bo);
3386 
3387 	if (drm_WARN_ON(&xe->drm, !(bo->flags & XE_BO_FLAG_NEEDS_CPU_ACCESS) ||
3388 			!force_contiguous(bo->flags)))
3389 		return -EINVAL;
3390 
3391 	if (!iosys_map_is_null(&bo->vmap))
3392 		return 0;
3393 
3394 	/*
3395 	 * We use this more or less deprecated interface for now since
3396 	 * ttm_bo_vmap() doesn't offer the optimization of kmapping
3397 	 * single page bos, which is done here.
3398 	 * TODO: Fix up ttm_bo_vmap to do that, or fix up ttm_bo_kmap
3399 	 * to use struct iosys_map.
3400 	 */
3401 	ret = ttm_bo_kmap(&bo->ttm, 0, xe_bo_size(bo) >> PAGE_SHIFT, &bo->kmap);
3402 	if (ret)
3403 		return ret;
3404 
3405 	virtual = ttm_kmap_obj_virtual(&bo->kmap, &is_iomem);
3406 	if (is_iomem)
3407 		iosys_map_set_vaddr_iomem(&bo->vmap, (void __iomem *)virtual);
3408 	else
3409 		iosys_map_set_vaddr(&bo->vmap, virtual);
3410 
3411 	return 0;
3412 }
3413 
3414 static void __xe_bo_vunmap(struct xe_bo *bo)
3415 {
3416 	if (!iosys_map_is_null(&bo->vmap)) {
3417 		iosys_map_clear(&bo->vmap);
3418 		ttm_bo_kunmap(&bo->kmap);
3419 	}
3420 }
3421 
3422 void xe_bo_vunmap(struct xe_bo *bo)
3423 {
3424 	xe_bo_assert_held(bo);
3425 	__xe_bo_vunmap(bo);
3426 }
3427 
3428 static int gem_create_set_pxp_type(struct xe_device *xe, struct xe_bo *bo, u64 value)
3429 {
3430 	if (value == DRM_XE_PXP_TYPE_NONE)
3431 		return 0;
3432 
3433 	/* we only support DRM_XE_PXP_TYPE_HWDRM for now */
3434 	if (XE_IOCTL_DBG(xe, value != DRM_XE_PXP_TYPE_HWDRM))
3435 		return -EINVAL;
3436 
3437 	return xe_pxp_key_assign(xe->pxp, bo);
3438 }
3439 
3440 typedef int (*xe_gem_create_set_property_fn)(struct xe_device *xe,
3441 					     struct xe_bo *bo,
3442 					     u64 value);
3443 
3444 static const xe_gem_create_set_property_fn gem_create_set_property_funcs[] = {
3445 	[DRM_XE_GEM_CREATE_SET_PROPERTY_PXP_TYPE] = gem_create_set_pxp_type,
3446 };
3447 
3448 static int gem_create_user_ext_set_property(struct xe_device *xe,
3449 					    struct xe_bo *bo,
3450 					    u64 extension)
3451 {
3452 	u64 __user *address = u64_to_user_ptr(extension);
3453 	struct drm_xe_ext_set_property ext;
3454 	int err;
3455 	u32 idx;
3456 
3457 	err = copy_from_user(&ext, address, sizeof(ext));
3458 	if (XE_IOCTL_DBG(xe, err))
3459 		return -EFAULT;
3460 
3461 	if (XE_IOCTL_DBG(xe, ext.property >=
3462 			 ARRAY_SIZE(gem_create_set_property_funcs)) ||
3463 	    XE_IOCTL_DBG(xe, ext.pad) ||
3464 	    XE_IOCTL_DBG(xe, ext.property != DRM_XE_GEM_CREATE_EXTENSION_SET_PROPERTY))
3465 		return -EINVAL;
3466 
3467 	idx = array_index_nospec(ext.property, ARRAY_SIZE(gem_create_set_property_funcs));
3468 	if (!gem_create_set_property_funcs[idx])
3469 		return -EINVAL;
3470 
3471 	return gem_create_set_property_funcs[idx](xe, bo, ext.value);
3472 }
3473 
3474 typedef int (*xe_gem_create_user_extension_fn)(struct xe_device *xe,
3475 					       struct xe_bo *bo,
3476 					       u64 extension);
3477 
3478 static const xe_gem_create_user_extension_fn gem_create_user_extension_funcs[] = {
3479 	[DRM_XE_GEM_CREATE_EXTENSION_SET_PROPERTY] = gem_create_user_ext_set_property,
3480 };
3481 
3482 #define MAX_USER_EXTENSIONS	16
3483 static int gem_create_user_extensions(struct xe_device *xe, struct xe_bo *bo,
3484 				      u64 extensions, int ext_number)
3485 {
3486 	u64 __user *address = u64_to_user_ptr(extensions);
3487 	struct drm_xe_user_extension ext;
3488 	int err;
3489 	u32 idx;
3490 
3491 	if (XE_IOCTL_DBG(xe, ext_number >= MAX_USER_EXTENSIONS))
3492 		return -E2BIG;
3493 
3494 	err = copy_from_user(&ext, address, sizeof(ext));
3495 	if (XE_IOCTL_DBG(xe, err))
3496 		return -EFAULT;
3497 
3498 	if (XE_IOCTL_DBG(xe, ext.pad) ||
3499 	    XE_IOCTL_DBG(xe, ext.name >= ARRAY_SIZE(gem_create_user_extension_funcs)))
3500 		return -EINVAL;
3501 
3502 	idx = array_index_nospec(ext.name,
3503 				 ARRAY_SIZE(gem_create_user_extension_funcs));
3504 	err = gem_create_user_extension_funcs[idx](xe, bo, extensions);
3505 	if (XE_IOCTL_DBG(xe, err))
3506 		return err;
3507 
3508 	if (ext.next_extension)
3509 		return gem_create_user_extensions(xe, bo, ext.next_extension,
3510 						  ++ext_number);
3511 
3512 	return 0;
3513 }
3514 
3515 int xe_gem_create_ioctl(struct drm_device *dev, void *data,
3516 			struct drm_file *file)
3517 {
3518 	struct xe_device *xe = to_xe_device(dev);
3519 	struct xe_file *xef = to_xe_file(file);
3520 	struct drm_xe_gem_create *args = data;
3521 	struct xe_validation_ctx ctx;
3522 	struct drm_exec exec;
3523 	struct xe_vm *vm = NULL;
3524 	struct xe_bo *bo;
3525 	unsigned int bo_flags;
3526 	u32 handle;
3527 	int err;
3528 
3529 	if (XE_IOCTL_DBG(xe, args->pad[0] || args->pad[1] || args->pad[2]) ||
3530 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
3531 		return -EINVAL;
3532 
3533 	/* at least one valid memory placement must be specified */
3534 	if (XE_IOCTL_DBG(xe, (args->placement & ~xe->info.mem_region_mask) ||
3535 			 !args->placement))
3536 		return -EINVAL;
3537 
3538 	if (XE_IOCTL_DBG(xe, args->flags &
3539 			 ~(DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING |
3540 			   DRM_XE_GEM_CREATE_FLAG_SCANOUT |
3541 			   DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM |
3542 			   DRM_XE_GEM_CREATE_FLAG_NO_COMPRESSION)))
3543 		return -EINVAL;
3544 
3545 	if (XE_IOCTL_DBG(xe, args->handle))
3546 		return -EINVAL;
3547 
3548 	if (XE_IOCTL_DBG(xe, !args->size))
3549 		return -EINVAL;
3550 
3551 	if (XE_IOCTL_DBG(xe, args->size > SIZE_MAX))
3552 		return -EINVAL;
3553 
3554 	if (XE_IOCTL_DBG(xe, args->size & ~PAGE_MASK))
3555 		return -EINVAL;
3556 
3557 	bo_flags = 0;
3558 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING)
3559 		bo_flags |= XE_BO_FLAG_DEFER_BACKING;
3560 
3561 	/*
3562 	 * Display scanout is always non-coherent with the CPU cache.
3563 	 */
3564 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_SCANOUT)
3565 		bo_flags |= XE_BO_FLAG_FORCE_WC;
3566 
3567 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_NO_COMPRESSION) {
3568 		if (XE_IOCTL_DBG(xe, GRAPHICS_VER(xe) < 20))
3569 			return -EOPNOTSUPP;
3570 		bo_flags |= XE_BO_FLAG_NO_COMPRESSION;
3571 	}
3572 
3573 	bo_flags |= args->placement << (ffs(XE_BO_FLAG_SYSTEM) - 1);
3574 
3575 	/* CCS formats need physical placement at a 64K alignment in VRAM. */
3576 	if ((bo_flags & XE_BO_FLAG_VRAM_MASK) &&
3577 	    (args->flags & DRM_XE_GEM_CREATE_FLAG_SCANOUT) &&
3578 	    !(xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K) &&
3579 	    IS_ALIGNED(args->size, SZ_64K))
3580 		bo_flags |= XE_BO_FLAG_NEEDS_64K;
3581 
3582 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM) {
3583 		if (XE_IOCTL_DBG(xe, !(bo_flags & XE_BO_FLAG_VRAM_MASK)))
3584 			return -EINVAL;
3585 
3586 		bo_flags |= XE_BO_FLAG_NEEDS_CPU_ACCESS;
3587 	}
3588 
3589 	if (XE_IOCTL_DBG(xe, !args->cpu_caching ||
3590 			 args->cpu_caching > DRM_XE_GEM_CPU_CACHING_WC))
3591 		return -EINVAL;
3592 
3593 	if (XE_IOCTL_DBG(xe, bo_flags & XE_BO_FLAG_VRAM_MASK &&
3594 			 args->cpu_caching != DRM_XE_GEM_CPU_CACHING_WC))
3595 		return -EINVAL;
3596 
3597 	if (XE_IOCTL_DBG(xe, bo_flags & XE_BO_FLAG_FORCE_WC &&
3598 			 args->cpu_caching == DRM_XE_GEM_CPU_CACHING_WB))
3599 		return -EINVAL;
3600 
3601 	if (args->vm_id) {
3602 		vm = xe_vm_lookup(xef, args->vm_id);
3603 		if (XE_IOCTL_DBG(xe, !vm))
3604 			return -ENOENT;
3605 	}
3606 
3607 	err = 0;
3608 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = true},
3609 			    err) {
3610 		if (vm) {
3611 			err = xe_vm_drm_exec_lock(vm, &exec);
3612 			drm_exec_retry_on_contention(&exec);
3613 			if (err)
3614 				break;
3615 		}
3616 		bo = xe_bo_create_user(xe, vm, args->size, args->cpu_caching,
3617 				       bo_flags, &exec);
3618 		drm_exec_retry_on_contention(&exec);
3619 		if (IS_ERR(bo)) {
3620 			err = PTR_ERR(bo);
3621 			xe_validation_retry_on_oom(&ctx, &err);
3622 			break;
3623 		}
3624 	}
3625 	if (err)
3626 		goto out_vm;
3627 
3628 	if (args->extensions) {
3629 		err = gem_create_user_extensions(xe, bo, args->extensions, 0);
3630 		if (err)
3631 			goto out_bulk;
3632 	}
3633 
3634 	err = drm_gem_handle_create(file, &bo->ttm.base, &handle);
3635 	if (err)
3636 		goto out_bulk;
3637 
3638 	xe_bo_debug_mixed_mode_cur_index_advance(xe, bo);
3639 
3640 	args->handle = handle;
3641 	goto out_put;
3642 
3643 out_bulk:
3644 	if (vm && !xe_vm_in_fault_mode(vm)) {
3645 		xe_vm_lock(vm, false);
3646 		__xe_bo_unset_bulk_move(bo);
3647 		xe_vm_unlock(vm);
3648 	}
3649 out_put:
3650 	xe_bo_put(bo);
3651 out_vm:
3652 	if (vm)
3653 		xe_vm_put(vm);
3654 
3655 	return err;
3656 }
3657 
3658 int xe_gem_mmap_offset_ioctl(struct drm_device *dev, void *data,
3659 			     struct drm_file *file)
3660 {
3661 	struct xe_device *xe = to_xe_device(dev);
3662 	struct drm_xe_gem_mmap_offset *args = data;
3663 	struct drm_gem_object *gem_obj;
3664 
3665 	if (XE_IOCTL_DBG(xe, args->extensions) ||
3666 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
3667 		return -EINVAL;
3668 
3669 	if (XE_IOCTL_DBG(xe, args->flags &
3670 			 ~DRM_XE_MMAP_OFFSET_FLAG_PCI_BARRIER))
3671 		return -EINVAL;
3672 
3673 	if (args->flags & DRM_XE_MMAP_OFFSET_FLAG_PCI_BARRIER) {
3674 		if (XE_IOCTL_DBG(xe, !IS_DGFX(xe)))
3675 			return -EINVAL;
3676 
3677 		if (XE_IOCTL_DBG(xe, args->handle))
3678 			return -EINVAL;
3679 
3680 		if (XE_IOCTL_DBG(xe, PAGE_SIZE > SZ_4K))
3681 			return -EINVAL;
3682 
3683 		BUILD_BUG_ON(((XE_PCI_BARRIER_MMAP_OFFSET >> XE_PTE_SHIFT) +
3684 			      SZ_4K) >= DRM_FILE_PAGE_OFFSET_START);
3685 		args->offset = XE_PCI_BARRIER_MMAP_OFFSET;
3686 		return 0;
3687 	}
3688 
3689 	gem_obj = drm_gem_object_lookup(file, args->handle);
3690 	if (XE_IOCTL_DBG(xe, !gem_obj))
3691 		return -ENOENT;
3692 
3693 	/* The mmap offset was set up at BO allocation time. */
3694 	args->offset = drm_vma_node_offset_addr(&gem_obj->vma_node);
3695 
3696 	xe_bo_put(gem_to_xe_bo(gem_obj));
3697 	return 0;
3698 }
3699 
3700 /**
3701  * xe_bo_decompress - schedule in-place decompress and install fence
3702  * @bo: buffer object (caller should hold drm_exec reservations for VM+BO)
3703  *
3704  * Schedules an in-place resolve via the migrate layer and installs the
3705  * returned dma_fence into the BO kernel reservation slot (DMA_RESV_USAGE_KERNEL).
3706  * In preempt fence mode, this operation interrupts hardware execution
3707  * which is expensive. Page fault mode is recommended for better performance.
3708  *
3709  * The resolve path only runs for VRAM-backed buffers (currently dGPU-only);
3710  * iGPU/system-memory objects fail the resource check and bypass the resolve.
3711  *
3712  * Returns 0 on success, negative errno on error.
3713  */
3714 int xe_bo_decompress(struct xe_bo *bo)
3715 {
3716 	struct xe_device *xe = xe_bo_device(bo);
3717 	struct xe_tile *tile = xe_device_get_root_tile(xe);
3718 	struct dma_fence *decomp_fence = NULL;
3719 	struct ttm_operation_ctx op_ctx = {
3720 		.interruptible = true,
3721 		.no_wait_gpu = false,
3722 		.gfp_retry_mayfail = false,
3723 	};
3724 	int err = 0;
3725 
3726 	/* Silently skip decompression for non-VRAM buffers */
3727 	if (!bo->ttm.resource || !mem_type_is_vram(bo->ttm.resource->mem_type))
3728 		return 0;
3729 
3730 	/* Notify before scheduling resolve */
3731 	err = xe_bo_move_notify(bo, &op_ctx);
3732 	if (err)
3733 		return err;
3734 
3735 	/* Reserve fence slot before scheduling */
3736 	err = dma_resv_reserve_fences(bo->ttm.base.resv, 1);
3737 	if (err)
3738 		return err;
3739 
3740 	/* Schedule the in-place decompression */
3741 	decomp_fence = xe_migrate_resolve(tile->migrate,
3742 					  bo,
3743 					  bo->ttm.resource);
3744 
3745 	if (IS_ERR(decomp_fence))
3746 		return PTR_ERR(decomp_fence);
3747 
3748 	/* Install kernel-usage fence */
3749 	dma_resv_add_fence(bo->ttm.base.resv, decomp_fence, DMA_RESV_USAGE_KERNEL);
3750 	dma_fence_put(decomp_fence);
3751 
3752 	return 0;
3753 }
3754 
3755 /**
3756  * xe_bo_lock() - Lock the buffer object's dma_resv object
3757  * @bo: The struct xe_bo whose lock is to be taken
3758  * @intr: Whether to perform any wait interruptible
3759  *
3760  * Locks the buffer object's dma_resv object. If the buffer object is
3761  * pointing to a shared dma_resv object, that shared lock is locked.
3762  *
3763  * Return: 0 on success, -EINTR if @intr is true and the wait for a
3764  * contended lock was interrupted. If @intr is set to false, the
3765  * function always returns 0.
3766  */
3767 int xe_bo_lock(struct xe_bo *bo, bool intr)
3768 {
3769 	if (intr)
3770 		return dma_resv_lock_interruptible(bo->ttm.base.resv, NULL);
3771 
3772 	dma_resv_lock(bo->ttm.base.resv, NULL);
3773 
3774 	return 0;
3775 }
3776 
3777 /**
3778  * xe_bo_unlock() - Unlock the buffer object's dma_resv object
3779  * @bo: The struct xe_bo whose lock is to be released.
3780  *
3781  * Unlock a buffer object lock that was locked by xe_bo_lock().
3782  */
3783 void xe_bo_unlock(struct xe_bo *bo)
3784 {
3785 	dma_resv_unlock(bo->ttm.base.resv);
3786 }
3787 
3788 /**
3789  * xe_bo_can_migrate - Whether a buffer object likely can be migrated
3790  * @bo: The buffer object to migrate
3791  * @mem_type: The TTM memory type intended to migrate to
3792  *
3793  * Check whether the buffer object supports migration to the
3794  * given memory type. Note that pinning may affect the ability to migrate as
3795  * returned by this function.
3796  *
3797  * This function is primarily intended as a helper for checking the
3798  * possibility to migrate buffer objects and can be called without
3799  * the object lock held.
3800  *
3801  * Return: true if migration is possible, false otherwise.
3802  */
3803 bool xe_bo_can_migrate(struct xe_bo *bo, u32 mem_type)
3804 {
3805 	unsigned int cur_place;
3806 
3807 	if (bo->ttm.type == ttm_bo_type_kernel)
3808 		return true;
3809 
3810 	if (bo->ttm.type == ttm_bo_type_sg)
3811 		return false;
3812 
3813 	for (cur_place = 0; cur_place < bo->placement.num_placement;
3814 	     cur_place++) {
3815 		if (bo->placements[cur_place].mem_type == mem_type)
3816 			return true;
3817 	}
3818 
3819 	return false;
3820 }
3821 
3822 static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place)
3823 {
3824 	memset(place, 0, sizeof(*place));
3825 	place->mem_type = mem_type;
3826 }
3827 
3828 /**
3829  * xe_bo_migrate - Migrate an object to the desired region id
3830  * @bo: The buffer object to migrate.
3831  * @mem_type: The TTM region type to migrate to.
3832  * @tctx: A pointer to a struct ttm_operation_ctx or NULL if
3833  * a default interruptibe ctx is to be used.
3834  * @exec: The drm_exec transaction to use for exhaustive eviction.
3835  *
3836  * Attempt to migrate the buffer object to the desired memory region. The
3837  * buffer object may not be pinned, and must be locked.
3838  * On successful completion, the object memory type will be updated,
3839  * but an async migration task may not have completed yet, and to
3840  * accomplish that, the object's kernel fences must be signaled with
3841  * the object lock held.
3842  *
3843  * Return: 0 on success. Negative error code on failure. In particular may
3844  * return -EINTR or -ERESTARTSYS if signal pending.
3845  */
3846 int xe_bo_migrate(struct xe_bo *bo, u32 mem_type, struct ttm_operation_ctx *tctx,
3847 		  struct drm_exec *exec)
3848 {
3849 	struct xe_device *xe = ttm_to_xe_device(bo->ttm.bdev);
3850 	struct ttm_operation_ctx ctx = {
3851 		.interruptible = true,
3852 		.no_wait_gpu = false,
3853 		.gfp_retry_mayfail = true,
3854 	};
3855 	struct ttm_placement placement;
3856 	struct ttm_place requested;
3857 
3858 	xe_bo_assert_held(bo);
3859 	tctx = tctx ? tctx : &ctx;
3860 
3861 	if (bo->ttm.resource->mem_type == mem_type)
3862 		return 0;
3863 
3864 	if (xe_bo_is_pinned(bo))
3865 		return -EBUSY;
3866 
3867 	if (!xe_bo_can_migrate(bo, mem_type))
3868 		return -EINVAL;
3869 
3870 	xe_place_from_ttm_type(mem_type, &requested);
3871 	placement.num_placement = 1;
3872 	placement.placement = &requested;
3873 
3874 	/*
3875 	 * Stolen needs to be handled like below VRAM handling if we ever need
3876 	 * to support it.
3877 	 */
3878 	drm_WARN_ON(&xe->drm, mem_type == XE_PL_STOLEN);
3879 
3880 	if (mem_type_is_vram(mem_type)) {
3881 		u32 c = 0;
3882 
3883 		add_vram(xe, bo, &requested, bo->flags, mem_type, &c);
3884 	}
3885 
3886 	if (!tctx->no_wait_gpu)
3887 		xe_validation_assert_exec(xe_bo_device(bo), exec, &bo->ttm.base);
3888 	return ttm_bo_validate(&bo->ttm, &placement, tctx);
3889 }
3890 
3891 /**
3892  * xe_bo_evict - Evict an object to evict placement
3893  * @bo: The buffer object to migrate.
3894  * @exec: The drm_exec transaction to use for exhaustive eviction.
3895  *
3896  * On successful completion, the object memory will be moved to evict
3897  * placement. This function blocks until the object has been fully moved.
3898  *
3899  * Return: 0 on success. Negative error code on failure.
3900  */
3901 int xe_bo_evict(struct xe_bo *bo, struct drm_exec *exec)
3902 {
3903 	struct ttm_operation_ctx ctx = {
3904 		.interruptible = false,
3905 		.no_wait_gpu = false,
3906 		.gfp_retry_mayfail = true,
3907 	};
3908 	struct ttm_placement placement;
3909 	int ret;
3910 
3911 	xe_evict_flags(&bo->ttm, &placement);
3912 	ret = ttm_bo_validate(&bo->ttm, &placement, &ctx);
3913 	if (ret)
3914 		return ret;
3915 
3916 	dma_resv_wait_timeout(bo->ttm.base.resv, DMA_RESV_USAGE_KERNEL,
3917 			      false, MAX_SCHEDULE_TIMEOUT);
3918 
3919 	return 0;
3920 }
3921 
3922 /**
3923  * xe_bo_needs_ccs_pages - Whether a bo needs to back up CCS pages when
3924  * placed in system memory.
3925  * @bo: The xe_bo
3926  *
3927  * Return: true if extra pages need to be allocated, false otherwise.
3928  */
3929 bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
3930 {
3931 	struct xe_device *xe = xe_bo_device(bo);
3932 
3933 	if (GRAPHICS_VER(xe) >= 20 && IS_DGFX(xe))
3934 		return false;
3935 
3936 	if (!xe_device_has_flat_ccs(xe) || bo->ttm.type != ttm_bo_type_device)
3937 		return false;
3938 
3939 	/* On discrete GPUs, if the GPU can access this buffer from
3940 	 * system memory (i.e., it allows XE_PL_TT placement), FlatCCS
3941 	 * can't be used since there's no CCS storage associated with
3942 	 * non-VRAM addresses.
3943 	 */
3944 	if (IS_DGFX(xe) && (bo->flags & XE_BO_FLAG_SYSTEM))
3945 		return false;
3946 
3947 	/* Check if userspace explicitly requested no compression */
3948 	if (bo->flags & XE_BO_FLAG_NO_COMPRESSION)
3949 		return false;
3950 
3951 	/*
3952 	 * For WB (Write-Back) CPU caching mode, check if the device
3953 	 * supports WB compression with coherency.
3954 	 */
3955 	if (bo->cpu_caching == DRM_XE_GEM_CPU_CACHING_WB &&
3956 	    xe->pat.idx[XE_CACHE_WB_COMPRESSION] == XE_PAT_INVALID_IDX)
3957 		return false;
3958 
3959 	return true;
3960 }
3961 
3962 /**
3963  * __xe_bo_release_dummy() - Dummy kref release function
3964  * @kref: The embedded struct kref.
3965  *
3966  * Dummy release function for xe_bo_put_deferred(). Keep off.
3967  */
3968 void __xe_bo_release_dummy(struct kref *kref)
3969 {
3970 }
3971 
3972 /**
3973  * xe_bo_put_commit() - Put bos whose put was deferred by xe_bo_put_deferred().
3974  * @deferred: The lockless list used for the call to xe_bo_put_deferred().
3975  *
3976  * Puts all bos whose put was deferred by xe_bo_put_deferred().
3977  * The @deferred list can be either an onstack local list or a global
3978  * shared list used by a workqueue.
3979  */
3980 void xe_bo_put_commit(struct llist_head *deferred)
3981 {
3982 	struct llist_node *freed;
3983 	struct xe_bo *bo, *next;
3984 
3985 	if (!deferred)
3986 		return;
3987 
3988 	freed = llist_del_all(deferred);
3989 	if (!freed)
3990 		return;
3991 
3992 	llist_for_each_entry_safe(bo, next, freed, freed)
3993 		drm_gem_object_free(&bo->ttm.base.refcount);
3994 }
3995 
3996 static void xe_bo_dev_work_func(struct work_struct *work)
3997 {
3998 	struct xe_bo_dev *bo_dev = container_of(work, typeof(*bo_dev), async_free);
3999 
4000 	xe_bo_put_commit(&bo_dev->async_list);
4001 }
4002 
4003 /**
4004  * xe_bo_dev_init() - Initialize BO dev to manage async BO freeing
4005  * @bo_dev: The BO dev structure
4006  */
4007 void xe_bo_dev_init(struct xe_bo_dev *bo_dev)
4008 {
4009 	INIT_WORK(&bo_dev->async_free, xe_bo_dev_work_func);
4010 }
4011 
4012 /**
4013  * xe_bo_dev_fini() - Finalize BO dev managing async BO freeing
4014  * @bo_dev: The BO dev structure
4015  */
4016 void xe_bo_dev_fini(struct xe_bo_dev *bo_dev)
4017 {
4018 	flush_work(&bo_dev->async_free);
4019 }
4020 
4021 void xe_bo_put(struct xe_bo *bo)
4022 {
4023 	struct xe_tile *tile;
4024 	u8 id;
4025 
4026 	might_sleep();
4027 	if (bo) {
4028 #ifdef CONFIG_PROC_FS
4029 		if (bo->client)
4030 			might_lock(&bo->client->bos_lock);
4031 #endif
4032 		for_each_tile(tile, xe_bo_device(bo), id)
4033 			if (bo->ggtt_node[id])
4034 				xe_ggtt_might_lock(tile->mem.ggtt);
4035 		drm_gem_object_put(&bo->ttm.base);
4036 	}
4037 }
4038 
4039 /**
4040  * xe_bo_dumb_create - Create a dumb bo as backing for a fb
4041  * @file_priv: ...
4042  * @dev: ...
4043  * @args: ...
4044  *
4045  * See dumb_create() hook in include/drm/drm_drv.h
4046  *
4047  * Return: ...
4048  */
4049 int xe_bo_dumb_create(struct drm_file *file_priv,
4050 		      struct drm_device *dev,
4051 		      struct drm_mode_create_dumb *args)
4052 {
4053 	struct xe_device *xe = to_xe_device(dev);
4054 	struct xe_bo *bo;
4055 	uint32_t handle;
4056 	int err;
4057 	u32 page_size = max_t(u32, PAGE_SIZE,
4058 		xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K ? SZ_64K : SZ_4K);
4059 
4060 	err = drm_mode_size_dumb(dev, args, SZ_64, page_size);
4061 	if (err)
4062 		return err;
4063 
4064 	bo = xe_bo_create_user(xe, NULL, args->size,
4065 			       DRM_XE_GEM_CPU_CACHING_WC,
4066 			       XE_BO_FLAG_VRAM_IF_DGFX(xe_device_get_root_tile(xe)) |
4067 			       XE_BO_FLAG_FORCE_WC |
4068 			       XE_BO_FLAG_NEEDS_CPU_ACCESS, NULL);
4069 	if (IS_ERR(bo))
4070 		return PTR_ERR(bo);
4071 
4072 	err = drm_gem_handle_create(file_priv, &bo->ttm.base, &handle);
4073 	/* drop reference from allocate - handle holds it now */
4074 	drm_gem_object_put(&bo->ttm.base);
4075 	if (!err)
4076 		args->handle = handle;
4077 	return err;
4078 }
4079 
4080 void xe_bo_runtime_pm_release_mmap_offset(struct xe_bo *bo)
4081 {
4082 	struct ttm_buffer_object *tbo = &bo->ttm;
4083 	struct ttm_device *bdev = tbo->bdev;
4084 
4085 	drm_vma_node_unmap(&tbo->base.vma_node, bdev->dev_mapping);
4086 
4087 	list_del_init(&bo->vram_userfault_link);
4088 }
4089 
4090 #if IS_ENABLED(CONFIG_DRM_XE_KUNIT_TEST)
4091 #include "tests/xe_bo.c"
4092 #endif
4093