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