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 
11 #include "i915_drv.h"
12 #include "intel_memory_region.h"
13 #include "intel_region_ttm.h"
14 
15 #include "gem/i915_gem_mman.h"
16 #include "gem/i915_gem_object.h"
17 #include "gem/i915_gem_region.h"
18 #include "gem/i915_gem_ttm.h"
19 #include "gem/i915_gem_ttm_move.h"
20 #include "gem/i915_gem_ttm_pm.h"
21 
22 #define I915_TTM_PRIO_PURGE     0
23 #define I915_TTM_PRIO_NO_PAGES  1
24 #define I915_TTM_PRIO_HAS_PAGES 2
25 
26 /*
27  * Size of struct ttm_place vector in on-stack struct ttm_placement allocs
28  */
29 #define I915_TTM_MAX_PLACEMENTS INTEL_REGION_UNKNOWN
30 
31 /**
32  * struct i915_ttm_tt - TTM page vector with additional private information
33  * @ttm: The base TTM page vector.
34  * @dev: The struct device used for dma mapping and unmapping.
35  * @cached_rsgt: The cached scatter-gather table.
36  * @is_shmem: Set if using shmem.
37  * @filp: The shmem file, if using shmem backend.
38  *
39  * Note that DMA may be going on right up to the point where the page-
40  * vector is unpopulated in delayed destroy. Hence keep the
41  * scatter-gather table mapped and cached up to that point. This is
42  * different from the cached gem object io scatter-gather table which
43  * doesn't have an associated dma mapping.
44  */
45 struct i915_ttm_tt {
46 	struct ttm_tt ttm;
47 	struct device *dev;
48 	struct i915_refct_sgt cached_rsgt;
49 
50 	bool is_shmem;
51 	struct file *filp;
52 };
53 
54 static const struct ttm_place sys_placement_flags = {
55 	.fpfn = 0,
56 	.lpfn = 0,
57 	.mem_type = I915_PL_SYSTEM,
58 	.flags = 0,
59 };
60 
61 static struct ttm_placement i915_sys_placement = {
62 	.num_placement = 1,
63 	.placement = &sys_placement_flags,
64 	.num_busy_placement = 1,
65 	.busy_placement = &sys_placement_flags,
66 };
67 
68 /**
69  * i915_ttm_sys_placement - Return the struct ttm_placement to be
70  * used for an object in system memory.
71  *
72  * Rather than making the struct extern, use this
73  * function.
74  *
75  * Return: A pointer to a static variable for sys placement.
76  */
77 struct ttm_placement *i915_ttm_sys_placement(void)
78 {
79 	return &i915_sys_placement;
80 }
81 
82 static int i915_ttm_err_to_gem(int err)
83 {
84 	/* Fastpath */
85 	if (likely(!err))
86 		return 0;
87 
88 	switch (err) {
89 	case -EBUSY:
90 		/*
91 		 * TTM likes to convert -EDEADLK to -EBUSY, and wants us to
92 		 * restart the operation, since we don't record the contending
93 		 * lock. We use -EAGAIN to restart.
94 		 */
95 		return -EAGAIN;
96 	case -ENOSPC:
97 		/*
98 		 * Memory type / region is full, and we can't evict.
99 		 * Except possibly system, that returns -ENOMEM;
100 		 */
101 		return -ENXIO;
102 	default:
103 		break;
104 	}
105 
106 	return err;
107 }
108 
109 static enum ttm_caching
110 i915_ttm_select_tt_caching(const struct drm_i915_gem_object *obj)
111 {
112 	/*
113 	 * Objects only allowed in system get cached cpu-mappings, or when
114 	 * evicting lmem-only buffers to system for swapping. Other objects get
115 	 * WC mapping for now. Even if in system.
116 	 */
117 	if (obj->mm.n_placements <= 1)
118 		return ttm_cached;
119 
120 	return ttm_write_combined;
121 }
122 
123 static void
124 i915_ttm_place_from_region(const struct intel_memory_region *mr,
125 			   struct ttm_place *place,
126 			   unsigned int flags)
127 {
128 	memset(place, 0, sizeof(*place));
129 	place->mem_type = intel_region_to_ttm_type(mr);
130 
131 	if (flags & I915_BO_ALLOC_CONTIGUOUS)
132 		place->flags = TTM_PL_FLAG_CONTIGUOUS;
133 }
134 
135 static void
136 i915_ttm_placement_from_obj(const struct drm_i915_gem_object *obj,
137 			    struct ttm_place *requested,
138 			    struct ttm_place *busy,
139 			    struct ttm_placement *placement)
140 {
141 	unsigned int num_allowed = obj->mm.n_placements;
142 	unsigned int flags = obj->flags;
143 	unsigned int i;
144 
145 	placement->num_placement = 1;
146 	i915_ttm_place_from_region(num_allowed ? obj->mm.placements[0] :
147 				   obj->mm.region, requested, flags);
148 
149 	/* Cache this on object? */
150 	placement->num_busy_placement = num_allowed;
151 	for (i = 0; i < placement->num_busy_placement; ++i)
152 		i915_ttm_place_from_region(obj->mm.placements[i], busy + i, flags);
153 
154 	if (num_allowed == 0) {
155 		*busy = *requested;
156 		placement->num_busy_placement = 1;
157 	}
158 
159 	placement->placement = requested;
160 	placement->busy_placement = busy;
161 }
162 
163 static int i915_ttm_tt_shmem_populate(struct ttm_device *bdev,
164 				      struct ttm_tt *ttm,
165 				      struct ttm_operation_ctx *ctx)
166 {
167 	struct drm_i915_private *i915 = container_of(bdev, typeof(*i915), bdev);
168 	struct intel_memory_region *mr = i915->mm.regions[INTEL_MEMORY_SYSTEM];
169 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
170 	const unsigned int max_segment = i915_sg_segment_size();
171 	const size_t size = (size_t)ttm->num_pages << PAGE_SHIFT;
172 	struct file *filp = i915_tt->filp;
173 	struct sgt_iter sgt_iter;
174 	struct sg_table *st;
175 	struct page *page;
176 	unsigned long i;
177 	int err;
178 
179 	if (!filp) {
180 		struct address_space *mapping;
181 		gfp_t mask;
182 
183 		filp = shmem_file_setup("i915-shmem-tt", size, VM_NORESERVE);
184 		if (IS_ERR(filp))
185 			return PTR_ERR(filp);
186 
187 		mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
188 
189 		mapping = filp->f_mapping;
190 		mapping_set_gfp_mask(mapping, mask);
191 		GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
192 
193 		i915_tt->filp = filp;
194 	}
195 
196 	st = &i915_tt->cached_rsgt.table;
197 	err = shmem_sg_alloc_table(i915, st, size, mr, filp->f_mapping,
198 				   max_segment);
199 	if (err)
200 		return err;
201 
202 	err = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL,
203 			      DMA_ATTR_SKIP_CPU_SYNC);
204 	if (err)
205 		goto err_free_st;
206 
207 	i = 0;
208 	for_each_sgt_page(page, sgt_iter, st)
209 		ttm->pages[i++] = page;
210 
211 	if (ttm->page_flags & TTM_TT_FLAG_SWAPPED)
212 		ttm->page_flags &= ~TTM_TT_FLAG_SWAPPED;
213 
214 	return 0;
215 
216 err_free_st:
217 	shmem_sg_free_table(st, filp->f_mapping, false, false);
218 
219 	return err;
220 }
221 
222 static void i915_ttm_tt_shmem_unpopulate(struct ttm_tt *ttm)
223 {
224 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
225 	bool backup = ttm->page_flags & TTM_TT_FLAG_SWAPPED;
226 	struct sg_table *st = &i915_tt->cached_rsgt.table;
227 
228 	shmem_sg_free_table(st, file_inode(i915_tt->filp)->i_mapping,
229 			    backup, backup);
230 }
231 
232 static void i915_ttm_tt_release(struct kref *ref)
233 {
234 	struct i915_ttm_tt *i915_tt =
235 		container_of(ref, typeof(*i915_tt), cached_rsgt.kref);
236 	struct sg_table *st = &i915_tt->cached_rsgt.table;
237 
238 	GEM_WARN_ON(st->sgl);
239 
240 	kfree(i915_tt);
241 }
242 
243 static const struct i915_refct_sgt_ops tt_rsgt_ops = {
244 	.release = i915_ttm_tt_release
245 };
246 
247 static struct ttm_tt *i915_ttm_tt_create(struct ttm_buffer_object *bo,
248 					 uint32_t page_flags)
249 {
250 	struct ttm_resource_manager *man =
251 		ttm_manager_type(bo->bdev, bo->resource->mem_type);
252 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
253 	enum ttm_caching caching;
254 	struct i915_ttm_tt *i915_tt;
255 	int ret;
256 
257 	if (!obj)
258 		return NULL;
259 
260 	i915_tt = kzalloc(sizeof(*i915_tt), GFP_KERNEL);
261 	if (!i915_tt)
262 		return NULL;
263 
264 	if (obj->flags & I915_BO_ALLOC_CPU_CLEAR &&
265 	    man->use_tt)
266 		page_flags |= TTM_TT_FLAG_ZERO_ALLOC;
267 
268 	caching = i915_ttm_select_tt_caching(obj);
269 	if (i915_gem_object_is_shrinkable(obj) && caching == ttm_cached) {
270 		page_flags |= TTM_TT_FLAG_EXTERNAL |
271 			      TTM_TT_FLAG_EXTERNAL_MAPPABLE;
272 		i915_tt->is_shmem = true;
273 	}
274 
275 	ret = ttm_tt_init(&i915_tt->ttm, bo, page_flags, caching);
276 	if (ret)
277 		goto err_free;
278 
279 	__i915_refct_sgt_init(&i915_tt->cached_rsgt, bo->base.size,
280 			      &tt_rsgt_ops);
281 
282 	i915_tt->dev = obj->base.dev->dev;
283 
284 	return &i915_tt->ttm;
285 
286 err_free:
287 	kfree(i915_tt);
288 	return NULL;
289 }
290 
291 static int i915_ttm_tt_populate(struct ttm_device *bdev,
292 				struct ttm_tt *ttm,
293 				struct ttm_operation_ctx *ctx)
294 {
295 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
296 
297 	if (i915_tt->is_shmem)
298 		return i915_ttm_tt_shmem_populate(bdev, ttm, ctx);
299 
300 	return ttm_pool_alloc(&bdev->pool, ttm, ctx);
301 }
302 
303 static void i915_ttm_tt_unpopulate(struct ttm_device *bdev, struct ttm_tt *ttm)
304 {
305 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
306 	struct sg_table *st = &i915_tt->cached_rsgt.table;
307 
308 	if (st->sgl)
309 		dma_unmap_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
310 
311 	if (i915_tt->is_shmem) {
312 		i915_ttm_tt_shmem_unpopulate(ttm);
313 	} else {
314 		sg_free_table(st);
315 		ttm_pool_free(&bdev->pool, ttm);
316 	}
317 }
318 
319 static void i915_ttm_tt_destroy(struct ttm_device *bdev, struct ttm_tt *ttm)
320 {
321 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
322 
323 	if (i915_tt->filp)
324 		fput(i915_tt->filp);
325 
326 	ttm_tt_fini(ttm);
327 	i915_refct_sgt_put(&i915_tt->cached_rsgt);
328 }
329 
330 static bool i915_ttm_eviction_valuable(struct ttm_buffer_object *bo,
331 				       const struct ttm_place *place)
332 {
333 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
334 
335 	if (!obj)
336 		return false;
337 
338 	/*
339 	 * EXTERNAL objects should never be swapped out by TTM, instead we need
340 	 * to handle that ourselves. TTM will already skip such objects for us,
341 	 * but we would like to avoid grabbing locks for no good reason.
342 	 */
343 	if (bo->ttm && bo->ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
344 		return false;
345 
346 	/* Will do for now. Our pinned objects are still on TTM's LRU lists */
347 	return i915_gem_object_evictable(obj);
348 }
349 
350 static void i915_ttm_evict_flags(struct ttm_buffer_object *bo,
351 				 struct ttm_placement *placement)
352 {
353 	*placement = i915_sys_placement;
354 }
355 
356 /**
357  * i915_ttm_free_cached_io_rsgt - Free object cached LMEM information
358  * @obj: The GEM object
359  * This function frees any LMEM-related information that is cached on
360  * the object. For example the radix tree for fast page lookup and the
361  * cached refcounted sg-table
362  */
363 void i915_ttm_free_cached_io_rsgt(struct drm_i915_gem_object *obj)
364 {
365 	struct radix_tree_iter iter;
366 	void __rcu **slot;
367 
368 	if (!obj->ttm.cached_io_rsgt)
369 		return;
370 
371 	rcu_read_lock();
372 	radix_tree_for_each_slot(slot, &obj->ttm.get_io_page.radix, &iter, 0)
373 		radix_tree_delete(&obj->ttm.get_io_page.radix, iter.index);
374 	rcu_read_unlock();
375 
376 	i915_refct_sgt_put(obj->ttm.cached_io_rsgt);
377 	obj->ttm.cached_io_rsgt = NULL;
378 }
379 
380 /**
381  * i915_ttm_purge - Clear an object of its memory
382  * @obj: The object
383  *
384  * This function is called to clear an object of it's memory when it is
385  * marked as not needed anymore.
386  *
387  * Return: 0 on success, negative error code on failure.
388  */
389 int i915_ttm_purge(struct drm_i915_gem_object *obj)
390 {
391 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
392 	struct i915_ttm_tt *i915_tt =
393 		container_of(bo->ttm, typeof(*i915_tt), ttm);
394 	struct ttm_operation_ctx ctx = {
395 		.interruptible = true,
396 		.no_wait_gpu = false,
397 	};
398 	struct ttm_placement place = {};
399 	int ret;
400 
401 	if (obj->mm.madv == __I915_MADV_PURGED)
402 		return 0;
403 
404 	ret = ttm_bo_validate(bo, &place, &ctx);
405 	if (ret)
406 		return ret;
407 
408 	if (bo->ttm && i915_tt->filp) {
409 		/*
410 		 * The below fput(which eventually calls shmem_truncate) might
411 		 * be delayed by worker, so when directly called to purge the
412 		 * pages(like by the shrinker) we should try to be more
413 		 * aggressive and release the pages immediately.
414 		 */
415 		shmem_truncate_range(file_inode(i915_tt->filp),
416 				     0, (loff_t)-1);
417 		fput(fetch_and_zero(&i915_tt->filp));
418 	}
419 
420 	obj->write_domain = 0;
421 	obj->read_domains = 0;
422 	i915_ttm_adjust_gem_after_move(obj);
423 	i915_ttm_free_cached_io_rsgt(obj);
424 	obj->mm.madv = __I915_MADV_PURGED;
425 
426 	return 0;
427 }
428 
429 static int i915_ttm_shrink(struct drm_i915_gem_object *obj, unsigned int flags)
430 {
431 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
432 	struct i915_ttm_tt *i915_tt =
433 		container_of(bo->ttm, typeof(*i915_tt), ttm);
434 	struct ttm_operation_ctx ctx = {
435 		.interruptible = true,
436 		.no_wait_gpu = flags & I915_GEM_OBJECT_SHRINK_NO_GPU_WAIT,
437 	};
438 	struct ttm_placement place = {};
439 	int ret;
440 
441 	if (!bo->ttm || bo->resource->mem_type != TTM_PL_SYSTEM)
442 		return 0;
443 
444 	GEM_BUG_ON(!i915_tt->is_shmem);
445 
446 	if (!i915_tt->filp)
447 		return 0;
448 
449 	ret = ttm_bo_wait_ctx(bo, &ctx);
450 	if (ret)
451 		return ret;
452 
453 	switch (obj->mm.madv) {
454 	case I915_MADV_DONTNEED:
455 		return i915_ttm_purge(obj);
456 	case __I915_MADV_PURGED:
457 		return 0;
458 	}
459 
460 	if (bo->ttm->page_flags & TTM_TT_FLAG_SWAPPED)
461 		return 0;
462 
463 	bo->ttm->page_flags |= TTM_TT_FLAG_SWAPPED;
464 	ret = ttm_bo_validate(bo, &place, &ctx);
465 	if (ret) {
466 		bo->ttm->page_flags &= ~TTM_TT_FLAG_SWAPPED;
467 		return ret;
468 	}
469 
470 	if (flags & I915_GEM_OBJECT_SHRINK_WRITEBACK)
471 		__shmem_writeback(obj->base.size, i915_tt->filp->f_mapping);
472 
473 	return 0;
474 }
475 
476 static void i915_ttm_delete_mem_notify(struct ttm_buffer_object *bo)
477 {
478 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
479 
480 	if (likely(obj)) {
481 		__i915_gem_object_pages_fini(obj);
482 		i915_ttm_free_cached_io_rsgt(obj);
483 	}
484 }
485 
486 static struct i915_refct_sgt *i915_ttm_tt_get_st(struct ttm_tt *ttm)
487 {
488 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
489 	struct sg_table *st;
490 	int ret;
491 
492 	if (i915_tt->cached_rsgt.table.sgl)
493 		return i915_refct_sgt_get(&i915_tt->cached_rsgt);
494 
495 	st = &i915_tt->cached_rsgt.table;
496 	ret = sg_alloc_table_from_pages_segment(st,
497 			ttm->pages, ttm->num_pages,
498 			0, (unsigned long)ttm->num_pages << PAGE_SHIFT,
499 			i915_sg_segment_size(), GFP_KERNEL);
500 	if (ret) {
501 		st->sgl = NULL;
502 		return ERR_PTR(ret);
503 	}
504 
505 	ret = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
506 	if (ret) {
507 		sg_free_table(st);
508 		return ERR_PTR(ret);
509 	}
510 
511 	return i915_refct_sgt_get(&i915_tt->cached_rsgt);
512 }
513 
514 /**
515  * i915_ttm_resource_get_st - Get a refcounted sg-table pointing to the
516  * resource memory
517  * @obj: The GEM object used for sg-table caching
518  * @res: The struct ttm_resource for which an sg-table is requested.
519  *
520  * This function returns a refcounted sg-table representing the memory
521  * pointed to by @res. If @res is the object's current resource it may also
522  * cache the sg_table on the object or attempt to access an already cached
523  * sg-table. The refcounted sg-table needs to be put when no-longer in use.
524  *
525  * Return: A valid pointer to a struct i915_refct_sgt or error pointer on
526  * failure.
527  */
528 struct i915_refct_sgt *
529 i915_ttm_resource_get_st(struct drm_i915_gem_object *obj,
530 			 struct ttm_resource *res)
531 {
532 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
533 
534 	if (!i915_ttm_gtt_binds_lmem(res))
535 		return i915_ttm_tt_get_st(bo->ttm);
536 
537 	/*
538 	 * If CPU mapping differs, we need to add the ttm_tt pages to
539 	 * the resulting st. Might make sense for GGTT.
540 	 */
541 	GEM_WARN_ON(!i915_ttm_cpu_maps_iomem(res));
542 	if (bo->resource == res) {
543 		if (!obj->ttm.cached_io_rsgt) {
544 			struct i915_refct_sgt *rsgt;
545 
546 			rsgt = intel_region_ttm_resource_to_rsgt(obj->mm.region,
547 								 res);
548 			if (IS_ERR(rsgt))
549 				return rsgt;
550 
551 			obj->ttm.cached_io_rsgt = rsgt;
552 		}
553 		return i915_refct_sgt_get(obj->ttm.cached_io_rsgt);
554 	}
555 
556 	return intel_region_ttm_resource_to_rsgt(obj->mm.region, res);
557 }
558 
559 static int i915_ttm_truncate(struct drm_i915_gem_object *obj)
560 {
561 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
562 	int err;
563 
564 	WARN_ON_ONCE(obj->mm.madv == I915_MADV_WILLNEED);
565 
566 	err = i915_ttm_move_notify(bo);
567 	if (err)
568 		return err;
569 
570 	return i915_ttm_purge(obj);
571 }
572 
573 static void i915_ttm_swap_notify(struct ttm_buffer_object *bo)
574 {
575 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
576 	int ret;
577 
578 	if (!obj)
579 		return;
580 
581 	ret = i915_ttm_move_notify(bo);
582 	GEM_WARN_ON(ret);
583 	GEM_WARN_ON(obj->ttm.cached_io_rsgt);
584 	if (!ret && obj->mm.madv != I915_MADV_WILLNEED)
585 		i915_ttm_purge(obj);
586 }
587 
588 static int i915_ttm_io_mem_reserve(struct ttm_device *bdev, struct ttm_resource *mem)
589 {
590 	if (!i915_ttm_cpu_maps_iomem(mem))
591 		return 0;
592 
593 	mem->bus.caching = ttm_write_combined;
594 	mem->bus.is_iomem = true;
595 
596 	return 0;
597 }
598 
599 static unsigned long i915_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
600 					 unsigned long page_offset)
601 {
602 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
603 	struct scatterlist *sg;
604 	unsigned long base;
605 	unsigned int ofs;
606 
607 	GEM_BUG_ON(!obj);
608 	GEM_WARN_ON(bo->ttm);
609 
610 	base = obj->mm.region->iomap.base - obj->mm.region->region.start;
611 	sg = __i915_gem_object_get_sg(obj, &obj->ttm.get_io_page, page_offset, &ofs, true);
612 
613 	return ((base + sg_dma_address(sg)) >> PAGE_SHIFT) + ofs;
614 }
615 
616 /*
617  * All callbacks need to take care not to downcast a struct ttm_buffer_object
618  * without checking its subclass, since it might be a TTM ghost object.
619  */
620 static struct ttm_device_funcs i915_ttm_bo_driver = {
621 	.ttm_tt_create = i915_ttm_tt_create,
622 	.ttm_tt_populate = i915_ttm_tt_populate,
623 	.ttm_tt_unpopulate = i915_ttm_tt_unpopulate,
624 	.ttm_tt_destroy = i915_ttm_tt_destroy,
625 	.eviction_valuable = i915_ttm_eviction_valuable,
626 	.evict_flags = i915_ttm_evict_flags,
627 	.move = i915_ttm_move,
628 	.swap_notify = i915_ttm_swap_notify,
629 	.delete_mem_notify = i915_ttm_delete_mem_notify,
630 	.io_mem_reserve = i915_ttm_io_mem_reserve,
631 	.io_mem_pfn = i915_ttm_io_mem_pfn,
632 };
633 
634 /**
635  * i915_ttm_driver - Return a pointer to the TTM device funcs
636  *
637  * Return: Pointer to statically allocated TTM device funcs.
638  */
639 struct ttm_device_funcs *i915_ttm_driver(void)
640 {
641 	return &i915_ttm_bo_driver;
642 }
643 
644 static int __i915_ttm_get_pages(struct drm_i915_gem_object *obj,
645 				struct ttm_placement *placement)
646 {
647 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
648 	struct ttm_operation_ctx ctx = {
649 		.interruptible = true,
650 		.no_wait_gpu = false,
651 	};
652 	int real_num_busy;
653 	int ret;
654 
655 	/* First try only the requested placement. No eviction. */
656 	real_num_busy = fetch_and_zero(&placement->num_busy_placement);
657 	ret = ttm_bo_validate(bo, placement, &ctx);
658 	if (ret) {
659 		ret = i915_ttm_err_to_gem(ret);
660 		/*
661 		 * Anything that wants to restart the operation gets to
662 		 * do that.
663 		 */
664 		if (ret == -EDEADLK || ret == -EINTR || ret == -ERESTARTSYS ||
665 		    ret == -EAGAIN)
666 			return ret;
667 
668 		/*
669 		 * If the initial attempt fails, allow all accepted placements,
670 		 * evicting if necessary.
671 		 */
672 		placement->num_busy_placement = real_num_busy;
673 		ret = ttm_bo_validate(bo, placement, &ctx);
674 		if (ret)
675 			return i915_ttm_err_to_gem(ret);
676 	}
677 
678 	if (bo->ttm && !ttm_tt_is_populated(bo->ttm)) {
679 		ret = ttm_tt_populate(bo->bdev, bo->ttm, &ctx);
680 		if (ret)
681 			return ret;
682 
683 		i915_ttm_adjust_domains_after_move(obj);
684 		i915_ttm_adjust_gem_after_move(obj);
685 	}
686 
687 	if (!i915_gem_object_has_pages(obj)) {
688 		struct i915_refct_sgt *rsgt =
689 			i915_ttm_resource_get_st(obj, bo->resource);
690 
691 		if (IS_ERR(rsgt))
692 			return PTR_ERR(rsgt);
693 
694 		GEM_BUG_ON(obj->mm.rsgt);
695 		obj->mm.rsgt = rsgt;
696 		__i915_gem_object_set_pages(obj, &rsgt->table,
697 					    i915_sg_dma_sizes(rsgt->table.sgl));
698 	}
699 
700 	i915_ttm_adjust_lru(obj);
701 	return ret;
702 }
703 
704 static int i915_ttm_get_pages(struct drm_i915_gem_object *obj)
705 {
706 	struct ttm_place requested, busy[I915_TTM_MAX_PLACEMENTS];
707 	struct ttm_placement placement;
708 
709 	GEM_BUG_ON(obj->mm.n_placements > I915_TTM_MAX_PLACEMENTS);
710 
711 	/* Move to the requested placement. */
712 	i915_ttm_placement_from_obj(obj, &requested, busy, &placement);
713 
714 	return __i915_ttm_get_pages(obj, &placement);
715 }
716 
717 /**
718  * DOC: Migration vs eviction
719  *
720  * GEM migration may not be the same as TTM migration / eviction. If
721  * the TTM core decides to evict an object it may be evicted to a
722  * TTM memory type that is not in the object's allowable GEM regions, or
723  * in fact theoretically to a TTM memory type that doesn't correspond to
724  * a GEM memory region. In that case the object's GEM region is not
725  * updated, and the data is migrated back to the GEM region at
726  * get_pages time. TTM may however set up CPU ptes to the object even
727  * when it is evicted.
728  * Gem forced migration using the i915_ttm_migrate() op, is allowed even
729  * to regions that are not in the object's list of allowable placements.
730  */
731 static int i915_ttm_migrate(struct drm_i915_gem_object *obj,
732 			    struct intel_memory_region *mr)
733 {
734 	struct ttm_place requested;
735 	struct ttm_placement placement;
736 	int ret;
737 
738 	i915_ttm_place_from_region(mr, &requested, obj->flags);
739 	placement.num_placement = 1;
740 	placement.num_busy_placement = 1;
741 	placement.placement = &requested;
742 	placement.busy_placement = &requested;
743 
744 	ret = __i915_ttm_get_pages(obj, &placement);
745 	if (ret)
746 		return ret;
747 
748 	/*
749 	 * Reinitialize the region bindings. This is primarily
750 	 * required for objects where the new region is not in
751 	 * its allowable placements.
752 	 */
753 	if (obj->mm.region != mr) {
754 		i915_gem_object_release_memory_region(obj);
755 		i915_gem_object_init_memory_region(obj, mr);
756 	}
757 
758 	return 0;
759 }
760 
761 static void i915_ttm_put_pages(struct drm_i915_gem_object *obj,
762 			       struct sg_table *st)
763 {
764 	/*
765 	 * We're currently not called from a shrinker, so put_pages()
766 	 * typically means the object is about to destroyed, or called
767 	 * from move_notify(). So just avoid doing much for now.
768 	 * If the object is not destroyed next, The TTM eviction logic
769 	 * and shrinkers will move it out if needed.
770 	 */
771 
772 	if (obj->mm.rsgt)
773 		i915_refct_sgt_put(fetch_and_zero(&obj->mm.rsgt));
774 }
775 
776 /**
777  * i915_ttm_adjust_lru - Adjust an object's position on relevant LRU lists.
778  * @obj: The object
779  */
780 void i915_ttm_adjust_lru(struct drm_i915_gem_object *obj)
781 {
782 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
783 	struct i915_ttm_tt *i915_tt =
784 		container_of(bo->ttm, typeof(*i915_tt), ttm);
785 	bool shrinkable =
786 		bo->ttm && i915_tt->filp && ttm_tt_is_populated(bo->ttm);
787 
788 	/*
789 	 * Don't manipulate the TTM LRUs while in TTM bo destruction.
790 	 * We're called through i915_ttm_delete_mem_notify().
791 	 */
792 	if (!kref_read(&bo->kref))
793 		return;
794 
795 	/*
796 	 * We skip managing the shrinker LRU in set_pages() and just manage
797 	 * everything here. This does at least solve the issue with having
798 	 * temporary shmem mappings(like with evicted lmem) not being visible to
799 	 * the shrinker. Only our shmem objects are shrinkable, everything else
800 	 * we keep as unshrinkable.
801 	 *
802 	 * To make sure everything plays nice we keep an extra shrink pin in TTM
803 	 * if the underlying pages are not currently shrinkable. Once we release
804 	 * our pin, like when the pages are moved to shmem, the pages will then
805 	 * be added to the shrinker LRU, assuming the caller isn't also holding
806 	 * a pin.
807 	 *
808 	 * TODO: consider maybe also bumping the shrinker list here when we have
809 	 * already unpinned it, which should give us something more like an LRU.
810 	 *
811 	 * TODO: There is a small window of opportunity for this function to
812 	 * get called from eviction after we've dropped the last GEM refcount,
813 	 * but before the TTM deleted flag is set on the object. Avoid
814 	 * adjusting the shrinker list in such cases, since the object is
815 	 * not available to the shrinker anyway due to its zero refcount.
816 	 * To fix this properly we should move to a TTM shrinker LRU list for
817 	 * these objects.
818 	 */
819 	if (kref_get_unless_zero(&obj->base.refcount)) {
820 		if (shrinkable != obj->mm.ttm_shrinkable) {
821 			if (shrinkable) {
822 				if (obj->mm.madv == I915_MADV_WILLNEED)
823 					__i915_gem_object_make_shrinkable(obj);
824 				else
825 					__i915_gem_object_make_purgeable(obj);
826 			} else {
827 				i915_gem_object_make_unshrinkable(obj);
828 			}
829 
830 			obj->mm.ttm_shrinkable = shrinkable;
831 		}
832 		i915_gem_object_put(obj);
833 	}
834 
835 	/*
836 	 * Put on the correct LRU list depending on the MADV status
837 	 */
838 	spin_lock(&bo->bdev->lru_lock);
839 	if (shrinkable) {
840 		/* Try to keep shmem_tt from being considered for shrinking. */
841 		bo->priority = TTM_MAX_BO_PRIORITY - 1;
842 	} else if (obj->mm.madv != I915_MADV_WILLNEED) {
843 		bo->priority = I915_TTM_PRIO_PURGE;
844 	} else if (!i915_gem_object_has_pages(obj)) {
845 		bo->priority = I915_TTM_PRIO_NO_PAGES;
846 	} else {
847 		bo->priority = I915_TTM_PRIO_HAS_PAGES;
848 	}
849 
850 	ttm_bo_move_to_lru_tail(bo, bo->resource, NULL);
851 	spin_unlock(&bo->bdev->lru_lock);
852 }
853 
854 /*
855  * TTM-backed gem object destruction requires some clarification.
856  * Basically we have two possibilities here. We can either rely on the
857  * i915 delayed destruction and put the TTM object when the object
858  * is idle. This would be detected by TTM which would bypass the
859  * TTM delayed destroy handling. The other approach is to put the TTM
860  * object early and rely on the TTM destroyed handling, and then free
861  * the leftover parts of the GEM object once TTM's destroyed list handling is
862  * complete. For now, we rely on the latter for two reasons:
863  * a) TTM can evict an object even when it's on the delayed destroy list,
864  * which in theory allows for complete eviction.
865  * b) There is work going on in TTM to allow freeing an object even when
866  * it's not idle, and using the TTM destroyed list handling could help us
867  * benefit from that.
868  */
869 static void i915_ttm_delayed_free(struct drm_i915_gem_object *obj)
870 {
871 	GEM_BUG_ON(!obj->ttm.created);
872 
873 	ttm_bo_put(i915_gem_to_ttm(obj));
874 }
875 
876 static vm_fault_t vm_fault_ttm(struct vm_fault *vmf)
877 {
878 	struct vm_area_struct *area = vmf->vma;
879 	struct ttm_buffer_object *bo = area->vm_private_data;
880 	struct drm_device *dev = bo->base.dev;
881 	struct drm_i915_gem_object *obj;
882 	vm_fault_t ret;
883 	int idx;
884 
885 	obj = i915_ttm_to_gem(bo);
886 	if (!obj)
887 		return VM_FAULT_SIGBUS;
888 
889 	/* Sanity check that we allow writing into this object */
890 	if (unlikely(i915_gem_object_is_readonly(obj) &&
891 		     area->vm_flags & VM_WRITE))
892 		return VM_FAULT_SIGBUS;
893 
894 	ret = ttm_bo_vm_reserve(bo, vmf);
895 	if (ret)
896 		return ret;
897 
898 	if (obj->mm.madv != I915_MADV_WILLNEED) {
899 		dma_resv_unlock(bo->base.resv);
900 		return VM_FAULT_SIGBUS;
901 	}
902 
903 	if (drm_dev_enter(dev, &idx)) {
904 		ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
905 					       TTM_BO_VM_NUM_PREFAULT);
906 		drm_dev_exit(idx);
907 	} else {
908 		ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
909 	}
910 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
911 		return ret;
912 
913 	i915_ttm_adjust_lru(obj);
914 
915 	dma_resv_unlock(bo->base.resv);
916 	return ret;
917 }
918 
919 static int
920 vm_access_ttm(struct vm_area_struct *area, unsigned long addr,
921 	      void *buf, int len, int write)
922 {
923 	struct drm_i915_gem_object *obj =
924 		i915_ttm_to_gem(area->vm_private_data);
925 
926 	if (i915_gem_object_is_readonly(obj) && write)
927 		return -EACCES;
928 
929 	return ttm_bo_vm_access(area, addr, buf, len, write);
930 }
931 
932 static void ttm_vm_open(struct vm_area_struct *vma)
933 {
934 	struct drm_i915_gem_object *obj =
935 		i915_ttm_to_gem(vma->vm_private_data);
936 
937 	GEM_BUG_ON(!obj);
938 	i915_gem_object_get(obj);
939 }
940 
941 static void ttm_vm_close(struct vm_area_struct *vma)
942 {
943 	struct drm_i915_gem_object *obj =
944 		i915_ttm_to_gem(vma->vm_private_data);
945 
946 	GEM_BUG_ON(!obj);
947 	i915_gem_object_put(obj);
948 }
949 
950 static const struct vm_operations_struct vm_ops_ttm = {
951 	.fault = vm_fault_ttm,
952 	.access = vm_access_ttm,
953 	.open = ttm_vm_open,
954 	.close = ttm_vm_close,
955 };
956 
957 static u64 i915_ttm_mmap_offset(struct drm_i915_gem_object *obj)
958 {
959 	/* The ttm_bo must be allocated with I915_BO_ALLOC_USER */
960 	GEM_BUG_ON(!drm_mm_node_allocated(&obj->base.vma_node.vm_node));
961 
962 	return drm_vma_node_offset_addr(&obj->base.vma_node);
963 }
964 
965 static void i915_ttm_unmap_virtual(struct drm_i915_gem_object *obj)
966 {
967 	ttm_bo_unmap_virtual(i915_gem_to_ttm(obj));
968 }
969 
970 static const struct drm_i915_gem_object_ops i915_gem_ttm_obj_ops = {
971 	.name = "i915_gem_object_ttm",
972 	.flags = I915_GEM_OBJECT_IS_SHRINKABLE |
973 		 I915_GEM_OBJECT_SELF_MANAGED_SHRINK_LIST,
974 
975 	.get_pages = i915_ttm_get_pages,
976 	.put_pages = i915_ttm_put_pages,
977 	.truncate = i915_ttm_truncate,
978 	.shrink = i915_ttm_shrink,
979 
980 	.adjust_lru = i915_ttm_adjust_lru,
981 	.delayed_free = i915_ttm_delayed_free,
982 	.migrate = i915_ttm_migrate,
983 
984 	.mmap_offset = i915_ttm_mmap_offset,
985 	.unmap_virtual = i915_ttm_unmap_virtual,
986 	.mmap_ops = &vm_ops_ttm,
987 };
988 
989 void i915_ttm_bo_destroy(struct ttm_buffer_object *bo)
990 {
991 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
992 
993 	i915_gem_object_release_memory_region(obj);
994 	mutex_destroy(&obj->ttm.get_io_page.lock);
995 
996 	if (obj->ttm.created) {
997 		/*
998 		 * We freely manage the shrinker LRU outide of the mm.pages life
999 		 * cycle. As a result when destroying the object we should be
1000 		 * extra paranoid and ensure we remove it from the LRU, before
1001 		 * we free the object.
1002 		 *
1003 		 * Touching the ttm_shrinkable outside of the object lock here
1004 		 * should be safe now that the last GEM object ref was dropped.
1005 		 */
1006 		if (obj->mm.ttm_shrinkable)
1007 			i915_gem_object_make_unshrinkable(obj);
1008 
1009 		i915_ttm_backup_free(obj);
1010 
1011 		/* This releases all gem object bindings to the backend. */
1012 		__i915_gem_free_object(obj);
1013 
1014 		call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
1015 	} else {
1016 		__i915_gem_object_fini(obj);
1017 	}
1018 }
1019 
1020 /**
1021  * __i915_gem_ttm_object_init - Initialize a ttm-backed i915 gem object
1022  * @mem: The initial memory region for the object.
1023  * @obj: The gem object.
1024  * @size: Object size in bytes.
1025  * @flags: gem object flags.
1026  *
1027  * Return: 0 on success, negative error code on failure.
1028  */
1029 int __i915_gem_ttm_object_init(struct intel_memory_region *mem,
1030 			       struct drm_i915_gem_object *obj,
1031 			       resource_size_t size,
1032 			       resource_size_t page_size,
1033 			       unsigned int flags)
1034 {
1035 	static struct lock_class_key lock_class;
1036 	struct drm_i915_private *i915 = mem->i915;
1037 	struct ttm_operation_ctx ctx = {
1038 		.interruptible = true,
1039 		.no_wait_gpu = false,
1040 	};
1041 	enum ttm_bo_type bo_type;
1042 	int ret;
1043 
1044 	drm_gem_private_object_init(&i915->drm, &obj->base, size);
1045 	i915_gem_object_init(obj, &i915_gem_ttm_obj_ops, &lock_class, flags);
1046 
1047 	/* Don't put on a region list until we're either locked or fully initialized. */
1048 	obj->mm.region = mem;
1049 	INIT_LIST_HEAD(&obj->mm.region_link);
1050 
1051 	INIT_RADIX_TREE(&obj->ttm.get_io_page.radix, GFP_KERNEL | __GFP_NOWARN);
1052 	mutex_init(&obj->ttm.get_io_page.lock);
1053 	bo_type = (obj->flags & I915_BO_ALLOC_USER) ? ttm_bo_type_device :
1054 		ttm_bo_type_kernel;
1055 
1056 	obj->base.vma_node.driver_private = i915_gem_to_ttm(obj);
1057 
1058 	/* Forcing the page size is kernel internal only */
1059 	GEM_BUG_ON(page_size && obj->mm.n_placements);
1060 
1061 	/*
1062 	 * Keep an extra shrink pin to prevent the object from being made
1063 	 * shrinkable too early. If the ttm_tt is ever allocated in shmem, we
1064 	 * drop the pin. The TTM backend manages the shrinker LRU itself,
1065 	 * outside of the normal mm.pages life cycle.
1066 	 */
1067 	i915_gem_object_make_unshrinkable(obj);
1068 
1069 	/*
1070 	 * If this function fails, it will call the destructor, but
1071 	 * our caller still owns the object. So no freeing in the
1072 	 * destructor until obj->ttm.created is true.
1073 	 * Similarly, in delayed_destroy, we can't call ttm_bo_put()
1074 	 * until successful initialization.
1075 	 */
1076 	ret = ttm_bo_init_reserved(&i915->bdev, i915_gem_to_ttm(obj), size,
1077 				   bo_type, &i915_sys_placement,
1078 				   page_size >> PAGE_SHIFT,
1079 				   &ctx, NULL, NULL, i915_ttm_bo_destroy);
1080 	if (ret)
1081 		return i915_ttm_err_to_gem(ret);
1082 
1083 	obj->ttm.created = true;
1084 	i915_gem_object_release_memory_region(obj);
1085 	i915_gem_object_init_memory_region(obj, mem);
1086 	i915_ttm_adjust_domains_after_move(obj);
1087 	i915_ttm_adjust_gem_after_move(obj);
1088 	i915_gem_object_unlock(obj);
1089 
1090 	return 0;
1091 }
1092 
1093 static const struct intel_memory_region_ops ttm_system_region_ops = {
1094 	.init_object = __i915_gem_ttm_object_init,
1095 	.release = intel_region_ttm_fini,
1096 };
1097 
1098 struct intel_memory_region *
1099 i915_gem_ttm_system_setup(struct drm_i915_private *i915,
1100 			  u16 type, u16 instance)
1101 {
1102 	struct intel_memory_region *mr;
1103 
1104 	mr = intel_memory_region_create(i915, 0,
1105 					totalram_pages() << PAGE_SHIFT,
1106 					PAGE_SIZE, 0,
1107 					type, instance,
1108 					&ttm_system_region_ops);
1109 	if (IS_ERR(mr))
1110 		return mr;
1111 
1112 	intel_memory_region_set_name(mr, "system-ttm");
1113 	return mr;
1114 }
1115