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