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