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