xref: /linux/drivers/gpu/drm/i915/gem/i915_gem_ttm.c (revision bdd1a21b52557ea8f61d0a5dc2f77151b576eb70)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2021 Intel Corporation
4  */
5 
6 #include <drm/ttm/ttm_bo_driver.h>
7 #include <drm/ttm/ttm_placement.h>
8 
9 #include "i915_drv.h"
10 #include "intel_memory_region.h"
11 #include "intel_region_ttm.h"
12 
13 #include "gem/i915_gem_object.h"
14 #include "gem/i915_gem_region.h"
15 #include "gem/i915_gem_ttm.h"
16 #include "gem/i915_gem_mman.h"
17 
18 #include "gt/intel_migrate.h"
19 #include "gt/intel_engine_pm.h"
20 
21 #define I915_PL_LMEM0 TTM_PL_PRIV
22 #define I915_PL_SYSTEM TTM_PL_SYSTEM
23 #define I915_PL_STOLEN TTM_PL_VRAM
24 #define I915_PL_GGTT TTM_PL_TT
25 
26 #define I915_TTM_PRIO_PURGE     0
27 #define I915_TTM_PRIO_NO_PAGES  1
28 #define I915_TTM_PRIO_HAS_PAGES 2
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_st: The cached scatter-gather table.
40  *
41  * Note that DMA may be going on right up to the point where the page-
42  * vector is unpopulated in delayed destroy. Hence keep the
43  * scatter-gather table mapped and cached up to that point. This is
44  * different from the cached gem object io scatter-gather table which
45  * doesn't have an associated dma mapping.
46  */
47 struct i915_ttm_tt {
48 	struct ttm_tt ttm;
49 	struct device *dev;
50 	struct sg_table *cached_st;
51 };
52 
53 static const struct ttm_place sys_placement_flags = {
54 	.fpfn = 0,
55 	.lpfn = 0,
56 	.mem_type = I915_PL_SYSTEM,
57 	.flags = 0,
58 };
59 
60 static struct ttm_placement i915_sys_placement = {
61 	.num_placement = 1,
62 	.placement = &sys_placement_flags,
63 	.num_busy_placement = 1,
64 	.busy_placement = &sys_placement_flags,
65 };
66 
67 static int i915_ttm_err_to_gem(int err)
68 {
69 	/* Fastpath */
70 	if (likely(!err))
71 		return 0;
72 
73 	switch (err) {
74 	case -EBUSY:
75 		/*
76 		 * TTM likes to convert -EDEADLK to -EBUSY, and wants us to
77 		 * restart the operation, since we don't record the contending
78 		 * lock. We use -EAGAIN to restart.
79 		 */
80 		return -EAGAIN;
81 	case -ENOSPC:
82 		/*
83 		 * Memory type / region is full, and we can't evict.
84 		 * Except possibly system, that returns -ENOMEM;
85 		 */
86 		return -ENXIO;
87 	default:
88 		break;
89 	}
90 
91 	return err;
92 }
93 
94 static bool gpu_binds_iomem(struct ttm_resource *mem)
95 {
96 	return mem->mem_type != TTM_PL_SYSTEM;
97 }
98 
99 static bool cpu_maps_iomem(struct ttm_resource *mem)
100 {
101 	/* Once / if we support GGTT, this is also false for cached ttm_tts */
102 	return mem->mem_type != TTM_PL_SYSTEM;
103 }
104 
105 static enum i915_cache_level
106 i915_ttm_cache_level(struct drm_i915_private *i915, struct ttm_resource *res,
107 		     struct ttm_tt *ttm)
108 {
109 	return ((HAS_LLC(i915) || HAS_SNOOP(i915)) && !gpu_binds_iomem(res) &&
110 		ttm->caching == ttm_cached) ? I915_CACHE_LLC :
111 		I915_CACHE_NONE;
112 }
113 
114 static void i915_ttm_adjust_lru(struct drm_i915_gem_object *obj);
115 
116 static enum ttm_caching
117 i915_ttm_select_tt_caching(const struct drm_i915_gem_object *obj)
118 {
119 	/*
120 	 * Objects only allowed in system get cached cpu-mappings.
121 	 * Other objects get WC mapping for now. Even if in system.
122 	 */
123 	if (obj->mm.region->type == INTEL_MEMORY_SYSTEM &&
124 	    obj->mm.n_placements <= 1)
125 		return ttm_cached;
126 
127 	return ttm_write_combined;
128 }
129 
130 static void
131 i915_ttm_place_from_region(const struct intel_memory_region *mr,
132 			   struct ttm_place *place,
133 			   unsigned int flags)
134 {
135 	memset(place, 0, sizeof(*place));
136 	place->mem_type = intel_region_to_ttm_type(mr);
137 
138 	if (flags & I915_BO_ALLOC_CONTIGUOUS)
139 		place->flags = TTM_PL_FLAG_CONTIGUOUS;
140 }
141 
142 static void
143 i915_ttm_placement_from_obj(const struct drm_i915_gem_object *obj,
144 			    struct ttm_place *requested,
145 			    struct ttm_place *busy,
146 			    struct ttm_placement *placement)
147 {
148 	unsigned int num_allowed = obj->mm.n_placements;
149 	unsigned int flags = obj->flags;
150 	unsigned int i;
151 
152 	placement->num_placement = 1;
153 	i915_ttm_place_from_region(num_allowed ? obj->mm.placements[0] :
154 				   obj->mm.region, requested, flags);
155 
156 	/* Cache this on object? */
157 	placement->num_busy_placement = num_allowed;
158 	for (i = 0; i < placement->num_busy_placement; ++i)
159 		i915_ttm_place_from_region(obj->mm.placements[i], busy + i, flags);
160 
161 	if (num_allowed == 0) {
162 		*busy = *requested;
163 		placement->num_busy_placement = 1;
164 	}
165 
166 	placement->placement = requested;
167 	placement->busy_placement = busy;
168 }
169 
170 static struct ttm_tt *i915_ttm_tt_create(struct ttm_buffer_object *bo,
171 					 uint32_t page_flags)
172 {
173 	struct ttm_resource_manager *man =
174 		ttm_manager_type(bo->bdev, bo->resource->mem_type);
175 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
176 	struct i915_ttm_tt *i915_tt;
177 	int ret;
178 
179 	i915_tt = kzalloc(sizeof(*i915_tt), GFP_KERNEL);
180 	if (!i915_tt)
181 		return NULL;
182 
183 	if (obj->flags & I915_BO_ALLOC_CPU_CLEAR &&
184 	    man->use_tt)
185 		page_flags |= TTM_PAGE_FLAG_ZERO_ALLOC;
186 
187 	ret = ttm_tt_init(&i915_tt->ttm, bo, page_flags,
188 			  i915_ttm_select_tt_caching(obj));
189 	if (ret) {
190 		kfree(i915_tt);
191 		return NULL;
192 	}
193 
194 	i915_tt->dev = obj->base.dev->dev;
195 
196 	return &i915_tt->ttm;
197 }
198 
199 static void i915_ttm_tt_unpopulate(struct ttm_device *bdev, struct ttm_tt *ttm)
200 {
201 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
202 
203 	if (i915_tt->cached_st) {
204 		dma_unmap_sgtable(i915_tt->dev, i915_tt->cached_st,
205 				  DMA_BIDIRECTIONAL, 0);
206 		sg_free_table(i915_tt->cached_st);
207 		kfree(i915_tt->cached_st);
208 		i915_tt->cached_st = NULL;
209 	}
210 	ttm_pool_free(&bdev->pool, ttm);
211 }
212 
213 static void i915_ttm_tt_destroy(struct ttm_device *bdev, struct ttm_tt *ttm)
214 {
215 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
216 
217 	ttm_tt_destroy_common(bdev, ttm);
218 	ttm_tt_fini(ttm);
219 	kfree(i915_tt);
220 }
221 
222 static bool i915_ttm_eviction_valuable(struct ttm_buffer_object *bo,
223 				       const struct ttm_place *place)
224 {
225 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
226 
227 	/* Will do for now. Our pinned objects are still on TTM's LRU lists */
228 	return i915_gem_object_evictable(obj);
229 }
230 
231 static void i915_ttm_evict_flags(struct ttm_buffer_object *bo,
232 				 struct ttm_placement *placement)
233 {
234 	*placement = i915_sys_placement;
235 }
236 
237 static int i915_ttm_move_notify(struct ttm_buffer_object *bo)
238 {
239 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
240 	int ret;
241 
242 	ret = i915_gem_object_unbind(obj, I915_GEM_OBJECT_UNBIND_ACTIVE);
243 	if (ret)
244 		return ret;
245 
246 	ret = __i915_gem_object_put_pages(obj);
247 	if (ret)
248 		return ret;
249 
250 	return 0;
251 }
252 
253 static void i915_ttm_free_cached_io_st(struct drm_i915_gem_object *obj)
254 {
255 	struct radix_tree_iter iter;
256 	void __rcu **slot;
257 
258 	if (!obj->ttm.cached_io_st)
259 		return;
260 
261 	rcu_read_lock();
262 	radix_tree_for_each_slot(slot, &obj->ttm.get_io_page.radix, &iter, 0)
263 		radix_tree_delete(&obj->ttm.get_io_page.radix, iter.index);
264 	rcu_read_unlock();
265 
266 	sg_free_table(obj->ttm.cached_io_st);
267 	kfree(obj->ttm.cached_io_st);
268 	obj->ttm.cached_io_st = NULL;
269 }
270 
271 static void
272 i915_ttm_adjust_domains_after_move(struct drm_i915_gem_object *obj)
273 {
274 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
275 
276 	if (cpu_maps_iomem(bo->resource) || bo->ttm->caching != ttm_cached) {
277 		obj->write_domain = I915_GEM_DOMAIN_WC;
278 		obj->read_domains = I915_GEM_DOMAIN_WC;
279 	} else {
280 		obj->write_domain = I915_GEM_DOMAIN_CPU;
281 		obj->read_domains = I915_GEM_DOMAIN_CPU;
282 	}
283 }
284 
285 static void i915_ttm_adjust_gem_after_move(struct drm_i915_gem_object *obj)
286 {
287 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
288 	unsigned int cache_level;
289 	unsigned int i;
290 
291 	/*
292 	 * If object was moved to an allowable region, update the object
293 	 * region to consider it migrated. Note that if it's currently not
294 	 * in an allowable region, it's evicted and we don't update the
295 	 * object region.
296 	 */
297 	if (intel_region_to_ttm_type(obj->mm.region) != bo->resource->mem_type) {
298 		for (i = 0; i < obj->mm.n_placements; ++i) {
299 			struct intel_memory_region *mr = obj->mm.placements[i];
300 
301 			if (intel_region_to_ttm_type(mr) == bo->resource->mem_type &&
302 			    mr != obj->mm.region) {
303 				i915_gem_object_release_memory_region(obj);
304 				i915_gem_object_init_memory_region(obj, mr);
305 				break;
306 			}
307 		}
308 	}
309 
310 	obj->mem_flags &= ~(I915_BO_FLAG_STRUCT_PAGE | I915_BO_FLAG_IOMEM);
311 
312 	obj->mem_flags |= cpu_maps_iomem(bo->resource) ? I915_BO_FLAG_IOMEM :
313 		I915_BO_FLAG_STRUCT_PAGE;
314 
315 	cache_level = i915_ttm_cache_level(to_i915(bo->base.dev), bo->resource,
316 					   bo->ttm);
317 	i915_gem_object_set_cache_coherency(obj, cache_level);
318 }
319 
320 static void i915_ttm_purge(struct drm_i915_gem_object *obj)
321 {
322 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
323 	struct ttm_operation_ctx ctx = {
324 		.interruptible = true,
325 		.no_wait_gpu = false,
326 	};
327 	struct ttm_placement place = {};
328 	int ret;
329 
330 	if (obj->mm.madv == __I915_MADV_PURGED)
331 		return;
332 
333 	/* TTM's purge interface. Note that we might be reentering. */
334 	ret = ttm_bo_validate(bo, &place, &ctx);
335 	if (!ret) {
336 		obj->write_domain = 0;
337 		obj->read_domains = 0;
338 		i915_ttm_adjust_gem_after_move(obj);
339 		i915_ttm_free_cached_io_st(obj);
340 		obj->mm.madv = __I915_MADV_PURGED;
341 	}
342 }
343 
344 static void i915_ttm_swap_notify(struct ttm_buffer_object *bo)
345 {
346 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
347 	int ret = i915_ttm_move_notify(bo);
348 
349 	GEM_WARN_ON(ret);
350 	GEM_WARN_ON(obj->ttm.cached_io_st);
351 	if (!ret && obj->mm.madv != I915_MADV_WILLNEED)
352 		i915_ttm_purge(obj);
353 }
354 
355 static void i915_ttm_delete_mem_notify(struct ttm_buffer_object *bo)
356 {
357 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
358 
359 	if (likely(obj)) {
360 		/* This releases all gem object bindings to the backend. */
361 		i915_ttm_free_cached_io_st(obj);
362 		__i915_gem_free_object(obj);
363 	}
364 }
365 
366 static struct intel_memory_region *
367 i915_ttm_region(struct ttm_device *bdev, int ttm_mem_type)
368 {
369 	struct drm_i915_private *i915 = container_of(bdev, typeof(*i915), bdev);
370 
371 	/* There's some room for optimization here... */
372 	GEM_BUG_ON(ttm_mem_type != I915_PL_SYSTEM &&
373 		   ttm_mem_type < I915_PL_LMEM0);
374 	if (ttm_mem_type == I915_PL_SYSTEM)
375 		return intel_memory_region_lookup(i915, INTEL_MEMORY_SYSTEM,
376 						  0);
377 
378 	return intel_memory_region_lookup(i915, INTEL_MEMORY_LOCAL,
379 					  ttm_mem_type - I915_PL_LMEM0);
380 }
381 
382 static struct sg_table *i915_ttm_tt_get_st(struct ttm_tt *ttm)
383 {
384 	struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
385 	struct scatterlist *sg;
386 	struct sg_table *st;
387 	int ret;
388 
389 	if (i915_tt->cached_st)
390 		return i915_tt->cached_st;
391 
392 	st = kzalloc(sizeof(*st), GFP_KERNEL);
393 	if (!st)
394 		return ERR_PTR(-ENOMEM);
395 
396 	sg = __sg_alloc_table_from_pages
397 		(st, ttm->pages, ttm->num_pages, 0,
398 		 (unsigned long)ttm->num_pages << PAGE_SHIFT,
399 		 i915_sg_segment_size(), NULL, 0, GFP_KERNEL);
400 	if (IS_ERR(sg)) {
401 		kfree(st);
402 		return ERR_CAST(sg);
403 	}
404 
405 	ret = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
406 	if (ret) {
407 		sg_free_table(st);
408 		kfree(st);
409 		return ERR_PTR(ret);
410 	}
411 
412 	i915_tt->cached_st = st;
413 	return st;
414 }
415 
416 static struct sg_table *
417 i915_ttm_resource_get_st(struct drm_i915_gem_object *obj,
418 			 struct ttm_resource *res)
419 {
420 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
421 
422 	if (!gpu_binds_iomem(res))
423 		return i915_ttm_tt_get_st(bo->ttm);
424 
425 	/*
426 	 * If CPU mapping differs, we need to add the ttm_tt pages to
427 	 * the resulting st. Might make sense for GGTT.
428 	 */
429 	GEM_WARN_ON(!cpu_maps_iomem(res));
430 	return intel_region_ttm_resource_to_st(obj->mm.region, res);
431 }
432 
433 static int i915_ttm_accel_move(struct ttm_buffer_object *bo,
434 			       struct ttm_resource *dst_mem,
435 			       struct sg_table *dst_st)
436 {
437 	struct drm_i915_private *i915 = container_of(bo->bdev, typeof(*i915),
438 						     bdev);
439 	struct ttm_resource_manager *src_man =
440 		ttm_manager_type(bo->bdev, bo->resource->mem_type);
441 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
442 	struct sg_table *src_st;
443 	struct i915_request *rq;
444 	struct ttm_tt *ttm = bo->ttm;
445 	enum i915_cache_level src_level, dst_level;
446 	int ret;
447 
448 	if (!i915->gt.migrate.context)
449 		return -EINVAL;
450 
451 	dst_level = i915_ttm_cache_level(i915, dst_mem, ttm);
452 	if (!ttm || !ttm_tt_is_populated(ttm)) {
453 		if (bo->type == ttm_bo_type_kernel)
454 			return -EINVAL;
455 
456 		if (ttm && !(ttm->page_flags & TTM_PAGE_FLAG_ZERO_ALLOC))
457 			return 0;
458 
459 		intel_engine_pm_get(i915->gt.migrate.context->engine);
460 		ret = intel_context_migrate_clear(i915->gt.migrate.context, NULL,
461 						  dst_st->sgl, dst_level,
462 						  gpu_binds_iomem(dst_mem),
463 						  0, &rq);
464 
465 		if (!ret && rq) {
466 			i915_request_wait(rq, 0, MAX_SCHEDULE_TIMEOUT);
467 			i915_request_put(rq);
468 		}
469 		intel_engine_pm_put(i915->gt.migrate.context->engine);
470 	} else {
471 		src_st = src_man->use_tt ? i915_ttm_tt_get_st(ttm) :
472 			obj->ttm.cached_io_st;
473 
474 		src_level = i915_ttm_cache_level(i915, bo->resource, ttm);
475 		intel_engine_pm_get(i915->gt.migrate.context->engine);
476 		ret = intel_context_migrate_copy(i915->gt.migrate.context,
477 						 NULL, src_st->sgl, src_level,
478 						 gpu_binds_iomem(bo->resource),
479 						 dst_st->sgl, dst_level,
480 						 gpu_binds_iomem(dst_mem),
481 						 &rq);
482 		if (!ret && rq) {
483 			i915_request_wait(rq, 0, MAX_SCHEDULE_TIMEOUT);
484 			i915_request_put(rq);
485 		}
486 		intel_engine_pm_put(i915->gt.migrate.context->engine);
487 	}
488 
489 	return ret;
490 }
491 
492 static int i915_ttm_move(struct ttm_buffer_object *bo, bool evict,
493 			 struct ttm_operation_ctx *ctx,
494 			 struct ttm_resource *dst_mem,
495 			 struct ttm_place *hop)
496 {
497 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
498 	struct ttm_resource_manager *dst_man =
499 		ttm_manager_type(bo->bdev, dst_mem->mem_type);
500 	struct intel_memory_region *dst_reg, *src_reg;
501 	union {
502 		struct ttm_kmap_iter_tt tt;
503 		struct ttm_kmap_iter_iomap io;
504 	} _dst_iter, _src_iter;
505 	struct ttm_kmap_iter *dst_iter, *src_iter;
506 	struct sg_table *dst_st;
507 	int ret;
508 
509 	dst_reg = i915_ttm_region(bo->bdev, dst_mem->mem_type);
510 	src_reg = i915_ttm_region(bo->bdev, bo->resource->mem_type);
511 	GEM_BUG_ON(!dst_reg || !src_reg);
512 
513 	/* Sync for now. We could do the actual copy async. */
514 	ret = ttm_bo_wait_ctx(bo, ctx);
515 	if (ret)
516 		return ret;
517 
518 	ret = i915_ttm_move_notify(bo);
519 	if (ret)
520 		return ret;
521 
522 	if (obj->mm.madv != I915_MADV_WILLNEED) {
523 		i915_ttm_purge(obj);
524 		ttm_resource_free(bo, &dst_mem);
525 		return 0;
526 	}
527 
528 	/* Populate ttm with pages if needed. Typically system memory. */
529 	if (bo->ttm && (dst_man->use_tt ||
530 			(bo->ttm->page_flags & TTM_PAGE_FLAG_SWAPPED))) {
531 		ret = ttm_tt_populate(bo->bdev, bo->ttm, ctx);
532 		if (ret)
533 			return ret;
534 	}
535 
536 	dst_st = i915_ttm_resource_get_st(obj, dst_mem);
537 	if (IS_ERR(dst_st))
538 		return PTR_ERR(dst_st);
539 
540 	ret = i915_ttm_accel_move(bo, dst_mem, dst_st);
541 	if (ret) {
542 		/* If we start mapping GGTT, we can no longer use man::use_tt here. */
543 		dst_iter = !cpu_maps_iomem(dst_mem) ?
544 			ttm_kmap_iter_tt_init(&_dst_iter.tt, bo->ttm) :
545 			ttm_kmap_iter_iomap_init(&_dst_iter.io, &dst_reg->iomap,
546 						 dst_st, dst_reg->region.start);
547 
548 		src_iter = !cpu_maps_iomem(bo->resource) ?
549 			ttm_kmap_iter_tt_init(&_src_iter.tt, bo->ttm) :
550 			ttm_kmap_iter_iomap_init(&_src_iter.io, &src_reg->iomap,
551 						 obj->ttm.cached_io_st,
552 						 src_reg->region.start);
553 
554 		ttm_move_memcpy(bo, dst_mem->num_pages, dst_iter, src_iter);
555 	}
556 	/* Below dst_mem becomes bo->resource. */
557 	ttm_bo_move_sync_cleanup(bo, dst_mem);
558 	i915_ttm_adjust_domains_after_move(obj);
559 	i915_ttm_free_cached_io_st(obj);
560 
561 	if (gpu_binds_iomem(dst_mem) || cpu_maps_iomem(dst_mem)) {
562 		obj->ttm.cached_io_st = dst_st;
563 		obj->ttm.get_io_page.sg_pos = dst_st->sgl;
564 		obj->ttm.get_io_page.sg_idx = 0;
565 	}
566 
567 	i915_ttm_adjust_gem_after_move(obj);
568 	return 0;
569 }
570 
571 static int i915_ttm_io_mem_reserve(struct ttm_device *bdev, struct ttm_resource *mem)
572 {
573 	if (!cpu_maps_iomem(mem))
574 		return 0;
575 
576 	mem->bus.caching = ttm_write_combined;
577 	mem->bus.is_iomem = true;
578 
579 	return 0;
580 }
581 
582 static unsigned long i915_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
583 					 unsigned long page_offset)
584 {
585 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
586 	unsigned long base = obj->mm.region->iomap.base - obj->mm.region->region.start;
587 	struct scatterlist *sg;
588 	unsigned int ofs;
589 
590 	GEM_WARN_ON(bo->ttm);
591 
592 	sg = __i915_gem_object_get_sg(obj, &obj->ttm.get_io_page, page_offset, &ofs, true);
593 
594 	return ((base + sg_dma_address(sg)) >> PAGE_SHIFT) + ofs;
595 }
596 
597 static struct ttm_device_funcs i915_ttm_bo_driver = {
598 	.ttm_tt_create = i915_ttm_tt_create,
599 	.ttm_tt_unpopulate = i915_ttm_tt_unpopulate,
600 	.ttm_tt_destroy = i915_ttm_tt_destroy,
601 	.eviction_valuable = i915_ttm_eviction_valuable,
602 	.evict_flags = i915_ttm_evict_flags,
603 	.move = i915_ttm_move,
604 	.swap_notify = i915_ttm_swap_notify,
605 	.delete_mem_notify = i915_ttm_delete_mem_notify,
606 	.io_mem_reserve = i915_ttm_io_mem_reserve,
607 	.io_mem_pfn = i915_ttm_io_mem_pfn,
608 };
609 
610 /**
611  * i915_ttm_driver - Return a pointer to the TTM device funcs
612  *
613  * Return: Pointer to statically allocated TTM device funcs.
614  */
615 struct ttm_device_funcs *i915_ttm_driver(void)
616 {
617 	return &i915_ttm_bo_driver;
618 }
619 
620 static int __i915_ttm_get_pages(struct drm_i915_gem_object *obj,
621 				struct ttm_placement *placement)
622 {
623 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
624 	struct ttm_operation_ctx ctx = {
625 		.interruptible = true,
626 		.no_wait_gpu = false,
627 	};
628 	struct sg_table *st;
629 	int real_num_busy;
630 	int ret;
631 
632 	/* First try only the requested placement. No eviction. */
633 	real_num_busy = fetch_and_zero(&placement->num_busy_placement);
634 	ret = ttm_bo_validate(bo, placement, &ctx);
635 	if (ret) {
636 		ret = i915_ttm_err_to_gem(ret);
637 		/*
638 		 * Anything that wants to restart the operation gets to
639 		 * do that.
640 		 */
641 		if (ret == -EDEADLK || ret == -EINTR || ret == -ERESTARTSYS ||
642 		    ret == -EAGAIN)
643 			return ret;
644 
645 		/*
646 		 * If the initial attempt fails, allow all accepted placements,
647 		 * evicting if necessary.
648 		 */
649 		placement->num_busy_placement = real_num_busy;
650 		ret = ttm_bo_validate(bo, placement, &ctx);
651 		if (ret)
652 			return i915_ttm_err_to_gem(ret);
653 	}
654 
655 	i915_ttm_adjust_lru(obj);
656 	if (bo->ttm && !ttm_tt_is_populated(bo->ttm)) {
657 		ret = ttm_tt_populate(bo->bdev, bo->ttm, &ctx);
658 		if (ret)
659 			return ret;
660 
661 		i915_ttm_adjust_domains_after_move(obj);
662 		i915_ttm_adjust_gem_after_move(obj);
663 	}
664 
665 	if (!i915_gem_object_has_pages(obj)) {
666 		/* Object either has a page vector or is an iomem object */
667 		st = bo->ttm ? i915_ttm_tt_get_st(bo->ttm) : obj->ttm.cached_io_st;
668 		if (IS_ERR(st))
669 			return PTR_ERR(st);
670 
671 		__i915_gem_object_set_pages(obj, st, i915_sg_dma_sizes(st->sgl));
672 	}
673 
674 	return ret;
675 }
676 
677 static int i915_ttm_get_pages(struct drm_i915_gem_object *obj)
678 {
679 	struct ttm_place requested, busy[I915_TTM_MAX_PLACEMENTS];
680 	struct ttm_placement placement;
681 
682 	GEM_BUG_ON(obj->mm.n_placements > I915_TTM_MAX_PLACEMENTS);
683 
684 	/* Move to the requested placement. */
685 	i915_ttm_placement_from_obj(obj, &requested, busy, &placement);
686 
687 	return __i915_ttm_get_pages(obj, &placement);
688 }
689 
690 /**
691  * DOC: Migration vs eviction
692  *
693  * GEM migration may not be the same as TTM migration / eviction. If
694  * the TTM core decides to evict an object it may be evicted to a
695  * TTM memory type that is not in the object's allowable GEM regions, or
696  * in fact theoretically to a TTM memory type that doesn't correspond to
697  * a GEM memory region. In that case the object's GEM region is not
698  * updated, and the data is migrated back to the GEM region at
699  * get_pages time. TTM may however set up CPU ptes to the object even
700  * when it is evicted.
701  * Gem forced migration using the i915_ttm_migrate() op, is allowed even
702  * to regions that are not in the object's list of allowable placements.
703  */
704 static int i915_ttm_migrate(struct drm_i915_gem_object *obj,
705 			    struct intel_memory_region *mr)
706 {
707 	struct ttm_place requested;
708 	struct ttm_placement placement;
709 	int ret;
710 
711 	i915_ttm_place_from_region(mr, &requested, obj->flags);
712 	placement.num_placement = 1;
713 	placement.num_busy_placement = 1;
714 	placement.placement = &requested;
715 	placement.busy_placement = &requested;
716 
717 	ret = __i915_ttm_get_pages(obj, &placement);
718 	if (ret)
719 		return ret;
720 
721 	/*
722 	 * Reinitialize the region bindings. This is primarily
723 	 * required for objects where the new region is not in
724 	 * its allowable placements.
725 	 */
726 	if (obj->mm.region != mr) {
727 		i915_gem_object_release_memory_region(obj);
728 		i915_gem_object_init_memory_region(obj, mr);
729 	}
730 
731 	return 0;
732 }
733 
734 static void i915_ttm_put_pages(struct drm_i915_gem_object *obj,
735 			       struct sg_table *st)
736 {
737 	/*
738 	 * We're currently not called from a shrinker, so put_pages()
739 	 * typically means the object is about to destroyed, or called
740 	 * from move_notify(). So just avoid doing much for now.
741 	 * If the object is not destroyed next, The TTM eviction logic
742 	 * and shrinkers will move it out if needed.
743 	 */
744 
745 	i915_ttm_adjust_lru(obj);
746 }
747 
748 static void i915_ttm_adjust_lru(struct drm_i915_gem_object *obj)
749 {
750 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
751 
752 	/*
753 	 * Don't manipulate the TTM LRUs while in TTM bo destruction.
754 	 * We're called through i915_ttm_delete_mem_notify().
755 	 */
756 	if (!kref_read(&bo->kref))
757 		return;
758 
759 	/*
760 	 * Put on the correct LRU list depending on the MADV status
761 	 */
762 	spin_lock(&bo->bdev->lru_lock);
763 	if (obj->mm.madv != I915_MADV_WILLNEED) {
764 		bo->priority = I915_TTM_PRIO_PURGE;
765 	} else if (!i915_gem_object_has_pages(obj)) {
766 		if (bo->priority < I915_TTM_PRIO_HAS_PAGES)
767 			bo->priority = I915_TTM_PRIO_HAS_PAGES;
768 	} else {
769 		if (bo->priority > I915_TTM_PRIO_NO_PAGES)
770 			bo->priority = I915_TTM_PRIO_NO_PAGES;
771 	}
772 
773 	ttm_bo_move_to_lru_tail(bo, bo->resource, NULL);
774 	spin_unlock(&bo->bdev->lru_lock);
775 }
776 
777 /*
778  * TTM-backed gem object destruction requires some clarification.
779  * Basically we have two possibilities here. We can either rely on the
780  * i915 delayed destruction and put the TTM object when the object
781  * is idle. This would be detected by TTM which would bypass the
782  * TTM delayed destroy handling. The other approach is to put the TTM
783  * object early and rely on the TTM destroyed handling, and then free
784  * the leftover parts of the GEM object once TTM's destroyed list handling is
785  * complete. For now, we rely on the latter for two reasons:
786  * a) TTM can evict an object even when it's on the delayed destroy list,
787  * which in theory allows for complete eviction.
788  * b) There is work going on in TTM to allow freeing an object even when
789  * it's not idle, and using the TTM destroyed list handling could help us
790  * benefit from that.
791  */
792 static void i915_ttm_delayed_free(struct drm_i915_gem_object *obj)
793 {
794 	if (obj->ttm.created) {
795 		ttm_bo_put(i915_gem_to_ttm(obj));
796 	} else {
797 		__i915_gem_free_object(obj);
798 		call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
799 	}
800 }
801 
802 static vm_fault_t vm_fault_ttm(struct vm_fault *vmf)
803 {
804 	struct vm_area_struct *area = vmf->vma;
805 	struct drm_i915_gem_object *obj =
806 		i915_ttm_to_gem(area->vm_private_data);
807 
808 	/* Sanity check that we allow writing into this object */
809 	if (unlikely(i915_gem_object_is_readonly(obj) &&
810 		     area->vm_flags & VM_WRITE))
811 		return VM_FAULT_SIGBUS;
812 
813 	return ttm_bo_vm_fault(vmf);
814 }
815 
816 static int
817 vm_access_ttm(struct vm_area_struct *area, unsigned long addr,
818 	      void *buf, int len, int write)
819 {
820 	struct drm_i915_gem_object *obj =
821 		i915_ttm_to_gem(area->vm_private_data);
822 
823 	if (i915_gem_object_is_readonly(obj) && write)
824 		return -EACCES;
825 
826 	return ttm_bo_vm_access(area, addr, buf, len, write);
827 }
828 
829 static void ttm_vm_open(struct vm_area_struct *vma)
830 {
831 	struct drm_i915_gem_object *obj =
832 		i915_ttm_to_gem(vma->vm_private_data);
833 
834 	GEM_BUG_ON(!obj);
835 	i915_gem_object_get(obj);
836 }
837 
838 static void ttm_vm_close(struct vm_area_struct *vma)
839 {
840 	struct drm_i915_gem_object *obj =
841 		i915_ttm_to_gem(vma->vm_private_data);
842 
843 	GEM_BUG_ON(!obj);
844 	i915_gem_object_put(obj);
845 }
846 
847 static const struct vm_operations_struct vm_ops_ttm = {
848 	.fault = vm_fault_ttm,
849 	.access = vm_access_ttm,
850 	.open = ttm_vm_open,
851 	.close = ttm_vm_close,
852 };
853 
854 static u64 i915_ttm_mmap_offset(struct drm_i915_gem_object *obj)
855 {
856 	/* The ttm_bo must be allocated with I915_BO_ALLOC_USER */
857 	GEM_BUG_ON(!drm_mm_node_allocated(&obj->base.vma_node.vm_node));
858 
859 	return drm_vma_node_offset_addr(&obj->base.vma_node);
860 }
861 
862 static const struct drm_i915_gem_object_ops i915_gem_ttm_obj_ops = {
863 	.name = "i915_gem_object_ttm",
864 
865 	.get_pages = i915_ttm_get_pages,
866 	.put_pages = i915_ttm_put_pages,
867 	.truncate = i915_ttm_purge,
868 	.adjust_lru = i915_ttm_adjust_lru,
869 	.delayed_free = i915_ttm_delayed_free,
870 	.migrate = i915_ttm_migrate,
871 	.mmap_offset = i915_ttm_mmap_offset,
872 	.mmap_ops = &vm_ops_ttm,
873 };
874 
875 void i915_ttm_bo_destroy(struct ttm_buffer_object *bo)
876 {
877 	struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
878 
879 	i915_gem_object_release_memory_region(obj);
880 	mutex_destroy(&obj->ttm.get_io_page.lock);
881 	if (obj->ttm.created)
882 		call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
883 }
884 
885 /**
886  * __i915_gem_ttm_object_init - Initialize a ttm-backed i915 gem object
887  * @mem: The initial memory region for the object.
888  * @obj: The gem object.
889  * @size: Object size in bytes.
890  * @flags: gem object flags.
891  *
892  * Return: 0 on success, negative error code on failure.
893  */
894 int __i915_gem_ttm_object_init(struct intel_memory_region *mem,
895 			       struct drm_i915_gem_object *obj,
896 			       resource_size_t size,
897 			       resource_size_t page_size,
898 			       unsigned int flags)
899 {
900 	static struct lock_class_key lock_class;
901 	struct drm_i915_private *i915 = mem->i915;
902 	struct ttm_operation_ctx ctx = {
903 		.interruptible = true,
904 		.no_wait_gpu = false,
905 	};
906 	enum ttm_bo_type bo_type;
907 	int ret;
908 
909 	drm_gem_private_object_init(&i915->drm, &obj->base, size);
910 	i915_gem_object_init(obj, &i915_gem_ttm_obj_ops, &lock_class, flags);
911 	i915_gem_object_init_memory_region(obj, mem);
912 	i915_gem_object_make_unshrinkable(obj);
913 	INIT_RADIX_TREE(&obj->ttm.get_io_page.radix, GFP_KERNEL | __GFP_NOWARN);
914 	mutex_init(&obj->ttm.get_io_page.lock);
915 	bo_type = (obj->flags & I915_BO_ALLOC_USER) ? ttm_bo_type_device :
916 		ttm_bo_type_kernel;
917 
918 	obj->base.vma_node.driver_private = i915_gem_to_ttm(obj);
919 
920 	/* Forcing the page size is kernel internal only */
921 	GEM_BUG_ON(page_size && obj->mm.n_placements);
922 
923 	/*
924 	 * If this function fails, it will call the destructor, but
925 	 * our caller still owns the object. So no freeing in the
926 	 * destructor until obj->ttm.created is true.
927 	 * Similarly, in delayed_destroy, we can't call ttm_bo_put()
928 	 * until successful initialization.
929 	 */
930 	ret = ttm_bo_init_reserved(&i915->bdev, i915_gem_to_ttm(obj), size,
931 				   bo_type, &i915_sys_placement,
932 				   page_size >> PAGE_SHIFT,
933 				   &ctx, NULL, NULL, i915_ttm_bo_destroy);
934 	if (ret)
935 		return i915_ttm_err_to_gem(ret);
936 
937 	obj->ttm.created = true;
938 	i915_ttm_adjust_domains_after_move(obj);
939 	i915_ttm_adjust_gem_after_move(obj);
940 	i915_gem_object_unlock(obj);
941 
942 	return 0;
943 }
944 
945 static const struct intel_memory_region_ops ttm_system_region_ops = {
946 	.init_object = __i915_gem_ttm_object_init,
947 };
948 
949 struct intel_memory_region *
950 i915_gem_ttm_system_setup(struct drm_i915_private *i915,
951 			  u16 type, u16 instance)
952 {
953 	struct intel_memory_region *mr;
954 
955 	mr = intel_memory_region_create(i915, 0,
956 					totalram_pages() << PAGE_SHIFT,
957 					PAGE_SIZE, 0,
958 					type, instance,
959 					&ttm_system_region_ops);
960 	if (IS_ERR(mr))
961 		return mr;
962 
963 	intel_memory_region_set_name(mr, "system-ttm");
964 	return mr;
965 }
966