xref: /linux/drivers/gpu/drm/xe/xe_bo.c (revision d53b8e36925256097a08d7cb749198d85cbf9b2b)
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 			u32 flags = 0;
798 
799 			if (mem_type_is_vram(new_mem->mem_type))
800 				flags |= XE_MIGRATE_CLEAR_FLAG_FULL;
801 			else if (handle_system_ccs)
802 				flags |= XE_MIGRATE_CLEAR_FLAG_CCS_DATA;
803 
804 			fence = xe_migrate_clear(migrate, bo, new_mem, flags);
805 		}
806 		else
807 			fence = xe_migrate_copy(migrate, bo, bo, old_mem,
808 						new_mem, handle_system_ccs);
809 		if (IS_ERR(fence)) {
810 			ret = PTR_ERR(fence);
811 			xe_pm_runtime_put(xe);
812 			goto out;
813 		}
814 		if (!move_lacks_source) {
815 			ret = ttm_bo_move_accel_cleanup(ttm_bo, fence, evict,
816 							true, new_mem);
817 			if (ret) {
818 				dma_fence_wait(fence, false);
819 				ttm_bo_move_null(ttm_bo, new_mem);
820 				ret = 0;
821 			}
822 		} else {
823 			/*
824 			 * ttm_bo_move_accel_cleanup() may blow up if
825 			 * bo->resource == NULL, so just attach the
826 			 * fence and set the new resource.
827 			 */
828 			dma_resv_add_fence(ttm_bo->base.resv, fence,
829 					   DMA_RESV_USAGE_KERNEL);
830 			ttm_bo_move_null(ttm_bo, new_mem);
831 		}
832 
833 		dma_fence_put(fence);
834 	}
835 
836 	xe_pm_runtime_put(xe);
837 
838 out:
839 	if ((!ttm_bo->resource || ttm_bo->resource->mem_type == XE_PL_SYSTEM) &&
840 	    ttm_bo->ttm)
841 		xe_tt_unmap_sg(ttm_bo->ttm);
842 
843 	return ret;
844 }
845 
846 /**
847  * xe_bo_evict_pinned() - Evict a pinned VRAM object to system memory
848  * @bo: The buffer object to move.
849  *
850  * On successful completion, the object memory will be moved to sytem memory.
851  *
852  * This is needed to for special handling of pinned VRAM object during
853  * suspend-resume.
854  *
855  * Return: 0 on success. Negative error code on failure.
856  */
857 int xe_bo_evict_pinned(struct xe_bo *bo)
858 {
859 	struct ttm_place place = {
860 		.mem_type = XE_PL_TT,
861 	};
862 	struct ttm_placement placement = {
863 		.placement = &place,
864 		.num_placement = 1,
865 	};
866 	struct ttm_operation_ctx ctx = {
867 		.interruptible = false,
868 	};
869 	struct ttm_resource *new_mem;
870 	int ret;
871 
872 	xe_bo_assert_held(bo);
873 
874 	if (WARN_ON(!bo->ttm.resource))
875 		return -EINVAL;
876 
877 	if (WARN_ON(!xe_bo_is_pinned(bo)))
878 		return -EINVAL;
879 
880 	if (WARN_ON(!xe_bo_is_vram(bo)))
881 		return -EINVAL;
882 
883 	ret = ttm_bo_mem_space(&bo->ttm, &placement, &new_mem, &ctx);
884 	if (ret)
885 		return ret;
886 
887 	if (!bo->ttm.ttm) {
888 		bo->ttm.ttm = xe_ttm_tt_create(&bo->ttm, 0);
889 		if (!bo->ttm.ttm) {
890 			ret = -ENOMEM;
891 			goto err_res_free;
892 		}
893 	}
894 
895 	ret = ttm_tt_populate(bo->ttm.bdev, bo->ttm.ttm, &ctx);
896 	if (ret)
897 		goto err_res_free;
898 
899 	ret = dma_resv_reserve_fences(bo->ttm.base.resv, 1);
900 	if (ret)
901 		goto err_res_free;
902 
903 	ret = xe_bo_move(&bo->ttm, false, &ctx, new_mem, NULL);
904 	if (ret)
905 		goto err_res_free;
906 
907 	return 0;
908 
909 err_res_free:
910 	ttm_resource_free(&bo->ttm, &new_mem);
911 	return ret;
912 }
913 
914 /**
915  * xe_bo_restore_pinned() - Restore a pinned VRAM object
916  * @bo: The buffer object to move.
917  *
918  * On successful completion, the object memory will be moved back to VRAM.
919  *
920  * This is needed to for special handling of pinned VRAM object during
921  * suspend-resume.
922  *
923  * Return: 0 on success. Negative error code on failure.
924  */
925 int xe_bo_restore_pinned(struct xe_bo *bo)
926 {
927 	struct ttm_operation_ctx ctx = {
928 		.interruptible = false,
929 	};
930 	struct ttm_resource *new_mem;
931 	int ret;
932 
933 	xe_bo_assert_held(bo);
934 
935 	if (WARN_ON(!bo->ttm.resource))
936 		return -EINVAL;
937 
938 	if (WARN_ON(!xe_bo_is_pinned(bo)))
939 		return -EINVAL;
940 
941 	if (WARN_ON(xe_bo_is_vram(bo) || !bo->ttm.ttm))
942 		return -EINVAL;
943 
944 	ret = ttm_bo_mem_space(&bo->ttm, &bo->placement, &new_mem, &ctx);
945 	if (ret)
946 		return ret;
947 
948 	ret = ttm_tt_populate(bo->ttm.bdev, bo->ttm.ttm, &ctx);
949 	if (ret)
950 		goto err_res_free;
951 
952 	ret = dma_resv_reserve_fences(bo->ttm.base.resv, 1);
953 	if (ret)
954 		goto err_res_free;
955 
956 	ret = xe_bo_move(&bo->ttm, false, &ctx, new_mem, NULL);
957 	if (ret)
958 		goto err_res_free;
959 
960 	return 0;
961 
962 err_res_free:
963 	ttm_resource_free(&bo->ttm, &new_mem);
964 	return ret;
965 }
966 
967 static unsigned long xe_ttm_io_mem_pfn(struct ttm_buffer_object *ttm_bo,
968 				       unsigned long page_offset)
969 {
970 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
971 	struct xe_res_cursor cursor;
972 	struct xe_mem_region *vram;
973 
974 	if (ttm_bo->resource->mem_type == XE_PL_STOLEN)
975 		return xe_ttm_stolen_io_offset(bo, page_offset << PAGE_SHIFT) >> PAGE_SHIFT;
976 
977 	vram = res_to_mem_region(ttm_bo->resource);
978 	xe_res_first(ttm_bo->resource, (u64)page_offset << PAGE_SHIFT, 0, &cursor);
979 	return (vram->io_start + cursor.start) >> PAGE_SHIFT;
980 }
981 
982 static void __xe_bo_vunmap(struct xe_bo *bo);
983 
984 /*
985  * TODO: Move this function to TTM so we don't rely on how TTM does its
986  * locking, thereby abusing TTM internals.
987  */
988 static bool xe_ttm_bo_lock_in_destructor(struct ttm_buffer_object *ttm_bo)
989 {
990 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
991 	bool locked;
992 
993 	xe_assert(xe, !kref_read(&ttm_bo->kref));
994 
995 	/*
996 	 * We can typically only race with TTM trylocking under the
997 	 * lru_lock, which will immediately be unlocked again since
998 	 * the ttm_bo refcount is zero at this point. So trylocking *should*
999 	 * always succeed here, as long as we hold the lru lock.
1000 	 */
1001 	spin_lock(&ttm_bo->bdev->lru_lock);
1002 	locked = dma_resv_trylock(ttm_bo->base.resv);
1003 	spin_unlock(&ttm_bo->bdev->lru_lock);
1004 	xe_assert(xe, locked);
1005 
1006 	return locked;
1007 }
1008 
1009 static void xe_ttm_bo_release_notify(struct ttm_buffer_object *ttm_bo)
1010 {
1011 	struct dma_resv_iter cursor;
1012 	struct dma_fence *fence;
1013 	struct dma_fence *replacement = NULL;
1014 	struct xe_bo *bo;
1015 
1016 	if (!xe_bo_is_xe_bo(ttm_bo))
1017 		return;
1018 
1019 	bo = ttm_to_xe_bo(ttm_bo);
1020 	xe_assert(xe_bo_device(bo), !(bo->created && kref_read(&ttm_bo->base.refcount)));
1021 
1022 	/*
1023 	 * Corner case where TTM fails to allocate memory and this BOs resv
1024 	 * still points the VMs resv
1025 	 */
1026 	if (ttm_bo->base.resv != &ttm_bo->base._resv)
1027 		return;
1028 
1029 	if (!xe_ttm_bo_lock_in_destructor(ttm_bo))
1030 		return;
1031 
1032 	/*
1033 	 * Scrub the preempt fences if any. The unbind fence is already
1034 	 * attached to the resv.
1035 	 * TODO: Don't do this for external bos once we scrub them after
1036 	 * unbind.
1037 	 */
1038 	dma_resv_for_each_fence(&cursor, ttm_bo->base.resv,
1039 				DMA_RESV_USAGE_BOOKKEEP, fence) {
1040 		if (xe_fence_is_xe_preempt(fence) &&
1041 		    !dma_fence_is_signaled(fence)) {
1042 			if (!replacement)
1043 				replacement = dma_fence_get_stub();
1044 
1045 			dma_resv_replace_fences(ttm_bo->base.resv,
1046 						fence->context,
1047 						replacement,
1048 						DMA_RESV_USAGE_BOOKKEEP);
1049 		}
1050 	}
1051 	dma_fence_put(replacement);
1052 
1053 	dma_resv_unlock(ttm_bo->base.resv);
1054 }
1055 
1056 static void xe_ttm_bo_delete_mem_notify(struct ttm_buffer_object *ttm_bo)
1057 {
1058 	if (!xe_bo_is_xe_bo(ttm_bo))
1059 		return;
1060 
1061 	/*
1062 	 * Object is idle and about to be destroyed. Release the
1063 	 * dma-buf attachment.
1064 	 */
1065 	if (ttm_bo->type == ttm_bo_type_sg && ttm_bo->sg) {
1066 		struct xe_ttm_tt *xe_tt = container_of(ttm_bo->ttm,
1067 						       struct xe_ttm_tt, ttm);
1068 
1069 		dma_buf_unmap_attachment(ttm_bo->base.import_attach, ttm_bo->sg,
1070 					 DMA_BIDIRECTIONAL);
1071 		ttm_bo->sg = NULL;
1072 		xe_tt->sg = NULL;
1073 	}
1074 }
1075 
1076 const struct ttm_device_funcs xe_ttm_funcs = {
1077 	.ttm_tt_create = xe_ttm_tt_create,
1078 	.ttm_tt_populate = xe_ttm_tt_populate,
1079 	.ttm_tt_unpopulate = xe_ttm_tt_unpopulate,
1080 	.ttm_tt_destroy = xe_ttm_tt_destroy,
1081 	.evict_flags = xe_evict_flags,
1082 	.move = xe_bo_move,
1083 	.io_mem_reserve = xe_ttm_io_mem_reserve,
1084 	.io_mem_pfn = xe_ttm_io_mem_pfn,
1085 	.release_notify = xe_ttm_bo_release_notify,
1086 	.eviction_valuable = ttm_bo_eviction_valuable,
1087 	.delete_mem_notify = xe_ttm_bo_delete_mem_notify,
1088 };
1089 
1090 static void xe_ttm_bo_destroy(struct ttm_buffer_object *ttm_bo)
1091 {
1092 	struct xe_bo *bo = ttm_to_xe_bo(ttm_bo);
1093 	struct xe_device *xe = ttm_to_xe_device(ttm_bo->bdev);
1094 
1095 	if (bo->ttm.base.import_attach)
1096 		drm_prime_gem_destroy(&bo->ttm.base, NULL);
1097 	drm_gem_object_release(&bo->ttm.base);
1098 
1099 	xe_assert(xe, list_empty(&ttm_bo->base.gpuva.list));
1100 
1101 	if (bo->ggtt_node && bo->ggtt_node->base.size)
1102 		xe_ggtt_remove_bo(bo->tile->mem.ggtt, bo);
1103 
1104 #ifdef CONFIG_PROC_FS
1105 	if (bo->client)
1106 		xe_drm_client_remove_bo(bo);
1107 #endif
1108 
1109 	if (bo->vm && xe_bo_is_user(bo))
1110 		xe_vm_put(bo->vm);
1111 
1112 	mutex_lock(&xe->mem_access.vram_userfault.lock);
1113 	if (!list_empty(&bo->vram_userfault_link))
1114 		list_del(&bo->vram_userfault_link);
1115 	mutex_unlock(&xe->mem_access.vram_userfault.lock);
1116 
1117 	kfree(bo);
1118 }
1119 
1120 static void xe_gem_object_free(struct drm_gem_object *obj)
1121 {
1122 	/* Our BO reference counting scheme works as follows:
1123 	 *
1124 	 * The gem object kref is typically used throughout the driver,
1125 	 * and the gem object holds a ttm_buffer_object refcount, so
1126 	 * that when the last gem object reference is put, which is when
1127 	 * we end up in this function, we put also that ttm_buffer_object
1128 	 * refcount. Anything using gem interfaces is then no longer
1129 	 * allowed to access the object in a way that requires a gem
1130 	 * refcount, including locking the object.
1131 	 *
1132 	 * driver ttm callbacks is allowed to use the ttm_buffer_object
1133 	 * refcount directly if needed.
1134 	 */
1135 	__xe_bo_vunmap(gem_to_xe_bo(obj));
1136 	ttm_bo_put(container_of(obj, struct ttm_buffer_object, base));
1137 }
1138 
1139 static void xe_gem_object_close(struct drm_gem_object *obj,
1140 				struct drm_file *file_priv)
1141 {
1142 	struct xe_bo *bo = gem_to_xe_bo(obj);
1143 
1144 	if (bo->vm && !xe_vm_in_fault_mode(bo->vm)) {
1145 		xe_assert(xe_bo_device(bo), xe_bo_is_user(bo));
1146 
1147 		xe_bo_lock(bo, false);
1148 		ttm_bo_set_bulk_move(&bo->ttm, NULL);
1149 		xe_bo_unlock(bo);
1150 	}
1151 }
1152 
1153 static vm_fault_t xe_gem_fault(struct vm_fault *vmf)
1154 {
1155 	struct ttm_buffer_object *tbo = vmf->vma->vm_private_data;
1156 	struct drm_device *ddev = tbo->base.dev;
1157 	struct xe_device *xe = to_xe_device(ddev);
1158 	struct xe_bo *bo = ttm_to_xe_bo(tbo);
1159 	bool needs_rpm = bo->flags & XE_BO_FLAG_VRAM_MASK;
1160 	vm_fault_t ret;
1161 	int idx;
1162 
1163 	if (needs_rpm)
1164 		xe_pm_runtime_get(xe);
1165 
1166 	ret = ttm_bo_vm_reserve(tbo, vmf);
1167 	if (ret)
1168 		goto out;
1169 
1170 	if (drm_dev_enter(ddev, &idx)) {
1171 		trace_xe_bo_cpu_fault(bo);
1172 
1173 		ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
1174 					       TTM_BO_VM_NUM_PREFAULT);
1175 		drm_dev_exit(idx);
1176 	} else {
1177 		ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
1178 	}
1179 
1180 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
1181 		goto out;
1182 	/*
1183 	 * ttm_bo_vm_reserve() already has dma_resv_lock.
1184 	 */
1185 	if (ret == VM_FAULT_NOPAGE && mem_type_is_vram(tbo->resource->mem_type)) {
1186 		mutex_lock(&xe->mem_access.vram_userfault.lock);
1187 		if (list_empty(&bo->vram_userfault_link))
1188 			list_add(&bo->vram_userfault_link, &xe->mem_access.vram_userfault.list);
1189 		mutex_unlock(&xe->mem_access.vram_userfault.lock);
1190 	}
1191 
1192 	dma_resv_unlock(tbo->base.resv);
1193 out:
1194 	if (needs_rpm)
1195 		xe_pm_runtime_put(xe);
1196 
1197 	return ret;
1198 }
1199 
1200 static const struct vm_operations_struct xe_gem_vm_ops = {
1201 	.fault = xe_gem_fault,
1202 	.open = ttm_bo_vm_open,
1203 	.close = ttm_bo_vm_close,
1204 	.access = ttm_bo_vm_access
1205 };
1206 
1207 static const struct drm_gem_object_funcs xe_gem_object_funcs = {
1208 	.free = xe_gem_object_free,
1209 	.close = xe_gem_object_close,
1210 	.mmap = drm_gem_ttm_mmap,
1211 	.export = xe_gem_prime_export,
1212 	.vm_ops = &xe_gem_vm_ops,
1213 };
1214 
1215 /**
1216  * xe_bo_alloc - Allocate storage for a struct xe_bo
1217  *
1218  * This funcition is intended to allocate storage to be used for input
1219  * to __xe_bo_create_locked(), in the case a pointer to the bo to be
1220  * created is needed before the call to __xe_bo_create_locked().
1221  * If __xe_bo_create_locked ends up never to be called, then the
1222  * storage allocated with this function needs to be freed using
1223  * xe_bo_free().
1224  *
1225  * Return: A pointer to an uninitialized struct xe_bo on success,
1226  * ERR_PTR(-ENOMEM) on error.
1227  */
1228 struct xe_bo *xe_bo_alloc(void)
1229 {
1230 	struct xe_bo *bo = kzalloc(sizeof(*bo), GFP_KERNEL);
1231 
1232 	if (!bo)
1233 		return ERR_PTR(-ENOMEM);
1234 
1235 	return bo;
1236 }
1237 
1238 /**
1239  * xe_bo_free - Free storage allocated using xe_bo_alloc()
1240  * @bo: The buffer object storage.
1241  *
1242  * Refer to xe_bo_alloc() documentation for valid use-cases.
1243  */
1244 void xe_bo_free(struct xe_bo *bo)
1245 {
1246 	kfree(bo);
1247 }
1248 
1249 struct xe_bo *___xe_bo_create_locked(struct xe_device *xe, struct xe_bo *bo,
1250 				     struct xe_tile *tile, struct dma_resv *resv,
1251 				     struct ttm_lru_bulk_move *bulk, size_t size,
1252 				     u16 cpu_caching, enum ttm_bo_type type,
1253 				     u32 flags)
1254 {
1255 	struct ttm_operation_ctx ctx = {
1256 		.interruptible = true,
1257 		.no_wait_gpu = false,
1258 	};
1259 	struct ttm_placement *placement;
1260 	uint32_t alignment;
1261 	size_t aligned_size;
1262 	int err;
1263 
1264 	/* Only kernel objects should set GT */
1265 	xe_assert(xe, !tile || type == ttm_bo_type_kernel);
1266 
1267 	if (XE_WARN_ON(!size)) {
1268 		xe_bo_free(bo);
1269 		return ERR_PTR(-EINVAL);
1270 	}
1271 
1272 	if (flags & (XE_BO_FLAG_VRAM_MASK | XE_BO_FLAG_STOLEN) &&
1273 	    !(flags & XE_BO_FLAG_IGNORE_MIN_PAGE_SIZE) &&
1274 	    ((xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K) ||
1275 	     (flags & (XE_BO_FLAG_NEEDS_64K | XE_BO_FLAG_NEEDS_2M)))) {
1276 		size_t align = flags & XE_BO_FLAG_NEEDS_2M ? SZ_2M : SZ_64K;
1277 
1278 		aligned_size = ALIGN(size, align);
1279 		if (type != ttm_bo_type_device)
1280 			size = ALIGN(size, align);
1281 		flags |= XE_BO_FLAG_INTERNAL_64K;
1282 		alignment = align >> PAGE_SHIFT;
1283 	} else {
1284 		aligned_size = ALIGN(size, SZ_4K);
1285 		flags &= ~XE_BO_FLAG_INTERNAL_64K;
1286 		alignment = SZ_4K >> PAGE_SHIFT;
1287 	}
1288 
1289 	if (type == ttm_bo_type_device && aligned_size != size)
1290 		return ERR_PTR(-EINVAL);
1291 
1292 	if (!bo) {
1293 		bo = xe_bo_alloc();
1294 		if (IS_ERR(bo))
1295 			return bo;
1296 	}
1297 
1298 	bo->ccs_cleared = false;
1299 	bo->tile = tile;
1300 	bo->size = size;
1301 	bo->flags = flags;
1302 	bo->cpu_caching = cpu_caching;
1303 	bo->ttm.base.funcs = &xe_gem_object_funcs;
1304 	bo->ttm.priority = XE_BO_PRIORITY_NORMAL;
1305 	INIT_LIST_HEAD(&bo->pinned_link);
1306 #ifdef CONFIG_PROC_FS
1307 	INIT_LIST_HEAD(&bo->client_link);
1308 #endif
1309 	INIT_LIST_HEAD(&bo->vram_userfault_link);
1310 
1311 	drm_gem_private_object_init(&xe->drm, &bo->ttm.base, size);
1312 
1313 	if (resv) {
1314 		ctx.allow_res_evict = !(flags & XE_BO_FLAG_NO_RESV_EVICT);
1315 		ctx.resv = resv;
1316 	}
1317 
1318 	if (!(flags & XE_BO_FLAG_FIXED_PLACEMENT)) {
1319 		err = __xe_bo_placement_for_flags(xe, bo, bo->flags);
1320 		if (WARN_ON(err)) {
1321 			xe_ttm_bo_destroy(&bo->ttm);
1322 			return ERR_PTR(err);
1323 		}
1324 	}
1325 
1326 	/* Defer populating type_sg bos */
1327 	placement = (type == ttm_bo_type_sg ||
1328 		     bo->flags & XE_BO_FLAG_DEFER_BACKING) ? &sys_placement :
1329 		&bo->placement;
1330 	err = ttm_bo_init_reserved(&xe->ttm, &bo->ttm, type,
1331 				   placement, alignment,
1332 				   &ctx, NULL, resv, xe_ttm_bo_destroy);
1333 	if (err)
1334 		return ERR_PTR(err);
1335 
1336 	/*
1337 	 * The VRAM pages underneath are potentially still being accessed by the
1338 	 * GPU, as per async GPU clearing and async evictions. However TTM makes
1339 	 * sure to add any corresponding move/clear fences into the objects
1340 	 * dma-resv using the DMA_RESV_USAGE_KERNEL slot.
1341 	 *
1342 	 * For KMD internal buffers we don't care about GPU clearing, however we
1343 	 * still need to handle async evictions, where the VRAM is still being
1344 	 * accessed by the GPU. Most internal callers are not expecting this,
1345 	 * since they are missing the required synchronisation before accessing
1346 	 * the memory. To keep things simple just sync wait any kernel fences
1347 	 * here, if the buffer is designated KMD internal.
1348 	 *
1349 	 * For normal userspace objects we should already have the required
1350 	 * pipelining or sync waiting elsewhere, since we already have to deal
1351 	 * with things like async GPU clearing.
1352 	 */
1353 	if (type == ttm_bo_type_kernel) {
1354 		long timeout = dma_resv_wait_timeout(bo->ttm.base.resv,
1355 						     DMA_RESV_USAGE_KERNEL,
1356 						     ctx.interruptible,
1357 						     MAX_SCHEDULE_TIMEOUT);
1358 
1359 		if (timeout < 0) {
1360 			if (!resv)
1361 				dma_resv_unlock(bo->ttm.base.resv);
1362 			xe_bo_put(bo);
1363 			return ERR_PTR(timeout);
1364 		}
1365 	}
1366 
1367 	bo->created = true;
1368 	if (bulk)
1369 		ttm_bo_set_bulk_move(&bo->ttm, bulk);
1370 	else
1371 		ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
1372 
1373 	return bo;
1374 }
1375 
1376 static int __xe_bo_fixed_placement(struct xe_device *xe,
1377 				   struct xe_bo *bo,
1378 				   u32 flags,
1379 				   u64 start, u64 end, u64 size)
1380 {
1381 	struct ttm_place *place = bo->placements;
1382 
1383 	if (flags & (XE_BO_FLAG_USER | XE_BO_FLAG_SYSTEM))
1384 		return -EINVAL;
1385 
1386 	place->flags = TTM_PL_FLAG_CONTIGUOUS;
1387 	place->fpfn = start >> PAGE_SHIFT;
1388 	place->lpfn = end >> PAGE_SHIFT;
1389 
1390 	switch (flags & (XE_BO_FLAG_STOLEN | XE_BO_FLAG_VRAM_MASK)) {
1391 	case XE_BO_FLAG_VRAM0:
1392 		place->mem_type = XE_PL_VRAM0;
1393 		break;
1394 	case XE_BO_FLAG_VRAM1:
1395 		place->mem_type = XE_PL_VRAM1;
1396 		break;
1397 	case XE_BO_FLAG_STOLEN:
1398 		place->mem_type = XE_PL_STOLEN;
1399 		break;
1400 
1401 	default:
1402 		/* 0 or multiple of the above set */
1403 		return -EINVAL;
1404 	}
1405 
1406 	bo->placement = (struct ttm_placement) {
1407 		.num_placement = 1,
1408 		.placement = place,
1409 	};
1410 
1411 	return 0;
1412 }
1413 
1414 static struct xe_bo *
1415 __xe_bo_create_locked(struct xe_device *xe,
1416 		      struct xe_tile *tile, struct xe_vm *vm,
1417 		      size_t size, u64 start, u64 end,
1418 		      u16 cpu_caching, enum ttm_bo_type type, u32 flags)
1419 {
1420 	struct xe_bo *bo = NULL;
1421 	int err;
1422 
1423 	if (vm)
1424 		xe_vm_assert_held(vm);
1425 
1426 	if (start || end != ~0ULL) {
1427 		bo = xe_bo_alloc();
1428 		if (IS_ERR(bo))
1429 			return bo;
1430 
1431 		flags |= XE_BO_FLAG_FIXED_PLACEMENT;
1432 		err = __xe_bo_fixed_placement(xe, bo, flags, start, end, size);
1433 		if (err) {
1434 			xe_bo_free(bo);
1435 			return ERR_PTR(err);
1436 		}
1437 	}
1438 
1439 	bo = ___xe_bo_create_locked(xe, bo, tile, vm ? xe_vm_resv(vm) : NULL,
1440 				    vm && !xe_vm_in_fault_mode(vm) &&
1441 				    flags & XE_BO_FLAG_USER ?
1442 				    &vm->lru_bulk_move : NULL, size,
1443 				    cpu_caching, type, flags);
1444 	if (IS_ERR(bo))
1445 		return bo;
1446 
1447 	/*
1448 	 * Note that instead of taking a reference no the drm_gpuvm_resv_bo(),
1449 	 * to ensure the shared resv doesn't disappear under the bo, the bo
1450 	 * will keep a reference to the vm, and avoid circular references
1451 	 * by having all the vm's bo refereferences released at vm close
1452 	 * time.
1453 	 */
1454 	if (vm && xe_bo_is_user(bo))
1455 		xe_vm_get(vm);
1456 	bo->vm = vm;
1457 
1458 	if (bo->flags & XE_BO_FLAG_GGTT) {
1459 		if (!tile && flags & XE_BO_FLAG_STOLEN)
1460 			tile = xe_device_get_root_tile(xe);
1461 
1462 		xe_assert(xe, tile);
1463 
1464 		if (flags & XE_BO_FLAG_FIXED_PLACEMENT) {
1465 			err = xe_ggtt_insert_bo_at(tile->mem.ggtt, bo,
1466 						   start + bo->size, U64_MAX);
1467 		} else {
1468 			err = xe_ggtt_insert_bo(tile->mem.ggtt, bo);
1469 		}
1470 		if (err)
1471 			goto err_unlock_put_bo;
1472 	}
1473 
1474 	return bo;
1475 
1476 err_unlock_put_bo:
1477 	__xe_bo_unset_bulk_move(bo);
1478 	xe_bo_unlock_vm_held(bo);
1479 	xe_bo_put(bo);
1480 	return ERR_PTR(err);
1481 }
1482 
1483 struct xe_bo *
1484 xe_bo_create_locked_range(struct xe_device *xe,
1485 			  struct xe_tile *tile, struct xe_vm *vm,
1486 			  size_t size, u64 start, u64 end,
1487 			  enum ttm_bo_type type, u32 flags)
1488 {
1489 	return __xe_bo_create_locked(xe, tile, vm, size, start, end, 0, type, flags);
1490 }
1491 
1492 struct xe_bo *xe_bo_create_locked(struct xe_device *xe, struct xe_tile *tile,
1493 				  struct xe_vm *vm, size_t size,
1494 				  enum ttm_bo_type type, u32 flags)
1495 {
1496 	return __xe_bo_create_locked(xe, tile, vm, size, 0, ~0ULL, 0, type, flags);
1497 }
1498 
1499 struct xe_bo *xe_bo_create_user(struct xe_device *xe, struct xe_tile *tile,
1500 				struct xe_vm *vm, size_t size,
1501 				u16 cpu_caching,
1502 				u32 flags)
1503 {
1504 	struct xe_bo *bo = __xe_bo_create_locked(xe, tile, vm, size, 0, ~0ULL,
1505 						 cpu_caching, ttm_bo_type_device,
1506 						 flags | XE_BO_FLAG_USER);
1507 	if (!IS_ERR(bo))
1508 		xe_bo_unlock_vm_held(bo);
1509 
1510 	return bo;
1511 }
1512 
1513 struct xe_bo *xe_bo_create(struct xe_device *xe, struct xe_tile *tile,
1514 			   struct xe_vm *vm, size_t size,
1515 			   enum ttm_bo_type type, u32 flags)
1516 {
1517 	struct xe_bo *bo = xe_bo_create_locked(xe, tile, vm, size, type, flags);
1518 
1519 	if (!IS_ERR(bo))
1520 		xe_bo_unlock_vm_held(bo);
1521 
1522 	return bo;
1523 }
1524 
1525 struct xe_bo *xe_bo_create_pin_map_at(struct xe_device *xe, struct xe_tile *tile,
1526 				      struct xe_vm *vm,
1527 				      size_t size, u64 offset,
1528 				      enum ttm_bo_type type, u32 flags)
1529 {
1530 	struct xe_bo *bo;
1531 	int err;
1532 	u64 start = offset == ~0ull ? 0 : offset;
1533 	u64 end = offset == ~0ull ? offset : start + size;
1534 
1535 	if (flags & XE_BO_FLAG_STOLEN &&
1536 	    xe_ttm_stolen_cpu_access_needs_ggtt(xe))
1537 		flags |= XE_BO_FLAG_GGTT;
1538 
1539 	bo = xe_bo_create_locked_range(xe, tile, vm, size, start, end, type,
1540 				       flags | XE_BO_FLAG_NEEDS_CPU_ACCESS);
1541 	if (IS_ERR(bo))
1542 		return bo;
1543 
1544 	err = xe_bo_pin(bo);
1545 	if (err)
1546 		goto err_put;
1547 
1548 	err = xe_bo_vmap(bo);
1549 	if (err)
1550 		goto err_unpin;
1551 
1552 	xe_bo_unlock_vm_held(bo);
1553 
1554 	return bo;
1555 
1556 err_unpin:
1557 	xe_bo_unpin(bo);
1558 err_put:
1559 	xe_bo_unlock_vm_held(bo);
1560 	xe_bo_put(bo);
1561 	return ERR_PTR(err);
1562 }
1563 
1564 struct xe_bo *xe_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
1565 				   struct xe_vm *vm, size_t size,
1566 				   enum ttm_bo_type type, u32 flags)
1567 {
1568 	return xe_bo_create_pin_map_at(xe, tile, vm, size, ~0ull, type, flags);
1569 }
1570 
1571 struct xe_bo *xe_bo_create_from_data(struct xe_device *xe, struct xe_tile *tile,
1572 				     const void *data, size_t size,
1573 				     enum ttm_bo_type type, u32 flags)
1574 {
1575 	struct xe_bo *bo = xe_bo_create_pin_map(xe, tile, NULL,
1576 						ALIGN(size, PAGE_SIZE),
1577 						type, flags);
1578 	if (IS_ERR(bo))
1579 		return bo;
1580 
1581 	xe_map_memcpy_to(xe, &bo->vmap, 0, data, size);
1582 
1583 	return bo;
1584 }
1585 
1586 static void __xe_bo_unpin_map_no_vm(void *arg)
1587 {
1588 	xe_bo_unpin_map_no_vm(arg);
1589 }
1590 
1591 struct xe_bo *xe_managed_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
1592 					   size_t size, u32 flags)
1593 {
1594 	struct xe_bo *bo;
1595 	int ret;
1596 
1597 	bo = xe_bo_create_pin_map(xe, tile, NULL, size, ttm_bo_type_kernel, flags);
1598 	if (IS_ERR(bo))
1599 		return bo;
1600 
1601 	ret = devm_add_action_or_reset(xe->drm.dev, __xe_bo_unpin_map_no_vm, bo);
1602 	if (ret)
1603 		return ERR_PTR(ret);
1604 
1605 	return bo;
1606 }
1607 
1608 struct xe_bo *xe_managed_bo_create_from_data(struct xe_device *xe, struct xe_tile *tile,
1609 					     const void *data, size_t size, u32 flags)
1610 {
1611 	struct xe_bo *bo = xe_managed_bo_create_pin_map(xe, tile, ALIGN(size, PAGE_SIZE), flags);
1612 
1613 	if (IS_ERR(bo))
1614 		return bo;
1615 
1616 	xe_map_memcpy_to(xe, &bo->vmap, 0, data, size);
1617 
1618 	return bo;
1619 }
1620 
1621 /**
1622  * xe_managed_bo_reinit_in_vram
1623  * @xe: xe device
1624  * @tile: Tile where the new buffer will be created
1625  * @src: Managed buffer object allocated in system memory
1626  *
1627  * Replace a managed src buffer object allocated in system memory with a new
1628  * one allocated in vram, copying the data between them.
1629  * Buffer object in VRAM is not going to have the same GGTT address, the caller
1630  * is responsible for making sure that any old references to it are updated.
1631  *
1632  * Returns 0 for success, negative error code otherwise.
1633  */
1634 int xe_managed_bo_reinit_in_vram(struct xe_device *xe, struct xe_tile *tile, struct xe_bo **src)
1635 {
1636 	struct xe_bo *bo;
1637 	u32 dst_flags = XE_BO_FLAG_VRAM_IF_DGFX(tile) | XE_BO_FLAG_GGTT;
1638 
1639 	dst_flags |= (*src)->flags & XE_BO_FLAG_GGTT_INVALIDATE;
1640 
1641 	xe_assert(xe, IS_DGFX(xe));
1642 	xe_assert(xe, !(*src)->vmap.is_iomem);
1643 
1644 	bo = xe_managed_bo_create_from_data(xe, tile, (*src)->vmap.vaddr,
1645 					    (*src)->size, dst_flags);
1646 	if (IS_ERR(bo))
1647 		return PTR_ERR(bo);
1648 
1649 	devm_release_action(xe->drm.dev, __xe_bo_unpin_map_no_vm, *src);
1650 	*src = bo;
1651 
1652 	return 0;
1653 }
1654 
1655 /*
1656  * XXX: This is in the VM bind data path, likely should calculate this once and
1657  * store, with a recalculation if the BO is moved.
1658  */
1659 uint64_t vram_region_gpu_offset(struct ttm_resource *res)
1660 {
1661 	struct xe_device *xe = ttm_to_xe_device(res->bo->bdev);
1662 
1663 	if (res->mem_type == XE_PL_STOLEN)
1664 		return xe_ttm_stolen_gpu_offset(xe);
1665 
1666 	return res_to_mem_region(res)->dpa_base;
1667 }
1668 
1669 /**
1670  * xe_bo_pin_external - pin an external BO
1671  * @bo: buffer object to be pinned
1672  *
1673  * Pin an external (not tied to a VM, can be exported via dma-buf / prime FD)
1674  * BO. Unique call compared to xe_bo_pin as this function has it own set of
1675  * asserts and code to ensure evict / restore on suspend / resume.
1676  *
1677  * Returns 0 for success, negative error code otherwise.
1678  */
1679 int xe_bo_pin_external(struct xe_bo *bo)
1680 {
1681 	struct xe_device *xe = xe_bo_device(bo);
1682 	int err;
1683 
1684 	xe_assert(xe, !bo->vm);
1685 	xe_assert(xe, xe_bo_is_user(bo));
1686 
1687 	if (!xe_bo_is_pinned(bo)) {
1688 		err = xe_bo_validate(bo, NULL, false);
1689 		if (err)
1690 			return err;
1691 
1692 		if (xe_bo_is_vram(bo)) {
1693 			spin_lock(&xe->pinned.lock);
1694 			list_add_tail(&bo->pinned_link,
1695 				      &xe->pinned.external_vram);
1696 			spin_unlock(&xe->pinned.lock);
1697 		}
1698 	}
1699 
1700 	ttm_bo_pin(&bo->ttm);
1701 
1702 	/*
1703 	 * FIXME: If we always use the reserve / unreserve functions for locking
1704 	 * we do not need this.
1705 	 */
1706 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
1707 
1708 	return 0;
1709 }
1710 
1711 int xe_bo_pin(struct xe_bo *bo)
1712 {
1713 	struct xe_device *xe = xe_bo_device(bo);
1714 	int err;
1715 
1716 	/* We currently don't expect user BO to be pinned */
1717 	xe_assert(xe, !xe_bo_is_user(bo));
1718 
1719 	/* Pinned object must be in GGTT or have pinned flag */
1720 	xe_assert(xe, bo->flags & (XE_BO_FLAG_PINNED |
1721 				   XE_BO_FLAG_GGTT));
1722 
1723 	/*
1724 	 * No reason we can't support pinning imported dma-bufs we just don't
1725 	 * expect to pin an imported dma-buf.
1726 	 */
1727 	xe_assert(xe, !bo->ttm.base.import_attach);
1728 
1729 	/* We only expect at most 1 pin */
1730 	xe_assert(xe, !xe_bo_is_pinned(bo));
1731 
1732 	err = xe_bo_validate(bo, NULL, false);
1733 	if (err)
1734 		return err;
1735 
1736 	/*
1737 	 * For pinned objects in on DGFX, which are also in vram, we expect
1738 	 * these to be in contiguous VRAM memory. Required eviction / restore
1739 	 * during suspend / resume (force restore to same physical address).
1740 	 */
1741 	if (IS_DGFX(xe) && !(IS_ENABLED(CONFIG_DRM_XE_DEBUG) &&
1742 	    bo->flags & XE_BO_FLAG_INTERNAL_TEST)) {
1743 		struct ttm_place *place = &(bo->placements[0]);
1744 
1745 		if (mem_type_is_vram(place->mem_type)) {
1746 			xe_assert(xe, place->flags & TTM_PL_FLAG_CONTIGUOUS);
1747 
1748 			place->fpfn = (xe_bo_addr(bo, 0, PAGE_SIZE) -
1749 				       vram_region_gpu_offset(bo->ttm.resource)) >> PAGE_SHIFT;
1750 			place->lpfn = place->fpfn + (bo->size >> PAGE_SHIFT);
1751 
1752 			spin_lock(&xe->pinned.lock);
1753 			list_add_tail(&bo->pinned_link, &xe->pinned.kernel_bo_present);
1754 			spin_unlock(&xe->pinned.lock);
1755 		}
1756 	}
1757 
1758 	ttm_bo_pin(&bo->ttm);
1759 
1760 	/*
1761 	 * FIXME: If we always use the reserve / unreserve functions for locking
1762 	 * we do not need this.
1763 	 */
1764 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
1765 
1766 	return 0;
1767 }
1768 
1769 /**
1770  * xe_bo_unpin_external - unpin an external BO
1771  * @bo: buffer object to be unpinned
1772  *
1773  * Unpin an external (not tied to a VM, can be exported via dma-buf / prime FD)
1774  * BO. Unique call compared to xe_bo_unpin as this function has it own set of
1775  * asserts and code to ensure evict / restore on suspend / resume.
1776  *
1777  * Returns 0 for success, negative error code otherwise.
1778  */
1779 void xe_bo_unpin_external(struct xe_bo *bo)
1780 {
1781 	struct xe_device *xe = xe_bo_device(bo);
1782 
1783 	xe_assert(xe, !bo->vm);
1784 	xe_assert(xe, xe_bo_is_pinned(bo));
1785 	xe_assert(xe, xe_bo_is_user(bo));
1786 
1787 	spin_lock(&xe->pinned.lock);
1788 	if (bo->ttm.pin_count == 1 && !list_empty(&bo->pinned_link))
1789 		list_del_init(&bo->pinned_link);
1790 	spin_unlock(&xe->pinned.lock);
1791 
1792 	ttm_bo_unpin(&bo->ttm);
1793 
1794 	/*
1795 	 * FIXME: If we always use the reserve / unreserve functions for locking
1796 	 * we do not need this.
1797 	 */
1798 	ttm_bo_move_to_lru_tail_unlocked(&bo->ttm);
1799 }
1800 
1801 void xe_bo_unpin(struct xe_bo *bo)
1802 {
1803 	struct xe_device *xe = xe_bo_device(bo);
1804 
1805 	xe_assert(xe, !bo->ttm.base.import_attach);
1806 	xe_assert(xe, xe_bo_is_pinned(bo));
1807 
1808 	if (IS_DGFX(xe) && !(IS_ENABLED(CONFIG_DRM_XE_DEBUG) &&
1809 	    bo->flags & XE_BO_FLAG_INTERNAL_TEST)) {
1810 		struct ttm_place *place = &(bo->placements[0]);
1811 
1812 		if (mem_type_is_vram(place->mem_type)) {
1813 			spin_lock(&xe->pinned.lock);
1814 			xe_assert(xe, !list_empty(&bo->pinned_link));
1815 			list_del_init(&bo->pinned_link);
1816 			spin_unlock(&xe->pinned.lock);
1817 		}
1818 	}
1819 
1820 	ttm_bo_unpin(&bo->ttm);
1821 }
1822 
1823 /**
1824  * xe_bo_validate() - Make sure the bo is in an allowed placement
1825  * @bo: The bo,
1826  * @vm: Pointer to a the vm the bo shares a locked dma_resv object with, or
1827  *      NULL. Used together with @allow_res_evict.
1828  * @allow_res_evict: Whether it's allowed to evict bos sharing @vm's
1829  *                   reservation object.
1830  *
1831  * Make sure the bo is in allowed placement, migrating it if necessary. If
1832  * needed, other bos will be evicted. If bos selected for eviction shares
1833  * the @vm's reservation object, they can be evicted iff @allow_res_evict is
1834  * set to true, otherwise they will be bypassed.
1835  *
1836  * Return: 0 on success, negative error code on failure. May return
1837  * -EINTR or -ERESTARTSYS if internal waits are interrupted by a signal.
1838  */
1839 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict)
1840 {
1841 	struct ttm_operation_ctx ctx = {
1842 		.interruptible = true,
1843 		.no_wait_gpu = false,
1844 	};
1845 
1846 	if (vm) {
1847 		lockdep_assert_held(&vm->lock);
1848 		xe_vm_assert_held(vm);
1849 
1850 		ctx.allow_res_evict = allow_res_evict;
1851 		ctx.resv = xe_vm_resv(vm);
1852 	}
1853 
1854 	return ttm_bo_validate(&bo->ttm, &bo->placement, &ctx);
1855 }
1856 
1857 bool xe_bo_is_xe_bo(struct ttm_buffer_object *bo)
1858 {
1859 	if (bo->destroy == &xe_ttm_bo_destroy)
1860 		return true;
1861 
1862 	return false;
1863 }
1864 
1865 /*
1866  * Resolve a BO address. There is no assert to check if the proper lock is held
1867  * so it should only be used in cases where it is not fatal to get the wrong
1868  * address, such as printing debug information, but not in cases where memory is
1869  * written based on this result.
1870  */
1871 dma_addr_t __xe_bo_addr(struct xe_bo *bo, u64 offset, size_t page_size)
1872 {
1873 	struct xe_device *xe = xe_bo_device(bo);
1874 	struct xe_res_cursor cur;
1875 	u64 page;
1876 
1877 	xe_assert(xe, page_size <= PAGE_SIZE);
1878 	page = offset >> PAGE_SHIFT;
1879 	offset &= (PAGE_SIZE - 1);
1880 
1881 	if (!xe_bo_is_vram(bo) && !xe_bo_is_stolen(bo)) {
1882 		xe_assert(xe, bo->ttm.ttm);
1883 
1884 		xe_res_first_sg(xe_bo_sg(bo), page << PAGE_SHIFT,
1885 				page_size, &cur);
1886 		return xe_res_dma(&cur) + offset;
1887 	} else {
1888 		struct xe_res_cursor cur;
1889 
1890 		xe_res_first(bo->ttm.resource, page << PAGE_SHIFT,
1891 			     page_size, &cur);
1892 		return cur.start + offset + vram_region_gpu_offset(bo->ttm.resource);
1893 	}
1894 }
1895 
1896 dma_addr_t xe_bo_addr(struct xe_bo *bo, u64 offset, size_t page_size)
1897 {
1898 	if (!READ_ONCE(bo->ttm.pin_count))
1899 		xe_bo_assert_held(bo);
1900 	return __xe_bo_addr(bo, offset, page_size);
1901 }
1902 
1903 int xe_bo_vmap(struct xe_bo *bo)
1904 {
1905 	void *virtual;
1906 	bool is_iomem;
1907 	int ret;
1908 
1909 	xe_bo_assert_held(bo);
1910 
1911 	if (!(bo->flags & XE_BO_FLAG_NEEDS_CPU_ACCESS))
1912 		return -EINVAL;
1913 
1914 	if (!iosys_map_is_null(&bo->vmap))
1915 		return 0;
1916 
1917 	/*
1918 	 * We use this more or less deprecated interface for now since
1919 	 * ttm_bo_vmap() doesn't offer the optimization of kmapping
1920 	 * single page bos, which is done here.
1921 	 * TODO: Fix up ttm_bo_vmap to do that, or fix up ttm_bo_kmap
1922 	 * to use struct iosys_map.
1923 	 */
1924 	ret = ttm_bo_kmap(&bo->ttm, 0, bo->size >> PAGE_SHIFT, &bo->kmap);
1925 	if (ret)
1926 		return ret;
1927 
1928 	virtual = ttm_kmap_obj_virtual(&bo->kmap, &is_iomem);
1929 	if (is_iomem)
1930 		iosys_map_set_vaddr_iomem(&bo->vmap, (void __iomem *)virtual);
1931 	else
1932 		iosys_map_set_vaddr(&bo->vmap, virtual);
1933 
1934 	return 0;
1935 }
1936 
1937 static void __xe_bo_vunmap(struct xe_bo *bo)
1938 {
1939 	if (!iosys_map_is_null(&bo->vmap)) {
1940 		iosys_map_clear(&bo->vmap);
1941 		ttm_bo_kunmap(&bo->kmap);
1942 	}
1943 }
1944 
1945 void xe_bo_vunmap(struct xe_bo *bo)
1946 {
1947 	xe_bo_assert_held(bo);
1948 	__xe_bo_vunmap(bo);
1949 }
1950 
1951 int xe_gem_create_ioctl(struct drm_device *dev, void *data,
1952 			struct drm_file *file)
1953 {
1954 	struct xe_device *xe = to_xe_device(dev);
1955 	struct xe_file *xef = to_xe_file(file);
1956 	struct drm_xe_gem_create *args = data;
1957 	struct xe_vm *vm = NULL;
1958 	struct xe_bo *bo;
1959 	unsigned int bo_flags;
1960 	u32 handle;
1961 	int err;
1962 
1963 	if (XE_IOCTL_DBG(xe, args->extensions) ||
1964 	    XE_IOCTL_DBG(xe, args->pad[0] || args->pad[1] || args->pad[2]) ||
1965 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
1966 		return -EINVAL;
1967 
1968 	/* at least one valid memory placement must be specified */
1969 	if (XE_IOCTL_DBG(xe, (args->placement & ~xe->info.mem_region_mask) ||
1970 			 !args->placement))
1971 		return -EINVAL;
1972 
1973 	if (XE_IOCTL_DBG(xe, args->flags &
1974 			 ~(DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING |
1975 			   DRM_XE_GEM_CREATE_FLAG_SCANOUT |
1976 			   DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM)))
1977 		return -EINVAL;
1978 
1979 	if (XE_IOCTL_DBG(xe, args->handle))
1980 		return -EINVAL;
1981 
1982 	if (XE_IOCTL_DBG(xe, !args->size))
1983 		return -EINVAL;
1984 
1985 	if (XE_IOCTL_DBG(xe, args->size > SIZE_MAX))
1986 		return -EINVAL;
1987 
1988 	if (XE_IOCTL_DBG(xe, args->size & ~PAGE_MASK))
1989 		return -EINVAL;
1990 
1991 	bo_flags = 0;
1992 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING)
1993 		bo_flags |= XE_BO_FLAG_DEFER_BACKING;
1994 
1995 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_SCANOUT)
1996 		bo_flags |= XE_BO_FLAG_SCANOUT;
1997 
1998 	bo_flags |= args->placement << (ffs(XE_BO_FLAG_SYSTEM) - 1);
1999 
2000 	/* CCS formats need physical placement at a 64K alignment in VRAM. */
2001 	if ((bo_flags & XE_BO_FLAG_VRAM_MASK) &&
2002 	    (bo_flags & XE_BO_FLAG_SCANOUT) &&
2003 	    !(xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K) &&
2004 	    IS_ALIGNED(args->size, SZ_64K))
2005 		bo_flags |= XE_BO_FLAG_NEEDS_64K;
2006 
2007 	if (args->flags & DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM) {
2008 		if (XE_IOCTL_DBG(xe, !(bo_flags & XE_BO_FLAG_VRAM_MASK)))
2009 			return -EINVAL;
2010 
2011 		bo_flags |= XE_BO_FLAG_NEEDS_CPU_ACCESS;
2012 	}
2013 
2014 	if (XE_IOCTL_DBG(xe, !args->cpu_caching ||
2015 			 args->cpu_caching > DRM_XE_GEM_CPU_CACHING_WC))
2016 		return -EINVAL;
2017 
2018 	if (XE_IOCTL_DBG(xe, bo_flags & XE_BO_FLAG_VRAM_MASK &&
2019 			 args->cpu_caching != DRM_XE_GEM_CPU_CACHING_WC))
2020 		return -EINVAL;
2021 
2022 	if (XE_IOCTL_DBG(xe, bo_flags & XE_BO_FLAG_SCANOUT &&
2023 			 args->cpu_caching == DRM_XE_GEM_CPU_CACHING_WB))
2024 		return -EINVAL;
2025 
2026 	if (args->vm_id) {
2027 		vm = xe_vm_lookup(xef, args->vm_id);
2028 		if (XE_IOCTL_DBG(xe, !vm))
2029 			return -ENOENT;
2030 		err = xe_vm_lock(vm, true);
2031 		if (err)
2032 			goto out_vm;
2033 	}
2034 
2035 	bo = xe_bo_create_user(xe, NULL, vm, args->size, args->cpu_caching,
2036 			       bo_flags);
2037 
2038 	if (vm)
2039 		xe_vm_unlock(vm);
2040 
2041 	if (IS_ERR(bo)) {
2042 		err = PTR_ERR(bo);
2043 		goto out_vm;
2044 	}
2045 
2046 	err = drm_gem_handle_create(file, &bo->ttm.base, &handle);
2047 	if (err)
2048 		goto out_bulk;
2049 
2050 	args->handle = handle;
2051 	goto out_put;
2052 
2053 out_bulk:
2054 	if (vm && !xe_vm_in_fault_mode(vm)) {
2055 		xe_vm_lock(vm, false);
2056 		__xe_bo_unset_bulk_move(bo);
2057 		xe_vm_unlock(vm);
2058 	}
2059 out_put:
2060 	xe_bo_put(bo);
2061 out_vm:
2062 	if (vm)
2063 		xe_vm_put(vm);
2064 
2065 	return err;
2066 }
2067 
2068 int xe_gem_mmap_offset_ioctl(struct drm_device *dev, void *data,
2069 			     struct drm_file *file)
2070 {
2071 	struct xe_device *xe = to_xe_device(dev);
2072 	struct drm_xe_gem_mmap_offset *args = data;
2073 	struct drm_gem_object *gem_obj;
2074 
2075 	if (XE_IOCTL_DBG(xe, args->extensions) ||
2076 	    XE_IOCTL_DBG(xe, args->reserved[0] || args->reserved[1]))
2077 		return -EINVAL;
2078 
2079 	if (XE_IOCTL_DBG(xe, args->flags))
2080 		return -EINVAL;
2081 
2082 	gem_obj = drm_gem_object_lookup(file, args->handle);
2083 	if (XE_IOCTL_DBG(xe, !gem_obj))
2084 		return -ENOENT;
2085 
2086 	/* The mmap offset was set up at BO allocation time. */
2087 	args->offset = drm_vma_node_offset_addr(&gem_obj->vma_node);
2088 
2089 	xe_bo_put(gem_to_xe_bo(gem_obj));
2090 	return 0;
2091 }
2092 
2093 /**
2094  * xe_bo_lock() - Lock the buffer object's dma_resv object
2095  * @bo: The struct xe_bo whose lock is to be taken
2096  * @intr: Whether to perform any wait interruptible
2097  *
2098  * Locks the buffer object's dma_resv object. If the buffer object is
2099  * pointing to a shared dma_resv object, that shared lock is locked.
2100  *
2101  * Return: 0 on success, -EINTR if @intr is true and the wait for a
2102  * contended lock was interrupted. If @intr is set to false, the
2103  * function always returns 0.
2104  */
2105 int xe_bo_lock(struct xe_bo *bo, bool intr)
2106 {
2107 	if (intr)
2108 		return dma_resv_lock_interruptible(bo->ttm.base.resv, NULL);
2109 
2110 	dma_resv_lock(bo->ttm.base.resv, NULL);
2111 
2112 	return 0;
2113 }
2114 
2115 /**
2116  * xe_bo_unlock() - Unlock the buffer object's dma_resv object
2117  * @bo: The struct xe_bo whose lock is to be released.
2118  *
2119  * Unlock a buffer object lock that was locked by xe_bo_lock().
2120  */
2121 void xe_bo_unlock(struct xe_bo *bo)
2122 {
2123 	dma_resv_unlock(bo->ttm.base.resv);
2124 }
2125 
2126 /**
2127  * xe_bo_can_migrate - Whether a buffer object likely can be migrated
2128  * @bo: The buffer object to migrate
2129  * @mem_type: The TTM memory type intended to migrate to
2130  *
2131  * Check whether the buffer object supports migration to the
2132  * given memory type. Note that pinning may affect the ability to migrate as
2133  * returned by this function.
2134  *
2135  * This function is primarily intended as a helper for checking the
2136  * possibility to migrate buffer objects and can be called without
2137  * the object lock held.
2138  *
2139  * Return: true if migration is possible, false otherwise.
2140  */
2141 bool xe_bo_can_migrate(struct xe_bo *bo, u32 mem_type)
2142 {
2143 	unsigned int cur_place;
2144 
2145 	if (bo->ttm.type == ttm_bo_type_kernel)
2146 		return true;
2147 
2148 	if (bo->ttm.type == ttm_bo_type_sg)
2149 		return false;
2150 
2151 	for (cur_place = 0; cur_place < bo->placement.num_placement;
2152 	     cur_place++) {
2153 		if (bo->placements[cur_place].mem_type == mem_type)
2154 			return true;
2155 	}
2156 
2157 	return false;
2158 }
2159 
2160 static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place)
2161 {
2162 	memset(place, 0, sizeof(*place));
2163 	place->mem_type = mem_type;
2164 }
2165 
2166 /**
2167  * xe_bo_migrate - Migrate an object to the desired region id
2168  * @bo: The buffer object to migrate.
2169  * @mem_type: The TTM region type to migrate to.
2170  *
2171  * Attempt to migrate the buffer object to the desired memory region. The
2172  * buffer object may not be pinned, and must be locked.
2173  * On successful completion, the object memory type will be updated,
2174  * but an async migration task may not have completed yet, and to
2175  * accomplish that, the object's kernel fences must be signaled with
2176  * the object lock held.
2177  *
2178  * Return: 0 on success. Negative error code on failure. In particular may
2179  * return -EINTR or -ERESTARTSYS if signal pending.
2180  */
2181 int xe_bo_migrate(struct xe_bo *bo, u32 mem_type)
2182 {
2183 	struct xe_device *xe = ttm_to_xe_device(bo->ttm.bdev);
2184 	struct ttm_operation_ctx ctx = {
2185 		.interruptible = true,
2186 		.no_wait_gpu = false,
2187 	};
2188 	struct ttm_placement placement;
2189 	struct ttm_place requested;
2190 
2191 	xe_bo_assert_held(bo);
2192 
2193 	if (bo->ttm.resource->mem_type == mem_type)
2194 		return 0;
2195 
2196 	if (xe_bo_is_pinned(bo))
2197 		return -EBUSY;
2198 
2199 	if (!xe_bo_can_migrate(bo, mem_type))
2200 		return -EINVAL;
2201 
2202 	xe_place_from_ttm_type(mem_type, &requested);
2203 	placement.num_placement = 1;
2204 	placement.placement = &requested;
2205 
2206 	/*
2207 	 * Stolen needs to be handled like below VRAM handling if we ever need
2208 	 * to support it.
2209 	 */
2210 	drm_WARN_ON(&xe->drm, mem_type == XE_PL_STOLEN);
2211 
2212 	if (mem_type_is_vram(mem_type)) {
2213 		u32 c = 0;
2214 
2215 		add_vram(xe, bo, &requested, bo->flags, mem_type, &c);
2216 	}
2217 
2218 	return ttm_bo_validate(&bo->ttm, &placement, &ctx);
2219 }
2220 
2221 /**
2222  * xe_bo_evict - Evict an object to evict placement
2223  * @bo: The buffer object to migrate.
2224  * @force_alloc: Set force_alloc in ttm_operation_ctx
2225  *
2226  * On successful completion, the object memory will be moved to evict
2227  * placement. Ths function blocks until the object has been fully moved.
2228  *
2229  * Return: 0 on success. Negative error code on failure.
2230  */
2231 int xe_bo_evict(struct xe_bo *bo, bool force_alloc)
2232 {
2233 	struct ttm_operation_ctx ctx = {
2234 		.interruptible = false,
2235 		.no_wait_gpu = false,
2236 		.force_alloc = force_alloc,
2237 	};
2238 	struct ttm_placement placement;
2239 	int ret;
2240 
2241 	xe_evict_flags(&bo->ttm, &placement);
2242 	ret = ttm_bo_validate(&bo->ttm, &placement, &ctx);
2243 	if (ret)
2244 		return ret;
2245 
2246 	dma_resv_wait_timeout(bo->ttm.base.resv, DMA_RESV_USAGE_KERNEL,
2247 			      false, MAX_SCHEDULE_TIMEOUT);
2248 
2249 	return 0;
2250 }
2251 
2252 /**
2253  * xe_bo_needs_ccs_pages - Whether a bo needs to back up CCS pages when
2254  * placed in system memory.
2255  * @bo: The xe_bo
2256  *
2257  * Return: true if extra pages need to be allocated, false otherwise.
2258  */
2259 bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
2260 {
2261 	struct xe_device *xe = xe_bo_device(bo);
2262 
2263 	if (GRAPHICS_VER(xe) >= 20 && IS_DGFX(xe))
2264 		return false;
2265 
2266 	if (!xe_device_has_flat_ccs(xe) || bo->ttm.type != ttm_bo_type_device)
2267 		return false;
2268 
2269 	/* On discrete GPUs, if the GPU can access this buffer from
2270 	 * system memory (i.e., it allows XE_PL_TT placement), FlatCCS
2271 	 * can't be used since there's no CCS storage associated with
2272 	 * non-VRAM addresses.
2273 	 */
2274 	if (IS_DGFX(xe) && (bo->flags & XE_BO_FLAG_SYSTEM))
2275 		return false;
2276 
2277 	return true;
2278 }
2279 
2280 /**
2281  * __xe_bo_release_dummy() - Dummy kref release function
2282  * @kref: The embedded struct kref.
2283  *
2284  * Dummy release function for xe_bo_put_deferred(). Keep off.
2285  */
2286 void __xe_bo_release_dummy(struct kref *kref)
2287 {
2288 }
2289 
2290 /**
2291  * xe_bo_put_commit() - Put bos whose put was deferred by xe_bo_put_deferred().
2292  * @deferred: The lockless list used for the call to xe_bo_put_deferred().
2293  *
2294  * Puts all bos whose put was deferred by xe_bo_put_deferred().
2295  * The @deferred list can be either an onstack local list or a global
2296  * shared list used by a workqueue.
2297  */
2298 void xe_bo_put_commit(struct llist_head *deferred)
2299 {
2300 	struct llist_node *freed;
2301 	struct xe_bo *bo, *next;
2302 
2303 	if (!deferred)
2304 		return;
2305 
2306 	freed = llist_del_all(deferred);
2307 	if (!freed)
2308 		return;
2309 
2310 	llist_for_each_entry_safe(bo, next, freed, freed)
2311 		drm_gem_object_free(&bo->ttm.base.refcount);
2312 }
2313 
2314 /**
2315  * xe_bo_dumb_create - Create a dumb bo as backing for a fb
2316  * @file_priv: ...
2317  * @dev: ...
2318  * @args: ...
2319  *
2320  * See dumb_create() hook in include/drm/drm_drv.h
2321  *
2322  * Return: ...
2323  */
2324 int xe_bo_dumb_create(struct drm_file *file_priv,
2325 		      struct drm_device *dev,
2326 		      struct drm_mode_create_dumb *args)
2327 {
2328 	struct xe_device *xe = to_xe_device(dev);
2329 	struct xe_bo *bo;
2330 	uint32_t handle;
2331 	int cpp = DIV_ROUND_UP(args->bpp, 8);
2332 	int err;
2333 	u32 page_size = max_t(u32, PAGE_SIZE,
2334 		xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K ? SZ_64K : SZ_4K);
2335 
2336 	args->pitch = ALIGN(args->width * cpp, 64);
2337 	args->size = ALIGN(mul_u32_u32(args->pitch, args->height),
2338 			   page_size);
2339 
2340 	bo = xe_bo_create_user(xe, NULL, NULL, args->size,
2341 			       DRM_XE_GEM_CPU_CACHING_WC,
2342 			       XE_BO_FLAG_VRAM_IF_DGFX(xe_device_get_root_tile(xe)) |
2343 			       XE_BO_FLAG_SCANOUT |
2344 			       XE_BO_FLAG_NEEDS_CPU_ACCESS);
2345 	if (IS_ERR(bo))
2346 		return PTR_ERR(bo);
2347 
2348 	err = drm_gem_handle_create(file_priv, &bo->ttm.base, &handle);
2349 	/* drop reference from allocate - handle holds it now */
2350 	drm_gem_object_put(&bo->ttm.base);
2351 	if (!err)
2352 		args->handle = handle;
2353 	return err;
2354 }
2355 
2356 void xe_bo_runtime_pm_release_mmap_offset(struct xe_bo *bo)
2357 {
2358 	struct ttm_buffer_object *tbo = &bo->ttm;
2359 	struct ttm_device *bdev = tbo->bdev;
2360 
2361 	drm_vma_node_unmap(&tbo->base.vma_node, bdev->dev_mapping);
2362 
2363 	list_del_init(&bo->vram_userfault_link);
2364 }
2365 
2366 #if IS_ENABLED(CONFIG_DRM_XE_KUNIT_TEST)
2367 #include "tests/xe_bo.c"
2368 #endif
2369