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