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_bo_driver.h>
9 #include <drm/ttm/ttm_placement.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 		place->fpfn = offset >> PAGE_SHIFT;
144 		place->lpfn = place->fpfn + (size >> PAGE_SHIFT);
145 	} else if (mr->io_size && mr->io_size < mr->total) {
146 		if (flags & I915_BO_ALLOC_GPU_ONLY) {
147 			place->flags |= TTM_PL_FLAG_TOPDOWN;
148 		} else {
149 			place->fpfn = 0;
150 			place->lpfn = mr->io_size >> PAGE_SHIFT;
151 		}
152 	}
153 }
154 
155 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)156 i915_ttm_placement_from_obj(const struct drm_i915_gem_object *obj,
157 			    struct ttm_place *requested,
158 			    struct ttm_place *busy,
159 			    struct ttm_placement *placement)
160 {
161 	unsigned int num_allowed = obj->mm.n_placements;
162 	unsigned int flags = obj->flags;
163 	unsigned int i;
164 
165 	placement->num_placement = 1;
166 	i915_ttm_place_from_region(num_allowed ? obj->mm.placements[0] :
167 				   obj->mm.region, requested, obj->bo_offset,
168 				   obj->base.size, flags);
169 
170 	/* Cache this on object? */
171 	placement->num_busy_placement = num_allowed;
172 	for (i = 0; i < placement->num_busy_placement; ++i)
173 		i915_ttm_place_from_region(obj->mm.placements[i], busy + i,
174 					   obj->bo_offset, obj->base.size, flags);
175 
176 	if (num_allowed == 0) {
177 		*busy = *requested;
178 		placement->num_busy_placement = 1;
179 	}
180 
181 	placement->placement = requested;
182 	placement->busy_placement = busy;
183 }
184 
i915_ttm_tt_shmem_populate(struct ttm_device * bdev,struct ttm_tt * ttm,struct ttm_operation_ctx * ctx)185 static int i915_ttm_tt_shmem_populate(struct ttm_device *bdev,
186 				      struct ttm_tt *ttm,
187 				      struct ttm_operation_ctx *ctx)
188 {
189 	struct drm_i915_private *i915 = container_of(bdev, typeof(*i915), bdev);
190 	struct intel_memory_region *mr = i915->mm.regions[INTEL_MEMORY_SYSTEM];
191 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
192 	const unsigned int max_segment = i915_sg_segment_size(i915->drm.dev);
193 	const size_t size = (size_t)ttm->num_pages << PAGE_SHIFT;
194 	struct file *filp = i915_tt->filp;
195 	struct sgt_iter sgt_iter;
196 	struct sg_table *st;
197 	struct page *page;
198 	unsigned long i;
199 	int err;
200 
201 	if (!filp) {
202 		struct address_space *mapping;
203 		gfp_t mask;
204 
205 		filp = shmem_file_setup("i915-shmem-tt", size, VM_NORESERVE);
206 		if (IS_ERR(filp))
207 			return PTR_ERR(filp);
208 
209 		mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
210 
211 		mapping = filp->f_mapping;
212 		mapping_set_gfp_mask(mapping, mask);
213 		GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
214 
215 		i915_tt->filp = filp;
216 	}
217 
218 	st = &i915_tt->cached_rsgt.table;
219 	err = shmem_sg_alloc_table(i915, st, size, mr, filp->f_mapping,
220 				   max_segment);
221 	if (err)
222 		return err;
223 
224 	err = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL,
225 			      DMA_ATTR_SKIP_CPU_SYNC);
226 	if (err)
227 		goto err_free_st;
228 
229 	i = 0;
230 	for_each_sgt_page(page, sgt_iter, st)
231 		ttm->pages[i++] = page;
232 
233 	if (ttm->page_flags & TTM_TT_FLAG_SWAPPED)
234 		ttm->page_flags &= ~TTM_TT_FLAG_SWAPPED;
235 
236 	return 0;
237 
238 err_free_st:
239 	shmem_sg_free_table(st, filp->f_mapping, false, false);
240 
241 	return err;
242 }
243 
i915_ttm_tt_shmem_unpopulate(struct ttm_tt * ttm)244 static void i915_ttm_tt_shmem_unpopulate(struct ttm_tt *ttm)
245 {
246 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
247 	bool backup = ttm->page_flags & TTM_TT_FLAG_SWAPPED;
248 	struct sg_table *st = &i915_tt->cached_rsgt.table;
249 
250 	shmem_sg_free_table(st, file_inode(i915_tt->filp)->i_mapping,
251 			    backup, backup);
252 }
253 
i915_ttm_tt_release(struct kref * ref)254 static void i915_ttm_tt_release(struct kref *ref)
255 {
256 	struct i915_ttm_tt *i915_tt =
257 		container_of(ref, typeof(*i915_tt), cached_rsgt.kref);
258 	struct sg_table *st = &i915_tt->cached_rsgt.table;
259 
260 	GEM_WARN_ON(st->sgl);
261 
262 	kfree(i915_tt);
263 }
264 
265 static const struct i915_refct_sgt_ops tt_rsgt_ops = {
266 	.release = i915_ttm_tt_release
267 };
268 
i915_ttm_tt_create(struct ttm_buffer_object * bo,uint32_t page_flags)269 static struct ttm_tt *i915_ttm_tt_create(struct ttm_buffer_object *bo,
270 					 uint32_t page_flags)
271 {
272 	struct drm_i915_private *i915 = container_of(bo->bdev, typeof(*i915),
273 						     bdev);
274 	struct ttm_resource_manager *man =
275 		ttm_manager_type(bo->bdev, bo->resource->mem_type);
276 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
277 	unsigned long ccs_pages = 0;
278 	enum ttm_caching caching;
279 	struct i915_ttm_tt *i915_tt;
280 	int ret;
281 
282 	if (i915_ttm_is_ghost_object(bo))
283 		return NULL;
284 
285 	i915_tt = kzalloc(sizeof(*i915_tt), GFP_KERNEL);
286 	if (!i915_tt)
287 		return NULL;
288 
289 	if (obj->flags & I915_BO_ALLOC_CPU_CLEAR &&
290 	    man->use_tt)
291 		page_flags |= TTM_TT_FLAG_ZERO_ALLOC;
292 
293 	caching = i915_ttm_select_tt_caching(obj);
294 	if (i915_gem_object_is_shrinkable(obj) && caching == ttm_cached) {
295 		page_flags |= TTM_TT_FLAG_EXTERNAL |
296 			      TTM_TT_FLAG_EXTERNAL_MAPPABLE;
297 		i915_tt->is_shmem = true;
298 	}
299 
300 	if (i915_gem_object_needs_ccs_pages(obj))
301 		ccs_pages = DIV_ROUND_UP(DIV_ROUND_UP(bo->base.size,
302 						      NUM_BYTES_PER_CCS_BYTE),
303 					 PAGE_SIZE);
304 
305 	ret = ttm_tt_init(&i915_tt->ttm, bo, page_flags, caching, ccs_pages);
306 	if (ret)
307 		goto err_free;
308 
309 	__i915_refct_sgt_init(&i915_tt->cached_rsgt, bo->base.size,
310 			      &tt_rsgt_ops);
311 
312 	i915_tt->dev = obj->base.dev->dev;
313 
314 	return &i915_tt->ttm;
315 
316 err_free:
317 	kfree(i915_tt);
318 	return NULL;
319 }
320 
i915_ttm_tt_populate(struct ttm_device * bdev,struct ttm_tt * ttm,struct ttm_operation_ctx * ctx)321 static int i915_ttm_tt_populate(struct ttm_device *bdev,
322 				struct ttm_tt *ttm,
323 				struct ttm_operation_ctx *ctx)
324 {
325 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
326 
327 	if (i915_tt->is_shmem)
328 		return i915_ttm_tt_shmem_populate(bdev, ttm, ctx);
329 
330 	return ttm_pool_alloc(&bdev->pool, ttm, ctx);
331 }
332 
i915_ttm_tt_unpopulate(struct ttm_device * bdev,struct ttm_tt * ttm)333 static void i915_ttm_tt_unpopulate(struct ttm_device *bdev, struct ttm_tt *ttm)
334 {
335 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
336 	struct sg_table *st = &i915_tt->cached_rsgt.table;
337 
338 	if (st->sgl)
339 		dma_unmap_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
340 
341 	if (i915_tt->is_shmem) {
342 		i915_ttm_tt_shmem_unpopulate(ttm);
343 	} else {
344 		sg_free_table(st);
345 		ttm_pool_free(&bdev->pool, ttm);
346 	}
347 }
348 
i915_ttm_tt_destroy(struct ttm_device * bdev,struct ttm_tt * ttm)349 static void i915_ttm_tt_destroy(struct ttm_device *bdev, struct ttm_tt *ttm)
350 {
351 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
352 
353 	if (i915_tt->filp)
354 		fput(i915_tt->filp);
355 
356 	ttm_tt_fini(ttm);
357 	i915_refct_sgt_put(&i915_tt->cached_rsgt);
358 }
359 
i915_ttm_eviction_valuable(struct ttm_buffer_object * bo,const struct ttm_place * place)360 static bool i915_ttm_eviction_valuable(struct ttm_buffer_object *bo,
361 				       const struct ttm_place *place)
362 {
363 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
364 
365 	if (i915_ttm_is_ghost_object(bo))
366 		return false;
367 
368 	/*
369 	 * EXTERNAL objects should never be swapped out by TTM, instead we need
370 	 * to handle that ourselves. TTM will already skip such objects for us,
371 	 * but we would like to avoid grabbing locks for no good reason.
372 	 */
373 	if (bo->ttm && bo->ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
374 		return false;
375 
376 	/* Will do for now. Our pinned objects are still on TTM's LRU lists */
377 	if (!i915_gem_object_evictable(obj))
378 		return false;
379 
380 	return ttm_bo_eviction_valuable(bo, place);
381 }
382 
i915_ttm_evict_flags(struct ttm_buffer_object * bo,struct ttm_placement * placement)383 static void i915_ttm_evict_flags(struct ttm_buffer_object *bo,
384 				 struct ttm_placement *placement)
385 {
386 	*placement = i915_sys_placement;
387 }
388 
389 /**
390  * i915_ttm_free_cached_io_rsgt - Free object cached LMEM information
391  * @obj: The GEM object
392  * This function frees any LMEM-related information that is cached on
393  * the object. For example the radix tree for fast page lookup and the
394  * cached refcounted sg-table
395  */
i915_ttm_free_cached_io_rsgt(struct drm_i915_gem_object * obj)396 void i915_ttm_free_cached_io_rsgt(struct drm_i915_gem_object *obj)
397 {
398 	struct radix_tree_iter iter;
399 	void __rcu **slot;
400 
401 	if (!obj->ttm.cached_io_rsgt)
402 		return;
403 
404 	rcu_read_lock();
405 	radix_tree_for_each_slot(slot, &obj->ttm.get_io_page.radix, &iter, 0)
406 		radix_tree_delete(&obj->ttm.get_io_page.radix, iter.index);
407 	rcu_read_unlock();
408 
409 	i915_refct_sgt_put(obj->ttm.cached_io_rsgt);
410 	obj->ttm.cached_io_rsgt = NULL;
411 }
412 
413 /**
414  * i915_ttm_purge - Clear an object of its memory
415  * @obj: The object
416  *
417  * This function is called to clear an object of it's memory when it is
418  * marked as not needed anymore.
419  *
420  * Return: 0 on success, negative error code on failure.
421  */
i915_ttm_purge(struct drm_i915_gem_object * obj)422 int i915_ttm_purge(struct drm_i915_gem_object *obj)
423 {
424 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
425 	struct i915_ttm_tt *i915_tt =
426 		container_of(bo->ttm, typeof(*i915_tt), ttm);
427 	struct ttm_operation_ctx ctx = {
428 		.interruptible = true,
429 		.no_wait_gpu = false,
430 	};
431 	struct ttm_placement place = {};
432 	int ret;
433 
434 	if (obj->mm.madv == __I915_MADV_PURGED)
435 		return 0;
436 
437 	ret = ttm_bo_validate(bo, &place, &ctx);
438 	if (ret)
439 		return ret;
440 
441 	if (bo->ttm && i915_tt->filp) {
442 		/*
443 		 * The below fput(which eventually calls shmem_truncate) might
444 		 * be delayed by worker, so when directly called to purge the
445 		 * pages(like by the shrinker) we should try to be more
446 		 * aggressive and release the pages immediately.
447 		 */
448 		shmem_truncate_range(file_inode(i915_tt->filp),
449 				     0, (loff_t)-1);
450 		fput(fetch_and_zero(&i915_tt->filp));
451 	}
452 
453 	obj->write_domain = 0;
454 	obj->read_domains = 0;
455 	i915_ttm_adjust_gem_after_move(obj);
456 	i915_ttm_free_cached_io_rsgt(obj);
457 	obj->mm.madv = __I915_MADV_PURGED;
458 
459 	return 0;
460 }
461 
i915_ttm_shrink(struct drm_i915_gem_object * obj,unsigned int flags)462 static int i915_ttm_shrink(struct drm_i915_gem_object *obj, unsigned int flags)
463 {
464 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
465 	struct i915_ttm_tt *i915_tt =
466 		container_of(bo->ttm, typeof(*i915_tt), ttm);
467 	struct ttm_operation_ctx ctx = {
468 		.interruptible = true,
469 		.no_wait_gpu = flags & I915_GEM_OBJECT_SHRINK_NO_GPU_WAIT,
470 	};
471 	struct ttm_placement place = {};
472 	int ret;
473 
474 	if (!bo->ttm || bo->resource->mem_type != TTM_PL_SYSTEM)
475 		return 0;
476 
477 	GEM_BUG_ON(!i915_tt->is_shmem);
478 
479 	if (!i915_tt->filp)
480 		return 0;
481 
482 	ret = ttm_bo_wait_ctx(bo, &ctx);
483 	if (ret)
484 		return ret;
485 
486 	switch (obj->mm.madv) {
487 	case I915_MADV_DONTNEED:
488 		return i915_ttm_purge(obj);
489 	case __I915_MADV_PURGED:
490 		return 0;
491 	}
492 
493 	if (bo->ttm->page_flags & TTM_TT_FLAG_SWAPPED)
494 		return 0;
495 
496 	bo->ttm->page_flags |= TTM_TT_FLAG_SWAPPED;
497 	ret = ttm_bo_validate(bo, &place, &ctx);
498 	if (ret) {
499 		bo->ttm->page_flags &= ~TTM_TT_FLAG_SWAPPED;
500 		return ret;
501 	}
502 
503 	if (flags & I915_GEM_OBJECT_SHRINK_WRITEBACK)
504 		__shmem_writeback(obj->base.size, i915_tt->filp->f_mapping);
505 
506 	return 0;
507 }
508 
i915_ttm_delete_mem_notify(struct ttm_buffer_object * bo)509 static void i915_ttm_delete_mem_notify(struct ttm_buffer_object *bo)
510 {
511 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
512 
513 	if (bo->resource && !i915_ttm_is_ghost_object(bo)) {
514 		__i915_gem_object_pages_fini(obj);
515 		i915_ttm_free_cached_io_rsgt(obj);
516 	}
517 }
518 
i915_ttm_tt_get_st(struct ttm_tt * ttm)519 static struct i915_refct_sgt *i915_ttm_tt_get_st(struct ttm_tt *ttm)
520 {
521 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
522 	struct sg_table *st;
523 	int ret;
524 
525 	if (i915_tt->cached_rsgt.table.sgl)
526 		return i915_refct_sgt_get(&i915_tt->cached_rsgt);
527 
528 	st = &i915_tt->cached_rsgt.table;
529 	ret = sg_alloc_table_from_pages_segment(st,
530 			ttm->pages, ttm->num_pages,
531 			0, (unsigned long)ttm->num_pages << PAGE_SHIFT,
532 			i915_sg_segment_size(i915_tt->dev), GFP_KERNEL);
533 	if (ret) {
534 		st->sgl = NULL;
535 		return ERR_PTR(ret);
536 	}
537 
538 	ret = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
539 	if (ret) {
540 		sg_free_table(st);
541 		return ERR_PTR(ret);
542 	}
543 
544 	return i915_refct_sgt_get(&i915_tt->cached_rsgt);
545 }
546 
547 /**
548  * i915_ttm_resource_get_st - Get a refcounted sg-table pointing to the
549  * resource memory
550  * @obj: The GEM object used for sg-table caching
551  * @res: The struct ttm_resource for which an sg-table is requested.
552  *
553  * This function returns a refcounted sg-table representing the memory
554  * pointed to by @res. If @res is the object's current resource it may also
555  * cache the sg_table on the object or attempt to access an already cached
556  * sg-table. The refcounted sg-table needs to be put when no-longer in use.
557  *
558  * Return: A valid pointer to a struct i915_refct_sgt or error pointer on
559  * failure.
560  */
561 struct i915_refct_sgt *
i915_ttm_resource_get_st(struct drm_i915_gem_object * obj,struct ttm_resource * res)562 i915_ttm_resource_get_st(struct drm_i915_gem_object *obj,
563 			 struct ttm_resource *res)
564 {
565 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
566 	u32 page_alignment;
567 
568 	if (!i915_ttm_gtt_binds_lmem(res))
569 		return i915_ttm_tt_get_st(bo->ttm);
570 
571 	page_alignment = bo->page_alignment << PAGE_SHIFT;
572 	if (!page_alignment)
573 		page_alignment = obj->mm.region->min_page_size;
574 
575 	/*
576 	 * If CPU mapping differs, we need to add the ttm_tt pages to
577 	 * the resulting st. Might make sense for GGTT.
578 	 */
579 	GEM_WARN_ON(!i915_ttm_cpu_maps_iomem(res));
580 	if (bo->resource == res) {
581 		if (!obj->ttm.cached_io_rsgt) {
582 			struct i915_refct_sgt *rsgt;
583 
584 			rsgt = intel_region_ttm_resource_to_rsgt(obj->mm.region,
585 								 res,
586 								 page_alignment);
587 			if (IS_ERR(rsgt))
588 				return rsgt;
589 
590 			obj->ttm.cached_io_rsgt = rsgt;
591 		}
592 		return i915_refct_sgt_get(obj->ttm.cached_io_rsgt);
593 	}
594 
595 	return intel_region_ttm_resource_to_rsgt(obj->mm.region, res,
596 						 page_alignment);
597 }
598 
i915_ttm_truncate(struct drm_i915_gem_object * obj)599 static int i915_ttm_truncate(struct drm_i915_gem_object *obj)
600 {
601 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
602 	int err;
603 
604 	WARN_ON_ONCE(obj->mm.madv == I915_MADV_WILLNEED);
605 
606 	err = ttm_bo_wait(bo, true, false);
607 	if (err)
608 		return err;
609 
610 	err = i915_ttm_move_notify(bo);
611 	if (err)
612 		return err;
613 
614 	return i915_ttm_purge(obj);
615 }
616 
i915_ttm_swap_notify(struct ttm_buffer_object * bo)617 static void i915_ttm_swap_notify(struct ttm_buffer_object *bo)
618 {
619 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
620 	int ret;
621 
622 	if (i915_ttm_is_ghost_object(bo))
623 		return;
624 
625 	ret = i915_ttm_move_notify(bo);
626 	GEM_WARN_ON(ret);
627 	GEM_WARN_ON(obj->ttm.cached_io_rsgt);
628 	if (!ret && obj->mm.madv != I915_MADV_WILLNEED)
629 		i915_ttm_purge(obj);
630 }
631 
632 /**
633  * i915_ttm_resource_mappable - Return true if the ttm resource is CPU
634  * accessible.
635  * @res: The TTM resource to check.
636  *
637  * This is interesting on small-BAR systems where we may encounter lmem objects
638  * that can't be accessed via the CPU.
639  */
i915_ttm_resource_mappable(struct ttm_resource * res)640 bool i915_ttm_resource_mappable(struct ttm_resource *res)
641 {
642 	struct i915_ttm_buddy_resource *bman_res = to_ttm_buddy_resource(res);
643 
644 	if (!i915_ttm_cpu_maps_iomem(res))
645 		return true;
646 
647 	return bman_res->used_visible_size == bman_res->base.num_pages;
648 }
649 
i915_ttm_io_mem_reserve(struct ttm_device * bdev,struct ttm_resource * mem)650 static int i915_ttm_io_mem_reserve(struct ttm_device *bdev, struct ttm_resource *mem)
651 {
652 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(mem->bo);
653 	bool unknown_state;
654 
655 	if (i915_ttm_is_ghost_object(mem->bo))
656 		return -EINVAL;
657 
658 	if (!kref_get_unless_zero(&obj->base.refcount))
659 		return -EINVAL;
660 
661 	assert_object_held(obj);
662 
663 	unknown_state = i915_gem_object_has_unknown_state(obj);
664 	i915_gem_object_put(obj);
665 	if (unknown_state)
666 		return -EINVAL;
667 
668 	if (!i915_ttm_cpu_maps_iomem(mem))
669 		return 0;
670 
671 	if (!i915_ttm_resource_mappable(mem))
672 		return -EINVAL;
673 
674 	mem->bus.caching = ttm_write_combined;
675 	mem->bus.is_iomem = true;
676 
677 	return 0;
678 }
679 
i915_ttm_io_mem_pfn(struct ttm_buffer_object * bo,unsigned long page_offset)680 static unsigned long i915_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
681 					 unsigned long page_offset)
682 {
683 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
684 	struct scatterlist *sg;
685 	unsigned long base;
686 	unsigned int ofs;
687 
688 	GEM_BUG_ON(i915_ttm_is_ghost_object(bo));
689 	GEM_WARN_ON(bo->ttm);
690 
691 	base = obj->mm.region->iomap.base - obj->mm.region->region.start;
692 	sg = __i915_gem_object_get_sg(obj, &obj->ttm.get_io_page, page_offset, &ofs, true);
693 
694 	return ((base + sg_dma_address(sg)) >> PAGE_SHIFT) + ofs;
695 }
696 
697 /*
698  * All callbacks need to take care not to downcast a struct ttm_buffer_object
699  * without checking its subclass, since it might be a TTM ghost object.
700  */
701 static struct ttm_device_funcs i915_ttm_bo_driver = {
702 	.ttm_tt_create = i915_ttm_tt_create,
703 	.ttm_tt_populate = i915_ttm_tt_populate,
704 	.ttm_tt_unpopulate = i915_ttm_tt_unpopulate,
705 	.ttm_tt_destroy = i915_ttm_tt_destroy,
706 	.eviction_valuable = i915_ttm_eviction_valuable,
707 	.evict_flags = i915_ttm_evict_flags,
708 	.move = i915_ttm_move,
709 	.swap_notify = i915_ttm_swap_notify,
710 	.delete_mem_notify = i915_ttm_delete_mem_notify,
711 	.io_mem_reserve = i915_ttm_io_mem_reserve,
712 	.io_mem_pfn = i915_ttm_io_mem_pfn,
713 };
714 
715 /**
716  * i915_ttm_driver - Return a pointer to the TTM device funcs
717  *
718  * Return: Pointer to statically allocated TTM device funcs.
719  */
i915_ttm_driver(void)720 struct ttm_device_funcs *i915_ttm_driver(void)
721 {
722 	return &i915_ttm_bo_driver;
723 }
724 
__i915_ttm_get_pages(struct drm_i915_gem_object * obj,struct ttm_placement * placement)725 static int __i915_ttm_get_pages(struct drm_i915_gem_object *obj,
726 				struct ttm_placement *placement)
727 {
728 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
729 	struct ttm_operation_ctx ctx = {
730 		.interruptible = true,
731 		.no_wait_gpu = false,
732 	};
733 	int real_num_busy;
734 	int ret;
735 
736 	/* First try only the requested placement. No eviction. */
737 	real_num_busy = fetch_and_zero(&placement->num_busy_placement);
738 	ret = ttm_bo_validate(bo, placement, &ctx);
739 	if (ret) {
740 		ret = i915_ttm_err_to_gem(ret);
741 		/*
742 		 * Anything that wants to restart the operation gets to
743 		 * do that.
744 		 */
745 		if (ret == -EDEADLK || ret == -EINTR || ret == -ERESTARTSYS ||
746 		    ret == -EAGAIN)
747 			return ret;
748 
749 		/*
750 		 * If the initial attempt fails, allow all accepted placements,
751 		 * evicting if necessary.
752 		 */
753 		placement->num_busy_placement = real_num_busy;
754 		ret = ttm_bo_validate(bo, placement, &ctx);
755 		if (ret)
756 			return i915_ttm_err_to_gem(ret);
757 	}
758 
759 	if (bo->ttm && !ttm_tt_is_populated(bo->ttm)) {
760 		ret = ttm_tt_populate(bo->bdev, bo->ttm, &ctx);
761 		if (ret)
762 			return ret;
763 
764 		i915_ttm_adjust_domains_after_move(obj);
765 		i915_ttm_adjust_gem_after_move(obj);
766 	}
767 
768 	if (!i915_gem_object_has_pages(obj)) {
769 		struct i915_refct_sgt *rsgt =
770 			i915_ttm_resource_get_st(obj, bo->resource);
771 
772 		if (IS_ERR(rsgt))
773 			return PTR_ERR(rsgt);
774 
775 		GEM_BUG_ON(obj->mm.rsgt);
776 		obj->mm.rsgt = rsgt;
777 		__i915_gem_object_set_pages(obj, &rsgt->table,
778 					    i915_sg_dma_sizes(rsgt->table.sgl));
779 	}
780 
781 	GEM_BUG_ON(bo->ttm && ((obj->base.size >> PAGE_SHIFT) < bo->ttm->num_pages));
782 	i915_ttm_adjust_lru(obj);
783 	return ret;
784 }
785 
i915_ttm_get_pages(struct drm_i915_gem_object * obj)786 static int i915_ttm_get_pages(struct drm_i915_gem_object *obj)
787 {
788 	struct ttm_place requested, busy[I915_TTM_MAX_PLACEMENTS];
789 	struct ttm_placement placement;
790 
791 	GEM_BUG_ON(obj->mm.n_placements > I915_TTM_MAX_PLACEMENTS);
792 
793 	/* Move to the requested placement. */
794 	i915_ttm_placement_from_obj(obj, &requested, busy, &placement);
795 
796 	return __i915_ttm_get_pages(obj, &placement);
797 }
798 
799 /**
800  * DOC: Migration vs eviction
801  *
802  * GEM migration may not be the same as TTM migration / eviction. If
803  * the TTM core decides to evict an object it may be evicted to a
804  * TTM memory type that is not in the object's allowable GEM regions, or
805  * in fact theoretically to a TTM memory type that doesn't correspond to
806  * a GEM memory region. In that case the object's GEM region is not
807  * updated, and the data is migrated back to the GEM region at
808  * get_pages time. TTM may however set up CPU ptes to the object even
809  * when it is evicted.
810  * Gem forced migration using the i915_ttm_migrate() op, is allowed even
811  * to regions that are not in the object's list of allowable placements.
812  */
__i915_ttm_migrate(struct drm_i915_gem_object * obj,struct intel_memory_region * mr,unsigned int flags)813 static int __i915_ttm_migrate(struct drm_i915_gem_object *obj,
814 			      struct intel_memory_region *mr,
815 			      unsigned int flags)
816 {
817 	struct ttm_place requested;
818 	struct ttm_placement placement;
819 	int ret;
820 
821 	i915_ttm_place_from_region(mr, &requested, obj->bo_offset,
822 				   obj->base.size, flags);
823 	placement.num_placement = 1;
824 	placement.num_busy_placement = 1;
825 	placement.placement = &requested;
826 	placement.busy_placement = &requested;
827 
828 	ret = __i915_ttm_get_pages(obj, &placement);
829 	if (ret)
830 		return ret;
831 
832 	/*
833 	 * Reinitialize the region bindings. This is primarily
834 	 * required for objects where the new region is not in
835 	 * its allowable placements.
836 	 */
837 	if (obj->mm.region != mr) {
838 		i915_gem_object_release_memory_region(obj);
839 		i915_gem_object_init_memory_region(obj, mr);
840 	}
841 
842 	return 0;
843 }
844 
i915_ttm_migrate(struct drm_i915_gem_object * obj,struct intel_memory_region * mr,unsigned int flags)845 static int i915_ttm_migrate(struct drm_i915_gem_object *obj,
846 			    struct intel_memory_region *mr,
847 			    unsigned int flags)
848 {
849 	return __i915_ttm_migrate(obj, mr, flags);
850 }
851 
i915_ttm_put_pages(struct drm_i915_gem_object * obj,struct sg_table * st)852 static void i915_ttm_put_pages(struct drm_i915_gem_object *obj,
853 			       struct sg_table *st)
854 {
855 	/*
856 	 * We're currently not called from a shrinker, so put_pages()
857 	 * typically means the object is about to destroyed, or called
858 	 * from move_notify(). So just avoid doing much for now.
859 	 * If the object is not destroyed next, The TTM eviction logic
860 	 * and shrinkers will move it out if needed.
861 	 */
862 
863 	if (obj->mm.rsgt)
864 		i915_refct_sgt_put(fetch_and_zero(&obj->mm.rsgt));
865 }
866 
867 /**
868  * i915_ttm_adjust_lru - Adjust an object's position on relevant LRU lists.
869  * @obj: The object
870  */
i915_ttm_adjust_lru(struct drm_i915_gem_object * obj)871 void i915_ttm_adjust_lru(struct drm_i915_gem_object *obj)
872 {
873 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
874 	struct i915_ttm_tt *i915_tt =
875 		container_of(bo->ttm, typeof(*i915_tt), ttm);
876 	bool shrinkable =
877 		bo->ttm && i915_tt->filp && ttm_tt_is_populated(bo->ttm);
878 
879 	/*
880 	 * Don't manipulate the TTM LRUs while in TTM bo destruction.
881 	 * We're called through i915_ttm_delete_mem_notify().
882 	 */
883 	if (!kref_read(&bo->kref))
884 		return;
885 
886 	/*
887 	 * We skip managing the shrinker LRU in set_pages() and just manage
888 	 * everything here. This does at least solve the issue with having
889 	 * temporary shmem mappings(like with evicted lmem) not being visible to
890 	 * the shrinker. Only our shmem objects are shrinkable, everything else
891 	 * we keep as unshrinkable.
892 	 *
893 	 * To make sure everything plays nice we keep an extra shrink pin in TTM
894 	 * if the underlying pages are not currently shrinkable. Once we release
895 	 * our pin, like when the pages are moved to shmem, the pages will then
896 	 * be added to the shrinker LRU, assuming the caller isn't also holding
897 	 * a pin.
898 	 *
899 	 * TODO: consider maybe also bumping the shrinker list here when we have
900 	 * already unpinned it, which should give us something more like an LRU.
901 	 *
902 	 * TODO: There is a small window of opportunity for this function to
903 	 * get called from eviction after we've dropped the last GEM refcount,
904 	 * but before the TTM deleted flag is set on the object. Avoid
905 	 * adjusting the shrinker list in such cases, since the object is
906 	 * not available to the shrinker anyway due to its zero refcount.
907 	 * To fix this properly we should move to a TTM shrinker LRU list for
908 	 * these objects.
909 	 */
910 	if (kref_get_unless_zero(&obj->base.refcount)) {
911 		if (shrinkable != obj->mm.ttm_shrinkable) {
912 			if (shrinkable) {
913 				if (obj->mm.madv == I915_MADV_WILLNEED)
914 					__i915_gem_object_make_shrinkable(obj);
915 				else
916 					__i915_gem_object_make_purgeable(obj);
917 			} else {
918 				i915_gem_object_make_unshrinkable(obj);
919 			}
920 
921 			obj->mm.ttm_shrinkable = shrinkable;
922 		}
923 		i915_gem_object_put(obj);
924 	}
925 
926 	/*
927 	 * Put on the correct LRU list depending on the MADV status
928 	 */
929 	spin_lock(&bo->bdev->lru_lock);
930 	if (shrinkable) {
931 		/* Try to keep shmem_tt from being considered for shrinking. */
932 		bo->priority = TTM_MAX_BO_PRIORITY - 1;
933 	} else if (obj->mm.madv != I915_MADV_WILLNEED) {
934 		bo->priority = I915_TTM_PRIO_PURGE;
935 	} else if (!i915_gem_object_has_pages(obj)) {
936 		bo->priority = I915_TTM_PRIO_NO_PAGES;
937 	} else {
938 		struct ttm_resource_manager *man =
939 			ttm_manager_type(bo->bdev, bo->resource->mem_type);
940 
941 		/*
942 		 * If we need to place an LMEM resource which doesn't need CPU
943 		 * access then we should try not to victimize mappable objects
944 		 * first, since we likely end up stealing more of the mappable
945 		 * portion. And likewise when we try to find space for a mappble
946 		 * object, we know not to ever victimize objects that don't
947 		 * occupy any mappable pages.
948 		 */
949 		if (i915_ttm_cpu_maps_iomem(bo->resource) &&
950 		    i915_ttm_buddy_man_visible_size(man) < man->size &&
951 		    !(obj->flags & I915_BO_ALLOC_GPU_ONLY))
952 			bo->priority = I915_TTM_PRIO_NEEDS_CPU_ACCESS;
953 		else
954 			bo->priority = I915_TTM_PRIO_HAS_PAGES;
955 	}
956 
957 	ttm_bo_move_to_lru_tail(bo);
958 	spin_unlock(&bo->bdev->lru_lock);
959 }
960 
961 /*
962  * TTM-backed gem object destruction requires some clarification.
963  * Basically we have two possibilities here. We can either rely on the
964  * i915 delayed destruction and put the TTM object when the object
965  * is idle. This would be detected by TTM which would bypass the
966  * TTM delayed destroy handling. The other approach is to put the TTM
967  * object early and rely on the TTM destroyed handling, and then free
968  * the leftover parts of the GEM object once TTM's destroyed list handling is
969  * complete. For now, we rely on the latter for two reasons:
970  * a) TTM can evict an object even when it's on the delayed destroy list,
971  * which in theory allows for complete eviction.
972  * b) There is work going on in TTM to allow freeing an object even when
973  * it's not idle, and using the TTM destroyed list handling could help us
974  * benefit from that.
975  */
i915_ttm_delayed_free(struct drm_i915_gem_object * obj)976 static void i915_ttm_delayed_free(struct drm_i915_gem_object *obj)
977 {
978 	GEM_BUG_ON(!obj->ttm.created);
979 
980 	ttm_bo_put(i915_gem_to_ttm(obj));
981 }
982 
vm_fault_ttm(struct vm_fault * vmf)983 static vm_fault_t vm_fault_ttm(struct vm_fault *vmf)
984 {
985 	struct vm_area_struct *area = vmf->vma;
986 	struct ttm_buffer_object *bo = area->vm_private_data;
987 	struct drm_device *dev = bo->base.dev;
988 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
989 	intel_wakeref_t wakeref = 0;
990 	vm_fault_t ret;
991 	int idx;
992 
993 	if (i915_ttm_is_ghost_object(bo))
994 		return VM_FAULT_SIGBUS;
995 
996 	/* Sanity check that we allow writing into this object */
997 	if (unlikely(i915_gem_object_is_readonly(obj) &&
998 		     area->vm_flags & VM_WRITE))
999 		return VM_FAULT_SIGBUS;
1000 
1001 	ret = ttm_bo_vm_reserve(bo, vmf);
1002 	if (ret)
1003 		return ret;
1004 
1005 	if (obj->mm.madv != I915_MADV_WILLNEED) {
1006 		dma_resv_unlock(bo->base.resv);
1007 		return VM_FAULT_SIGBUS;
1008 	}
1009 
1010 	if (!i915_ttm_resource_mappable(bo->resource)) {
1011 		int err = -ENODEV;
1012 		int i;
1013 
1014 		for (i = 0; i < obj->mm.n_placements; i++) {
1015 			struct intel_memory_region *mr = obj->mm.placements[i];
1016 			unsigned int flags;
1017 
1018 			if (!mr->io_size && mr->type != INTEL_MEMORY_SYSTEM)
1019 				continue;
1020 
1021 			flags = obj->flags;
1022 			flags &= ~I915_BO_ALLOC_GPU_ONLY;
1023 			err = __i915_ttm_migrate(obj, mr, flags);
1024 			if (!err)
1025 				break;
1026 		}
1027 
1028 		if (err) {
1029 			drm_dbg(dev, "Unable to make resource CPU accessible\n");
1030 			dma_resv_unlock(bo->base.resv);
1031 			ret = VM_FAULT_SIGBUS;
1032 			goto out_rpm;
1033 		}
1034 	}
1035 
1036 	if (i915_ttm_cpu_maps_iomem(bo->resource))
1037 		wakeref = intel_runtime_pm_get(&to_i915(obj->base.dev)->runtime_pm);
1038 
1039 	if (drm_dev_enter(dev, &idx)) {
1040 		ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
1041 					       TTM_BO_VM_NUM_PREFAULT);
1042 		drm_dev_exit(idx);
1043 	} else {
1044 		ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
1045 	}
1046 
1047 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
1048 		goto out_rpm;
1049 
1050 	/*
1051 	 * ttm_bo_vm_reserve() already has dma_resv_lock.
1052 	 * userfault_count is protected by dma_resv lock and rpm wakeref.
1053 	 */
1054 	if (ret == VM_FAULT_NOPAGE && wakeref && !obj->userfault_count) {
1055 		obj->userfault_count = 1;
1056 		spin_lock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1057 		list_add(&obj->userfault_link, &to_i915(obj->base.dev)->runtime_pm.lmem_userfault_list);
1058 		spin_unlock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1059 	}
1060 
1061 	if (wakeref & CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND)
1062 		intel_wakeref_auto(&to_i915(obj->base.dev)->runtime_pm.userfault_wakeref,
1063 				   msecs_to_jiffies_timeout(CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND));
1064 
1065 	i915_ttm_adjust_lru(obj);
1066 
1067 	dma_resv_unlock(bo->base.resv);
1068 
1069 out_rpm:
1070 	if (wakeref)
1071 		intel_runtime_pm_put(&to_i915(obj->base.dev)->runtime_pm, wakeref);
1072 
1073 	return ret;
1074 }
1075 
1076 static int
vm_access_ttm(struct vm_area_struct * area,unsigned long addr,void * buf,int len,int write)1077 vm_access_ttm(struct vm_area_struct *area, unsigned long addr,
1078 	      void *buf, int len, int write)
1079 {
1080 	struct drm_i915_gem_object *obj =
1081 		i915_ttm_to_gem(area->vm_private_data);
1082 
1083 	if (i915_gem_object_is_readonly(obj) && write)
1084 		return -EACCES;
1085 
1086 	return ttm_bo_vm_access(area, addr, buf, len, write);
1087 }
1088 
ttm_vm_open(struct vm_area_struct * vma)1089 static void ttm_vm_open(struct vm_area_struct *vma)
1090 {
1091 	struct drm_i915_gem_object *obj =
1092 		i915_ttm_to_gem(vma->vm_private_data);
1093 
1094 	GEM_BUG_ON(i915_ttm_is_ghost_object(vma->vm_private_data));
1095 	i915_gem_object_get(obj);
1096 }
1097 
ttm_vm_close(struct vm_area_struct * vma)1098 static void ttm_vm_close(struct vm_area_struct *vma)
1099 {
1100 	struct drm_i915_gem_object *obj =
1101 		i915_ttm_to_gem(vma->vm_private_data);
1102 
1103 	GEM_BUG_ON(i915_ttm_is_ghost_object(vma->vm_private_data));
1104 	i915_gem_object_put(obj);
1105 }
1106 
1107 static const struct vm_operations_struct vm_ops_ttm = {
1108 	.fault = vm_fault_ttm,
1109 	.access = vm_access_ttm,
1110 	.open = ttm_vm_open,
1111 	.close = ttm_vm_close,
1112 };
1113 
i915_ttm_mmap_offset(struct drm_i915_gem_object * obj)1114 static u64 i915_ttm_mmap_offset(struct drm_i915_gem_object *obj)
1115 {
1116 	/* The ttm_bo must be allocated with I915_BO_ALLOC_USER */
1117 	GEM_BUG_ON(!drm_mm_node_allocated(&obj->base.vma_node.vm_node));
1118 
1119 	return drm_vma_node_offset_addr(&obj->base.vma_node);
1120 }
1121 
i915_ttm_unmap_virtual(struct drm_i915_gem_object * obj)1122 static void i915_ttm_unmap_virtual(struct drm_i915_gem_object *obj)
1123 {
1124 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
1125 	intel_wakeref_t wakeref = 0;
1126 
1127 	assert_object_held_shared(obj);
1128 
1129 	if (i915_ttm_cpu_maps_iomem(bo->resource)) {
1130 		wakeref = intel_runtime_pm_get(&to_i915(obj->base.dev)->runtime_pm);
1131 
1132 		/* userfault_count is protected by obj lock and rpm wakeref. */
1133 		if (obj->userfault_count) {
1134 			spin_lock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1135 			list_del(&obj->userfault_link);
1136 			spin_unlock(&to_i915(obj->base.dev)->runtime_pm.lmem_userfault_lock);
1137 			obj->userfault_count = 0;
1138 		}
1139 	}
1140 
1141 	ttm_bo_unmap_virtual(i915_gem_to_ttm(obj));
1142 
1143 	if (wakeref)
1144 		intel_runtime_pm_put(&to_i915(obj->base.dev)->runtime_pm, wakeref);
1145 }
1146 
1147 static const struct drm_i915_gem_object_ops i915_gem_ttm_obj_ops = {
1148 	.name = "i915_gem_object_ttm",
1149 	.flags = I915_GEM_OBJECT_IS_SHRINKABLE |
1150 		 I915_GEM_OBJECT_SELF_MANAGED_SHRINK_LIST,
1151 
1152 	.get_pages = i915_ttm_get_pages,
1153 	.put_pages = i915_ttm_put_pages,
1154 	.truncate = i915_ttm_truncate,
1155 	.shrink = i915_ttm_shrink,
1156 
1157 	.adjust_lru = i915_ttm_adjust_lru,
1158 	.delayed_free = i915_ttm_delayed_free,
1159 	.migrate = i915_ttm_migrate,
1160 
1161 	.mmap_offset = i915_ttm_mmap_offset,
1162 	.unmap_virtual = i915_ttm_unmap_virtual,
1163 	.mmap_ops = &vm_ops_ttm,
1164 };
1165 
i915_ttm_bo_destroy(struct ttm_buffer_object * bo)1166 void i915_ttm_bo_destroy(struct ttm_buffer_object *bo)
1167 {
1168 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
1169 
1170 	i915_gem_object_release_memory_region(obj);
1171 	mutex_destroy(&obj->ttm.get_io_page.lock);
1172 
1173 	if (obj->ttm.created) {
1174 		/*
1175 		 * We freely manage the shrinker LRU outide of the mm.pages life
1176 		 * cycle. As a result when destroying the object we should be
1177 		 * extra paranoid and ensure we remove it from the LRU, before
1178 		 * we free the object.
1179 		 *
1180 		 * Touching the ttm_shrinkable outside of the object lock here
1181 		 * should be safe now that the last GEM object ref was dropped.
1182 		 */
1183 		if (obj->mm.ttm_shrinkable)
1184 			i915_gem_object_make_unshrinkable(obj);
1185 
1186 		i915_ttm_backup_free(obj);
1187 
1188 		/* This releases all gem object bindings to the backend. */
1189 		__i915_gem_free_object(obj);
1190 
1191 		call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
1192 	} else {
1193 		__i915_gem_object_fini(obj);
1194 	}
1195 }
1196 
1197 /**
1198  * __i915_gem_ttm_object_init - Initialize a ttm-backed i915 gem object
1199  * @mem: The initial memory region for the object.
1200  * @obj: The gem object.
1201  * @size: Object size in bytes.
1202  * @flags: gem object flags.
1203  *
1204  * Return: 0 on success, negative error code on failure.
1205  */
__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)1206 int __i915_gem_ttm_object_init(struct intel_memory_region *mem,
1207 			       struct drm_i915_gem_object *obj,
1208 			       resource_size_t offset,
1209 			       resource_size_t size,
1210 			       resource_size_t page_size,
1211 			       unsigned int flags)
1212 {
1213 	static struct lock_class_key lock_class;
1214 	struct drm_i915_private *i915 = mem->i915;
1215 	struct ttm_operation_ctx ctx = {
1216 		.interruptible = true,
1217 		.no_wait_gpu = false,
1218 	};
1219 	enum ttm_bo_type bo_type;
1220 	int ret;
1221 
1222 	drm_gem_private_object_init(&i915->drm, &obj->base, size);
1223 	i915_gem_object_init(obj, &i915_gem_ttm_obj_ops, &lock_class, flags);
1224 
1225 	obj->bo_offset = offset;
1226 
1227 	/* Don't put on a region list until we're either locked or fully initialized. */
1228 	obj->mm.region = mem;
1229 	INIT_LIST_HEAD(&obj->mm.region_link);
1230 
1231 	INIT_RADIX_TREE(&obj->ttm.get_io_page.radix, GFP_KERNEL | __GFP_NOWARN);
1232 	mutex_init(&obj->ttm.get_io_page.lock);
1233 	bo_type = (obj->flags & I915_BO_ALLOC_USER) ? ttm_bo_type_device :
1234 		ttm_bo_type_kernel;
1235 
1236 	obj->base.vma_node.driver_private = i915_gem_to_ttm(obj);
1237 
1238 	/* Forcing the page size is kernel internal only */
1239 	GEM_BUG_ON(page_size && obj->mm.n_placements);
1240 
1241 	/*
1242 	 * Keep an extra shrink pin to prevent the object from being made
1243 	 * shrinkable too early. If the ttm_tt is ever allocated in shmem, we
1244 	 * drop the pin. The TTM backend manages the shrinker LRU itself,
1245 	 * outside of the normal mm.pages life cycle.
1246 	 */
1247 	i915_gem_object_make_unshrinkable(obj);
1248 
1249 	/*
1250 	 * If this function fails, it will call the destructor, but
1251 	 * our caller still owns the object. So no freeing in the
1252 	 * destructor until obj->ttm.created is true.
1253 	 * Similarly, in delayed_destroy, we can't call ttm_bo_put()
1254 	 * until successful initialization.
1255 	 */
1256 	ret = ttm_bo_init_reserved(&i915->bdev, i915_gem_to_ttm(obj), bo_type,
1257 				   &i915_sys_placement, page_size >> PAGE_SHIFT,
1258 				   &ctx, NULL, NULL, i915_ttm_bo_destroy);
1259 	if (ret)
1260 		return i915_ttm_err_to_gem(ret);
1261 
1262 	obj->ttm.created = true;
1263 	i915_gem_object_release_memory_region(obj);
1264 	i915_gem_object_init_memory_region(obj, mem);
1265 	i915_ttm_adjust_domains_after_move(obj);
1266 	i915_ttm_adjust_gem_after_move(obj);
1267 	i915_gem_object_unlock(obj);
1268 
1269 	return 0;
1270 }
1271 
1272 static const struct intel_memory_region_ops ttm_system_region_ops = {
1273 	.init_object = __i915_gem_ttm_object_init,
1274 	.release = intel_region_ttm_fini,
1275 };
1276 
1277 struct intel_memory_region *
i915_gem_ttm_system_setup(struct drm_i915_private * i915,u16 type,u16 instance)1278 i915_gem_ttm_system_setup(struct drm_i915_private *i915,
1279 			  u16 type, u16 instance)
1280 {
1281 	struct intel_memory_region *mr;
1282 
1283 	mr = intel_memory_region_create(i915, 0,
1284 					totalram_pages() << PAGE_SHIFT,
1285 					PAGE_SIZE, 0, 0,
1286 					type, instance,
1287 					&ttm_system_region_ops);
1288 	if (IS_ERR(mr))
1289 		return mr;
1290 
1291 	intel_memory_region_set_name(mr, "system-ttm");
1292 	return mr;
1293 }
1294