xref: /openbsd/sys/dev/pci/drm/i915/gem/i915_gem_ttm.c (revision 55570727)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2021 Intel Corporation
4  */
5 
6 #include <linux/shmem_fs.h>
7 
8 #include <drm/ttm/ttm_placement.h>
9 #include <drm/ttm/ttm_tt.h>
10 #include <drm/drm_buddy.h>
11 
12 #include "i915_drv.h"
13 #include "i915_ttm_buddy_manager.h"
14 #include "intel_memory_region.h"
15 #include "intel_region_ttm.h"
16 
17 #include "gem/i915_gem_mman.h"
18 #include "gem/i915_gem_object.h"
19 #include "gem/i915_gem_region.h"
20 #include "gem/i915_gem_ttm.h"
21 #include "gem/i915_gem_ttm_move.h"
22 #include "gem/i915_gem_ttm_pm.h"
23 #include "gt/intel_gpu_commands.h"
24 
25 #define I915_TTM_PRIO_PURGE     0
26 #define I915_TTM_PRIO_NO_PAGES  1
27 #define I915_TTM_PRIO_HAS_PAGES 2
28 #define I915_TTM_PRIO_NEEDS_CPU_ACCESS 3
29 
30 /*
31  * Size of struct ttm_place vector in on-stack struct ttm_placement allocs
32  */
33 #define I915_TTM_MAX_PLACEMENTS INTEL_REGION_UNKNOWN
34 
35 /**
36  * struct i915_ttm_tt - TTM page vector with additional private information
37  * @ttm: The base TTM page vector.
38  * @dev: The struct device used for dma mapping and unmapping.
39  * @cached_rsgt: The cached scatter-gather table.
40  * @is_shmem: Set if using shmem.
41  * @filp: The shmem file, if using shmem backend.
42  *
43  * Note that DMA may be going on right up to the point where the page-
44  * vector is unpopulated in delayed destroy. Hence keep the
45  * scatter-gather table mapped and cached up to that point. This is
46  * different from the cached gem object io scatter-gather table which
47  * doesn't have an associated dma mapping.
48  */
49 struct i915_ttm_tt {
50 	struct ttm_tt ttm;
51 	struct device *dev;
52 	struct i915_refct_sgt cached_rsgt;
53 
54 	bool is_shmem;
55 	struct file *filp;
56 };
57 
58 static const struct ttm_place sys_placement_flags = {
59 	.fpfn = 0,
60 	.lpfn = 0,
61 	.mem_type = I915_PL_SYSTEM,
62 	.flags = 0,
63 };
64 
65 static struct ttm_placement i915_sys_placement = {
66 	.num_placement = 1,
67 	.placement = &sys_placement_flags,
68 	.num_busy_placement = 1,
69 	.busy_placement = &sys_placement_flags,
70 };
71 
72 /**
73  * i915_ttm_sys_placement - Return the struct ttm_placement to be
74  * used for an object in system memory.
75  *
76  * Rather than making the struct extern, use this
77  * function.
78  *
79  * Return: A pointer to a static variable for sys placement.
80  */
i915_ttm_sys_placement(void)81 struct ttm_placement *i915_ttm_sys_placement(void)
82 {
83 	return &i915_sys_placement;
84 }
85 
i915_ttm_err_to_gem(int err)86 static int i915_ttm_err_to_gem(int err)
87 {
88 	/* Fastpath */
89 	if (likely(!err))
90 		return 0;
91 
92 	switch (err) {
93 	case -EBUSY:
94 		/*
95 		 * TTM likes to convert -EDEADLK to -EBUSY, and wants us to
96 		 * restart the operation, since we don't record the contending
97 		 * lock. We use -EAGAIN to restart.
98 		 */
99 		return -EAGAIN;
100 	case -ENOSPC:
101 		/*
102 		 * Memory type / region is full, and we can't evict.
103 		 * Except possibly system, that returns -ENOMEM;
104 		 */
105 		return -ENXIO;
106 	default:
107 		break;
108 	}
109 
110 	return err;
111 }
112 
113 static enum ttm_caching
i915_ttm_select_tt_caching(const struct drm_i915_gem_object * obj)114 i915_ttm_select_tt_caching(const struct drm_i915_gem_object *obj)
115 {
116 	/*
117 	 * Objects only allowed in system get cached cpu-mappings, or when
118 	 * evicting lmem-only buffers to system for swapping. Other objects get
119 	 * WC mapping for now. Even if in system.
120 	 */
121 	if (obj->mm.n_placements <= 1)
122 		return ttm_cached;
123 
124 	return ttm_write_combined;
125 }
126 
127 static void
i915_ttm_place_from_region(const struct intel_memory_region * mr,struct ttm_place * place,resource_size_t offset,resource_size_t size,unsigned int flags)128 i915_ttm_place_from_region(const struct intel_memory_region *mr,
129 			   struct ttm_place *place,
130 			   resource_size_t offset,
131 			   resource_size_t size,
132 			   unsigned int flags)
133 {
134 	memset(place, 0, sizeof(*place));
135 	place->mem_type = intel_region_to_ttm_type(mr);
136 
137 	if (mr->type == INTEL_MEMORY_SYSTEM)
138 		return;
139 
140 	if (flags & I915_BO_ALLOC_CONTIGUOUS)
141 		place->flags |= TTM_PL_FLAG_CONTIGUOUS;
142 	if (offset != I915_BO_INVALID_OFFSET) {
143 		WARN_ON(overflows_type(offset >> PAGE_SHIFT, place->fpfn));
144 		place->fpfn = offset >> PAGE_SHIFT;
145 		WARN_ON(overflows_type(place->fpfn + (size >> PAGE_SHIFT), place->lpfn));
146 		place->lpfn = place->fpfn + (size >> PAGE_SHIFT);
147 	} else if (resource_size(&mr->io) && resource_size(&mr->io) < mr->total) {
148 		if (flags & I915_BO_ALLOC_GPU_ONLY) {
149 			place->flags |= TTM_PL_FLAG_TOPDOWN;
150 		} else {
151 			place->fpfn = 0;
152 			WARN_ON(overflows_type(resource_size(&mr->io) >> PAGE_SHIFT, place->lpfn));
153 			place->lpfn = resource_size(&mr->io) >> PAGE_SHIFT;
154 		}
155 	}
156 }
157 
158 static void
i915_ttm_placement_from_obj(const struct drm_i915_gem_object * obj,struct ttm_place * requested,struct ttm_place * busy,struct ttm_placement * placement)159 i915_ttm_placement_from_obj(const struct drm_i915_gem_object *obj,
160 			    struct ttm_place *requested,
161 			    struct ttm_place *busy,
162 			    struct ttm_placement *placement)
163 {
164 	unsigned int num_allowed = obj->mm.n_placements;
165 	unsigned int flags = obj->flags;
166 	unsigned int i;
167 
168 	placement->num_placement = 1;
169 	i915_ttm_place_from_region(num_allowed ? obj->mm.placements[0] :
170 				   obj->mm.region, requested, obj->bo_offset,
171 				   obj->base.size, flags);
172 
173 	/* Cache this on object? */
174 	placement->num_busy_placement = num_allowed;
175 	for (i = 0; i < placement->num_busy_placement; ++i)
176 		i915_ttm_place_from_region(obj->mm.placements[i], busy + i,
177 					   obj->bo_offset, obj->base.size, flags);
178 
179 	if (num_allowed == 0) {
180 		*busy = *requested;
181 		placement->num_busy_placement = 1;
182 	}
183 
184 	placement->placement = requested;
185 	placement->busy_placement = busy;
186 }
187 
i915_ttm_tt_shmem_populate(struct ttm_device * bdev,struct ttm_tt * ttm,struct ttm_operation_ctx * ctx)188 static int i915_ttm_tt_shmem_populate(struct ttm_device *bdev,
189 				      struct ttm_tt *ttm,
190 				      struct ttm_operation_ctx *ctx)
191 {
192 	STUB();
193 	return -ENOSYS;
194 #ifdef notyet
195 	struct drm_i915_private *i915 = container_of(bdev, typeof(*i915), bdev);
196 	struct intel_memory_region *mr = i915->mm.regions[INTEL_MEMORY_SYSTEM];
197 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
198 	const unsigned int max_segment = i915_sg_segment_size(i915->drm.dev);
199 	const size_t size = (size_t)ttm->num_pages << PAGE_SHIFT;
200 	struct file *filp = i915_tt->filp;
201 	struct sgt_iter sgt_iter;
202 	struct sg_table *st;
203 	struct vm_page *page;
204 	unsigned long i;
205 	int err;
206 
207 	if (!filp) {
208 		struct address_space *mapping;
209 		gfp_t mask;
210 
211 		filp = shmem_file_setup("i915-shmem-tt", size, VM_NORESERVE);
212 		if (IS_ERR(filp))
213 			return PTR_ERR(filp);
214 
215 		mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
216 
217 		mapping = filp->f_mapping;
218 		mapping_set_gfp_mask(mapping, mask);
219 		GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
220 
221 		i915_tt->filp = filp;
222 	}
223 
224 	st = &i915_tt->cached_rsgt.table;
225 	err = shmem_sg_alloc_table(i915, st, size, mr, filp->f_mapping,
226 				   max_segment);
227 	if (err)
228 		return err;
229 
230 	err = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL,
231 			      DMA_ATTR_SKIP_CPU_SYNC);
232 	if (err)
233 		goto err_free_st;
234 
235 	i = 0;
236 	for_each_sgt_page(page, sgt_iter, st)
237 		ttm->pages[i++] = page;
238 
239 	if (ttm->page_flags & TTM_TT_FLAG_SWAPPED)
240 		ttm->page_flags &= ~TTM_TT_FLAG_SWAPPED;
241 
242 	return 0;
243 
244 err_free_st:
245 	shmem_sg_free_table(st, filp->f_mapping, false, false);
246 
247 	return err;
248 #endif
249 }
250 
i915_ttm_tt_shmem_unpopulate(struct ttm_tt * ttm)251 static void i915_ttm_tt_shmem_unpopulate(struct ttm_tt *ttm)
252 {
253 	STUB();
254 #ifdef notyet
255 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
256 	bool backup = ttm->page_flags & TTM_TT_FLAG_SWAPPED;
257 	struct sg_table *st = &i915_tt->cached_rsgt.table;
258 
259 	shmem_sg_free_table(st, file_inode(i915_tt->filp)->i_mapping,
260 			    backup, backup);
261 #endif
262 }
263 
i915_ttm_tt_release(struct kref * ref)264 static void i915_ttm_tt_release(struct kref *ref)
265 {
266 	struct i915_ttm_tt *i915_tt =
267 		container_of(ref, typeof(*i915_tt), cached_rsgt.kref);
268 	struct sg_table *st = &i915_tt->cached_rsgt.table;
269 
270 	GEM_WARN_ON(st->sgl);
271 
272 	kfree(i915_tt);
273 }
274 
275 static const struct i915_refct_sgt_ops tt_rsgt_ops = {
276 	.release = i915_ttm_tt_release
277 };
278 
i915_ttm_tt_create(struct ttm_buffer_object * bo,uint32_t page_flags)279 static struct ttm_tt *i915_ttm_tt_create(struct ttm_buffer_object *bo,
280 					 uint32_t page_flags)
281 {
282 	struct drm_i915_private *i915 = container_of(bo->bdev, typeof(*i915),
283 						     bdev);
284 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
285 	unsigned long ccs_pages = 0;
286 	enum ttm_caching caching;
287 	struct i915_ttm_tt *i915_tt;
288 	int ret;
289 
290 	if (i915_ttm_is_ghost_object(bo))
291 		return NULL;
292 
293 	i915_tt = kzalloc(sizeof(*i915_tt), GFP_KERNEL);
294 	if (!i915_tt)
295 		return NULL;
296 
297 	if (obj->flags & I915_BO_ALLOC_CPU_CLEAR && (!bo->resource ||
298 	    ttm_manager_type(bo->bdev, bo->resource->mem_type)->use_tt))
299 		page_flags |= TTM_TT_FLAG_ZERO_ALLOC;
300 
301 	caching = i915_ttm_select_tt_caching(obj);
302 	if (i915_gem_object_is_shrinkable(obj) && caching == ttm_cached) {
303 		page_flags |= TTM_TT_FLAG_EXTERNAL |
304 			      TTM_TT_FLAG_EXTERNAL_MAPPABLE;
305 		i915_tt->is_shmem = true;
306 	}
307 
308 	if (i915_gem_object_needs_ccs_pages(obj))
309 		ccs_pages = DIV_ROUND_UP(DIV_ROUND_UP(bo->base.size,
310 						      NUM_BYTES_PER_CCS_BYTE),
311 					 PAGE_SIZE);
312 
313 	ret = ttm_tt_init(&i915_tt->ttm, bo, page_flags, caching, ccs_pages);
314 	if (ret)
315 		goto err_free;
316 
317 	__i915_refct_sgt_init(&i915_tt->cached_rsgt, bo->base.size,
318 			      &tt_rsgt_ops);
319 
320 	i915_tt->dev = obj->base.dev->dev;
321 
322 	return &i915_tt->ttm;
323 
324 err_free:
325 	kfree(i915_tt);
326 	return NULL;
327 }
328 
i915_ttm_tt_populate(struct ttm_device * bdev,struct ttm_tt * ttm,struct ttm_operation_ctx * ctx)329 static int i915_ttm_tt_populate(struct ttm_device *bdev,
330 				struct ttm_tt *ttm,
331 				struct ttm_operation_ctx *ctx)
332 {
333 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
334 
335 	if (i915_tt->is_shmem)
336 		return i915_ttm_tt_shmem_populate(bdev, ttm, ctx);
337 
338 	return ttm_pool_alloc(&bdev->pool, ttm, ctx);
339 }
340 
i915_ttm_tt_unpopulate(struct ttm_device * bdev,struct ttm_tt * ttm)341 static void i915_ttm_tt_unpopulate(struct ttm_device *bdev, struct ttm_tt *ttm)
342 {
343 	STUB();
344 #ifdef notyet
345 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
346 	struct sg_table *st = &i915_tt->cached_rsgt.table;
347 
348 	if (st->sgl)
349 		dma_unmap_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
350 
351 	if (i915_tt->is_shmem) {
352 		i915_ttm_tt_shmem_unpopulate(ttm);
353 	} else {
354 		sg_free_table(st);
355 		ttm_pool_free(&bdev->pool, ttm);
356 	}
357 #endif
358 }
359 
i915_ttm_tt_destroy(struct ttm_device * bdev,struct ttm_tt * ttm)360 static void i915_ttm_tt_destroy(struct ttm_device *bdev, struct ttm_tt *ttm)
361 {
362 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
363 
364 	if (i915_tt->filp)
365 		fput(i915_tt->filp);
366 
367 	ttm_tt_fini(ttm);
368 	i915_refct_sgt_put(&i915_tt->cached_rsgt);
369 }
370 
i915_ttm_eviction_valuable(struct ttm_buffer_object * bo,const struct ttm_place * place)371 static bool i915_ttm_eviction_valuable(struct ttm_buffer_object *bo,
372 				       const struct ttm_place *place)
373 {
374 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
375 
376 	if (i915_ttm_is_ghost_object(bo))
377 		return false;
378 
379 	/*
380 	 * EXTERNAL objects should never be swapped out by TTM, instead we need
381 	 * to handle that ourselves. TTM will already skip such objects for us,
382 	 * but we would like to avoid grabbing locks for no good reason.
383 	 */
384 	if (bo->ttm && bo->ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
385 		return false;
386 
387 	/* Will do for now. Our pinned objects are still on TTM's LRU lists */
388 	if (!i915_gem_object_evictable(obj))
389 		return false;
390 
391 	return ttm_bo_eviction_valuable(bo, place);
392 }
393 
i915_ttm_evict_flags(struct ttm_buffer_object * bo,struct ttm_placement * placement)394 static void i915_ttm_evict_flags(struct ttm_buffer_object *bo,
395 				 struct ttm_placement *placement)
396 {
397 	*placement = i915_sys_placement;
398 }
399 
400 /**
401  * i915_ttm_free_cached_io_rsgt - Free object cached LMEM information
402  * @obj: The GEM object
403  * This function frees any LMEM-related information that is cached on
404  * the object. For example the radix tree for fast page lookup and the
405  * cached refcounted sg-table
406  */
i915_ttm_free_cached_io_rsgt(struct drm_i915_gem_object * obj)407 void i915_ttm_free_cached_io_rsgt(struct drm_i915_gem_object *obj)
408 {
409 	struct radix_tree_iter iter;
410 	void __rcu **slot;
411 
412 	if (!obj->ttm.cached_io_rsgt)
413 		return;
414 
415 	rcu_read_lock();
416 	radix_tree_for_each_slot(slot, &obj->ttm.get_io_page.radix, &iter, 0)
417 		radix_tree_delete(&obj->ttm.get_io_page.radix, iter.index);
418 	rcu_read_unlock();
419 
420 	i915_refct_sgt_put(obj->ttm.cached_io_rsgt);
421 	obj->ttm.cached_io_rsgt = NULL;
422 }
423 
424 /**
425  * i915_ttm_purge - Clear an object of its memory
426  * @obj: The object
427  *
428  * This function is called to clear an object of it's memory when it is
429  * marked as not needed anymore.
430  *
431  * Return: 0 on success, negative error code on failure.
432  */
i915_ttm_purge(struct drm_i915_gem_object * obj)433 int i915_ttm_purge(struct drm_i915_gem_object *obj)
434 {
435 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
436 	struct i915_ttm_tt *i915_tt =
437 		container_of(bo->ttm, typeof(*i915_tt), ttm);
438 	struct ttm_operation_ctx ctx = {
439 		.interruptible = true,
440 		.no_wait_gpu = false,
441 	};
442 	struct ttm_placement place = {};
443 	int ret;
444 
445 	if (obj->mm.madv == __I915_MADV_PURGED)
446 		return 0;
447 
448 	ret = ttm_bo_validate(bo, &place, &ctx);
449 	if (ret)
450 		return ret;
451 
452 	if (bo->ttm && i915_tt->filp) {
453 		/*
454 		 * The below fput(which eventually calls shmem_truncate) might
455 		 * be delayed by worker, so when directly called to purge the
456 		 * pages(like by the shrinker) we should try to be more
457 		 * aggressive and release the pages immediately.
458 		 */
459 #ifdef __linux__
460 		shmem_truncate_range(file_inode(i915_tt->filp),
461 				     0, (loff_t)-1);
462 #else
463 		rw_enter(obj->base.uao->vmobjlock, RW_WRITE);
464 		obj->base.uao->pgops->pgo_flush(obj->base.uao, 0, obj->base.size,
465 		    PGO_ALLPAGES | PGO_FREE);
466 		rw_exit(obj->base.uao->vmobjlock);
467 #endif
468 		fput(fetch_and_zero(&i915_tt->filp));
469 	}
470 
471 	obj->write_domain = 0;
472 	obj->read_domains = 0;
473 	i915_ttm_adjust_gem_after_move(obj);
474 	i915_ttm_free_cached_io_rsgt(obj);
475 	obj->mm.madv = __I915_MADV_PURGED;
476 
477 	return 0;
478 }
479 
i915_ttm_shrink(struct drm_i915_gem_object * obj,unsigned int flags)480 static int i915_ttm_shrink(struct drm_i915_gem_object *obj, unsigned int flags)
481 {
482 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
483 	struct i915_ttm_tt *i915_tt =
484 		container_of(bo->ttm, typeof(*i915_tt), ttm);
485 	struct ttm_operation_ctx ctx = {
486 		.interruptible = true,
487 		.no_wait_gpu = flags & I915_GEM_OBJECT_SHRINK_NO_GPU_WAIT,
488 	};
489 	struct ttm_placement place = {};
490 	int ret;
491 
492 	if (!bo->ttm || i915_ttm_cpu_maps_iomem(bo->resource))
493 		return 0;
494 
495 	GEM_BUG_ON(!i915_tt->is_shmem);
496 
497 	if (!i915_tt->filp)
498 		return 0;
499 
500 	ret = ttm_bo_wait_ctx(bo, &ctx);
501 	if (ret)
502 		return ret;
503 
504 	switch (obj->mm.madv) {
505 	case I915_MADV_DONTNEED:
506 		return i915_ttm_purge(obj);
507 	case __I915_MADV_PURGED:
508 		return 0;
509 	}
510 
511 	if (bo->ttm->page_flags & TTM_TT_FLAG_SWAPPED)
512 		return 0;
513 
514 	bo->ttm->page_flags |= TTM_TT_FLAG_SWAPPED;
515 	ret = ttm_bo_validate(bo, &place, &ctx);
516 	if (ret) {
517 		bo->ttm->page_flags &= ~TTM_TT_FLAG_SWAPPED;
518 		return ret;
519 	}
520 
521 	if (flags & I915_GEM_OBJECT_SHRINK_WRITEBACK)
522 #ifdef notyet
523 		__shmem_writeback(obj->base.size, i915_tt->filp->f_mapping);
524 #else
525 		STUB();
526 #endif
527 
528 	return 0;
529 }
530 
i915_ttm_delete_mem_notify(struct ttm_buffer_object * bo)531 static void i915_ttm_delete_mem_notify(struct ttm_buffer_object *bo)
532 {
533 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
534 
535 	/*
536 	 * This gets called twice by ttm, so long as we have a ttm resource or
537 	 * ttm_tt then we can still safely call this. Due to pipeline-gutting,
538 	 * we maybe have NULL bo->resource, but in that case we should always
539 	 * have a ttm alive (like if the pages are swapped out).
540 	 */
541 	if ((bo->resource || bo->ttm) && !i915_ttm_is_ghost_object(bo)) {
542 		__i915_gem_object_pages_fini(obj);
543 		i915_ttm_free_cached_io_rsgt(obj);
544 	}
545 }
546 
i915_ttm_tt_get_st(struct ttm_tt * ttm)547 static struct i915_refct_sgt *i915_ttm_tt_get_st(struct ttm_tt *ttm)
548 {
549 	STUB();
550 	return ERR_PTR(-ENOSYS);
551 #ifdef notyet
552 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
553 	struct sg_table *st;
554 	int ret;
555 
556 	if (i915_tt->cached_rsgt.table.sgl)
557 		return i915_refct_sgt_get(&i915_tt->cached_rsgt);
558 
559 	st = &i915_tt->cached_rsgt.table;
560 	ret = sg_alloc_table_from_pages_segment(st,
561 			ttm->pages, ttm->num_pages,
562 			0, (unsigned long)ttm->num_pages << PAGE_SHIFT,
563 			i915_sg_segment_size(i915_tt->dev), GFP_KERNEL);
564 	if (ret) {
565 		st->sgl = NULL;
566 		return ERR_PTR(ret);
567 	}
568 
569 	ret = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
570 	if (ret) {
571 		sg_free_table(st);
572 		return ERR_PTR(ret);
573 	}
574 
575 	return i915_refct_sgt_get(&i915_tt->cached_rsgt);
576 #endif
577 }
578 
579 /**
580  * i915_ttm_resource_get_st - Get a refcounted sg-table pointing to the
581  * resource memory
582  * @obj: The GEM object used for sg-table caching
583  * @res: The struct ttm_resource for which an sg-table is requested.
584  *
585  * This function returns a refcounted sg-table representing the memory
586  * pointed to by @res. If @res is the object's current resource it may also
587  * cache the sg_table on the object or attempt to access an already cached
588  * sg-table. The refcounted sg-table needs to be put when no-longer in use.
589  *
590  * Return: A valid pointer to a struct i915_refct_sgt or error pointer on
591  * failure.
592  */
593 struct i915_refct_sgt *
i915_ttm_resource_get_st(struct drm_i915_gem_object * obj,struct ttm_resource * res)594 i915_ttm_resource_get_st(struct drm_i915_gem_object *obj,
595 			 struct ttm_resource *res)
596 {
597 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
598 	u32 page_alignment;
599 
600 	if (!i915_ttm_gtt_binds_lmem(res))
601 		return i915_ttm_tt_get_st(bo->ttm);
602 
603 	page_alignment = bo->page_alignment << PAGE_SHIFT;
604 	if (!page_alignment)
605 		page_alignment = obj->mm.region->min_page_size;
606 
607 	/*
608 	 * If CPU mapping differs, we need to add the ttm_tt pages to
609 	 * the resulting st. Might make sense for GGTT.
610 	 */
611 	GEM_WARN_ON(!i915_ttm_cpu_maps_iomem(res));
612 	if (bo->resource == res) {
613 		if (!obj->ttm.cached_io_rsgt) {
614 			struct i915_refct_sgt *rsgt;
615 
616 			rsgt = intel_region_ttm_resource_to_rsgt(obj->mm.region,
617 								 res,
618 								 page_alignment);
619 			if (IS_ERR(rsgt))
620 				return rsgt;
621 
622 			obj->ttm.cached_io_rsgt = rsgt;
623 		}
624 		return i915_refct_sgt_get(obj->ttm.cached_io_rsgt);
625 	}
626 
627 	return intel_region_ttm_resource_to_rsgt(obj->mm.region, res,
628 						 page_alignment);
629 }
630 
i915_ttm_truncate(struct drm_i915_gem_object * obj)631 static int i915_ttm_truncate(struct drm_i915_gem_object *obj)
632 {
633 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
634 	long err;
635 
636 	WARN_ON_ONCE(obj->mm.madv == I915_MADV_WILLNEED);
637 
638 	err = dma_resv_wait_timeout(bo->base.resv, DMA_RESV_USAGE_BOOKKEEP,
639 				    true, 15 * HZ);
640 	if (err < 0)
641 		return err;
642 	if (err == 0)
643 		return -EBUSY;
644 
645 	err = i915_ttm_move_notify(bo);
646 	if (err)
647 		return err;
648 
649 	return i915_ttm_purge(obj);
650 }
651 
i915_ttm_swap_notify(struct ttm_buffer_object * bo)652 static void i915_ttm_swap_notify(struct ttm_buffer_object *bo)
653 {
654 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
655 	int ret;
656 
657 	if (i915_ttm_is_ghost_object(bo))
658 		return;
659 
660 	ret = i915_ttm_move_notify(bo);
661 	GEM_WARN_ON(ret);
662 	GEM_WARN_ON(obj->ttm.cached_io_rsgt);
663 	if (!ret && obj->mm.madv != I915_MADV_WILLNEED)
664 		i915_ttm_purge(obj);
665 }
666 
667 /**
668  * i915_ttm_resource_mappable - Return true if the ttm resource is CPU
669  * accessible.
670  * @res: The TTM resource to check.
671  *
672  * This is interesting on small-BAR systems where we may encounter lmem objects
673  * that can't be accessed via the CPU.
674  */
i915_ttm_resource_mappable(struct ttm_resource * res)675 bool i915_ttm_resource_mappable(struct ttm_resource *res)
676 {
677 	struct i915_ttm_buddy_resource *bman_res = to_ttm_buddy_resource(res);
678 
679 	if (!i915_ttm_cpu_maps_iomem(res))
680 		return true;
681 
682 	return bman_res->used_visible_size == PFN_UP(bman_res->base.size);
683 }
684 
i915_ttm_io_mem_reserve(struct ttm_device * bdev,struct ttm_resource * mem)685 static int i915_ttm_io_mem_reserve(struct ttm_device *bdev, struct ttm_resource *mem)
686 {
687 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(mem->bo);
688 	bool unknown_state;
689 
690 	if (i915_ttm_is_ghost_object(mem->bo))
691 		return -EINVAL;
692 
693 	if (!kref_get_unless_zero(&obj->base.refcount))
694 		return -EINVAL;
695 
696 	assert_object_held(obj);
697 
698 	unknown_state = i915_gem_object_has_unknown_state(obj);
699 	i915_gem_object_put(obj);
700 	if (unknown_state)
701 		return -EINVAL;
702 
703 	if (!i915_ttm_cpu_maps_iomem(mem))
704 		return 0;
705 
706 	if (!i915_ttm_resource_mappable(mem))
707 		return -EINVAL;
708 
709 	mem->bus.caching = ttm_write_combined;
710 	mem->bus.is_iomem = true;
711 
712 	return 0;
713 }
714 
i915_ttm_io_mem_pfn(struct ttm_buffer_object * bo,unsigned long page_offset)715 static unsigned long i915_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
716 					 unsigned long page_offset)
717 {
718 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
719 	struct scatterlist *sg;
720 	unsigned long base;
721 	unsigned int ofs;
722 
723 	GEM_BUG_ON(i915_ttm_is_ghost_object(bo));
724 	GEM_WARN_ON(bo->ttm);
725 
726 	base = obj->mm.region->iomap.base - obj->mm.region->region.start;
727 	sg = i915_gem_object_page_iter_get_sg(obj, &obj->ttm.get_io_page, page_offset, &ofs);
728 
729 	return ((base + sg_dma_address(sg)) >> PAGE_SHIFT) + ofs;
730 }
731 
i915_ttm_access_memory(struct ttm_buffer_object * bo,unsigned long offset,void * buf,int len,int write)732 static int i915_ttm_access_memory(struct ttm_buffer_object *bo,
733 				  unsigned long offset, void *buf,
734 				  int len, int write)
735 {
736 	STUB();
737 	return -ENOSYS;
738 #ifdef notyet
739 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
740 	resource_size_t iomap = obj->mm.region->iomap.base -
741 		obj->mm.region->region.start;
742 	unsigned long page = offset >> PAGE_SHIFT;
743 	unsigned long bytes_left = len;
744 
745 	/*
746 	 * TODO: For now just let it fail if the resource is non-mappable,
747 	 * otherwise we need to perform the memcpy from the gpu here, without
748 	 * interfering with the object (like moving the entire thing).
749 	 */
750 	if (!i915_ttm_resource_mappable(bo->resource))
751 		return -EIO;
752 
753 	offset -= page << PAGE_SHIFT;
754 	do {
755 		unsigned long bytes = min(bytes_left, PAGE_SIZE - offset);
756 		void __iomem *ptr;
757 		dma_addr_t daddr;
758 
759 		daddr = i915_gem_object_get_dma_address(obj, page);
760 		ptr = ioremap_wc(iomap + daddr + offset, bytes);
761 		if (!ptr)
762 			return -EIO;
763 
764 		if (write)
765 			memcpy_toio(ptr, buf, bytes);
766 		else
767 			memcpy_fromio(buf, ptr, bytes);
768 		iounmap(ptr);
769 
770 		page++;
771 		buf += bytes;
772 		bytes_left -= bytes;
773 		offset = 0;
774 	} while (bytes_left);
775 
776 	return len;
777 #endif
778 }
779 
780 /*
781  * All callbacks need to take care not to downcast a struct ttm_buffer_object
782  * without checking its subclass, since it might be a TTM ghost object.
783  */
784 static struct ttm_device_funcs i915_ttm_bo_driver = {
785 	.ttm_tt_create = i915_ttm_tt_create,
786 	.ttm_tt_populate = i915_ttm_tt_populate,
787 	.ttm_tt_unpopulate = i915_ttm_tt_unpopulate,
788 	.ttm_tt_destroy = i915_ttm_tt_destroy,
789 	.eviction_valuable = i915_ttm_eviction_valuable,
790 	.evict_flags = i915_ttm_evict_flags,
791 	.move = i915_ttm_move,
792 	.swap_notify = i915_ttm_swap_notify,
793 	.delete_mem_notify = i915_ttm_delete_mem_notify,
794 	.io_mem_reserve = i915_ttm_io_mem_reserve,
795 	.io_mem_pfn = i915_ttm_io_mem_pfn,
796 	.access_memory = i915_ttm_access_memory,
797 };
798 
799 /**
800  * i915_ttm_driver - Return a pointer to the TTM device funcs
801  *
802  * Return: Pointer to statically allocated TTM device funcs.
803  */
i915_ttm_driver(void)804 struct ttm_device_funcs *i915_ttm_driver(void)
805 {
806 	return &i915_ttm_bo_driver;
807 }
808 
__i915_ttm_get_pages(struct drm_i915_gem_object * obj,struct ttm_placement * placement)809 static int __i915_ttm_get_pages(struct drm_i915_gem_object *obj,
810 				struct ttm_placement *placement)
811 {
812 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
813 	struct ttm_operation_ctx ctx = {
814 		.interruptible = true,
815 		.no_wait_gpu = false,
816 	};
817 	int real_num_busy;
818 	int ret;
819 
820 	/* First try only the requested placement. No eviction. */
821 	real_num_busy = fetch_and_zero(&placement->num_busy_placement);
822 	ret = ttm_bo_validate(bo, placement, &ctx);
823 	if (ret) {
824 		ret = i915_ttm_err_to_gem(ret);
825 		/*
826 		 * Anything that wants to restart the operation gets to
827 		 * do that.
828 		 */
829 		if (ret == -EDEADLK || ret == -EINTR || ret == -ERESTARTSYS ||
830 		    ret == -EAGAIN)
831 			return ret;
832 
833 		/*
834 		 * If the initial attempt fails, allow all accepted placements,
835 		 * evicting if necessary.
836 		 */
837 		placement->num_busy_placement = real_num_busy;
838 		ret = ttm_bo_validate(bo, placement, &ctx);
839 		if (ret)
840 			return i915_ttm_err_to_gem(ret);
841 	}
842 
843 	if (bo->ttm && !ttm_tt_is_populated(bo->ttm)) {
844 		ret = ttm_tt_populate(bo->bdev, bo->ttm, &ctx);
845 		if (ret)
846 			return ret;
847 
848 		i915_ttm_adjust_domains_after_move(obj);
849 		i915_ttm_adjust_gem_after_move(obj);
850 	}
851 
852 	if (!i915_gem_object_has_pages(obj)) {
853 		struct i915_refct_sgt *rsgt =
854 			i915_ttm_resource_get_st(obj, bo->resource);
855 
856 		if (IS_ERR(rsgt))
857 			return PTR_ERR(rsgt);
858 
859 		GEM_BUG_ON(obj->mm.rsgt);
860 		obj->mm.rsgt = rsgt;
861 		__i915_gem_object_set_pages(obj, &rsgt->table);
862 	}
863 
864 	GEM_BUG_ON(bo->ttm && ((obj->base.size >> PAGE_SHIFT) < bo->ttm->num_pages));
865 	i915_ttm_adjust_lru(obj);
866 	return ret;
867 }
868 
i915_ttm_get_pages(struct drm_i915_gem_object * obj)869 static int i915_ttm_get_pages(struct drm_i915_gem_object *obj)
870 {
871 	struct ttm_place requested, busy[I915_TTM_MAX_PLACEMENTS];
872 	struct ttm_placement placement;
873 
874 	/* restricted by sg_alloc_table */
875 	if (overflows_type(obj->base.size >> PAGE_SHIFT, unsigned int))
876 		return -E2BIG;
877 
878 	GEM_BUG_ON(obj->mm.n_placements > I915_TTM_MAX_PLACEMENTS);
879 
880 	/* Move to the requested placement. */
881 	i915_ttm_placement_from_obj(obj, &requested, busy, &placement);
882 
883 	return __i915_ttm_get_pages(obj, &placement);
884 }
885 
886 /**
887  * DOC: Migration vs eviction
888  *
889  * GEM migration may not be the same as TTM migration / eviction. If
890  * the TTM core decides to evict an object it may be evicted to a
891  * TTM memory type that is not in the object's allowable GEM regions, or
892  * in fact theoretically to a TTM memory type that doesn't correspond to
893  * a GEM memory region. In that case the object's GEM region is not
894  * updated, and the data is migrated back to the GEM region at
895  * get_pages time. TTM may however set up CPU ptes to the object even
896  * when it is evicted.
897  * Gem forced migration using the i915_ttm_migrate() op, is allowed even
898  * to regions that are not in the object's list of allowable placements.
899  */
__i915_ttm_migrate(struct drm_i915_gem_object * obj,struct intel_memory_region * mr,unsigned int flags)900 static int __i915_ttm_migrate(struct drm_i915_gem_object *obj,
901 			      struct intel_memory_region *mr,
902 			      unsigned int flags)
903 {
904 	struct ttm_place requested;
905 	struct ttm_placement placement;
906 	int ret;
907 
908 	i915_ttm_place_from_region(mr, &requested, obj->bo_offset,
909 				   obj->base.size, flags);
910 	placement.num_placement = 1;
911 	placement.num_busy_placement = 1;
912 	placement.placement = &requested;
913 	placement.busy_placement = &requested;
914 
915 	ret = __i915_ttm_get_pages(obj, &placement);
916 	if (ret)
917 		return ret;
918 
919 	/*
920 	 * Reinitialize the region bindings. This is primarily
921 	 * required for objects where the new region is not in
922 	 * its allowable placements.
923 	 */
924 	if (obj->mm.region != mr) {
925 		i915_gem_object_release_memory_region(obj);
926 		i915_gem_object_init_memory_region(obj, mr);
927 	}
928 
929 	return 0;
930 }
931 
i915_ttm_migrate(struct drm_i915_gem_object * obj,struct intel_memory_region * mr,unsigned int flags)932 static int i915_ttm_migrate(struct drm_i915_gem_object *obj,
933 			    struct intel_memory_region *mr,
934 			    unsigned int flags)
935 {
936 	return __i915_ttm_migrate(obj, mr, flags);
937 }
938 
i915_ttm_put_pages(struct drm_i915_gem_object * obj,struct sg_table * st)939 static void i915_ttm_put_pages(struct drm_i915_gem_object *obj,
940 			       struct sg_table *st)
941 {
942 	/*
943 	 * We're currently not called from a shrinker, so put_pages()
944 	 * typically means the object is about to destroyed, or called
945 	 * from move_notify(). So just avoid doing much for now.
946 	 * If the object is not destroyed next, The TTM eviction logic
947 	 * and shrinkers will move it out if needed.
948 	 */
949 
950 	if (obj->mm.rsgt)
951 		i915_refct_sgt_put(fetch_and_zero(&obj->mm.rsgt));
952 }
953 
954 /**
955  * i915_ttm_adjust_lru - Adjust an object's position on relevant LRU lists.
956  * @obj: The object
957  */
i915_ttm_adjust_lru(struct drm_i915_gem_object * obj)958 void i915_ttm_adjust_lru(struct drm_i915_gem_object *obj)
959 {
960 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
961 	struct i915_ttm_tt *i915_tt =
962 		container_of(bo->ttm, typeof(*i915_tt), ttm);
963 	bool shrinkable =
964 		bo->ttm && i915_tt->filp && ttm_tt_is_populated(bo->ttm);
965 
966 	/*
967 	 * Don't manipulate the TTM LRUs while in TTM bo destruction.
968 	 * We're called through i915_ttm_delete_mem_notify().
969 	 */
970 	if (!kref_read(&bo->kref))
971 		return;
972 
973 	/*
974 	 * We skip managing the shrinker LRU in set_pages() and just manage
975 	 * everything here. This does at least solve the issue with having
976 	 * temporary shmem mappings(like with evicted lmem) not being visible to
977 	 * the shrinker. Only our shmem objects are shrinkable, everything else
978 	 * we keep as unshrinkable.
979 	 *
980 	 * To make sure everything plays nice we keep an extra shrink pin in TTM
981 	 * if the underlying pages are not currently shrinkable. Once we release
982 	 * our pin, like when the pages are moved to shmem, the pages will then
983 	 * be added to the shrinker LRU, assuming the caller isn't also holding
984 	 * a pin.
985 	 *
986 	 * TODO: consider maybe also bumping the shrinker list here when we have
987 	 * already unpinned it, which should give us something more like an LRU.
988 	 *
989 	 * TODO: There is a small window of opportunity for this function to
990 	 * get called from eviction after we've dropped the last GEM refcount,
991 	 * but before the TTM deleted flag is set on the object. Avoid
992 	 * adjusting the shrinker list in such cases, since the object is
993 	 * not available to the shrinker anyway due to its zero refcount.
994 	 * To fix this properly we should move to a TTM shrinker LRU list for
995 	 * these objects.
996 	 */
997 	if (kref_get_unless_zero(&obj->base.refcount)) {
998 		if (shrinkable != obj->mm.ttm_shrinkable) {
999 			if (shrinkable) {
1000 				if (obj->mm.madv == I915_MADV_WILLNEED)
1001 					__i915_gem_object_make_shrinkable(obj);
1002 				else
1003 					__i915_gem_object_make_purgeable(obj);
1004 			} else {
1005 				i915_gem_object_make_unshrinkable(obj);
1006 			}
1007 
1008 			obj->mm.ttm_shrinkable = shrinkable;
1009 		}
1010 		i915_gem_object_put(obj);
1011 	}
1012 
1013 	/*
1014 	 * Put on the correct LRU list depending on the MADV status
1015 	 */
1016 	spin_lock(&bo->bdev->lru_lock);
1017 	if (shrinkable) {
1018 		/* Try to keep shmem_tt from being considered for shrinking. */
1019 		bo->priority = TTM_MAX_BO_PRIORITY - 1;
1020 	} else if (obj->mm.madv != I915_MADV_WILLNEED) {
1021 		bo->priority = I915_TTM_PRIO_PURGE;
1022 	} else if (!i915_gem_object_has_pages(obj)) {
1023 		bo->priority = I915_TTM_PRIO_NO_PAGES;
1024 	} else {
1025 		struct ttm_resource_manager *man =
1026 			ttm_manager_type(bo->bdev, bo->resource->mem_type);
1027 
1028 		/*
1029 		 * If we need to place an LMEM resource which doesn't need CPU
1030 		 * access then we should try not to victimize mappable objects
1031 		 * first, since we likely end up stealing more of the mappable
1032 		 * portion. And likewise when we try to find space for a mappble
1033 		 * object, we know not to ever victimize objects that don't
1034 		 * occupy any mappable pages.
1035 		 */
1036 		if (i915_ttm_cpu_maps_iomem(bo->resource) &&
1037 		    i915_ttm_buddy_man_visible_size(man) < man->size &&
1038 		    !(obj->flags & I915_BO_ALLOC_GPU_ONLY))
1039 			bo->priority = I915_TTM_PRIO_NEEDS_CPU_ACCESS;
1040 		else
1041 			bo->priority = I915_TTM_PRIO_HAS_PAGES;
1042 	}
1043 
1044 	ttm_bo_move_to_lru_tail(bo);
1045 	spin_unlock(&bo->bdev->lru_lock);
1046 }
1047 
1048 /*
1049  * TTM-backed gem object destruction requires some clarification.
1050  * Basically we have two possibilities here. We can either rely on the
1051  * i915 delayed destruction and put the TTM object when the object
1052  * is idle. This would be detected by TTM which would bypass the
1053  * TTM delayed destroy handling. The other approach is to put the TTM
1054  * object early and rely on the TTM destroyed handling, and then free
1055  * the leftover parts of the GEM object once TTM's destroyed list handling is
1056  * complete. For now, we rely on the latter for two reasons:
1057  * a) TTM can evict an object even when it's on the delayed destroy list,
1058  * which in theory allows for complete eviction.
1059  * b) There is work going on in TTM to allow freeing an object even when
1060  * it's not idle, and using the TTM destroyed list handling could help us
1061  * benefit from that.
1062  */
i915_ttm_delayed_free(struct drm_i915_gem_object * obj)1063 static void i915_ttm_delayed_free(struct drm_i915_gem_object *obj)
1064 {
1065 	GEM_BUG_ON(!obj->ttm.created);
1066 
1067 	ttm_bo_put(i915_gem_to_ttm(obj));
1068 }
1069 
1070 #ifdef __linux__
1071 
vm_fault_ttm(struct vm_fault * vmf)1072 static vm_fault_t vm_fault_ttm(struct vm_fault *vmf)
1073 {
1074 	struct vm_area_struct *area = vmf->vma;
1075 	struct ttm_buffer_object *bo = area->vm_private_data;
1076 	struct drm_device *dev = bo->base.dev;
1077 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
1078 	intel_wakeref_t wakeref = 0;
1079 	vm_fault_t ret;
1080 	int idx;
1081 
1082 	/* Sanity check that we allow writing into this object */
1083 	if (unlikely(i915_gem_object_is_readonly(obj) &&
1084 		     area->vm_flags & VM_WRITE))
1085 		return VM_FAULT_SIGBUS;
1086 
1087 	ret = ttm_bo_vm_reserve(bo, vmf);
1088 	if (ret)
1089 		return ret;
1090 
1091 	if (obj->mm.madv != I915_MADV_WILLNEED) {
1092 		dma_resv_unlock(bo->base.resv);
1093 		return VM_FAULT_SIGBUS;
1094 	}
1095 
1096 	/*
1097 	 * This must be swapped out with shmem ttm_tt (pipeline-gutting).
1098 	 * Calling ttm_bo_validate() here with TTM_PL_SYSTEM should only go as
1099 	 * far as far doing a ttm_bo_move_null(), which should skip all the
1100 	 * other junk.
1101 	 */
1102 	if (!bo->resource) {
1103 		struct ttm_operation_ctx ctx = {
1104 			.interruptible = true,
1105 			.no_wait_gpu = true, /* should be idle already */
1106 		};
1107 		int err;
1108 
1109 		GEM_BUG_ON(!bo->ttm || !(bo->ttm->page_flags & TTM_TT_FLAG_SWAPPED));
1110 
1111 		err = ttm_bo_validate(bo, i915_ttm_sys_placement(), &ctx);
1112 		if (err) {
1113 			dma_resv_unlock(bo->base.resv);
1114 			return VM_FAULT_SIGBUS;
1115 		}
1116 	} else if (!i915_ttm_resource_mappable(bo->resource)) {
1117 		int err = -ENODEV;
1118 		int i;
1119 
1120 		for (i = 0; i < obj->mm.n_placements; i++) {
1121 			struct intel_memory_region *mr = obj->mm.placements[i];
1122 			unsigned int flags;
1123 
1124 			if (!resource_size(&mr->io) && mr->type != INTEL_MEMORY_SYSTEM)
1125 				continue;
1126 
1127 			flags = obj->flags;
1128 			flags &= ~I915_BO_ALLOC_GPU_ONLY;
1129 			err = __i915_ttm_migrate(obj, mr, flags);
1130 			if (!err)
1131 				break;
1132 		}
1133 
1134 		if (err) {
1135 			drm_dbg(dev, "Unable to make resource CPU accessible(err = %pe)\n",
1136 				ERR_PTR(err));
1137 			dma_resv_unlock(bo->base.resv);
1138 			ret = VM_FAULT_SIGBUS;
1139 			goto out_rpm;
1140 		}
1141 	}
1142 
1143 	if (i915_ttm_cpu_maps_iomem(bo->resource))
1144 		wakeref = intel_runtime_pm_get(&to_i915(obj->base.dev)->runtime_pm);
1145 
1146 	if (drm_dev_enter(dev, &idx)) {
1147 		ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
1148 					       TTM_BO_VM_NUM_PREFAULT);
1149 		drm_dev_exit(idx);
1150 	} else {
1151 		ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
1152 	}
1153 
1154 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
1155 		goto out_rpm;
1156 
1157 	/*
1158 	 * ttm_bo_vm_reserve() already has dma_resv_lock.
1159 	 * userfault_count is protected by dma_resv lock and rpm wakeref.
1160 	 */
1161 	if (ret == VM_FAULT_NOPAGE && wakeref && !obj->userfault_count) {
1162 		obj->userfault_count = 1;
1163 		spin_lock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1164 		list_add(&obj->userfault_link, &to_i915(obj->base.dev)->runtime_pm.lmem_userfault_list);
1165 		spin_unlock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1166 
1167 		GEM_WARN_ON(!i915_ttm_cpu_maps_iomem(bo->resource));
1168 	}
1169 
1170 	if (wakeref && CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND != 0)
1171 		intel_wakeref_auto(&to_i915(obj->base.dev)->runtime_pm.userfault_wakeref,
1172 				   msecs_to_jiffies_timeout(CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND));
1173 
1174 	i915_ttm_adjust_lru(obj);
1175 
1176 	dma_resv_unlock(bo->base.resv);
1177 
1178 out_rpm:
1179 	if (wakeref)
1180 		intel_runtime_pm_put(&to_i915(obj->base.dev)->runtime_pm, wakeref);
1181 
1182 	return ret;
1183 }
1184 
1185 static int
vm_access_ttm(struct vm_area_struct * area,unsigned long addr,void * buf,int len,int write)1186 vm_access_ttm(struct vm_area_struct *area, unsigned long addr,
1187 	      void *buf, int len, int write)
1188 {
1189 	struct drm_i915_gem_object *obj =
1190 		i915_ttm_to_gem(area->vm_private_data);
1191 
1192 	if (i915_gem_object_is_readonly(obj) && write)
1193 		return -EACCES;
1194 
1195 	return ttm_bo_vm_access(area, addr, buf, len, write);
1196 }
1197 
ttm_vm_open(struct vm_area_struct * vma)1198 static void ttm_vm_open(struct vm_area_struct *vma)
1199 {
1200 	struct drm_i915_gem_object *obj =
1201 		i915_ttm_to_gem(vma->vm_private_data);
1202 
1203 	GEM_BUG_ON(i915_ttm_is_ghost_object(vma->vm_private_data));
1204 	i915_gem_object_get(obj);
1205 }
1206 
ttm_vm_close(struct vm_area_struct * vma)1207 static void ttm_vm_close(struct vm_area_struct *vma)
1208 {
1209 	struct drm_i915_gem_object *obj =
1210 		i915_ttm_to_gem(vma->vm_private_data);
1211 
1212 	GEM_BUG_ON(i915_ttm_is_ghost_object(vma->vm_private_data));
1213 	i915_gem_object_put(obj);
1214 }
1215 
1216 static const struct vm_operations_struct vm_ops_ttm = {
1217 	.fault = vm_fault_ttm,
1218 	.access = vm_access_ttm,
1219 	.open = ttm_vm_open,
1220 	.close = ttm_vm_close,
1221 };
1222 
1223 #else /* !__linux__ */
1224 
1225 static int
1226 
vm_fault_ttm(struct uvm_faultinfo * ufi,vaddr_t vaddr,vm_page_t * pps,int npages,int centeridx,vm_fault_t fault_type,vm_prot_t access_type,int flags)1227 vm_fault_ttm(struct uvm_faultinfo *ufi, vaddr_t vaddr, vm_page_t *pps,
1228     int npages, int centeridx, vm_fault_t fault_type,
1229     vm_prot_t access_type, int flags)
1230 {
1231 	struct uvm_object *uobj = ufi->entry->object.uvm_obj;
1232 	struct ttm_buffer_object *bo = (struct ttm_buffer_object *)uobj;
1233 	struct drm_device *dev = bo->base.dev;
1234 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
1235 	intel_wakeref_t wakeref = 0;
1236 	vm_fault_t ret;
1237 	int idx;
1238 	int write = !!(access_type & PROT_WRITE);
1239 
1240 	/* Sanity check that we allow writing into this object */
1241 	if (unlikely(i915_gem_object_is_readonly(obj) && write)) {
1242 		uvmfault_unlockall(ufi, NULL, &obj->base.uobj);
1243 		return VM_PAGER_BAD;
1244 	}
1245 
1246 	ret = ttm_bo_vm_reserve(bo);
1247 	if (ret) {
1248 		switch (ret) {
1249 		case VM_FAULT_NOPAGE:
1250 			ret = VM_PAGER_OK;
1251 			break;
1252 		case VM_FAULT_RETRY:
1253 			ret = VM_PAGER_REFAULT;
1254 			break;
1255 		default:
1256 			ret = VM_PAGER_BAD;
1257 			break;
1258 		}
1259 		uvmfault_unlockall(ufi, NULL, &obj->base.uobj);
1260 		return ret;
1261 	}
1262 
1263 	if (obj->mm.madv != I915_MADV_WILLNEED) {
1264 		dma_resv_unlock(bo->base.resv);
1265 		uvmfault_unlockall(ufi, NULL, &obj->base.uobj);
1266 		return VM_PAGER_BAD;
1267 	}
1268 
1269 	/*
1270 	 * This must be swapped out with shmem ttm_tt (pipeline-gutting).
1271 	 * Calling ttm_bo_validate() here with TTM_PL_SYSTEM should only go as
1272 	 * far as far doing a ttm_bo_move_null(), which should skip all the
1273 	 * other junk.
1274 	 */
1275 	if (!bo->resource) {
1276 		struct ttm_operation_ctx ctx = {
1277 			.interruptible = true,
1278 			.no_wait_gpu = true, /* should be idle already */
1279 		};
1280 		int err;
1281 
1282 		GEM_BUG_ON(!bo->ttm || !(bo->ttm->page_flags & TTM_TT_FLAG_SWAPPED));
1283 
1284 		err = ttm_bo_validate(bo, i915_ttm_sys_placement(), &ctx);
1285 		if (err) {
1286 			dma_resv_unlock(bo->base.resv);
1287 			uvmfault_unlockall(ufi, NULL, &obj->base.uobj);
1288 			return VM_PAGER_BAD;
1289 		}
1290 	} else if (!i915_ttm_resource_mappable(bo->resource)) {
1291 		int err = -ENODEV;
1292 		int i;
1293 
1294 		for (i = 0; i < obj->mm.n_placements; i++) {
1295 			struct intel_memory_region *mr = obj->mm.placements[i];
1296 			unsigned int flags;
1297 
1298 			if (!resource_size(&mr->io) && mr->type != INTEL_MEMORY_SYSTEM)
1299 				continue;
1300 
1301 			flags = obj->flags;
1302 			flags &= ~I915_BO_ALLOC_GPU_ONLY;
1303 			err = __i915_ttm_migrate(obj, mr, flags);
1304 			if (!err)
1305 				break;
1306 		}
1307 
1308 		if (err) {
1309 			drm_dbg(dev, "Unable to make resource CPU accessible(err = %pe)\n",
1310 				ERR_PTR(err));
1311 			dma_resv_unlock(bo->base.resv);
1312 			ret = VM_FAULT_SIGBUS;
1313 			goto out_rpm;
1314 		}
1315 	}
1316 
1317 	if (i915_ttm_cpu_maps_iomem(bo->resource))
1318 		wakeref = intel_runtime_pm_get(&to_i915(obj->base.dev)->runtime_pm);
1319 
1320 	if (drm_dev_enter(dev, &idx)) {
1321 		ret = ttm_bo_vm_fault_reserved(ufi, vaddr,
1322 					       TTM_BO_VM_NUM_PREFAULT, 1);
1323 		drm_dev_exit(idx);
1324 	} else {
1325 		STUB();
1326 #ifdef notyet
1327 		ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
1328 #else
1329 		STUB();
1330 		ret = VM_FAULT_NOPAGE;
1331 #endif
1332 	}
1333 #ifdef __linux__
1334 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
1335 		goto out_rpm;
1336 #endif
1337 
1338 	/*
1339 	 * ttm_bo_vm_reserve() already has dma_resv_lock.
1340 	 * userfault_count is protected by dma_resv lock and rpm wakeref.
1341 	 */
1342 	if (ret == VM_FAULT_NOPAGE && wakeref && !obj->userfault_count) {
1343 		obj->userfault_count = 1;
1344 		spin_lock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1345 		list_add(&obj->userfault_link, &to_i915(obj->base.dev)->runtime_pm.lmem_userfault_list);
1346 		spin_unlock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1347 
1348 		GEM_WARN_ON(!i915_ttm_cpu_maps_iomem(bo->resource));
1349 	}
1350 
1351 	if (wakeref & CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND)
1352 		intel_wakeref_auto(&to_i915(obj->base.dev)->runtime_pm.userfault_wakeref,
1353 				   msecs_to_jiffies_timeout(CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND));
1354 
1355 	i915_ttm_adjust_lru(obj);
1356 
1357 	dma_resv_unlock(bo->base.resv);
1358 
1359 out_rpm:
1360 	switch (ret) {
1361 	case VM_FAULT_NOPAGE:
1362 		ret = VM_PAGER_OK;
1363 		break;
1364 	case VM_FAULT_RETRY:
1365 		ret = VM_PAGER_REFAULT;
1366 		break;
1367 	default:
1368 		ret = VM_PAGER_BAD;
1369 		break;
1370 	}
1371 
1372 	if (wakeref)
1373 		intel_runtime_pm_put(&to_i915(obj->base.dev)->runtime_pm, wakeref);
1374 
1375 	uvmfault_unlockall(ufi, NULL, &obj->base.uobj);
1376 
1377 	return ret;
1378 }
1379 
1380 static void
ttm_vm_reference(struct uvm_object * uobj)1381 ttm_vm_reference(struct uvm_object *uobj)
1382 {
1383 	struct drm_i915_gem_object *obj =
1384 		i915_ttm_to_gem((struct ttm_buffer_object *)uobj);
1385 
1386 	i915_gem_object_get(obj);
1387 }
1388 
1389 static void
ttm_vm_detach(struct uvm_object * uobj)1390 ttm_vm_detach(struct uvm_object *uobj)
1391 {
1392 	struct drm_i915_gem_object *obj =
1393 		i915_ttm_to_gem((struct ttm_buffer_object *)uobj);
1394 
1395 	i915_gem_object_put(obj);
1396 }
1397 
1398 const struct uvm_pagerops vm_ops_ttm = {
1399 	.pgo_fault = vm_fault_ttm,
1400 	.pgo_reference = ttm_vm_reference,
1401 	.pgo_detach = ttm_vm_detach,
1402 };
1403 
1404 #endif
1405 
i915_ttm_mmap_offset(struct drm_i915_gem_object * obj)1406 static u64 i915_ttm_mmap_offset(struct drm_i915_gem_object *obj)
1407 {
1408 	/* The ttm_bo must be allocated with I915_BO_ALLOC_USER */
1409 	GEM_BUG_ON(!drm_mm_node_allocated(&obj->base.vma_node.vm_node));
1410 
1411 	return drm_vma_node_offset_addr(&obj->base.vma_node);
1412 }
1413 
i915_ttm_unmap_virtual(struct drm_i915_gem_object * obj)1414 static void i915_ttm_unmap_virtual(struct drm_i915_gem_object *obj)
1415 {
1416 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
1417 	intel_wakeref_t wakeref = 0;
1418 
1419 	assert_object_held_shared(obj);
1420 
1421 	if (i915_ttm_cpu_maps_iomem(bo->resource)) {
1422 		wakeref = intel_runtime_pm_get(&to_i915(obj->base.dev)->runtime_pm);
1423 
1424 		/* userfault_count is protected by obj lock and rpm wakeref. */
1425 		if (obj->userfault_count) {
1426 			spin_lock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1427 			list_del(&obj->userfault_link);
1428 			spin_unlock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1429 			obj->userfault_count = 0;
1430 		}
1431 	}
1432 
1433 	GEM_WARN_ON(obj->userfault_count);
1434 
1435 	ttm_bo_unmap_virtual(i915_gem_to_ttm(obj));
1436 
1437 	if (wakeref)
1438 		intel_runtime_pm_put(&to_i915(obj->base.dev)->runtime_pm, wakeref);
1439 }
1440 
1441 static const struct drm_i915_gem_object_ops i915_gem_ttm_obj_ops = {
1442 	.name = "i915_gem_object_ttm",
1443 	.flags = I915_GEM_OBJECT_IS_SHRINKABLE |
1444 		 I915_GEM_OBJECT_SELF_MANAGED_SHRINK_LIST,
1445 
1446 	.get_pages = i915_ttm_get_pages,
1447 	.put_pages = i915_ttm_put_pages,
1448 	.truncate = i915_ttm_truncate,
1449 	.shrink = i915_ttm_shrink,
1450 
1451 	.adjust_lru = i915_ttm_adjust_lru,
1452 	.delayed_free = i915_ttm_delayed_free,
1453 	.migrate = i915_ttm_migrate,
1454 
1455 	.mmap_offset = i915_ttm_mmap_offset,
1456 	.unmap_virtual = i915_ttm_unmap_virtual,
1457 	.mmap_ops = &vm_ops_ttm,
1458 };
1459 
i915_ttm_bo_destroy(struct ttm_buffer_object * bo)1460 void i915_ttm_bo_destroy(struct ttm_buffer_object *bo)
1461 {
1462 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
1463 
1464 	i915_gem_object_release_memory_region(obj);
1465 	mutex_destroy(&obj->ttm.get_io_page.lock);
1466 
1467 	if (obj->ttm.created) {
1468 		/*
1469 		 * We freely manage the shrinker LRU outide of the mm.pages life
1470 		 * cycle. As a result when destroying the object we should be
1471 		 * extra paranoid and ensure we remove it from the LRU, before
1472 		 * we free the object.
1473 		 *
1474 		 * Touching the ttm_shrinkable outside of the object lock here
1475 		 * should be safe now that the last GEM object ref was dropped.
1476 		 */
1477 		if (obj->mm.ttm_shrinkable)
1478 			i915_gem_object_make_unshrinkable(obj);
1479 
1480 		i915_ttm_backup_free(obj);
1481 
1482 		/* This releases all gem object bindings to the backend. */
1483 		__i915_gem_free_object(obj);
1484 
1485 		call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
1486 	} else {
1487 		__i915_gem_object_fini(obj);
1488 	}
1489 }
1490 
1491 /*
1492  * __i915_gem_ttm_object_init - Initialize a ttm-backed i915 gem object
1493  * @mem: The initial memory region for the object.
1494  * @obj: The gem object.
1495  * @size: Object size in bytes.
1496  * @flags: gem object flags.
1497  *
1498  * Return: 0 on success, negative error code on failure.
1499  */
__i915_gem_ttm_object_init(struct intel_memory_region * mem,struct drm_i915_gem_object * obj,resource_size_t offset,resource_size_t size,resource_size_t page_size,unsigned int flags)1500 int __i915_gem_ttm_object_init(struct intel_memory_region *mem,
1501 			       struct drm_i915_gem_object *obj,
1502 			       resource_size_t offset,
1503 			       resource_size_t size,
1504 			       resource_size_t page_size,
1505 			       unsigned int flags)
1506 {
1507 	static struct lock_class_key lock_class;
1508 	struct drm_i915_private *i915 = mem->i915;
1509 	struct ttm_operation_ctx ctx = {
1510 		.interruptible = true,
1511 		.no_wait_gpu = false,
1512 	};
1513 	enum ttm_bo_type bo_type;
1514 	int ret;
1515 
1516 	drm_gem_private_object_init(&i915->drm, &obj->base, size);
1517 	i915_gem_object_init(obj, &i915_gem_ttm_obj_ops, &lock_class, flags);
1518 
1519 	obj->bo_offset = offset;
1520 
1521 	/* Don't put on a region list until we're either locked or fully initialized. */
1522 	obj->mm.region = mem;
1523 	INIT_LIST_HEAD(&obj->mm.region_link);
1524 
1525 	INIT_RADIX_TREE(&obj->ttm.get_io_page.radix, GFP_KERNEL | __GFP_NOWARN);
1526 	rw_init(&obj->ttm.get_io_page.lock, "i915ttm");
1527 	bo_type = (obj->flags & I915_BO_ALLOC_USER) ? ttm_bo_type_device :
1528 		ttm_bo_type_kernel;
1529 
1530 	obj->base.vma_node.driver_private = i915_gem_to_ttm(obj);
1531 
1532 	/* Forcing the page size is kernel internal only */
1533 	GEM_BUG_ON(page_size && obj->mm.n_placements);
1534 
1535 	/*
1536 	 * Keep an extra shrink pin to prevent the object from being made
1537 	 * shrinkable too early. If the ttm_tt is ever allocated in shmem, we
1538 	 * drop the pin. The TTM backend manages the shrinker LRU itself,
1539 	 * outside of the normal mm.pages life cycle.
1540 	 */
1541 	i915_gem_object_make_unshrinkable(obj);
1542 
1543 	/*
1544 	 * If this function fails, it will call the destructor, but
1545 	 * our caller still owns the object. So no freeing in the
1546 	 * destructor until obj->ttm.created is true.
1547 	 * Similarly, in delayed_destroy, we can't call ttm_bo_put()
1548 	 * until successful initialization.
1549 	 */
1550 	ret = ttm_bo_init_reserved(&i915->bdev, i915_gem_to_ttm(obj), bo_type,
1551 				   &i915_sys_placement, page_size >> PAGE_SHIFT,
1552 				   &ctx, NULL, NULL, i915_ttm_bo_destroy);
1553 
1554 	/*
1555 	 * XXX: The ttm_bo_init_reserved() functions returns -ENOSPC if the size
1556 	 * is too big to add vma. The direct function that returns -ENOSPC is
1557 	 * drm_mm_insert_node_in_range(). To handle the same error as other code
1558 	 * that returns -E2BIG when the size is too large, it converts -ENOSPC to
1559 	 * -E2BIG.
1560 	 */
1561 	if (size >> PAGE_SHIFT > INT_MAX && ret == -ENOSPC)
1562 		ret = -E2BIG;
1563 
1564 	if (ret)
1565 		return i915_ttm_err_to_gem(ret);
1566 
1567 	obj->ttm.created = true;
1568 	i915_gem_object_release_memory_region(obj);
1569 	i915_gem_object_init_memory_region(obj, mem);
1570 	i915_ttm_adjust_domains_after_move(obj);
1571 	i915_ttm_adjust_gem_after_move(obj);
1572 	i915_gem_object_unlock(obj);
1573 
1574 	return 0;
1575 }
1576 
1577 static const struct intel_memory_region_ops ttm_system_region_ops = {
1578 	.init_object = __i915_gem_ttm_object_init,
1579 	.release = intel_region_ttm_fini,
1580 };
1581 
1582 struct intel_memory_region *
i915_gem_ttm_system_setup(struct drm_i915_private * i915,u16 type,u16 instance)1583 i915_gem_ttm_system_setup(struct drm_i915_private *i915,
1584 			  u16 type, u16 instance)
1585 {
1586 	struct intel_memory_region *mr;
1587 
1588 	mr = intel_memory_region_create(i915, 0,
1589 					totalram_pages() << PAGE_SHIFT,
1590 					PAGE_SIZE, 0, 0,
1591 					type, instance,
1592 					&ttm_system_region_ops);
1593 	if (IS_ERR(mr))
1594 		return mr;
1595 
1596 	intel_memory_region_set_name(mr, "system-ttm");
1597 	return mr;
1598 }
1599