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