xref: /linux/drivers/gpu/drm/xe/xe_bo.c (revision 4f77c3462308c62ffe7129cc18b9ac937f44b5a5)
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 
10 #include <drm/drm_drv.h>
11 #include <drm/drm_gem_ttm_helper.h>
12 #include <drm/drm_managed.h>
13 #include <drm/ttm/ttm_device.h>
14 #include <drm/ttm/ttm_placement.h>
15 #include <drm/ttm/ttm_tt.h>
16 #include <drm/xe_drm.h>
17 
18 #include "xe_device.h"
19 #include "xe_dma_buf.h"
20 #include "xe_drm_client.h"
21 #include "xe_ggtt.h"
22 #include "xe_gt.h"
23 #include "xe_map.h"
24 #include "xe_migrate.h"
25 #include "xe_pm.h"
26 #include "xe_preempt_fence.h"
27 #include "xe_res_cursor.h"
28 #include "xe_trace_bo.h"
29 #include "xe_ttm_stolen_mgr.h"
30 #include "xe_vm.h"
31 
32 const char *const xe_mem_type_to_name[TTM_NUM_MEM_TYPES]  = {
33 	[XE_PL_SYSTEM] = "system",
34 	[XE_PL_TT] = "gtt",
35 	[XE_PL_VRAM0] = "vram0",
36 	[XE_PL_VRAM1] = "vram1",
37 	[XE_PL_STOLEN] = "stolen"
38 };
39 
40 static const struct ttm_place sys_placement_flags = {
41 	.fpfn = 0,
42 	.lpfn = 0,
43 	.mem_type = XE_PL_SYSTEM,
44 	.flags = 0,
45 };
46 
47 static struct ttm_placement sys_placement = {
48 	.num_placement = 1,
49 	.placement = &sys_placement_flags,
50 };
51 
52 static const struct ttm_place tt_placement_flags[] = {
53 	{
54 		.fpfn = 0,
55 		.lpfn = 0,
56 		.mem_type = XE_PL_TT,
57 		.flags = TTM_PL_FLAG_DESIRED,
58 	},
59 	{
60 		.fpfn = 0,
61 		.lpfn = 0,
62 		.mem_type = XE_PL_SYSTEM,
63 		.flags = TTM_PL_FLAG_FALLBACK,
64 	}
65 };
66 
67 static struct ttm_placement tt_placement = {
68 	.num_placement = 2,
69 	.placement = tt_placement_flags,
70 };
71 
72 bool mem_type_is_vram(u32 mem_type)
73 {
74 	return mem_type >= XE_PL_VRAM0 && mem_type != XE_PL_STOLEN;
75 }
76 
77 static bool resource_is_stolen_vram(struct xe_device *xe, struct ttm_resource *res)
78 {
79 	return res->mem_type == XE_PL_STOLEN && IS_DGFX(xe);
80 }
81 
82 static bool resource_is_vram(struct ttm_resource *res)
83 {
84 	return mem_type_is_vram(res->mem_type);
85 }
86 
87 bool xe_bo_is_vram(struct xe_bo *bo)
88 {
89 	return resource_is_vram(bo->ttm.resource) ||
90 		resource_is_stolen_vram(xe_bo_device(bo), bo->ttm.resource);
91 }
92 
93 bool xe_bo_is_stolen(struct xe_bo *bo)
94 {
95 	return bo->ttm.resource->mem_type == XE_PL_STOLEN;
96 }
97 
98 /**
99  * xe_bo_has_single_placement - check if BO is placed only in one memory location
100  * @bo: The BO
101  *
102  * This function checks whether a given BO is placed in only one memory location.
103  *
104  * Returns: true if the BO is placed in a single memory location, false otherwise.
105  *
106  */
107 bool xe_bo_has_single_placement(struct xe_bo *bo)
108 {
109 	return bo->placement.num_placement == 1;
110 }
111 
112 /**
113  * xe_bo_is_stolen_devmem - check if BO is of stolen type accessed via PCI BAR
114  * @bo: The BO
115  *
116  * The stolen memory is accessed through the PCI BAR for both DGFX and some
117  * integrated platforms that have a dedicated bit in the PTE for devmem (DM).
118  *
119  * Returns: true if it's stolen memory accessed via PCI BAR, false otherwise.
120  */
121 bool xe_bo_is_stolen_devmem(struct xe_bo *bo)
122 {
123 	return xe_bo_is_stolen(bo) &&
124 		GRAPHICS_VERx100(xe_bo_device(bo)) >= 1270;
125 }
126 
127 static bool xe_bo_is_user(struct xe_bo *bo)
128 {
129 	return bo->flags & XE_BO_FLAG_USER;
130 }
131 
132 static struct xe_migrate *
133 mem_type_to_migrate(struct xe_device *xe, u32 mem_type)
134 {
135 	struct xe_tile *tile;
136 
137 	xe_assert(xe, mem_type == XE_PL_STOLEN || mem_type_is_vram(mem_type));
138 	tile = &xe->tiles[mem_type == XE_PL_STOLEN ? 0 : (mem_type - XE_PL_VRAM0)];
139 	return tile->migrate;
140 }
141 
142 static struct xe_mem_region *res_to_mem_region(struct ttm_resource *res)
143 {
144 	struct xe_device *xe = ttm_to_xe_device(res->bo->bdev);
145 	struct ttm_resource_manager *mgr;
146 
147 	xe_assert(xe, resource_is_vram(res));
148 	mgr = ttm_manager_type(&xe->ttm, res->mem_type);
149 	return to_xe_ttm_vram_mgr(mgr)->vram;
150 }
151 
152 static void try_add_system(struct xe_device *xe, struct xe_bo *bo,
153 			   u32 bo_flags, u32 *c)
154 {
155 	if (bo_flags & XE_BO_FLAG_SYSTEM) {
156 		xe_assert(xe, *c < ARRAY_SIZE(bo->placements));
157 
158 		bo->placements[*c] = (struct ttm_place) {
159 			.mem_type = XE_PL_TT,
160 		};
161 		*c += 1;
162 	}
163 }
164 
165 static void add_vram(struct xe_device *xe, struct xe_bo *bo,
166 		     struct ttm_place *places, u32 bo_flags, u32 mem_type, u32 *c)
167 {
168 	struct ttm_place place = { .mem_type = mem_type };
169 	struct xe_mem_region *vram;
170 	u64 io_size;
171 
172 	xe_assert(xe, *c < ARRAY_SIZE(bo->placements));
173 
174 	vram = to_xe_ttm_vram_mgr(ttm_manager_type(&xe->ttm, mem_type))->vram;
175 	xe_assert(xe, vram && vram->usable_size);
176 	io_size = vram->io_size;
177 
178 	/*
179 	 * For eviction / restore on suspend / resume objects
180 	 * pinned in VRAM must be contiguous
181 	 */
182 	if (bo_flags & (XE_BO_FLAG_PINNED |
183 			XE_BO_FLAG_GGTT))
184 		place.flags |= TTM_PL_FLAG_CONTIGUOUS;
185 
186 	if (io_size < vram->usable_size) {
187 		if (bo_flags & XE_BO_FLAG_NEEDS_CPU_ACCESS) {
188 			place.fpfn = 0;
189 			place.lpfn = io_size >> PAGE_SHIFT;
190 		} else {
191 			place.flags |= TTM_PL_FLAG_TOPDOWN;
192 		}
193 	}
194 	places[*c] = place;
195 	*c += 1;
196 }
197 
198 static void try_add_vram(struct xe_device *xe, struct xe_bo *bo,
199 			 u32 bo_flags, u32 *c)
200 {
201 	if (bo_flags & XE_BO_FLAG_VRAM0)
202 		add_vram(xe, bo, bo->placements, bo_flags, XE_PL_VRAM0, c);
203 	if (bo_flags & XE_BO_FLAG_VRAM1)
204 		add_vram(xe, bo, bo->placements, bo_flags, XE_PL_VRAM1, c);
205 }
206 
207 static void try_add_stolen(struct xe_device *xe, struct xe_bo *bo,
208 			   u32 bo_flags, u32 *c)
209 {
210 	if (bo_flags & XE_BO_FLAG_STOLEN) {
211 		xe_assert(xe, *c < ARRAY_SIZE(bo->placements));
212 
213 		bo->placements[*c] = (struct ttm_place) {
214 			.mem_type = XE_PL_STOLEN,
215 			.flags = bo_flags & (XE_BO_FLAG_PINNED |
216 					     XE_BO_FLAG_GGTT) ?
217 				TTM_PL_FLAG_CONTIGUOUS : 0,
218 		};
219 		*c += 1;
220 	}
221 }
222 
223 static int __xe_bo_placement_for_flags(struct xe_device *xe, struct xe_bo *bo,
224 				       u32 bo_flags)
225 {
226 	u32 c = 0;
227 
228 	try_add_vram(xe, bo, bo_flags, &c);
229 	try_add_system(xe, bo, bo_flags, &c);
230 	try_add_stolen(xe, bo, bo_flags, &c);
231 
232 	if (!c)
233 		return -EINVAL;
234 
235 	bo->placement = (struct ttm_placement) {
236 		.num_placement = c,
237 		.placement = bo->placements,
238 	};
239 
240 	return 0;
241 }
242 
243 int xe_bo_placement_for_flags(struct xe_device *xe, struct xe_bo *bo,
244 			      u32 bo_flags)
245 {
246 	xe_bo_assert_held(bo);
247 	return __xe_bo_placement_for_flags(xe, bo, bo_flags);
248 }
249 
250 static void xe_evict_flags(struct ttm_buffer_object *tbo,
251 			   struct ttm_placement *placement)
252 {
253 	if (!xe_bo_is_xe_bo(tbo)) {
254 		/* Don't handle scatter gather BOs */
255 		if (tbo->type == ttm_bo_type_sg) {
256 			placement->num_placement = 0;
257 			return;
258 		}
259 
260 		*placement = sys_placement;
261 		return;
262 	}
263 
264 	/*
265 	 * For xe, sg bos that are evicted to system just triggers a
266 	 * rebind of the sg list upon subsequent validation to XE_PL_TT.
267 	 */
268 	switch (tbo->resource->mem_type) {
269 	case XE_PL_VRAM0:
270 	case XE_PL_VRAM1:
271 	case XE_PL_STOLEN:
272 		*placement = tt_placement;
273 		break;
274 	case XE_PL_TT:
275 	default:
276 		*placement = sys_placement;
277 		break;
278 	}
279 }
280 
281 struct xe_ttm_tt {
282 	struct ttm_tt ttm;
283 	struct device *dev;
284 	struct sg_table sgt;
285 	struct sg_table *sg;
286 };
287 
288 static int xe_tt_map_sg(struct ttm_tt *tt)
289 {
290 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
291 	unsigned long num_pages = tt->num_pages;
292 	int ret;
293 
294 	XE_WARN_ON(tt->page_flags & TTM_TT_FLAG_EXTERNAL);
295 
296 	if (xe_tt->sg)
297 		return 0;
298 
299 	ret = sg_alloc_table_from_pages_segment(&xe_tt->sgt, tt->pages,
300 						num_pages, 0,
301 						(u64)num_pages << PAGE_SHIFT,
302 						xe_sg_segment_size(xe_tt->dev),
303 						GFP_KERNEL);
304 	if (ret)
305 		return ret;
306 
307 	xe_tt->sg = &xe_tt->sgt;
308 	ret = dma_map_sgtable(xe_tt->dev, xe_tt->sg, DMA_BIDIRECTIONAL,
309 			      DMA_ATTR_SKIP_CPU_SYNC);
310 	if (ret) {
311 		sg_free_table(xe_tt->sg);
312 		xe_tt->sg = NULL;
313 		return ret;
314 	}
315 
316 	return 0;
317 }
318 
319 static void xe_tt_unmap_sg(struct ttm_tt *tt)
320 {
321 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
322 
323 	if (xe_tt->sg) {
324 		dma_unmap_sgtable(xe_tt->dev, xe_tt->sg,
325 				  DMA_BIDIRECTIONAL, 0);
326 		sg_free_table(xe_tt->sg);
327 		xe_tt->sg = NULL;
328 	}
329 }
330 
331 struct sg_table *xe_bo_sg(struct xe_bo *bo)
332 {
333 	struct ttm_tt *tt = bo->ttm.ttm;
334 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
335 
336 	return xe_tt->sg;
337 }
338 
339 static struct ttm_tt *xe_ttm_tt_create(struct ttm_buffer_object *ttm_bo,
340 				       u32 page_flags)
341 {
342 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
343 	struct xe_device *xe = xe_bo_device(bo);
344 	struct xe_ttm_tt *tt;
345 	unsigned long extra_pages;
346 	enum ttm_caching caching = ttm_cached;
347 	int err;
348 
349 	tt = kzalloc(sizeof(*tt), GFP_KERNEL);
350 	if (!tt)
351 		return NULL;
352 
353 	tt->dev = xe->drm.dev;
354 
355 	extra_pages = 0;
356 	if (xe_bo_needs_ccs_pages(bo))
357 		extra_pages = DIV_ROUND_UP(xe_device_ccs_bytes(xe, bo->size),
358 					   PAGE_SIZE);
359 
360 	/*
361 	 * DGFX system memory is always WB / ttm_cached, since
362 	 * other caching modes are only supported on x86. DGFX
363 	 * GPU system memory accesses are always coherent with the
364 	 * CPU.
365 	 */
366 	if (!IS_DGFX(xe)) {
367 		switch (bo->cpu_caching) {
368 		case DRM_XE_GEM_CPU_CACHING_WC:
369 			caching = ttm_write_combined;
370 			break;
371 		default:
372 			caching = ttm_cached;
373 			break;
374 		}
375 
376 		WARN_ON((bo->flags & XE_BO_FLAG_USER) && !bo->cpu_caching);
377 
378 		/*
379 		 * Display scanout is always non-coherent with the CPU cache.
380 		 *
381 		 * For Xe_LPG and beyond, PPGTT PTE lookups are also
382 		 * non-coherent and require a CPU:WC mapping.
383 		 */
384 		if ((!bo->cpu_caching && bo->flags & XE_BO_FLAG_SCANOUT) ||
385 		    (xe->info.graphics_verx100 >= 1270 &&
386 		     bo->flags & XE_BO_FLAG_PAGETABLE))
387 			caching = ttm_write_combined;
388 	}
389 
390 	if (bo->flags & XE_BO_FLAG_NEEDS_UC) {
391 		/*
392 		 * Valid only for internally-created buffers only, for
393 		 * which cpu_caching is never initialized.
394 		 */
395 		xe_assert(xe, bo->cpu_caching == 0);
396 		caching = ttm_uncached;
397 	}
398 
399 	err = ttm_tt_init(&tt->ttm, &bo->ttm, page_flags, caching, extra_pages);
400 	if (err) {
401 		kfree(tt);
402 		return NULL;
403 	}
404 
405 	return &tt->ttm;
406 }
407 
408 static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
409 			      struct ttm_operation_ctx *ctx)
410 {
411 	int err;
412 
413 	/*
414 	 * dma-bufs are not populated with pages, and the dma-
415 	 * addresses are set up when moved to XE_PL_TT.
416 	 */
417 	if (tt->page_flags & TTM_TT_FLAG_EXTERNAL)
418 		return 0;
419 
420 	err = ttm_pool_alloc(&ttm_dev->pool, tt, ctx);
421 	if (err)
422 		return err;
423 
424 	return err;
425 }
426 
427 static void xe_ttm_tt_unpopulate(struct ttm_device *ttm_dev, struct ttm_tt *tt)
428 {
429 	if (tt->page_flags & TTM_TT_FLAG_EXTERNAL)
430 		return;
431 
432 	xe_tt_unmap_sg(tt);
433 
434 	return ttm_pool_free(&ttm_dev->pool, tt);
435 }
436 
437 static void xe_ttm_tt_destroy(struct ttm_device *ttm_dev, struct ttm_tt *tt)
438 {
439 	ttm_tt_fini(tt);
440 	kfree(tt);
441 }
442 
443 static int xe_ttm_io_mem_reserve(struct ttm_device *bdev,
444 				 struct ttm_resource *mem)
445 {
446 	struct xe_device *xe = ttm_to_xe_device(bdev);
447 
448 	switch (mem->mem_type) {
449 	case XE_PL_SYSTEM:
450 	case XE_PL_TT:
451 		return 0;
452 	case XE_PL_VRAM0:
453 	case XE_PL_VRAM1: {
454 		struct xe_ttm_vram_mgr_resource *vres =
455 			to_xe_ttm_vram_mgr_resource(mem);
456 		struct xe_mem_region *vram = res_to_mem_region(mem);
457 
458 		if (vres->used_visible_size < mem->size)
459 			return -EINVAL;
460 
461 		mem->bus.offset = mem->start << PAGE_SHIFT;
462 
463 		if (vram->mapping &&
464 		    mem->placement & TTM_PL_FLAG_CONTIGUOUS)
465 			mem->bus.addr = (u8 __force *)vram->mapping +
466 				mem->bus.offset;
467 
468 		mem->bus.offset += vram->io_start;
469 		mem->bus.is_iomem = true;
470 
471 #if  !defined(CONFIG_X86)
472 		mem->bus.caching = ttm_write_combined;
473 #endif
474 		return 0;
475 	} case XE_PL_STOLEN:
476 		return xe_ttm_stolen_io_mem_reserve(xe, mem);
477 	default:
478 		return -EINVAL;
479 	}
480 }
481 
482 static int xe_bo_trigger_rebind(struct xe_device *xe, struct xe_bo *bo,
483 				const struct ttm_operation_ctx *ctx)
484 {
485 	struct dma_resv_iter cursor;
486 	struct dma_fence *fence;
487 	struct drm_gem_object *obj = &bo->ttm.base;
488 	struct drm_gpuvm_bo *vm_bo;
489 	bool idle = false;
490 	int ret = 0;
491 
492 	dma_resv_assert_held(bo->ttm.base.resv);
493 
494 	if (!list_empty(&bo->ttm.base.gpuva.list)) {
495 		dma_resv_iter_begin(&cursor, bo->ttm.base.resv,
496 				    DMA_RESV_USAGE_BOOKKEEP);
497 		dma_resv_for_each_fence_unlocked(&cursor, fence)
498 			dma_fence_enable_sw_signaling(fence);
499 		dma_resv_iter_end(&cursor);
500 	}
501 
502 	drm_gem_for_each_gpuvm_bo(vm_bo, obj) {
503 		struct xe_vm *vm = gpuvm_to_vm(vm_bo->vm);
504 		struct drm_gpuva *gpuva;
505 
506 		if (!xe_vm_in_fault_mode(vm)) {
507 			drm_gpuvm_bo_evict(vm_bo, true);
508 			continue;
509 		}
510 
511 		if (!idle) {
512 			long timeout;
513 
514 			if (ctx->no_wait_gpu &&
515 			    !dma_resv_test_signaled(bo->ttm.base.resv,
516 						    DMA_RESV_USAGE_BOOKKEEP))
517 				return -EBUSY;
518 
519 			timeout = dma_resv_wait_timeout(bo->ttm.base.resv,
520 							DMA_RESV_USAGE_BOOKKEEP,
521 							ctx->interruptible,
522 							MAX_SCHEDULE_TIMEOUT);
523 			if (!timeout)
524 				return -ETIME;
525 			if (timeout < 0)
526 				return timeout;
527 
528 			idle = true;
529 		}
530 
531 		drm_gpuvm_bo_for_each_va(gpuva, vm_bo) {
532 			struct xe_vma *vma = gpuva_to_vma(gpuva);
533 
534 			trace_xe_vma_evict(vma);
535 			ret = xe_vm_invalidate_vma(vma);
536 			if (XE_WARN_ON(ret))
537 				return ret;
538 		}
539 	}
540 
541 	return ret;
542 }
543 
544 /*
545  * The dma-buf map_attachment() / unmap_attachment() is hooked up here.
546  * Note that unmapping the attachment is deferred to the next
547  * map_attachment time, or to bo destroy (after idling) whichever comes first.
548  * This is to avoid syncing before unmap_attachment(), assuming that the
549  * caller relies on idling the reservation object before moving the
550  * backing store out. Should that assumption not hold, then we will be able
551  * to unconditionally call unmap_attachment() when moving out to system.
552  */
553 static int xe_bo_move_dmabuf(struct ttm_buffer_object *ttm_bo,
554 			     struct ttm_resource *new_res)
555 {
556 	struct dma_buf_attachment *attach = ttm_bo->base.import_attach;
557 	struct xe_ttm_tt *xe_tt = container_of(ttm_bo->ttm, struct xe_ttm_tt,
558 					       ttm);
559 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
560 	struct sg_table *sg;
561 
562 	xe_assert(xe, attach);
563 	xe_assert(xe, ttm_bo->ttm);
564 
565 	if (new_res->mem_type == XE_PL_SYSTEM)
566 		goto out;
567 
568 	if (ttm_bo->sg) {
569 		dma_buf_unmap_attachment(attach, ttm_bo->sg, DMA_BIDIRECTIONAL);
570 		ttm_bo->sg = NULL;
571 	}
572 
573 	sg = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
574 	if (IS_ERR(sg))
575 		return PTR_ERR(sg);
576 
577 	ttm_bo->sg = sg;
578 	xe_tt->sg = sg;
579 
580 out:
581 	ttm_bo_move_null(ttm_bo, new_res);
582 
583 	return 0;
584 }
585 
586 /**
587  * xe_bo_move_notify - Notify subsystems of a pending move
588  * @bo: The buffer object
589  * @ctx: The struct ttm_operation_ctx controlling locking and waits.
590  *
591  * This function notifies subsystems of an upcoming buffer move.
592  * Upon receiving such a notification, subsystems should schedule
593  * halting access to the underlying pages and optionally add a fence
594  * to the buffer object's dma_resv object, that signals when access is
595  * stopped. The caller will wait on all dma_resv fences before
596  * starting the move.
597  *
598  * A subsystem may commence access to the object after obtaining
599  * bindings to the new backing memory under the object lock.
600  *
601  * Return: 0 on success, -EINTR or -ERESTARTSYS if interrupted in fault mode,
602  * negative error code on error.
603  */
604 static int xe_bo_move_notify(struct xe_bo *bo,
605 			     const struct ttm_operation_ctx *ctx)
606 {
607 	struct ttm_buffer_object *ttm_bo = &bo->ttm;
608 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
609 	struct ttm_resource *old_mem = ttm_bo->resource;
610 	u32 old_mem_type = old_mem ? old_mem->mem_type : XE_PL_SYSTEM;
611 	int ret;
612 
613 	/*
614 	 * If this starts to call into many components, consider
615 	 * using a notification chain here.
616 	 */
617 
618 	if (xe_bo_is_pinned(bo))
619 		return -EINVAL;
620 
621 	xe_bo_vunmap(bo);
622 	ret = xe_bo_trigger_rebind(xe, bo, ctx);
623 	if (ret)
624 		return ret;
625 
626 	/* Don't call move_notify() for imported dma-bufs. */
627 	if (ttm_bo->base.dma_buf && !ttm_bo->base.import_attach)
628 		dma_buf_move_notify(ttm_bo->base.dma_buf);
629 
630 	/*
631 	 * TTM has already nuked the mmap for us (see ttm_bo_unmap_virtual),
632 	 * so if we moved from VRAM make sure to unlink this from the userfault
633 	 * tracking.
634 	 */
635 	if (mem_type_is_vram(old_mem_type)) {
636 		mutex_lock(&xe->mem_access.vram_userfault.lock);
637 		if (!list_empty(&bo->vram_userfault_link))
638 			list_del_init(&bo->vram_userfault_link);
639 		mutex_unlock(&xe->mem_access.vram_userfault.lock);
640 	}
641 
642 	return 0;
643 }
644 
645 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
646 		      struct ttm_operation_ctx *ctx,
647 		      struct ttm_resource *new_mem,
648 		      struct ttm_place *hop)
649 {
650 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
651 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
652 	struct ttm_resource *old_mem = ttm_bo->resource;
653 	u32 old_mem_type = old_mem ? old_mem->mem_type : XE_PL_SYSTEM;
654 	struct ttm_tt *ttm = ttm_bo->ttm;
655 	struct xe_migrate *migrate = NULL;
656 	struct dma_fence *fence;
657 	bool move_lacks_source;
658 	bool tt_has_data;
659 	bool needs_clear;
660 	bool handle_system_ccs = (!IS_DGFX(xe) && xe_bo_needs_ccs_pages(bo) &&
661 				  ttm && ttm_tt_is_populated(ttm)) ? true : false;
662 	int ret = 0;
663 
664 	/* Bo creation path, moving to system or TT. */
665 	if ((!old_mem && ttm) && !handle_system_ccs) {
666 		if (new_mem->mem_type == XE_PL_TT)
667 			ret = xe_tt_map_sg(ttm);
668 		if (!ret)
669 			ttm_bo_move_null(ttm_bo, new_mem);
670 		goto out;
671 	}
672 
673 	if (ttm_bo->type == ttm_bo_type_sg) {
674 		ret = xe_bo_move_notify(bo, ctx);
675 		if (!ret)
676 			ret = xe_bo_move_dmabuf(ttm_bo, new_mem);
677 		return ret;
678 	}
679 
680 	tt_has_data = ttm && (ttm_tt_is_populated(ttm) ||
681 			      (ttm->page_flags & TTM_TT_FLAG_SWAPPED));
682 
683 	move_lacks_source = handle_system_ccs ? (!bo->ccs_cleared)  :
684 						(!mem_type_is_vram(old_mem_type) && !tt_has_data);
685 
686 	needs_clear = (ttm && ttm->page_flags & TTM_TT_FLAG_ZERO_ALLOC) ||
687 		(!ttm && ttm_bo->type == ttm_bo_type_device);
688 
689 	if (new_mem->mem_type == XE_PL_TT) {
690 		ret = xe_tt_map_sg(ttm);
691 		if (ret)
692 			goto out;
693 	}
694 
695 	if ((move_lacks_source && !needs_clear)) {
696 		ttm_bo_move_null(ttm_bo, new_mem);
697 		goto out;
698 	}
699 
700 	if (old_mem_type == XE_PL_SYSTEM && new_mem->mem_type == XE_PL_TT && !handle_system_ccs) {
701 		ttm_bo_move_null(ttm_bo, new_mem);
702 		goto out;
703 	}
704 
705 	/*
706 	 * Failed multi-hop where the old_mem is still marked as
707 	 * TTM_PL_FLAG_TEMPORARY, should just be a dummy move.
708 	 */
709 	if (old_mem_type == XE_PL_TT &&
710 	    new_mem->mem_type == XE_PL_TT) {
711 		ttm_bo_move_null(ttm_bo, new_mem);
712 		goto out;
713 	}
714 
715 	if (!move_lacks_source && !xe_bo_is_pinned(bo)) {
716 		ret = xe_bo_move_notify(bo, ctx);
717 		if (ret)
718 			goto out;
719 	}
720 
721 	if (old_mem_type == XE_PL_TT &&
722 	    new_mem->mem_type == XE_PL_SYSTEM) {
723 		long timeout = dma_resv_wait_timeout(ttm_bo->base.resv,
724 						     DMA_RESV_USAGE_BOOKKEEP,
725 						     true,
726 						     MAX_SCHEDULE_TIMEOUT);
727 		if (timeout < 0) {
728 			ret = timeout;
729 			goto out;
730 		}
731 
732 		if (!handle_system_ccs) {
733 			ttm_bo_move_null(ttm_bo, new_mem);
734 			goto out;
735 		}
736 	}
737 
738 	if (!move_lacks_source &&
739 	    ((old_mem_type == XE_PL_SYSTEM && resource_is_vram(new_mem)) ||
740 	     (mem_type_is_vram(old_mem_type) &&
741 	      new_mem->mem_type == XE_PL_SYSTEM))) {
742 		hop->fpfn = 0;
743 		hop->lpfn = 0;
744 		hop->mem_type = XE_PL_TT;
745 		hop->flags = TTM_PL_FLAG_TEMPORARY;
746 		ret = -EMULTIHOP;
747 		goto out;
748 	}
749 
750 	if (bo->tile)
751 		migrate = bo->tile->migrate;
752 	else if (resource_is_vram(new_mem))
753 		migrate = mem_type_to_migrate(xe, new_mem->mem_type);
754 	else if (mem_type_is_vram(old_mem_type))
755 		migrate = mem_type_to_migrate(xe, old_mem_type);
756 	else
757 		migrate = xe->tiles[0].migrate;
758 
759 	xe_assert(xe, migrate);
760 	trace_xe_bo_move(bo, new_mem->mem_type, old_mem_type, move_lacks_source);
761 	xe_pm_runtime_get_noresume(xe);
762 
763 	if (xe_bo_is_pinned(bo) && !xe_bo_is_user(bo)) {
764 		/*
765 		 * Kernel memory that is pinned should only be moved on suspend
766 		 * / resume, some of the pinned memory is required for the
767 		 * device to resume / use the GPU to move other evicted memory
768 		 * (user memory) around. This likely could be optimized a bit
769 		 * futher where we find the minimum set of pinned memory
770 		 * required for resume but for simplity doing a memcpy for all
771 		 * pinned memory.
772 		 */
773 		ret = xe_bo_vmap(bo);
774 		if (!ret) {
775 			ret = ttm_bo_move_memcpy(ttm_bo, ctx, new_mem);
776 
777 			/* Create a new VMAP once kernel BO back in VRAM */
778 			if (!ret && resource_is_vram(new_mem)) {
779 				struct xe_mem_region *vram = res_to_mem_region(new_mem);
780 				void __iomem *new_addr = vram->mapping +
781 					(new_mem->start << PAGE_SHIFT);
782 
783 				if (XE_WARN_ON(new_mem->start == XE_BO_INVALID_OFFSET)) {
784 					ret = -EINVAL;
785 					xe_pm_runtime_put(xe);
786 					goto out;
787 				}
788 
789 				xe_assert(xe, new_mem->start ==
790 					  bo->placements->fpfn);
791 
792 				iosys_map_set_vaddr_iomem(&bo->vmap, new_addr);
793 			}
794 		}
795 	} else {
796 		if (move_lacks_source)
797 			fence = xe_migrate_clear(migrate, bo, new_mem);
798 		else
799 			fence = xe_migrate_copy(migrate, bo, bo, old_mem,
800 						new_mem, handle_system_ccs);
801 		if (IS_ERR(fence)) {
802 			ret = PTR_ERR(fence);
803 			xe_pm_runtime_put(xe);
804 			goto out;
805 		}
806 		if (!move_lacks_source) {
807 			ret = ttm_bo_move_accel_cleanup(ttm_bo, fence, evict,
808 							true, new_mem);
809 			if (ret) {
810 				dma_fence_wait(fence, false);
811 				ttm_bo_move_null(ttm_bo, new_mem);
812 				ret = 0;
813 			}
814 		} else {
815 			/*
816 			 * ttm_bo_move_accel_cleanup() may blow up if
817 			 * bo->resource == NULL, so just attach the
818 			 * fence and set the new resource.
819 			 */
820 			dma_resv_add_fence(ttm_bo->base.resv, fence,
821 					   DMA_RESV_USAGE_KERNEL);
822 			ttm_bo_move_null(ttm_bo, new_mem);
823 		}
824 
825 		dma_fence_put(fence);
826 	}
827 
828 	xe_pm_runtime_put(xe);
829 
830 out:
831 	if ((!ttm_bo->resource || ttm_bo->resource->mem_type == XE_PL_SYSTEM) &&
832 	    ttm_bo->ttm)
833 		xe_tt_unmap_sg(ttm_bo->ttm);
834 
835 	return ret;
836 }
837 
838 /**
839  * xe_bo_evict_pinned() - Evict a pinned VRAM object to system memory
840  * @bo: The buffer object to move.
841  *
842  * On successful completion, the object memory will be moved to sytem memory.
843  *
844  * This is needed to for special handling of pinned VRAM object during
845  * suspend-resume.
846  *
847  * Return: 0 on success. Negative error code on failure.
848  */
849 int xe_bo_evict_pinned(struct xe_bo *bo)
850 {
851 	struct ttm_place place = {
852 		.mem_type = XE_PL_TT,
853 	};
854 	struct ttm_placement placement = {
855 		.placement = &place,
856 		.num_placement = 1,
857 	};
858 	struct ttm_operation_ctx ctx = {
859 		.interruptible = false,
860 	};
861 	struct ttm_resource *new_mem;
862 	int ret;
863 
864 	xe_bo_assert_held(bo);
865 
866 	if (WARN_ON(!bo->ttm.resource))
867 		return -EINVAL;
868 
869 	if (WARN_ON(!xe_bo_is_pinned(bo)))
870 		return -EINVAL;
871 
872 	if (WARN_ON(!xe_bo_is_vram(bo)))
873 		return -EINVAL;
874 
875 	ret = ttm_bo_mem_space(&bo->ttm, &placement, &new_mem, &ctx);
876 	if (ret)
877 		return ret;
878 
879 	if (!bo->ttm.ttm) {
880 		bo->ttm.ttm = xe_ttm_tt_create(&bo->ttm, 0);
881 		if (!bo->ttm.ttm) {
882 			ret = -ENOMEM;
883 			goto err_res_free;
884 		}
885 	}
886 
887 	ret = ttm_tt_populate(bo->ttm.bdev, bo->ttm.ttm, &ctx);
888 	if (ret)
889 		goto err_res_free;
890 
891 	ret = dma_resv_reserve_fences(bo->ttm.base.resv, 1);
892 	if (ret)
893 		goto err_res_free;
894 
895 	ret = xe_bo_move(&bo->ttm, false, &ctx, new_mem, NULL);
896 	if (ret)
897 		goto err_res_free;
898 
899 	return 0;
900 
901 err_res_free:
902 	ttm_resource_free(&bo->ttm, &new_mem);
903 	return ret;
904 }
905 
906 /**
907  * xe_bo_restore_pinned() - Restore a pinned VRAM object
908  * @bo: The buffer object to move.
909  *
910  * On successful completion, the object memory will be moved back to VRAM.
911  *
912  * This is needed to for special handling of pinned VRAM object during
913  * suspend-resume.
914  *
915  * Return: 0 on success. Negative error code on failure.
916  */
917 int xe_bo_restore_pinned(struct xe_bo *bo)
918 {
919 	struct ttm_operation_ctx ctx = {
920 		.interruptible = false,
921 	};
922 	struct ttm_resource *new_mem;
923 	int ret;
924 
925 	xe_bo_assert_held(bo);
926 
927 	if (WARN_ON(!bo->ttm.resource))
928 		return -EINVAL;
929 
930 	if (WARN_ON(!xe_bo_is_pinned(bo)))
931 		return -EINVAL;
932 
933 	if (WARN_ON(xe_bo_is_vram(bo) || !bo->ttm.ttm))
934 		return -EINVAL;
935 
936 	ret = ttm_bo_mem_space(&bo->ttm, &bo->placement, &new_mem, &ctx);
937 	if (ret)
938 		return ret;
939 
940 	ret = ttm_tt_populate(bo->ttm.bdev, bo->ttm.ttm, &ctx);
941 	if (ret)
942 		goto err_res_free;
943 
944 	ret = dma_resv_reserve_fences(bo->ttm.base.resv, 1);
945 	if (ret)
946 		goto err_res_free;
947 
948 	ret = xe_bo_move(&bo->ttm, false, &ctx, new_mem, NULL);
949 	if (ret)
950 		goto err_res_free;
951 
952 	return 0;
953 
954 err_res_free:
955 	ttm_resource_free(&bo->ttm, &new_mem);
956 	return ret;
957 }
958 
959 static unsigned long xe_ttm_io_mem_pfn(struct ttm_buffer_object *ttm_bo,
960 				       unsigned long page_offset)
961 {
962 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
963 	struct xe_res_cursor cursor;
964 	struct xe_mem_region *vram;
965 
966 	if (ttm_bo->resource->mem_type == XE_PL_STOLEN)
967 		return xe_ttm_stolen_io_offset(bo, page_offset << PAGE_SHIFT) >> PAGE_SHIFT;
968 
969 	vram = res_to_mem_region(ttm_bo->resource);
970 	xe_res_first(ttm_bo->resource, (u64)page_offset << PAGE_SHIFT, 0, &cursor);
971 	return (vram->io_start + cursor.start) >> PAGE_SHIFT;
972 }
973 
974 static void __xe_bo_vunmap(struct xe_bo *bo);
975 
976 /*
977  * TODO: Move this function to TTM so we don't rely on how TTM does its
978  * locking, thereby abusing TTM internals.
979  */
980 static bool xe_ttm_bo_lock_in_destructor(struct ttm_buffer_object *ttm_bo)
981 {
982 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
983 	bool locked;
984 
985 	xe_assert(xe, !kref_read(&ttm_bo->kref));
986 
987 	/*
988 	 * We can typically only race with TTM trylocking under the
989 	 * lru_lock, which will immediately be unlocked again since
990 	 * the ttm_bo refcount is zero at this point. So trylocking *should*
991 	 * always succeed here, as long as we hold the lru lock.
992 	 */
993 	spin_lock(&ttm_bo->bdev->lru_lock);
994 	locked = dma_resv_trylock(ttm_bo->base.resv);
995 	spin_unlock(&ttm_bo->bdev->lru_lock);
996 	xe_assert(xe, locked);
997 
998 	return locked;
999 }
1000 
1001 static void xe_ttm_bo_release_notify(struct ttm_buffer_object *ttm_bo)
1002 {
1003 	struct dma_resv_iter cursor;
1004 	struct dma_fence *fence;
1005 	struct dma_fence *replacement = NULL;
1006 	struct xe_bo *bo;
1007 
1008 	if (!xe_bo_is_xe_bo(ttm_bo))
1009 		return;
1010 
1011 	bo = ttm_to_xe_bo(ttm_bo);
1012 	xe_assert(xe_bo_device(bo), !(bo->created && kref_read(&ttm_bo->base.refcount)));
1013 
1014 	/*
1015 	 * Corner case where TTM fails to allocate memory and this BOs resv
1016 	 * still points the VMs resv
1017 	 */
1018 	if (ttm_bo->base.resv != &ttm_bo->base._resv)
1019 		return;
1020 
1021 	if (!xe_ttm_bo_lock_in_destructor(ttm_bo))
1022 		return;
1023 
1024 	/*
1025 	 * Scrub the preempt fences if any. The unbind fence is already
1026 	 * attached to the resv.
1027 	 * TODO: Don't do this for external bos once we scrub them after
1028 	 * unbind.
1029 	 */
1030 	dma_resv_for_each_fence(&cursor, ttm_bo->base.resv,
1031 				DMA_RESV_USAGE_BOOKKEEP, fence) {
1032 		if (xe_fence_is_xe_preempt(fence) &&
1033 		    !dma_fence_is_signaled(fence)) {
1034 			if (!replacement)
1035 				replacement = dma_fence_get_stub();
1036 
1037 			dma_resv_replace_fences(ttm_bo->base.resv,
1038 						fence->context,
1039 						replacement,
1040 						DMA_RESV_USAGE_BOOKKEEP);
1041 		}
1042 	}
1043 	dma_fence_put(replacement);
1044 
1045 	dma_resv_unlock(ttm_bo->base.resv);
1046 }
1047 
1048 static void xe_ttm_bo_delete_mem_notify(struct ttm_buffer_object *ttm_bo)
1049 {
1050 	if (!xe_bo_is_xe_bo(ttm_bo))
1051 		return;
1052 
1053 	/*
1054 	 * Object is idle and about to be destroyed. Release the
1055 	 * dma-buf attachment.
1056 	 */
1057 	if (ttm_bo->type == ttm_bo_type_sg && ttm_bo->sg) {
1058 		struct xe_ttm_tt *xe_tt = container_of(ttm_bo->ttm,
1059 						       struct xe_ttm_tt, ttm);
1060 
1061 		dma_buf_unmap_attachment(ttm_bo->base.import_attach, ttm_bo->sg,
1062 					 DMA_BIDIRECTIONAL);
1063 		ttm_bo->sg = NULL;
1064 		xe_tt->sg = NULL;
1065 	}
1066 }
1067 
1068 const struct ttm_device_funcs xe_ttm_funcs = {
1069 	.ttm_tt_create = xe_ttm_tt_create,
1070 	.ttm_tt_populate = xe_ttm_tt_populate,
1071 	.ttm_tt_unpopulate = xe_ttm_tt_unpopulate,
1072 	.ttm_tt_destroy = xe_ttm_tt_destroy,
1073 	.evict_flags = xe_evict_flags,
1074 	.move = xe_bo_move,
1075 	.io_mem_reserve = xe_ttm_io_mem_reserve,
1076 	.io_mem_pfn = xe_ttm_io_mem_pfn,
1077 	.release_notify = xe_ttm_bo_release_notify,
1078 	.eviction_valuable = ttm_bo_eviction_valuable,
1079 	.delete_mem_notify = xe_ttm_bo_delete_mem_notify,
1080 };
1081 
1082 static void xe_ttm_bo_destroy(struct ttm_buffer_object *ttm_bo)
1083 {
1084 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
1085 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
1086 
1087 	if (bo->ttm.base.import_attach)
1088 		drm_prime_gem_destroy(&bo->ttm.base, NULL);
1089 	drm_gem_object_release(&bo->ttm.base);
1090 
1091 	xe_assert(xe, list_empty(&ttm_bo->base.gpuva.list));
1092 
1093 	if (bo->ggtt_node.size)
1094 		xe_ggtt_remove_bo(bo->tile->mem.ggtt, bo);
1095 
1096 #ifdef CONFIG_PROC_FS
1097 	if (bo->client)
1098 		xe_drm_client_remove_bo(bo);
1099 #endif
1100 
1101 	if (bo->vm && xe_bo_is_user(bo))
1102 		xe_vm_put(bo->vm);
1103 
1104 	mutex_lock(&xe->mem_access.vram_userfault.lock);
1105 	if (!list_empty(&bo->vram_userfault_link))
1106 		list_del(&bo->vram_userfault_link);
1107 	mutex_unlock(&xe->mem_access.vram_userfault.lock);
1108 
1109 	kfree(bo);
1110 }
1111 
1112 static void xe_gem_object_free(struct drm_gem_object *obj)
1113 {
1114 	/* Our BO reference counting scheme works as follows:
1115 	 *
1116 	 * The gem object kref is typically used throughout the driver,
1117 	 * and the gem object holds a ttm_buffer_object refcount, so
1118 	 * that when the last gem object reference is put, which is when
1119 	 * we end up in this function, we put also that ttm_buffer_object
1120 	 * refcount. Anything using gem interfaces is then no longer
1121 	 * allowed to access the object in a way that requires a gem
1122 	 * refcount, including locking the object.
1123 	 *
1124 	 * driver ttm callbacks is allowed to use the ttm_buffer_object
1125 	 * refcount directly if needed.
1126 	 */
1127 	__xe_bo_vunmap(gem_to_xe_bo(obj));
1128 	ttm_bo_put(container_of(obj, struct ttm_buffer_object, base));
1129 }
1130 
1131 static void xe_gem_object_close(struct drm_gem_object *obj,
1132 				struct drm_file *file_priv)
1133 {
1134 	struct xe_bo *bo = gem_to_xe_bo(obj);
1135 
1136 	if (bo->vm && !xe_vm_in_fault_mode(bo->vm)) {
1137 		xe_assert(xe_bo_device(bo), xe_bo_is_user(bo));
1138 
1139 		xe_bo_lock(bo, false);
1140 		ttm_bo_set_bulk_move(&bo->ttm, NULL);
1141 		xe_bo_unlock(bo);
1142 	}
1143 }
1144 
1145 static vm_fault_t xe_gem_fault(struct vm_fault *vmf)
1146 {
1147 	struct ttm_buffer_object *tbo = vmf->vma->vm_private_data;
1148 	struct drm_device *ddev = tbo->base.dev;
1149 	struct xe_device *xe = to_xe_device(ddev);
1150 	struct xe_bo *bo = ttm_to_xe_bo(tbo);
1151 	bool needs_rpm = bo->flags & XE_BO_FLAG_VRAM_MASK;
1152 	vm_fault_t ret;
1153 	int idx;
1154 
1155 	if (needs_rpm)
1156 		xe_pm_runtime_get(xe);
1157 
1158 	ret = ttm_bo_vm_reserve(tbo, vmf);
1159 	if (ret)
1160 		goto out;
1161 
1162 	if (drm_dev_enter(ddev, &idx)) {
1163 		trace_xe_bo_cpu_fault(bo);
1164 
1165 		ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
1166 					       TTM_BO_VM_NUM_PREFAULT);
1167 		drm_dev_exit(idx);
1168 	} else {
1169 		ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
1170 	}
1171 
1172 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
1173 		goto out;
1174 	/*
1175 	 * ttm_bo_vm_reserve() already has dma_resv_lock.
1176 	 */
1177 	if (ret == VM_FAULT_NOPAGE && mem_type_is_vram(tbo->resource->mem_type)) {
1178 		mutex_lock(&xe->mem_access.vram_userfault.lock);
1179 		if (list_empty(&bo->vram_userfault_link))
1180 			list_add(&bo->vram_userfault_link, &xe->mem_access.vram_userfault.list);
1181 		mutex_unlock(&xe->mem_access.vram_userfault.lock);
1182 	}
1183 
1184 	dma_resv_unlock(tbo->base.resv);
1185 out:
1186 	if (needs_rpm)
1187 		xe_pm_runtime_put(xe);
1188 
1189 	return ret;
1190 }
1191 
1192 static const struct vm_operations_struct xe_gem_vm_ops = {
1193 	.fault = xe_gem_fault,
1194 	.open = ttm_bo_vm_open,
1195 	.close = ttm_bo_vm_close,
1196 	.access = ttm_bo_vm_access
1197 };
1198 
1199 static const struct drm_gem_object_funcs xe_gem_object_funcs = {
1200 	.free = xe_gem_object_free,
1201 	.close = xe_gem_object_close,
1202 	.mmap = drm_gem_ttm_mmap,
1203 	.export = xe_gem_prime_export,
1204 	.vm_ops = &xe_gem_vm_ops,
1205 };
1206 
1207 /**
1208  * xe_bo_alloc - Allocate storage for a struct xe_bo
1209  *
1210  * This funcition is intended to allocate storage to be used for input
1211  * to __xe_bo_create_locked(), in the case a pointer to the bo to be
1212  * created is needed before the call to __xe_bo_create_locked().
1213  * If __xe_bo_create_locked ends up never to be called, then the
1214  * storage allocated with this function needs to be freed using
1215  * xe_bo_free().
1216  *
1217  * Return: A pointer to an uninitialized struct xe_bo on success,
1218  * ERR_PTR(-ENOMEM) on error.
1219  */
1220 struct xe_bo *xe_bo_alloc(void)
1221 {
1222 	struct xe_bo *bo = kzalloc(sizeof(*bo), GFP_KERNEL);
1223 
1224 	if (!bo)
1225 		return ERR_PTR(-ENOMEM);
1226 
1227 	return bo;
1228 }
1229 
1230 /**
1231  * xe_bo_free - Free storage allocated using xe_bo_alloc()
1232  * @bo: The buffer object storage.
1233  *
1234  * Refer to xe_bo_alloc() documentation for valid use-cases.
1235  */
1236 void xe_bo_free(struct xe_bo *bo)
1237 {
1238 	kfree(bo);
1239 }
1240 
1241 struct xe_bo *___xe_bo_create_locked(struct xe_device *xe, struct xe_bo *bo,
1242 				     struct xe_tile *tile, struct dma_resv *resv,
1243 				     struct ttm_lru_bulk_move *bulk, size_t size,
1244 				     u16 cpu_caching, enum ttm_bo_type type,
1245 				     u32 flags)
1246 {
1247 	struct ttm_operation_ctx ctx = {
1248 		.interruptible = true,
1249 		.no_wait_gpu = false,
1250 	};
1251 	struct ttm_placement *placement;
1252 	uint32_t alignment;
1253 	size_t aligned_size;
1254 	int err;
1255 
1256 	/* Only kernel objects should set GT */
1257 	xe_assert(xe, !tile || type == ttm_bo_type_kernel);
1258 
1259 	if (XE_WARN_ON(!size)) {
1260 		xe_bo_free(bo);
1261 		return ERR_PTR(-EINVAL);
1262 	}
1263 
1264 	if (flags & (XE_BO_FLAG_VRAM_MASK | XE_BO_FLAG_STOLEN) &&
1265 	    !(flags & XE_BO_FLAG_IGNORE_MIN_PAGE_SIZE) &&
1266 	    ((xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K) ||
1267 	     (flags & XE_BO_NEEDS_64K))) {
1268 		aligned_size = ALIGN(size, SZ_64K);
1269 		if (type != ttm_bo_type_device)
1270 			size = ALIGN(size, SZ_64K);
1271 		flags |= XE_BO_FLAG_INTERNAL_64K;
1272 		alignment = SZ_64K >> PAGE_SHIFT;
1273 
1274 	} else {
1275 		aligned_size = ALIGN(size, SZ_4K);
1276 		flags &= ~XE_BO_FLAG_INTERNAL_64K;
1277 		alignment = SZ_4K >> PAGE_SHIFT;
1278 	}
1279 
1280 	if (type == ttm_bo_type_device && aligned_size != size)
1281 		return ERR_PTR(-EINVAL);
1282 
1283 	if (!bo) {
1284 		bo = xe_bo_alloc();
1285 		if (IS_ERR(bo))
1286 			return bo;
1287 	}
1288 
1289 	bo->ccs_cleared = false;
1290 	bo->tile = tile;
1291 	bo->size = size;
1292 	bo->flags = flags;
1293 	bo->cpu_caching = cpu_caching;
1294 	bo->ttm.base.funcs = &xe_gem_object_funcs;
1295 	bo->ttm.priority = XE_BO_PRIORITY_NORMAL;
1296 	INIT_LIST_HEAD(&bo->pinned_link);
1297 #ifdef CONFIG_PROC_FS
1298 	INIT_LIST_HEAD(&bo->client_link);
1299 #endif
1300 	INIT_LIST_HEAD(&bo->vram_userfault_link);
1301 
1302 	drm_gem_private_object_init(&xe->drm, &bo->ttm.base, size);
1303 
1304 	if (resv) {
1305 		ctx.allow_res_evict = !(flags & XE_BO_FLAG_NO_RESV_EVICT);
1306 		ctx.resv = resv;
1307 	}
1308 
1309 	if (!(flags & XE_BO_FLAG_FIXED_PLACEMENT)) {
1310 		err = __xe_bo_placement_for_flags(xe, bo, bo->flags);
1311 		if (WARN_ON(err)) {
1312 			xe_ttm_bo_destroy(&bo->ttm);
1313 			return ERR_PTR(err);
1314 		}
1315 	}
1316 
1317 	/* Defer populating type_sg bos */
1318 	placement = (type == ttm_bo_type_sg ||
1319 		     bo->flags & XE_BO_FLAG_DEFER_BACKING) ? &sys_placement :
1320 		&bo->placement;
1321 	err = ttm_bo_init_reserved(&xe->ttm, &bo->ttm, type,
1322 				   placement, alignment,
1323 				   &ctx, NULL, resv, xe_ttm_bo_destroy);
1324 	if (err)
1325 		return ERR_PTR(err);
1326 
1327 	/*
1328 	 * The VRAM pages underneath are potentially still being accessed by the
1329 	 * GPU, as per async GPU clearing and async evictions. However TTM makes
1330 	 * sure to add any corresponding move/clear fences into the objects
1331 	 * dma-resv using the DMA_RESV_USAGE_KERNEL slot.
1332 	 *
1333 	 * For KMD internal buffers we don't care about GPU clearing, however we
1334 	 * still need to handle async evictions, where the VRAM is still being
1335 	 * accessed by the GPU. Most internal callers are not expecting this,
1336 	 * since they are missing the required synchronisation before accessing
1337 	 * the memory. To keep things simple just sync wait any kernel fences
1338 	 * here, if the buffer is designated KMD internal.
1339 	 *
1340 	 * For normal userspace objects we should already have the required
1341 	 * pipelining or sync waiting elsewhere, since we already have to deal
1342 	 * with things like async GPU clearing.
1343 	 */
1344 	if (type == ttm_bo_type_kernel) {
1345 		long timeout = dma_resv_wait_timeout(bo->ttm.base.resv,
1346 						     DMA_RESV_USAGE_KERNEL,
1347 						     ctx.interruptible,
1348 						     MAX_SCHEDULE_TIMEOUT);
1349 
1350 		if (timeout < 0) {
1351 			if (!resv)
1352 				dma_resv_unlock(bo->ttm.base.resv);
1353 			xe_bo_put(bo);
1354 			return ERR_PTR(timeout);
1355 		}
1356 	}
1357 
1358 	bo->created = true;
1359 	if (bulk)
1360 		ttm_bo_set_bulk_move(&bo->ttm, bulk);
1361 	else
1362 		ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
1363 
1364 	return bo;
1365 }
1366 
1367 static int __xe_bo_fixed_placement(struct xe_device *xe,
1368 				   struct xe_bo *bo,
1369 				   u32 flags,
1370 				   u64 start, u64 end, u64 size)
1371 {
1372 	struct ttm_place *place = bo->placements;
1373 
1374 	if (flags & (XE_BO_FLAG_USER | XE_BO_FLAG_SYSTEM))
1375 		return -EINVAL;
1376 
1377 	place->flags = TTM_PL_FLAG_CONTIGUOUS;
1378 	place->fpfn = start >> PAGE_SHIFT;
1379 	place->lpfn = end >> PAGE_SHIFT;
1380 
1381 	switch (flags & (XE_BO_FLAG_STOLEN | XE_BO_FLAG_VRAM_MASK)) {
1382 	case XE_BO_FLAG_VRAM0:
1383 		place->mem_type = XE_PL_VRAM0;
1384 		break;
1385 	case XE_BO_FLAG_VRAM1:
1386 		place->mem_type = XE_PL_VRAM1;
1387 		break;
1388 	case XE_BO_FLAG_STOLEN:
1389 		place->mem_type = XE_PL_STOLEN;
1390 		break;
1391 
1392 	default:
1393 		/* 0 or multiple of the above set */
1394 		return -EINVAL;
1395 	}
1396 
1397 	bo->placement = (struct ttm_placement) {
1398 		.num_placement = 1,
1399 		.placement = place,
1400 	};
1401 
1402 	return 0;
1403 }
1404 
1405 static struct xe_bo *
1406 __xe_bo_create_locked(struct xe_device *xe,
1407 		      struct xe_tile *tile, struct xe_vm *vm,
1408 		      size_t size, u64 start, u64 end,
1409 		      u16 cpu_caching, enum ttm_bo_type type, u32 flags)
1410 {
1411 	struct xe_bo *bo = NULL;
1412 	int err;
1413 
1414 	if (vm)
1415 		xe_vm_assert_held(vm);
1416 
1417 	if (start || end != ~0ULL) {
1418 		bo = xe_bo_alloc();
1419 		if (IS_ERR(bo))
1420 			return bo;
1421 
1422 		flags |= XE_BO_FLAG_FIXED_PLACEMENT;
1423 		err = __xe_bo_fixed_placement(xe, bo, flags, start, end, size);
1424 		if (err) {
1425 			xe_bo_free(bo);
1426 			return ERR_PTR(err);
1427 		}
1428 	}
1429 
1430 	bo = ___xe_bo_create_locked(xe, bo, tile, vm ? xe_vm_resv(vm) : NULL,
1431 				    vm && !xe_vm_in_fault_mode(vm) &&
1432 				    flags & XE_BO_FLAG_USER ?
1433 				    &vm->lru_bulk_move : NULL, size,
1434 				    cpu_caching, type, flags);
1435 	if (IS_ERR(bo))
1436 		return bo;
1437 
1438 	/*
1439 	 * Note that instead of taking a reference no the drm_gpuvm_resv_bo(),
1440 	 * to ensure the shared resv doesn't disappear under the bo, the bo
1441 	 * will keep a reference to the vm, and avoid circular references
1442 	 * by having all the vm's bo refereferences released at vm close
1443 	 * time.
1444 	 */
1445 	if (vm && xe_bo_is_user(bo))
1446 		xe_vm_get(vm);
1447 	bo->vm = vm;
1448 
1449 	if (bo->flags & XE_BO_FLAG_GGTT) {
1450 		if (!tile && flags & XE_BO_FLAG_STOLEN)
1451 			tile = xe_device_get_root_tile(xe);
1452 
1453 		xe_assert(xe, tile);
1454 
1455 		if (flags & XE_BO_FLAG_FIXED_PLACEMENT) {
1456 			err = xe_ggtt_insert_bo_at(tile->mem.ggtt, bo,
1457 						   start + bo->size, U64_MAX);
1458 		} else {
1459 			err = xe_ggtt_insert_bo(tile->mem.ggtt, bo);
1460 		}
1461 		if (err)
1462 			goto err_unlock_put_bo;
1463 	}
1464 
1465 	return bo;
1466 
1467 err_unlock_put_bo:
1468 	__xe_bo_unset_bulk_move(bo);
1469 	xe_bo_unlock_vm_held(bo);
1470 	xe_bo_put(bo);
1471 	return ERR_PTR(err);
1472 }
1473 
1474 struct xe_bo *
1475 xe_bo_create_locked_range(struct xe_device *xe,
1476 			  struct xe_tile *tile, struct xe_vm *vm,
1477 			  size_t size, u64 start, u64 end,
1478 			  enum ttm_bo_type type, u32 flags)
1479 {
1480 	return __xe_bo_create_locked(xe, tile, vm, size, start, end, 0, type, flags);
1481 }
1482 
1483 struct xe_bo *xe_bo_create_locked(struct xe_device *xe, struct xe_tile *tile,
1484 				  struct xe_vm *vm, size_t size,
1485 				  enum ttm_bo_type type, u32 flags)
1486 {
1487 	return __xe_bo_create_locked(xe, tile, vm, size, 0, ~0ULL, 0, type, flags);
1488 }
1489 
1490 struct xe_bo *xe_bo_create_user(struct xe_device *xe, struct xe_tile *tile,
1491 				struct xe_vm *vm, size_t size,
1492 				u16 cpu_caching,
1493 				enum ttm_bo_type type,
1494 				u32 flags)
1495 {
1496 	struct xe_bo *bo = __xe_bo_create_locked(xe, tile, vm, size, 0, ~0ULL,
1497 						 cpu_caching, type,
1498 						 flags | XE_BO_FLAG_USER);
1499 	if (!IS_ERR(bo))
1500 		xe_bo_unlock_vm_held(bo);
1501 
1502 	return bo;
1503 }
1504 
1505 struct xe_bo *xe_bo_create(struct xe_device *xe, struct xe_tile *tile,
1506 			   struct xe_vm *vm, size_t size,
1507 			   enum ttm_bo_type type, u32 flags)
1508 {
1509 	struct xe_bo *bo = xe_bo_create_locked(xe, tile, vm, size, type, flags);
1510 
1511 	if (!IS_ERR(bo))
1512 		xe_bo_unlock_vm_held(bo);
1513 
1514 	return bo;
1515 }
1516 
1517 struct xe_bo *xe_bo_create_pin_map_at(struct xe_device *xe, struct xe_tile *tile,
1518 				      struct xe_vm *vm,
1519 				      size_t size, u64 offset,
1520 				      enum ttm_bo_type type, u32 flags)
1521 {
1522 	struct xe_bo *bo;
1523 	int err;
1524 	u64 start = offset == ~0ull ? 0 : offset;
1525 	u64 end = offset == ~0ull ? offset : start + size;
1526 
1527 	if (flags & XE_BO_FLAG_STOLEN &&
1528 	    xe_ttm_stolen_cpu_access_needs_ggtt(xe))
1529 		flags |= XE_BO_FLAG_GGTT;
1530 
1531 	bo = xe_bo_create_locked_range(xe, tile, vm, size, start, end, type,
1532 				       flags | XE_BO_FLAG_NEEDS_CPU_ACCESS);
1533 	if (IS_ERR(bo))
1534 		return bo;
1535 
1536 	err = xe_bo_pin(bo);
1537 	if (err)
1538 		goto err_put;
1539 
1540 	err = xe_bo_vmap(bo);
1541 	if (err)
1542 		goto err_unpin;
1543 
1544 	xe_bo_unlock_vm_held(bo);
1545 
1546 	return bo;
1547 
1548 err_unpin:
1549 	xe_bo_unpin(bo);
1550 err_put:
1551 	xe_bo_unlock_vm_held(bo);
1552 	xe_bo_put(bo);
1553 	return ERR_PTR(err);
1554 }
1555 
1556 struct xe_bo *xe_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
1557 				   struct xe_vm *vm, size_t size,
1558 				   enum ttm_bo_type type, u32 flags)
1559 {
1560 	return xe_bo_create_pin_map_at(xe, tile, vm, size, ~0ull, type, flags);
1561 }
1562 
1563 struct xe_bo *xe_bo_create_from_data(struct xe_device *xe, struct xe_tile *tile,
1564 				     const void *data, size_t size,
1565 				     enum ttm_bo_type type, u32 flags)
1566 {
1567 	struct xe_bo *bo = xe_bo_create_pin_map(xe, tile, NULL,
1568 						ALIGN(size, PAGE_SIZE),
1569 						type, flags);
1570 	if (IS_ERR(bo))
1571 		return bo;
1572 
1573 	xe_map_memcpy_to(xe, &bo->vmap, 0, data, size);
1574 
1575 	return bo;
1576 }
1577 
1578 static void __xe_bo_unpin_map_no_vm(void *arg)
1579 {
1580 	xe_bo_unpin_map_no_vm(arg);
1581 }
1582 
1583 struct xe_bo *xe_managed_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
1584 					   size_t size, u32 flags)
1585 {
1586 	struct xe_bo *bo;
1587 	int ret;
1588 
1589 	bo = xe_bo_create_pin_map(xe, tile, NULL, size, ttm_bo_type_kernel, flags);
1590 	if (IS_ERR(bo))
1591 		return bo;
1592 
1593 	ret = devm_add_action_or_reset(xe->drm.dev, __xe_bo_unpin_map_no_vm, bo);
1594 	if (ret)
1595 		return ERR_PTR(ret);
1596 
1597 	return bo;
1598 }
1599 
1600 struct xe_bo *xe_managed_bo_create_from_data(struct xe_device *xe, struct xe_tile *tile,
1601 					     const void *data, size_t size, u32 flags)
1602 {
1603 	struct xe_bo *bo = xe_managed_bo_create_pin_map(xe, tile, ALIGN(size, PAGE_SIZE), flags);
1604 
1605 	if (IS_ERR(bo))
1606 		return bo;
1607 
1608 	xe_map_memcpy_to(xe, &bo->vmap, 0, data, size);
1609 
1610 	return bo;
1611 }
1612 
1613 /**
1614  * xe_managed_bo_reinit_in_vram
1615  * @xe: xe device
1616  * @tile: Tile where the new buffer will be created
1617  * @src: Managed buffer object allocated in system memory
1618  *
1619  * Replace a managed src buffer object allocated in system memory with a new
1620  * one allocated in vram, copying the data between them.
1621  * Buffer object in VRAM is not going to have the same GGTT address, the caller
1622  * is responsible for making sure that any old references to it are updated.
1623  *
1624  * Returns 0 for success, negative error code otherwise.
1625  */
1626 int xe_managed_bo_reinit_in_vram(struct xe_device *xe, struct xe_tile *tile, struct xe_bo **src)
1627 {
1628 	struct xe_bo *bo;
1629 	u32 dst_flags = XE_BO_FLAG_VRAM_IF_DGFX(tile) | XE_BO_FLAG_GGTT;
1630 
1631 	dst_flags |= (*src)->flags & XE_BO_FLAG_GGTT_INVALIDATE;
1632 
1633 	xe_assert(xe, IS_DGFX(xe));
1634 	xe_assert(xe, !(*src)->vmap.is_iomem);
1635 
1636 	bo = xe_managed_bo_create_from_data(xe, tile, (*src)->vmap.vaddr,
1637 					    (*src)->size, dst_flags);
1638 	if (IS_ERR(bo))
1639 		return PTR_ERR(bo);
1640 
1641 	devm_release_action(xe->drm.dev, __xe_bo_unpin_map_no_vm, *src);
1642 	*src = bo;
1643 
1644 	return 0;
1645 }
1646 
1647 /*
1648  * XXX: This is in the VM bind data path, likely should calculate this once and
1649  * store, with a recalculation if the BO is moved.
1650  */
1651 uint64_t vram_region_gpu_offset(struct ttm_resource *res)
1652 {
1653 	struct xe_device *xe = ttm_to_xe_device(res->bo->bdev);
1654 
1655 	if (res->mem_type == XE_PL_STOLEN)
1656 		return xe_ttm_stolen_gpu_offset(xe);
1657 
1658 	return res_to_mem_region(res)->dpa_base;
1659 }
1660 
1661 /**
1662  * xe_bo_pin_external - pin an external BO
1663  * @bo: buffer object to be pinned
1664  *
1665  * Pin an external (not tied to a VM, can be exported via dma-buf / prime FD)
1666  * BO. Unique call compared to xe_bo_pin as this function has it own set of
1667  * asserts and code to ensure evict / restore on suspend / resume.
1668  *
1669  * Returns 0 for success, negative error code otherwise.
1670  */
1671 int xe_bo_pin_external(struct xe_bo *bo)
1672 {
1673 	struct xe_device *xe = xe_bo_device(bo);
1674 	int err;
1675 
1676 	xe_assert(xe, !bo->vm);
1677 	xe_assert(xe, xe_bo_is_user(bo));
1678 
1679 	if (!xe_bo_is_pinned(bo)) {
1680 		err = xe_bo_validate(bo, NULL, false);
1681 		if (err)
1682 			return err;
1683 
1684 		if (xe_bo_is_vram(bo)) {
1685 			spin_lock(&xe->pinned.lock);
1686 			list_add_tail(&bo->pinned_link,
1687 				      &xe->pinned.external_vram);
1688 			spin_unlock(&xe->pinned.lock);
1689 		}
1690 	}
1691 
1692 	ttm_bo_pin(&bo->ttm);
1693 
1694 	/*
1695 	 * FIXME: If we always use the reserve / unreserve functions for locking
1696 	 * we do not need this.
1697 	 */
1698 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
1699 
1700 	return 0;
1701 }
1702 
1703 int xe_bo_pin(struct xe_bo *bo)
1704 {
1705 	struct xe_device *xe = xe_bo_device(bo);
1706 	int err;
1707 
1708 	/* We currently don't expect user BO to be pinned */
1709 	xe_assert(xe, !xe_bo_is_user(bo));
1710 
1711 	/* Pinned object must be in GGTT or have pinned flag */
1712 	xe_assert(xe, bo->flags & (XE_BO_FLAG_PINNED |
1713 				   XE_BO_FLAG_GGTT));
1714 
1715 	/*
1716 	 * No reason we can't support pinning imported dma-bufs we just don't
1717 	 * expect to pin an imported dma-buf.
1718 	 */
1719 	xe_assert(xe, !bo->ttm.base.import_attach);
1720 
1721 	/* We only expect at most 1 pin */
1722 	xe_assert(xe, !xe_bo_is_pinned(bo));
1723 
1724 	err = xe_bo_validate(bo, NULL, false);
1725 	if (err)
1726 		return err;
1727 
1728 	/*
1729 	 * For pinned objects in on DGFX, which are also in vram, we expect
1730 	 * these to be in contiguous VRAM memory. Required eviction / restore
1731 	 * during suspend / resume (force restore to same physical address).
1732 	 */
1733 	if (IS_DGFX(xe) && !(IS_ENABLED(CONFIG_DRM_XE_DEBUG) &&
1734 	    bo->flags & XE_BO_FLAG_INTERNAL_TEST)) {
1735 		struct ttm_place *place = &(bo->placements[0]);
1736 
1737 		if (mem_type_is_vram(place->mem_type)) {
1738 			xe_assert(xe, place->flags & TTM_PL_FLAG_CONTIGUOUS);
1739 
1740 			place->fpfn = (xe_bo_addr(bo, 0, PAGE_SIZE) -
1741 				       vram_region_gpu_offset(bo->ttm.resource)) >> PAGE_SHIFT;
1742 			place->lpfn = place->fpfn + (bo->size >> PAGE_SHIFT);
1743 
1744 			spin_lock(&xe->pinned.lock);
1745 			list_add_tail(&bo->pinned_link, &xe->pinned.kernel_bo_present);
1746 			spin_unlock(&xe->pinned.lock);
1747 		}
1748 	}
1749 
1750 	ttm_bo_pin(&bo->ttm);
1751 
1752 	/*
1753 	 * FIXME: If we always use the reserve / unreserve functions for locking
1754 	 * we do not need this.
1755 	 */
1756 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
1757 
1758 	return 0;
1759 }
1760 
1761 /**
1762  * xe_bo_unpin_external - unpin an external BO
1763  * @bo: buffer object to be unpinned
1764  *
1765  * Unpin an external (not tied to a VM, can be exported via dma-buf / prime FD)
1766  * BO. Unique call compared to xe_bo_unpin as this function has it own set of
1767  * asserts and code to ensure evict / restore on suspend / resume.
1768  *
1769  * Returns 0 for success, negative error code otherwise.
1770  */
1771 void xe_bo_unpin_external(struct xe_bo *bo)
1772 {
1773 	struct xe_device *xe = xe_bo_device(bo);
1774 
1775 	xe_assert(xe, !bo->vm);
1776 	xe_assert(xe, xe_bo_is_pinned(bo));
1777 	xe_assert(xe, xe_bo_is_user(bo));
1778 
1779 	spin_lock(&xe->pinned.lock);
1780 	if (bo->ttm.pin_count == 1 && !list_empty(&bo->pinned_link))
1781 		list_del_init(&bo->pinned_link);
1782 	spin_unlock(&xe->pinned.lock);
1783 
1784 	ttm_bo_unpin(&bo->ttm);
1785 
1786 	/*
1787 	 * FIXME: If we always use the reserve / unreserve functions for locking
1788 	 * we do not need this.
1789 	 */
1790 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
1791 }
1792 
1793 void xe_bo_unpin(struct xe_bo *bo)
1794 {
1795 	struct xe_device *xe = xe_bo_device(bo);
1796 
1797 	xe_assert(xe, !bo->ttm.base.import_attach);
1798 	xe_assert(xe, xe_bo_is_pinned(bo));
1799 
1800 	if (IS_DGFX(xe) && !(IS_ENABLED(CONFIG_DRM_XE_DEBUG) &&
1801 	    bo->flags & XE_BO_FLAG_INTERNAL_TEST)) {
1802 		struct ttm_place *place = &(bo->placements[0]);
1803 
1804 		if (mem_type_is_vram(place->mem_type)) {
1805 			spin_lock(&xe->pinned.lock);
1806 			xe_assert(xe, !list_empty(&bo->pinned_link));
1807 			list_del_init(&bo->pinned_link);
1808 			spin_unlock(&xe->pinned.lock);
1809 		}
1810 	}
1811 
1812 	ttm_bo_unpin(&bo->ttm);
1813 }
1814 
1815 /**
1816  * xe_bo_validate() - Make sure the bo is in an allowed placement
1817  * @bo: The bo,
1818  * @vm: Pointer to a the vm the bo shares a locked dma_resv object with, or
1819  *      NULL. Used together with @allow_res_evict.
1820  * @allow_res_evict: Whether it's allowed to evict bos sharing @vm's
1821  *                   reservation object.
1822  *
1823  * Make sure the bo is in allowed placement, migrating it if necessary. If
1824  * needed, other bos will be evicted. If bos selected for eviction shares
1825  * the @vm's reservation object, they can be evicted iff @allow_res_evict is
1826  * set to true, otherwise they will be bypassed.
1827  *
1828  * Return: 0 on success, negative error code on failure. May return
1829  * -EINTR or -ERESTARTSYS if internal waits are interrupted by a signal.
1830  */
1831 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict)
1832 {
1833 	struct ttm_operation_ctx ctx = {
1834 		.interruptible = true,
1835 		.no_wait_gpu = false,
1836 	};
1837 
1838 	if (vm) {
1839 		lockdep_assert_held(&vm->lock);
1840 		xe_vm_assert_held(vm);
1841 
1842 		ctx.allow_res_evict = allow_res_evict;
1843 		ctx.resv = xe_vm_resv(vm);
1844 	}
1845 
1846 	return ttm_bo_validate(&bo->ttm, &bo->placement, &ctx);
1847 }
1848 
1849 bool xe_bo_is_xe_bo(struct ttm_buffer_object *bo)
1850 {
1851 	if (bo->destroy == &xe_ttm_bo_destroy)
1852 		return true;
1853 
1854 	return false;
1855 }
1856 
1857 /*
1858  * Resolve a BO address. There is no assert to check if the proper lock is held
1859  * so it should only be used in cases where it is not fatal to get the wrong
1860  * address, such as printing debug information, but not in cases where memory is
1861  * written based on this result.
1862  */
1863 dma_addr_t __xe_bo_addr(struct xe_bo *bo, u64 offset, size_t page_size)
1864 {
1865 	struct xe_device *xe = xe_bo_device(bo);
1866 	struct xe_res_cursor cur;
1867 	u64 page;
1868 
1869 	xe_assert(xe, page_size <= PAGE_SIZE);
1870 	page = offset >> PAGE_SHIFT;
1871 	offset &= (PAGE_SIZE - 1);
1872 
1873 	if (!xe_bo_is_vram(bo) && !xe_bo_is_stolen(bo)) {
1874 		xe_assert(xe, bo->ttm.ttm);
1875 
1876 		xe_res_first_sg(xe_bo_sg(bo), page << PAGE_SHIFT,
1877 				page_size, &cur);
1878 		return xe_res_dma(&cur) + offset;
1879 	} else {
1880 		struct xe_res_cursor cur;
1881 
1882 		xe_res_first(bo->ttm.resource, page << PAGE_SHIFT,
1883 			     page_size, &cur);
1884 		return cur.start + offset + vram_region_gpu_offset(bo->ttm.resource);
1885 	}
1886 }
1887 
1888 dma_addr_t xe_bo_addr(struct xe_bo *bo, u64 offset, size_t page_size)
1889 {
1890 	if (!READ_ONCE(bo->ttm.pin_count))
1891 		xe_bo_assert_held(bo);
1892 	return __xe_bo_addr(bo, offset, page_size);
1893 }
1894 
1895 int xe_bo_vmap(struct xe_bo *bo)
1896 {
1897 	void *virtual;
1898 	bool is_iomem;
1899 	int ret;
1900 
1901 	xe_bo_assert_held(bo);
1902 
1903 	if (!(bo->flags & XE_BO_FLAG_NEEDS_CPU_ACCESS))
1904 		return -EINVAL;
1905 
1906 	if (!iosys_map_is_null(&bo->vmap))
1907 		return 0;
1908 
1909 	/*
1910 	 * We use this more or less deprecated interface for now since
1911 	 * ttm_bo_vmap() doesn't offer the optimization of kmapping
1912 	 * single page bos, which is done here.
1913 	 * TODO: Fix up ttm_bo_vmap to do that, or fix up ttm_bo_kmap
1914 	 * to use struct iosys_map.
1915 	 */
1916 	ret = ttm_bo_kmap(&bo->ttm, 0, bo->size >> PAGE_SHIFT, &bo->kmap);
1917 	if (ret)
1918 		return ret;
1919 
1920 	virtual = ttm_kmap_obj_virtual(&bo->kmap, &is_iomem);
1921 	if (is_iomem)
1922 		iosys_map_set_vaddr_iomem(&bo->vmap, (void __iomem *)virtual);
1923 	else
1924 		iosys_map_set_vaddr(&bo->vmap, virtual);
1925 
1926 	return 0;
1927 }
1928 
1929 static void __xe_bo_vunmap(struct xe_bo *bo)
1930 {
1931 	if (!iosys_map_is_null(&bo->vmap)) {
1932 		iosys_map_clear(&bo->vmap);
1933 		ttm_bo_kunmap(&bo->kmap);
1934 	}
1935 }
1936 
1937 void xe_bo_vunmap(struct xe_bo *bo)
1938 {
1939 	xe_bo_assert_held(bo);
1940 	__xe_bo_vunmap(bo);
1941 }
1942 
1943 int xe_gem_create_ioctl(struct drm_device *dev, void *data,
1944 			struct drm_file *file)
1945 {
1946 	struct xe_device *xe = to_xe_device(dev);
1947 	struct xe_file *xef = to_xe_file(file);
1948 	struct drm_xe_gem_create *args = data;
1949 	struct xe_vm *vm = NULL;
1950 	struct xe_bo *bo;
1951 	unsigned int bo_flags;
1952 	u32 handle;
1953 	int err;
1954 
1955 	if (XE_IOCTL_DBG(xe, args->extensions) ||
1956 	    XE_IOCTL_DBG(xe, args->pad[0] || args->pad[1] || args->pad[2]) ||
1957 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
1958 		return -EINVAL;
1959 
1960 	/* at least one valid memory placement must be specified */
1961 	if (XE_IOCTL_DBG(xe, (args->placement & ~xe->info.mem_region_mask) ||
1962 			 !args->placement))
1963 		return -EINVAL;
1964 
1965 	if (XE_IOCTL_DBG(xe, args->flags &
1966 			 ~(DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING |
1967 			   DRM_XE_GEM_CREATE_FLAG_SCANOUT |
1968 			   DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM)))
1969 		return -EINVAL;
1970 
1971 	if (XE_IOCTL_DBG(xe, args->handle))
1972 		return -EINVAL;
1973 
1974 	if (XE_IOCTL_DBG(xe, !args->size))
1975 		return -EINVAL;
1976 
1977 	if (XE_IOCTL_DBG(xe, args->size > SIZE_MAX))
1978 		return -EINVAL;
1979 
1980 	if (XE_IOCTL_DBG(xe, args->size & ~PAGE_MASK))
1981 		return -EINVAL;
1982 
1983 	bo_flags = 0;
1984 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING)
1985 		bo_flags |= XE_BO_FLAG_DEFER_BACKING;
1986 
1987 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_SCANOUT)
1988 		bo_flags |= XE_BO_FLAG_SCANOUT;
1989 
1990 	bo_flags |= args->placement << (ffs(XE_BO_FLAG_SYSTEM) - 1);
1991 
1992 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM) {
1993 		if (XE_IOCTL_DBG(xe, !(bo_flags & XE_BO_FLAG_VRAM_MASK)))
1994 			return -EINVAL;
1995 
1996 		bo_flags |= XE_BO_FLAG_NEEDS_CPU_ACCESS;
1997 	}
1998 
1999 	if (XE_IOCTL_DBG(xe, !args->cpu_caching ||
2000 			 args->cpu_caching > DRM_XE_GEM_CPU_CACHING_WC))
2001 		return -EINVAL;
2002 
2003 	if (XE_IOCTL_DBG(xe, bo_flags & XE_BO_FLAG_VRAM_MASK &&
2004 			 args->cpu_caching != DRM_XE_GEM_CPU_CACHING_WC))
2005 		return -EINVAL;
2006 
2007 	if (XE_IOCTL_DBG(xe, bo_flags & XE_BO_FLAG_SCANOUT &&
2008 			 args->cpu_caching == DRM_XE_GEM_CPU_CACHING_WB))
2009 		return -EINVAL;
2010 
2011 	if (args->vm_id) {
2012 		vm = xe_vm_lookup(xef, args->vm_id);
2013 		if (XE_IOCTL_DBG(xe, !vm))
2014 			return -ENOENT;
2015 		err = xe_vm_lock(vm, true);
2016 		if (err)
2017 			goto out_vm;
2018 	}
2019 
2020 	bo = xe_bo_create_user(xe, NULL, vm, args->size, args->cpu_caching,
2021 			       ttm_bo_type_device, bo_flags);
2022 
2023 	if (vm)
2024 		xe_vm_unlock(vm);
2025 
2026 	if (IS_ERR(bo)) {
2027 		err = PTR_ERR(bo);
2028 		goto out_vm;
2029 	}
2030 
2031 	err = drm_gem_handle_create(file, &bo->ttm.base, &handle);
2032 	if (err)
2033 		goto out_bulk;
2034 
2035 	args->handle = handle;
2036 	goto out_put;
2037 
2038 out_bulk:
2039 	if (vm && !xe_vm_in_fault_mode(vm)) {
2040 		xe_vm_lock(vm, false);
2041 		__xe_bo_unset_bulk_move(bo);
2042 		xe_vm_unlock(vm);
2043 	}
2044 out_put:
2045 	xe_bo_put(bo);
2046 out_vm:
2047 	if (vm)
2048 		xe_vm_put(vm);
2049 
2050 	return err;
2051 }
2052 
2053 int xe_gem_mmap_offset_ioctl(struct drm_device *dev, void *data,
2054 			     struct drm_file *file)
2055 {
2056 	struct xe_device *xe = to_xe_device(dev);
2057 	struct drm_xe_gem_mmap_offset *args = data;
2058 	struct drm_gem_object *gem_obj;
2059 
2060 	if (XE_IOCTL_DBG(xe, args->extensions) ||
2061 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
2062 		return -EINVAL;
2063 
2064 	if (XE_IOCTL_DBG(xe, args->flags))
2065 		return -EINVAL;
2066 
2067 	gem_obj = drm_gem_object_lookup(file, args->handle);
2068 	if (XE_IOCTL_DBG(xe, !gem_obj))
2069 		return -ENOENT;
2070 
2071 	/* The mmap offset was set up at BO allocation time. */
2072 	args->offset = drm_vma_node_offset_addr(&gem_obj->vma_node);
2073 
2074 	xe_bo_put(gem_to_xe_bo(gem_obj));
2075 	return 0;
2076 }
2077 
2078 /**
2079  * xe_bo_lock() - Lock the buffer object's dma_resv object
2080  * @bo: The struct xe_bo whose lock is to be taken
2081  * @intr: Whether to perform any wait interruptible
2082  *
2083  * Locks the buffer object's dma_resv object. If the buffer object is
2084  * pointing to a shared dma_resv object, that shared lock is locked.
2085  *
2086  * Return: 0 on success, -EINTR if @intr is true and the wait for a
2087  * contended lock was interrupted. If @intr is set to false, the
2088  * function always returns 0.
2089  */
2090 int xe_bo_lock(struct xe_bo *bo, bool intr)
2091 {
2092 	if (intr)
2093 		return dma_resv_lock_interruptible(bo->ttm.base.resv, NULL);
2094 
2095 	dma_resv_lock(bo->ttm.base.resv, NULL);
2096 
2097 	return 0;
2098 }
2099 
2100 /**
2101  * xe_bo_unlock() - Unlock the buffer object's dma_resv object
2102  * @bo: The struct xe_bo whose lock is to be released.
2103  *
2104  * Unlock a buffer object lock that was locked by xe_bo_lock().
2105  */
2106 void xe_bo_unlock(struct xe_bo *bo)
2107 {
2108 	dma_resv_unlock(bo->ttm.base.resv);
2109 }
2110 
2111 /**
2112  * xe_bo_can_migrate - Whether a buffer object likely can be migrated
2113  * @bo: The buffer object to migrate
2114  * @mem_type: The TTM memory type intended to migrate to
2115  *
2116  * Check whether the buffer object supports migration to the
2117  * given memory type. Note that pinning may affect the ability to migrate as
2118  * returned by this function.
2119  *
2120  * This function is primarily intended as a helper for checking the
2121  * possibility to migrate buffer objects and can be called without
2122  * the object lock held.
2123  *
2124  * Return: true if migration is possible, false otherwise.
2125  */
2126 bool xe_bo_can_migrate(struct xe_bo *bo, u32 mem_type)
2127 {
2128 	unsigned int cur_place;
2129 
2130 	if (bo->ttm.type == ttm_bo_type_kernel)
2131 		return true;
2132 
2133 	if (bo->ttm.type == ttm_bo_type_sg)
2134 		return false;
2135 
2136 	for (cur_place = 0; cur_place < bo->placement.num_placement;
2137 	     cur_place++) {
2138 		if (bo->placements[cur_place].mem_type == mem_type)
2139 			return true;
2140 	}
2141 
2142 	return false;
2143 }
2144 
2145 static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place)
2146 {
2147 	memset(place, 0, sizeof(*place));
2148 	place->mem_type = mem_type;
2149 }
2150 
2151 /**
2152  * xe_bo_migrate - Migrate an object to the desired region id
2153  * @bo: The buffer object to migrate.
2154  * @mem_type: The TTM region type to migrate to.
2155  *
2156  * Attempt to migrate the buffer object to the desired memory region. The
2157  * buffer object may not be pinned, and must be locked.
2158  * On successful completion, the object memory type will be updated,
2159  * but an async migration task may not have completed yet, and to
2160  * accomplish that, the object's kernel fences must be signaled with
2161  * the object lock held.
2162  *
2163  * Return: 0 on success. Negative error code on failure. In particular may
2164  * return -EINTR or -ERESTARTSYS if signal pending.
2165  */
2166 int xe_bo_migrate(struct xe_bo *bo, u32 mem_type)
2167 {
2168 	struct xe_device *xe = ttm_to_xe_device(bo->ttm.bdev);
2169 	struct ttm_operation_ctx ctx = {
2170 		.interruptible = true,
2171 		.no_wait_gpu = false,
2172 	};
2173 	struct ttm_placement placement;
2174 	struct ttm_place requested;
2175 
2176 	xe_bo_assert_held(bo);
2177 
2178 	if (bo->ttm.resource->mem_type == mem_type)
2179 		return 0;
2180 
2181 	if (xe_bo_is_pinned(bo))
2182 		return -EBUSY;
2183 
2184 	if (!xe_bo_can_migrate(bo, mem_type))
2185 		return -EINVAL;
2186 
2187 	xe_place_from_ttm_type(mem_type, &requested);
2188 	placement.num_placement = 1;
2189 	placement.placement = &requested;
2190 
2191 	/*
2192 	 * Stolen needs to be handled like below VRAM handling if we ever need
2193 	 * to support it.
2194 	 */
2195 	drm_WARN_ON(&xe->drm, mem_type == XE_PL_STOLEN);
2196 
2197 	if (mem_type_is_vram(mem_type)) {
2198 		u32 c = 0;
2199 
2200 		add_vram(xe, bo, &requested, bo->flags, mem_type, &c);
2201 	}
2202 
2203 	return ttm_bo_validate(&bo->ttm, &placement, &ctx);
2204 }
2205 
2206 /**
2207  * xe_bo_evict - Evict an object to evict placement
2208  * @bo: The buffer object to migrate.
2209  * @force_alloc: Set force_alloc in ttm_operation_ctx
2210  *
2211  * On successful completion, the object memory will be moved to evict
2212  * placement. Ths function blocks until the object has been fully moved.
2213  *
2214  * Return: 0 on success. Negative error code on failure.
2215  */
2216 int xe_bo_evict(struct xe_bo *bo, bool force_alloc)
2217 {
2218 	struct ttm_operation_ctx ctx = {
2219 		.interruptible = false,
2220 		.no_wait_gpu = false,
2221 		.force_alloc = force_alloc,
2222 	};
2223 	struct ttm_placement placement;
2224 	int ret;
2225 
2226 	xe_evict_flags(&bo->ttm, &placement);
2227 	ret = ttm_bo_validate(&bo->ttm, &placement, &ctx);
2228 	if (ret)
2229 		return ret;
2230 
2231 	dma_resv_wait_timeout(bo->ttm.base.resv, DMA_RESV_USAGE_KERNEL,
2232 			      false, MAX_SCHEDULE_TIMEOUT);
2233 
2234 	return 0;
2235 }
2236 
2237 /**
2238  * xe_bo_needs_ccs_pages - Whether a bo needs to back up CCS pages when
2239  * placed in system memory.
2240  * @bo: The xe_bo
2241  *
2242  * Return: true if extra pages need to be allocated, false otherwise.
2243  */
2244 bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
2245 {
2246 	struct xe_device *xe = xe_bo_device(bo);
2247 
2248 	if (GRAPHICS_VER(xe) >= 20 && IS_DGFX(xe))
2249 		return false;
2250 
2251 	if (!xe_device_has_flat_ccs(xe) || bo->ttm.type != ttm_bo_type_device)
2252 		return false;
2253 
2254 	/* On discrete GPUs, if the GPU can access this buffer from
2255 	 * system memory (i.e., it allows XE_PL_TT placement), FlatCCS
2256 	 * can't be used since there's no CCS storage associated with
2257 	 * non-VRAM addresses.
2258 	 */
2259 	if (IS_DGFX(xe) && (bo->flags & XE_BO_FLAG_SYSTEM))
2260 		return false;
2261 
2262 	return true;
2263 }
2264 
2265 /**
2266  * __xe_bo_release_dummy() - Dummy kref release function
2267  * @kref: The embedded struct kref.
2268  *
2269  * Dummy release function for xe_bo_put_deferred(). Keep off.
2270  */
2271 void __xe_bo_release_dummy(struct kref *kref)
2272 {
2273 }
2274 
2275 /**
2276  * xe_bo_put_commit() - Put bos whose put was deferred by xe_bo_put_deferred().
2277  * @deferred: The lockless list used for the call to xe_bo_put_deferred().
2278  *
2279  * Puts all bos whose put was deferred by xe_bo_put_deferred().
2280  * The @deferred list can be either an onstack local list or a global
2281  * shared list used by a workqueue.
2282  */
2283 void xe_bo_put_commit(struct llist_head *deferred)
2284 {
2285 	struct llist_node *freed;
2286 	struct xe_bo *bo, *next;
2287 
2288 	if (!deferred)
2289 		return;
2290 
2291 	freed = llist_del_all(deferred);
2292 	if (!freed)
2293 		return;
2294 
2295 	llist_for_each_entry_safe(bo, next, freed, freed)
2296 		drm_gem_object_free(&bo->ttm.base.refcount);
2297 }
2298 
2299 /**
2300  * xe_bo_dumb_create - Create a dumb bo as backing for a fb
2301  * @file_priv: ...
2302  * @dev: ...
2303  * @args: ...
2304  *
2305  * See dumb_create() hook in include/drm/drm_drv.h
2306  *
2307  * Return: ...
2308  */
2309 int xe_bo_dumb_create(struct drm_file *file_priv,
2310 		      struct drm_device *dev,
2311 		      struct drm_mode_create_dumb *args)
2312 {
2313 	struct xe_device *xe = to_xe_device(dev);
2314 	struct xe_bo *bo;
2315 	uint32_t handle;
2316 	int cpp = DIV_ROUND_UP(args->bpp, 8);
2317 	int err;
2318 	u32 page_size = max_t(u32, PAGE_SIZE,
2319 		xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K ? SZ_64K : SZ_4K);
2320 
2321 	args->pitch = ALIGN(args->width * cpp, 64);
2322 	args->size = ALIGN(mul_u32_u32(args->pitch, args->height),
2323 			   page_size);
2324 
2325 	bo = xe_bo_create_user(xe, NULL, NULL, args->size,
2326 			       DRM_XE_GEM_CPU_CACHING_WC,
2327 			       ttm_bo_type_device,
2328 			       XE_BO_FLAG_VRAM_IF_DGFX(xe_device_get_root_tile(xe)) |
2329 			       XE_BO_FLAG_SCANOUT |
2330 			       XE_BO_FLAG_NEEDS_CPU_ACCESS);
2331 	if (IS_ERR(bo))
2332 		return PTR_ERR(bo);
2333 
2334 	err = drm_gem_handle_create(file_priv, &bo->ttm.base, &handle);
2335 	/* drop reference from allocate - handle holds it now */
2336 	drm_gem_object_put(&bo->ttm.base);
2337 	if (!err)
2338 		args->handle = handle;
2339 	return err;
2340 }
2341 
2342 void xe_bo_runtime_pm_release_mmap_offset(struct xe_bo *bo)
2343 {
2344 	struct ttm_buffer_object *tbo = &bo->ttm;
2345 	struct ttm_device *bdev = tbo->bdev;
2346 
2347 	drm_vma_node_unmap(&tbo->base.vma_node, bdev->dev_mapping);
2348 
2349 	list_del_init(&bo->vram_userfault_link);
2350 }
2351 
2352 #if IS_ENABLED(CONFIG_DRM_XE_KUNIT_TEST)
2353 #include "tests/xe_bo.c"
2354 #endif
2355