xref: /linux/drivers/gpu/drm/ttm/ttm_bo.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
2 /**************************************************************************
3  *
4  * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sub license, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * The above copyright notice and this permission notice (including the
16  * next paragraph) shall be included in all copies or substantial portions
17  * of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
22  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
23  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25  * USE OR OTHER DEALINGS IN THE SOFTWARE.
26  *
27  **************************************************************************/
28 /*
29  * Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
30  */
31 
32 #define pr_fmt(fmt) "[TTM] " fmt
33 
34 #include <drm/drm_print.h>
35 #include <drm/drm_util.h>
36 #include <drm/ttm/ttm_allocation.h>
37 #include <drm/ttm/ttm_bo.h>
38 #include <drm/ttm/ttm_placement.h>
39 #include <drm/ttm/ttm_tt.h>
40 
41 #include <linux/export.h>
42 #include <linux/jiffies.h>
43 #include <linux/slab.h>
44 #include <linux/sched.h>
45 #include <linux/mm.h>
46 #include <linux/file.h>
47 #include <linux/module.h>
48 #include <linux/atomic.h>
49 #include <linux/cgroup_dmem.h>
50 #include <linux/dma-resv.h>
51 
52 #include "ttm_module.h"
53 #include "ttm_bo_internal.h"
54 
55 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
56 					struct ttm_placement *placement)
57 {
58 	struct drm_printer p = drm_dbg_printer(NULL, DRM_UT_CORE, TTM_PFX);
59 	struct ttm_resource_manager *man;
60 	int i, mem_type;
61 
62 	for (i = 0; i < placement->num_placement; i++) {
63 		mem_type = placement->placement[i].mem_type;
64 		drm_printf(&p, "  placement[%d]=0x%08X (%d)\n",
65 			   i, placement->placement[i].flags, mem_type);
66 		man = ttm_manager_type(bo->bdev, mem_type);
67 		ttm_resource_manager_debug(man, &p);
68 	}
69 }
70 
71 /**
72  * ttm_bo_move_to_lru_tail
73  *
74  * @bo: The buffer object.
75  *
76  * Move this BO to the tail of all lru lists used to lookup and reserve an
77  * object. This function must be called with struct ttm_global::lru_lock
78  * held, and is used to make a BO less likely to be considered for eviction.
79  */
80 void ttm_bo_move_to_lru_tail(struct ttm_buffer_object *bo)
81 {
82 	dma_resv_assert_held(bo->base.resv);
83 
84 	if (bo->resource)
85 		ttm_resource_move_to_lru_tail(bo->resource);
86 }
87 EXPORT_SYMBOL(ttm_bo_move_to_lru_tail);
88 
89 /**
90  * ttm_bo_set_bulk_move - update BOs bulk move object
91  *
92  * @bo: The buffer object.
93  * @bulk: bulk move structure
94  *
95  * Update the BOs bulk move object, making sure that resources are added/removed
96  * as well. A bulk move allows to move many resource on the LRU at once,
97  * resulting in much less overhead of maintaining the LRU.
98  * The only requirement is that the resources stay together on the LRU and are
99  * never separated. This is enforces by setting the bulk_move structure on a BO.
100  * ttm_lru_bulk_move_tail() should be used to move all resources to the tail of
101  * their LRU list.
102  */
103 void ttm_bo_set_bulk_move(struct ttm_buffer_object *bo,
104 			  struct ttm_lru_bulk_move *bulk)
105 {
106 	dma_resv_assert_held(bo->base.resv);
107 
108 	if (bo->bulk_move == bulk)
109 		return;
110 
111 	spin_lock(&bo->bdev->lru_lock);
112 	if (bo->resource)
113 		ttm_resource_del_bulk_move(bo->resource, bo);
114 	bo->bulk_move = bulk;
115 	if (bo->resource)
116 		ttm_resource_add_bulk_move(bo->resource, bo);
117 	spin_unlock(&bo->bdev->lru_lock);
118 }
119 EXPORT_SYMBOL(ttm_bo_set_bulk_move);
120 
121 static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo,
122 				  struct ttm_resource *mem, bool evict,
123 				  struct ttm_operation_ctx *ctx,
124 				  struct ttm_place *hop)
125 {
126 	struct ttm_device *bdev = bo->bdev;
127 	bool old_use_tt, new_use_tt;
128 	int ret;
129 
130 	old_use_tt = !bo->resource || ttm_manager_type(bdev, bo->resource->mem_type)->use_tt;
131 	new_use_tt = ttm_manager_type(bdev, mem->mem_type)->use_tt;
132 
133 	ttm_bo_unmap_virtual(bo);
134 
135 	/*
136 	 * Create and bind a ttm if required.
137 	 */
138 
139 	if (new_use_tt) {
140 		/* Zero init the new TTM structure if the old location should
141 		 * have used one as well.
142 		 */
143 		ret = ttm_tt_create(bo, old_use_tt);
144 		if (ret)
145 			goto out_err;
146 
147 		if (mem->mem_type != TTM_PL_SYSTEM) {
148 			ret = ttm_bo_populate(bo, ctx);
149 			if (ret)
150 				goto out_err;
151 		}
152 	}
153 
154 	ret = dma_resv_reserve_fences(bo->base.resv, 1);
155 	if (ret)
156 		goto out_err;
157 
158 	ret = bdev->funcs->move(bo, evict, ctx, mem, hop);
159 	if (ret) {
160 		if (ret == -EMULTIHOP)
161 			return ret;
162 		goto out_err;
163 	}
164 
165 	ctx->bytes_moved += bo->base.size;
166 	return 0;
167 
168 out_err:
169 	if (!old_use_tt)
170 		ttm_bo_tt_destroy(bo);
171 
172 	return ret;
173 }
174 
175 /*
176  * Call bo::reserved.
177  * Will release GPU memory type usage on destruction.
178  * This is the place to put in driver specific hooks to release
179  * driver private resources.
180  * Will release the bo::reserved lock.
181  */
182 
183 static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo)
184 {
185 	if (bo->bdev->funcs->delete_mem_notify)
186 		bo->bdev->funcs->delete_mem_notify(bo);
187 
188 	ttm_bo_tt_destroy(bo);
189 	ttm_resource_free(bo, &bo->resource);
190 }
191 
192 static int ttm_bo_individualize_resv(struct ttm_buffer_object *bo)
193 {
194 	int r;
195 
196 	if (bo->base.resv == &bo->base._resv)
197 		return 0;
198 
199 	BUG_ON(!dma_resv_trylock(&bo->base._resv));
200 
201 	r = dma_resv_copy_fences(&bo->base._resv, bo->base.resv);
202 	dma_resv_unlock(&bo->base._resv);
203 	if (r)
204 		return r;
205 
206 	if (bo->type != ttm_bo_type_sg) {
207 		/* This works because the BO is about to be destroyed and nobody
208 		 * reference it any more. The only tricky case is the trylock on
209 		 * the resv object while holding the lru_lock.
210 		 */
211 		spin_lock(&bo->bdev->lru_lock);
212 		bo->base.resv = &bo->base._resv;
213 		spin_unlock(&bo->bdev->lru_lock);
214 	}
215 
216 	return r;
217 }
218 
219 static void ttm_bo_flush_all_fences(struct ttm_buffer_object *bo)
220 {
221 	struct dma_resv *resv = &bo->base._resv;
222 	struct dma_resv_iter cursor;
223 	struct dma_fence *fence;
224 
225 	dma_resv_iter_begin(&cursor, resv, DMA_RESV_USAGE_BOOKKEEP);
226 	dma_resv_for_each_fence_unlocked(&cursor, fence)
227 		dma_fence_enable_signaling(fence);
228 	dma_resv_iter_end(&cursor);
229 }
230 
231 /*
232  * Block for the dma_resv object to become idle, lock the buffer and clean up
233  * the resource and tt object.
234  */
235 static void ttm_bo_delayed_delete(struct work_struct *work)
236 {
237 	struct ttm_buffer_object *bo;
238 
239 	bo = container_of(work, typeof(*bo), delayed_delete);
240 
241 	dma_resv_wait_timeout(&bo->base._resv, DMA_RESV_USAGE_BOOKKEEP, false,
242 			      MAX_SCHEDULE_TIMEOUT);
243 	dma_resv_lock(bo->base.resv, NULL);
244 	ttm_bo_cleanup_memtype_use(bo);
245 	dma_resv_unlock(bo->base.resv);
246 	ttm_bo_put(bo);
247 }
248 
249 static void ttm_bo_release(struct kref *kref)
250 {
251 	struct ttm_buffer_object *bo =
252 	    container_of(kref, struct ttm_buffer_object, kref);
253 	struct ttm_device *bdev = bo->bdev;
254 	int ret;
255 
256 	WARN_ON_ONCE(bo->pin_count);
257 	WARN_ON_ONCE(bo->bulk_move);
258 
259 	if (!bo->deleted) {
260 		ret = ttm_bo_individualize_resv(bo);
261 		if (ret) {
262 			/* Last resort, if we fail to allocate memory for the
263 			 * fences block for the BO to become idle
264 			 */
265 			dma_resv_wait_timeout(bo->base.resv,
266 					      DMA_RESV_USAGE_BOOKKEEP, false,
267 					      30 * HZ);
268 		}
269 
270 		if (bdev->funcs->release_notify)
271 			bdev->funcs->release_notify(bo);
272 
273 		drm_vma_offset_remove(bdev->vma_manager, &bo->base.vma_node);
274 		ttm_mem_io_free(bdev, bo->resource);
275 
276 		if (!dma_resv_test_signaled(&bo->base._resv,
277 					    DMA_RESV_USAGE_BOOKKEEP) ||
278 		    (want_init_on_free() && (bo->ttm != NULL)) ||
279 		    bo->type == ttm_bo_type_sg ||
280 		    !dma_resv_trylock(bo->base.resv)) {
281 			/* The BO is not idle, resurrect it for delayed destroy */
282 			ttm_bo_flush_all_fences(bo);
283 			bo->deleted = true;
284 
285 			spin_lock(&bdev->lru_lock);
286 
287 			/*
288 			 * Make pinned bos immediately available to
289 			 * shrinkers, now that they are queued for
290 			 * destruction.
291 			 *
292 			 * FIXME: QXL is triggering this. Can be removed when the
293 			 * driver is fixed.
294 			 */
295 			if (bo->pin_count) {
296 				bo->pin_count = 0;
297 				ttm_resource_move_to_lru_tail(bo->resource);
298 			}
299 
300 			kref_init(&bo->kref);
301 			spin_unlock(&bdev->lru_lock);
302 
303 			INIT_WORK(&bo->delayed_delete, ttm_bo_delayed_delete);
304 
305 			/* Schedule the worker on the closest NUMA node. This
306 			 * improves performance since system memory might be
307 			 * cleared on free and that is best done on a CPU core
308 			 * close to it.
309 			 */
310 			queue_work_node(bdev->pool.nid, bdev->wq, &bo->delayed_delete);
311 			return;
312 		}
313 
314 		ttm_bo_cleanup_memtype_use(bo);
315 		dma_resv_unlock(bo->base.resv);
316 	}
317 
318 	atomic_dec(&ttm_glob.bo_count);
319 	bo->destroy(bo);
320 }
321 
322 /* TODO: remove! */
323 void ttm_bo_put(struct ttm_buffer_object *bo)
324 {
325 	kref_put(&bo->kref, ttm_bo_release);
326 }
327 
328 void ttm_bo_fini(struct ttm_buffer_object *bo)
329 {
330 	ttm_bo_put(bo);
331 }
332 EXPORT_SYMBOL(ttm_bo_fini);
333 
334 static int ttm_bo_bounce_temp_buffer(struct ttm_buffer_object *bo,
335 				     struct ttm_operation_ctx *ctx,
336 				     struct ttm_place *hop)
337 {
338 	struct ttm_placement hop_placement;
339 	struct ttm_resource *hop_mem;
340 	int ret;
341 
342 	hop_placement.num_placement = 1;
343 	hop_placement.placement = hop;
344 
345 	/* find space in the bounce domain */
346 	ret = ttm_bo_mem_space(bo, &hop_placement, &hop_mem, ctx);
347 	if (ret)
348 		return ret;
349 	/* move to the bounce domain */
350 	ret = ttm_bo_handle_move_mem(bo, hop_mem, false, ctx, NULL);
351 	if (ret) {
352 		ttm_resource_free(bo, &hop_mem);
353 		return ret;
354 	}
355 	return 0;
356 }
357 
358 static int ttm_bo_evict(struct ttm_buffer_object *bo,
359 			struct ttm_operation_ctx *ctx)
360 {
361 	struct ttm_resource *evict_mem;
362 	struct ttm_placement placement;
363 	struct ttm_place hop;
364 	int ret = 0;
365 
366 	memset(&hop, 0, sizeof(hop));
367 
368 	dma_resv_assert_held(bo->base.resv);
369 
370 	placement.num_placement = 0;
371 	bo->bdev->funcs->evict_flags(bo, &placement);
372 
373 	if (!placement.num_placement) {
374 		ret = ttm_bo_wait_ctx(bo, ctx);
375 		if (ret)
376 			return ret;
377 
378 		/*
379 		 * Since we've already synced, this frees backing store
380 		 * immediately.
381 		 */
382 		return ttm_bo_pipeline_gutting(bo);
383 	}
384 
385 	ret = ttm_bo_mem_space(bo, &placement, &evict_mem, ctx);
386 	if (ret) {
387 		if (ret != -ERESTARTSYS) {
388 			pr_err("Failed to find memory space for buffer 0x%p eviction\n",
389 			       bo);
390 			ttm_bo_mem_space_debug(bo, &placement);
391 		}
392 		goto out;
393 	}
394 
395 	do {
396 		ret = ttm_bo_handle_move_mem(bo, evict_mem, true, ctx, &hop);
397 		if (ret != -EMULTIHOP)
398 			break;
399 
400 		ret = ttm_bo_bounce_temp_buffer(bo, ctx, &hop);
401 	} while (!ret);
402 
403 	if (ret) {
404 		ttm_resource_free(bo, &evict_mem);
405 		if (ret != -ERESTARTSYS && ret != -EINTR)
406 			pr_err("Buffer eviction failed\n");
407 	}
408 out:
409 	return ret;
410 }
411 
412 /**
413  * ttm_bo_eviction_valuable
414  *
415  * @bo: The buffer object to evict
416  * @place: the placement we need to make room for
417  *
418  * Check if it is valuable to evict the BO to make room for the given placement.
419  */
420 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
421 			      const struct ttm_place *place)
422 {
423 	struct ttm_resource *res = bo->resource;
424 
425 	dma_resv_assert_held(bo->base.resv);
426 
427 	if (res->mem_type == TTM_PL_SYSTEM)
428 		return true;
429 
430 	/* Don't evict this BO if it's outside of the
431 	 * requested placement range
432 	 */
433 	return ttm_resource_intersects(bo->bdev, res, place, bo->base.size);
434 }
435 EXPORT_SYMBOL(ttm_bo_eviction_valuable);
436 
437 /**
438  * ttm_bo_evict_first() - Evict the first bo on the manager's LRU list.
439  * @bdev: The ttm device.
440  * @man: The manager whose bo to evict.
441  * @ctx: The TTM operation ctx governing the eviction.
442  *
443  * Return: 0 if successful or the resource disappeared. Negative error code on error.
444  */
445 int ttm_bo_evict_first(struct ttm_device *bdev, struct ttm_resource_manager *man,
446 		       struct ttm_operation_ctx *ctx)
447 {
448 	struct ttm_resource_cursor cursor;
449 	struct ttm_buffer_object *bo;
450 	struct ttm_resource *res;
451 	unsigned int mem_type;
452 	int ret = 0;
453 
454 	spin_lock(&bdev->lru_lock);
455 	ttm_resource_cursor_init(&cursor, man);
456 	res = ttm_resource_manager_first(&cursor);
457 	ttm_resource_cursor_fini(&cursor);
458 	if (!res) {
459 		ret = -ENOENT;
460 		goto out_no_ref;
461 	}
462 	bo = res->bo;
463 	if (!ttm_bo_get_unless_zero(bo))
464 		goto out_no_ref;
465 	mem_type = res->mem_type;
466 	spin_unlock(&bdev->lru_lock);
467 	ret = ttm_bo_reserve(bo, ctx->interruptible, ctx->no_wait_gpu, NULL);
468 	if (ret)
469 		goto out_no_lock;
470 	if (!bo->resource || bo->resource->mem_type != mem_type)
471 		goto out_bo_moved;
472 
473 	if (bo->deleted) {
474 		ret = ttm_bo_wait_ctx(bo, ctx);
475 		if (!ret)
476 			ttm_bo_cleanup_memtype_use(bo);
477 	} else {
478 		ret = ttm_bo_evict(bo, ctx);
479 	}
480 out_bo_moved:
481 	dma_resv_unlock(bo->base.resv);
482 out_no_lock:
483 	ttm_bo_put(bo);
484 	return ret;
485 
486 out_no_ref:
487 	spin_unlock(&bdev->lru_lock);
488 	return ret;
489 }
490 
491 struct ttm_bo_alloc_state {
492 	/** @charge_pool: The memory pool the resource is charged to */
493 	struct dmem_cgroup_pool_state *charge_pool;
494 	/** @limit_pool: Which pool limit we should test against */
495 	struct dmem_cgroup_pool_state *limit_pool;
496 	/** @in_evict: Whether we are currently evicting buffers */
497 	bool in_evict;
498 	/** @may_try_low: If only unprotected BOs, i.e. BOs whose cgroup
499 	 *  is exceeding its dmem low/min protection, should be considered for eviction
500 	 */
501 	bool may_try_low;
502 };
503 
504 /**
505  * ttm_bo_alloc_at_place - Attempt allocating a BO's backing store in a place
506  *
507  * @bo: The buffer to allocate the backing store of
508  * @place: The place to attempt allocation in
509  * @ctx: ttm_operation_ctx associated with this allocation
510  * @force_space: If we should evict buffers to force space
511  * @res: On allocation success, the resulting struct ttm_resource.
512  * @alloc_state: Object holding allocation state such as charged cgroups.
513  *
514  * Returns:
515  * -EBUSY: No space available, but allocation should be retried with ttm_bo_evict_alloc.
516  * -ENOSPC: No space available, allocation should not be retried.
517  * -ERESTARTSYS: An interruptible sleep was interrupted by a signal.
518  *
519  */
520 static int ttm_bo_alloc_at_place(struct ttm_buffer_object *bo,
521 				 const struct ttm_place *place,
522 				 bool force_space,
523 				 struct ttm_resource **res,
524 				 struct ttm_bo_alloc_state *alloc_state)
525 {
526 	bool may_evict;
527 	int ret;
528 
529 	may_evict = !alloc_state->in_evict && force_space &&
530 		    place->mem_type != TTM_PL_SYSTEM;
531 	if (!alloc_state->charge_pool) {
532 		ret = ttm_resource_try_charge(bo, place, &alloc_state->charge_pool,
533 					      force_space ? &alloc_state->limit_pool
534 							  : NULL);
535 		if (ret) {
536 			/*
537 			 * -EAGAIN means the charge failed, which we treat
538 			 * like an allocation failure. Therefore, return an
539 			 * error code indicating the allocation failed -
540 			 * either -EBUSY if the allocation should be
541 			 * retried with eviction, or -ENOSPC if there should
542 			 * be no second attempt.
543 			 */
544 			if (!alloc_state->in_evict)
545 				alloc_state->may_try_low = may_evict;
546 			if (ret == -EAGAIN)
547 				ret = may_evict ? -EBUSY : -ENOSPC;
548 			return ret;
549 		}
550 	}
551 
552 	/*
553 	 * cgroup protection plays a special role in eviction.
554 	 * Conceptually, protection of memory via the dmem cgroup controller
555 	 * entitles the protected cgroup to use a certain amount of memory.
556 	 * There are two types of protection - the 'low' limit is a
557 	 * "best-effort" protection, whereas the 'min' limit provides a hard
558 	 * guarantee that memory within the cgroup's allowance will not be
559 	 * evicted under any circumstance.
560 	 *
561 	 * To faithfully model this concept in TTM, we also need to take cgroup
562 	 * protection into account when allocating. When allocation in one
563 	 * place fails, TTM will default to trying other places first before
564 	 * evicting.
565 	 * If the allocation is covered by dmem cgroup protection, however,
566 	 * this prevents the allocation from using the memory it is "entitled"
567 	 * to. To make sure unprotected allocations cannot push new protected
568 	 * allocations out of places they are "entitled" to use, we should
569 	 * evict buffers not covered by any cgroup protection, if this
570 	 * allocation is covered by cgroup protection.
571 	 *
572 	 * Buffers covered by 'min' protection are a special case - the 'min'
573 	 * limit is a stronger guarantee than 'low', and thus buffers protected
574 	 * by 'low' but not 'min' should also be considered for eviction.
575 	 * Buffers protected by 'min' will never be considered for eviction
576 	 * anyway, so the regular eviction path should be triggered here.
577 	 * Buffers protected by 'low' but not 'min' will take a special
578 	 * eviction path that only evicts buffers covered by neither 'low' or
579 	 * 'min' protections.
580 	 */
581 	if (!alloc_state->in_evict) {
582 		may_evict |= dmem_cgroup_below_min(NULL, alloc_state->charge_pool);
583 		alloc_state->may_try_low = may_evict;
584 
585 		may_evict |= dmem_cgroup_below_low(NULL, alloc_state->charge_pool);
586 	}
587 
588 	ret = ttm_resource_alloc(bo, place, res, alloc_state->charge_pool);
589 	if (ret) {
590 		if (ret == -ENOSPC && may_evict)
591 			ret = -EBUSY;
592 		return ret;
593 	}
594 
595 	/*
596 	 * Ownership of charge_pool has been transferred to the TTM resource,
597 	 * don't make the caller think we still hold a reference to it.
598 	 */
599 	alloc_state->charge_pool = NULL;
600 	return 0;
601 }
602 
603 /**
604  * struct ttm_bo_evict_walk - Parameters for the evict walk.
605  */
606 struct ttm_bo_evict_walk {
607 	/** @walk: The walk base parameters. */
608 	struct ttm_lru_walk walk;
609 	/** @place: The place passed to the resource allocation. */
610 	const struct ttm_place *place;
611 	/** @evictor: The buffer object we're trying to make room for. */
612 	struct ttm_buffer_object *evictor;
613 	/** @res: The allocated resource if any. */
614 	struct ttm_resource **res;
615 	/** @evicted: Number of successful evictions. */
616 	unsigned long evicted;
617 
618 	/** @try_low: Whether we should attempt to evict BO's with low watermark threshold */
619 	bool try_low;
620 	/** @hit_low: If we cannot evict a bo when @try_low is false (first pass) */
621 	bool hit_low;
622 
623 	/** @alloc_state: State associated with the allocation attempt. */
624 	struct ttm_bo_alloc_state *alloc_state;
625 };
626 
627 static s64 ttm_bo_evict_cb(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo)
628 {
629 	struct ttm_bo_evict_walk *evict_walk =
630 		container_of(walk, typeof(*evict_walk), walk);
631 	struct dmem_cgroup_pool_state *limit_pool, *ancestor = NULL;
632 	s64 bo_size = bo->base.size;
633 	bool evict_valuable;
634 	s64 lret;
635 
636 	/*
637 	 * If may_try_low is not set, then we're trying to evict unprotected
638 	 * buffers in favor of a protected allocation for charge_pool. Explicitly skip
639 	 * buffers belonging to the same cgroup here - that cgroup is definitely protected,
640 	 * even though dmem_cgroup_state_evict_valuable would allow the eviction because a
641 	 * cgroup is always allowed to evict from itself even if it is protected.
642 	 */
643 	if (!evict_walk->alloc_state->may_try_low &&
644 			bo->resource->css == evict_walk->alloc_state->charge_pool)
645 		return 0;
646 
647 	limit_pool = evict_walk->alloc_state->limit_pool;
648 	/*
649 	 * If there is no explicit limit pool, find the root of the shared subtree between
650 	 * evictor and evictee. This is important so that recursive protection rules can
651 	 * apply properly: Recursive protection distributes cgroup protection afforded
652 	 * to a parent cgroup but not used explicitly by a child cgroup between all child
653 	 * cgroups (see docs of effective_protection in mm/page_counter.c). However, when
654 	 * direct siblings compete for memory, siblings that were explicitly protected
655 	 * should get prioritized over siblings that weren't. This only happens correctly
656 	 * when the root of the shared subtree is passed to
657 	 * dmem_cgroup_state_evict_valuable. Otherwise, the effective-protection
658 	 * calculation cannot distinguish direct siblings from unrelated subtrees and the
659 	 * calculated protection ends up wrong.
660 	 */
661 	if (!limit_pool) {
662 		ancestor = dmem_cgroup_get_common_ancestor(bo->resource->css,
663 							   evict_walk->alloc_state->charge_pool);
664 		limit_pool = ancestor;
665 	}
666 
667 	evict_valuable = dmem_cgroup_state_evict_valuable(limit_pool, bo->resource->css,
668 							  evict_walk->try_low,
669 							  &evict_walk->hit_low);
670 	if (ancestor)
671 		dmem_cgroup_pool_state_put(ancestor);
672 
673 	if (!evict_valuable)
674 		return 0;
675 
676 	/*
677 	 * evict_walk->place is NULL in cgroup drain mode.  Drivers'
678 	 * eviction_valuable() callbacks must handle a NULL place, treating it
679 	 * as "any placement": the TTM base implementation already does so via
680 	 * ttm_resource_intersects().
681 	 */
682 	if (bo->pin_count || !bo->bdev->funcs->eviction_valuable(bo, evict_walk->place))
683 		return 0;
684 
685 	if (bo->deleted) {
686 		lret = ttm_bo_wait_ctx(bo, walk->arg.ctx);
687 		if (!lret)
688 			ttm_bo_cleanup_memtype_use(bo);
689 	} else {
690 		lret = ttm_bo_evict(bo, walk->arg.ctx);
691 	}
692 
693 	if (lret)
694 		goto out;
695 
696 	evict_walk->evicted++;
697 	if (evict_walk->res) {
698 		lret = ttm_bo_alloc_at_place(evict_walk->evictor,
699 					     evict_walk->place, false,
700 					     evict_walk->res,
701 					     evict_walk->alloc_state);
702 		if (lret == 0)
703 			return 1;
704 	} else {
705 		/* Cgroup drain: return bytes freed for byte-denominated progress. */
706 		return bo_size;
707 	}
708 out:
709 	/* Errors that should terminate the walk. */
710 	if (lret == -ENOSPC)
711 		return -EBUSY;
712 
713 	return lret;
714 }
715 
716 static const struct ttm_lru_walk_ops ttm_evict_walk_ops = {
717 	.process_bo = ttm_bo_evict_cb,
718 };
719 
720 static int ttm_bo_evict_alloc(struct ttm_device *bdev,
721 			      struct ttm_resource_manager *man,
722 			      const struct ttm_place *place,
723 			      struct ttm_buffer_object *evictor,
724 			      struct ttm_operation_ctx *ctx,
725 			      struct ww_acquire_ctx *ticket,
726 			      struct ttm_resource **res,
727 			      struct ttm_bo_alloc_state *state)
728 {
729 	struct ttm_bo_evict_walk evict_walk = {
730 		.walk = {
731 			.ops = &ttm_evict_walk_ops,
732 			.arg = {
733 				.ctx = ctx,
734 				.ticket = ticket,
735 			}
736 		},
737 		.place = place,
738 		.evictor = evictor,
739 		.res = res,
740 		.alloc_state = state,
741 	};
742 	s64 lret;
743 
744 	state->in_evict = true;
745 
746 	evict_walk.walk.arg.trylock_only = true;
747 	lret = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man, 1);
748 
749 	/* If we failed to find enough BOs to evict, but we skipped over
750 	 * some BOs because they were covered by dmem low protection, retry
751 	 * evicting these protected BOs too, except if we're told not to
752 	 * consider protected BOs at all.
753 	 */
754 	if (!lret && evict_walk.hit_low && state->may_try_low) {
755 		evict_walk.try_low = true;
756 		lret = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man, 1);
757 	}
758 	if (lret || !ticket)
759 		goto out;
760 
761 	/* Reset low limit */
762 	evict_walk.try_low = evict_walk.hit_low = false;
763 	/* If ticket-locking, repeat while making progress. */
764 	evict_walk.walk.arg.trylock_only = false;
765 
766 retry:
767 	do {
768 		/* The walk may clear the evict_walk.walk.ticket field */
769 		evict_walk.walk.arg.ticket = ticket;
770 		evict_walk.evicted = 0;
771 		lret = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man, 1);
772 	} while (!lret && evict_walk.evicted);
773 
774 	/* We hit the low limit? Try once more */
775 	if (!lret && evict_walk.hit_low && !evict_walk.try_low &&
776 			state->may_try_low) {
777 		evict_walk.try_low = true;
778 		goto retry;
779 	}
780 out:
781 	state->in_evict = false;
782 	if (lret < 0)
783 		return lret;
784 	if (lret == 0)
785 		return -EBUSY;
786 	return 0;
787 }
788 
789 /**
790  * ttm_bo_evict_cgroup() - Evict buffer objects charged to a specific cgroup.
791  * @bdev: The TTM device.
792  * @man: The resource manager whose LRU to walk.
793  * @limit_pool: The cgroup pool state whose members should be evicted.
794  * @target_bytes: Number of bytes to free.
795  * @ctx: The TTM operation context.
796  *
797  * Walk the LRU of @man and evict buffer objects that are charged to the
798  * cgroup identified by @limit_pool, until at least @target_bytes have been
799  * freed.  Mirrors the two-pass (trylock -> sleeping-lock, low-watermark)
800  * strategy used by ttm_bo_evict_alloc().
801  *
802  * Return: >= @target_bytes on full success, 0..target_bytes-1 if partial,
803  *         negative error code on fatal error.
804  */
805 s64 ttm_bo_evict_cgroup(struct ttm_device *bdev,
806 			struct ttm_resource_manager *man,
807 			struct dmem_cgroup_pool_state *limit_pool,
808 			s64 target_bytes,
809 			struct ttm_operation_ctx *ctx)
810 {
811 	struct ttm_bo_evict_walk evict_walk = {
812 		.walk = {
813 			.ops = &ttm_evict_walk_ops,
814 			.arg = { .ctx = ctx },
815 		},
816 		.alloc_state = &(struct ttm_bo_alloc_state) {
817 			.limit_pool = limit_pool,
818 			.in_evict = true,
819 		},
820 		/* place, evictor, res left NULL: selects cgroup drain mode */
821 	};
822 	s64 lret, pass;
823 
824 	evict_walk.walk.arg.trylock_only = true;
825 	lret = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man, target_bytes);
826 	if (lret < 0 || lret >= target_bytes)
827 		return lret;
828 
829 	/* Second pass: also evict BOs at the low watermark. */
830 	if (evict_walk.hit_low) {
831 		evict_walk.try_low = true;
832 		pass = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man,
833 					      target_bytes - lret);
834 		if (pass < 0)
835 			return pass;
836 		lret += pass;
837 		if (lret >= target_bytes)
838 			return lret;
839 	}
840 
841 	/* Full sleeping-lock pass for remaining target. */
842 	evict_walk.try_low = evict_walk.hit_low = false;
843 	evict_walk.walk.arg.trylock_only = false;
844 
845 retry:
846 	evict_walk.walk.arg.sleeping_lock = true;
847 	do {
848 		evict_walk.evicted = 0;
849 		pass = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man,
850 					      target_bytes - lret);
851 		if (pass < 0) {
852 			lret = pass;
853 			goto out;
854 		}
855 		lret += pass;
856 	} while (lret < target_bytes && evict_walk.evicted);
857 
858 	/* One more attempt if we hit the low limit during sleeping-lock pass. */
859 	if (lret < target_bytes && evict_walk.hit_low && !evict_walk.try_low) {
860 		evict_walk.try_low = true;
861 		goto retry;
862 	}
863 
864 out:
865 	return lret;
866 }
867 EXPORT_SYMBOL(ttm_bo_evict_cgroup);
868 
869 /**
870  * ttm_bo_pin - Pin the buffer object.
871  * @bo: The buffer object to pin
872  *
873  * Make sure the buffer is not evicted any more during memory pressure.
874  * @bo must be unpinned again by calling ttm_bo_unpin().
875  */
876 void ttm_bo_pin(struct ttm_buffer_object *bo)
877 {
878 	dma_resv_assert_held(bo->base.resv);
879 	WARN_ON_ONCE(!kref_read(&bo->kref));
880 	spin_lock(&bo->bdev->lru_lock);
881 	if (bo->resource)
882 		ttm_resource_del_bulk_move(bo->resource, bo);
883 	if (!bo->pin_count++ && bo->resource)
884 		ttm_resource_move_to_lru_tail(bo->resource);
885 	spin_unlock(&bo->bdev->lru_lock);
886 }
887 EXPORT_SYMBOL(ttm_bo_pin);
888 
889 /**
890  * ttm_bo_unpin - Unpin the buffer object.
891  * @bo: The buffer object to unpin
892  *
893  * Allows the buffer object to be evicted again during memory pressure.
894  */
895 void ttm_bo_unpin(struct ttm_buffer_object *bo)
896 {
897 	dma_resv_assert_held(bo->base.resv);
898 	WARN_ON_ONCE(!kref_read(&bo->kref));
899 	if (WARN_ON_ONCE(!bo->pin_count))
900 		return;
901 
902 	spin_lock(&bo->bdev->lru_lock);
903 	if (!--bo->pin_count && bo->resource) {
904 		ttm_resource_add_bulk_move(bo->resource, bo);
905 		ttm_resource_move_to_lru_tail(bo->resource);
906 	}
907 	spin_unlock(&bo->bdev->lru_lock);
908 }
909 EXPORT_SYMBOL(ttm_bo_unpin);
910 
911 /*
912  * Add the pipelined eviction fencesto the BO as kernel dependency and reserve new
913  * fence slots.
914  */
915 static int ttm_bo_add_pipelined_eviction_fences(struct ttm_buffer_object *bo,
916 						struct ttm_resource_manager *man,
917 						bool no_wait_gpu)
918 {
919 	struct dma_fence *fence;
920 	int i;
921 
922 	spin_lock(&man->eviction_lock);
923 	for (i = 0; i < TTM_NUM_MOVE_FENCES; i++) {
924 		fence = man->eviction_fences[i];
925 		if (!fence)
926 			continue;
927 
928 		if (no_wait_gpu) {
929 			if (!dma_fence_is_signaled(fence)) {
930 				spin_unlock(&man->eviction_lock);
931 				return -EBUSY;
932 			}
933 		} else {
934 			dma_resv_add_fence(bo->base.resv, fence, DMA_RESV_USAGE_KERNEL);
935 		}
936 	}
937 	spin_unlock(&man->eviction_lock);
938 
939 	/* TODO: this call should be removed. */
940 	return dma_resv_reserve_fences(bo->base.resv, 1);
941 }
942 
943 /**
944  * ttm_bo_alloc_resource - Allocate backing store for a BO
945  *
946  * @bo: Pointer to a struct ttm_buffer_object of which we want a resource for
947  * @placement: Proposed new placement for the buffer object
948  * @ctx: if and how to sleep, lock buffers and alloc memory
949  * @force_space: If we should evict buffers to force space
950  * @res: The resulting struct ttm_resource.
951  *
952  * Allocates a resource for the buffer object pointed to by @bo, using the
953  * placement flags in @placement, potentially evicting other buffer objects when
954  * @force_space is true.
955  * This function may sleep while waiting for resources to become available.
956  * Returns:
957  * -EBUSY: No space available (only if no_wait == true).
958  * -ENOSPC: Could not allocate space for the buffer object, either due to
959  * fragmentation or concurrent allocators.
960  * -ERESTARTSYS: An interruptible sleep was interrupted by a signal.
961  */
962 static int ttm_bo_alloc_resource(struct ttm_buffer_object *bo,
963 				 struct ttm_placement *placement,
964 				 struct ttm_operation_ctx *ctx,
965 				 bool force_space,
966 				 struct ttm_resource **res)
967 {
968 	struct ttm_device *bdev = bo->bdev;
969 	struct ww_acquire_ctx *ticket;
970 	int i, ret;
971 
972 	ticket = dma_resv_locking_ctx(bo->base.resv);
973 	ret = dma_resv_reserve_fences(bo->base.resv, TTM_NUM_MOVE_FENCES);
974 	if (unlikely(ret))
975 		return ret;
976 
977 	for (i = 0; i < placement->num_placement; ++i) {
978 		const struct ttm_place *place = &placement->placement[i];
979 		struct ttm_bo_alloc_state alloc_state = {};
980 		struct ttm_resource_manager *man;
981 
982 		man = ttm_manager_type(bdev, place->mem_type);
983 		if (!man || !ttm_resource_manager_used(man))
984 			continue;
985 
986 		if (place->flags & (force_space ? TTM_PL_FLAG_DESIRED :
987 				    TTM_PL_FLAG_FALLBACK))
988 			continue;
989 
990 		ret = ttm_bo_alloc_at_place(bo, place, force_space, res,
991 					    &alloc_state);
992 
993 		if (ret == -ENOSPC) {
994 			dmem_cgroup_uncharge(alloc_state.charge_pool, bo->base.size);
995 			dmem_cgroup_pool_state_put(alloc_state.limit_pool);
996 			continue;
997 		} else if (ret == -EBUSY) {
998 			ret = ttm_bo_evict_alloc(bdev, man, place, bo, ctx,
999 						 ticket, res, &alloc_state);
1000 
1001 			dmem_cgroup_pool_state_put(alloc_state.limit_pool);
1002 
1003 			if (ret) {
1004 				dmem_cgroup_uncharge(alloc_state.charge_pool,
1005 						bo->base.size);
1006 				if (ret == -EBUSY)
1007 					continue;
1008 				return ret;
1009 			}
1010 		} else if (ret) {
1011 			dmem_cgroup_uncharge(alloc_state.charge_pool, bo->base.size);
1012 			dmem_cgroup_pool_state_put(alloc_state.limit_pool);
1013 			return ret;
1014 		}
1015 
1016 		ret = ttm_bo_add_pipelined_eviction_fences(bo, man, ctx->no_wait_gpu);
1017 		if (unlikely(ret)) {
1018 			ttm_resource_free(bo, res);
1019 			if (ret == -EBUSY)
1020 				continue;
1021 
1022 			return ret;
1023 		}
1024 		return 0;
1025 	}
1026 
1027 	return -ENOSPC;
1028 }
1029 
1030 /*
1031  * ttm_bo_mem_space - Wrapper around ttm_bo_alloc_resource
1032  *
1033  * @bo: Pointer to a struct ttm_buffer_object of which we want a resource for
1034  * @placement: Proposed new placement for the buffer object
1035  * @res: The resulting struct ttm_resource.
1036  * @ctx: if and how to sleep, lock buffers and alloc memory
1037  *
1038  * Tries both idle allocation and forcefully eviction of buffers. See
1039  * ttm_bo_alloc_resource for details.
1040  */
1041 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1042 		     struct ttm_placement *placement,
1043 		     struct ttm_resource **res,
1044 		     struct ttm_operation_ctx *ctx)
1045 {
1046 	bool force_space = false;
1047 	int ret;
1048 
1049 	do {
1050 		ret = ttm_bo_alloc_resource(bo, placement, ctx,
1051 					    force_space, res);
1052 		force_space = !force_space;
1053 	} while (ret == -ENOSPC && force_space);
1054 
1055 	return ret;
1056 }
1057 EXPORT_SYMBOL(ttm_bo_mem_space);
1058 
1059 /**
1060  * ttm_bo_validate
1061  *
1062  * @bo: The buffer object.
1063  * @placement: Proposed placement for the buffer object.
1064  * @ctx: validation parameters.
1065  *
1066  * Changes placement and caching policy of the buffer object
1067  * according proposed placement.
1068  * Returns
1069  * -EINVAL on invalid proposed placement.
1070  * -ENOMEM on out-of-memory condition.
1071  * -EBUSY if no_wait is true and buffer busy.
1072  * -ERESTARTSYS if interrupted by a signal.
1073  */
1074 int ttm_bo_validate(struct ttm_buffer_object *bo,
1075 		    struct ttm_placement *placement,
1076 		    struct ttm_operation_ctx *ctx)
1077 {
1078 	struct ttm_resource *res;
1079 	struct ttm_place hop;
1080 	bool force_space;
1081 	int ret;
1082 
1083 	dma_resv_assert_held(bo->base.resv);
1084 
1085 	/*
1086 	 * Remove the backing store if no placement is given.
1087 	 */
1088 	if (!placement->num_placement)
1089 		return ttm_bo_pipeline_gutting(bo);
1090 
1091 	force_space = false;
1092 	do {
1093 		/* Check whether we need to move buffer. */
1094 		if (bo->resource &&
1095 		    ttm_resource_compatible(bo->resource, placement,
1096 					    force_space))
1097 			return 0;
1098 
1099 		/* Moving of pinned BOs is forbidden */
1100 		if (bo->pin_count)
1101 			return -EINVAL;
1102 
1103 		/*
1104 		 * Determine where to move the buffer.
1105 		 *
1106 		 * If driver determines move is going to need
1107 		 * an extra step then it will return -EMULTIHOP
1108 		 * and the buffer will be moved to the temporary
1109 		 * stop and the driver will be called to make
1110 		 * the second hop.
1111 		 */
1112 		ret = ttm_bo_alloc_resource(bo, placement, ctx, force_space,
1113 					    &res);
1114 		force_space = !force_space;
1115 		if (ret == -ENOSPC)
1116 			continue;
1117 		if (ret)
1118 			return ret;
1119 
1120 bounce:
1121 		ret = ttm_bo_handle_move_mem(bo, res, false, ctx, &hop);
1122 		if (ret == -EMULTIHOP) {
1123 			ret = ttm_bo_bounce_temp_buffer(bo, ctx, &hop);
1124 			/* try and move to final place now. */
1125 			if (!ret)
1126 				goto bounce;
1127 		}
1128 		if (ret) {
1129 			ttm_resource_free(bo, &res);
1130 			return ret;
1131 		}
1132 
1133 	} while (ret && force_space);
1134 
1135 	/* For backward compatibility with userspace */
1136 	if (ret == -ENOSPC)
1137 		return bo->bdev->alloc_flags & TTM_ALLOCATION_PROPAGATE_ENOSPC ?
1138 		       ret : -ENOMEM;
1139 
1140 	/*
1141 	 * We might need to add a TTM.
1142 	 */
1143 	if (!bo->resource || bo->resource->mem_type == TTM_PL_SYSTEM) {
1144 		ret = ttm_tt_create(bo, true);
1145 		if (ret)
1146 			return ret;
1147 	}
1148 	return 0;
1149 }
1150 EXPORT_SYMBOL(ttm_bo_validate);
1151 
1152 /**
1153  * ttm_bo_init_reserved
1154  *
1155  * @bdev: Pointer to a ttm_device struct.
1156  * @bo: Pointer to a ttm_buffer_object to be initialized.
1157  * @type: Requested type of buffer object.
1158  * @placement: Initial placement for buffer object.
1159  * @alignment: Data alignment in pages.
1160  * @ctx: TTM operation context for memory allocation.
1161  * @sg: Scatter-gather table.
1162  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
1163  * @destroy: Destroy function. Use NULL for kfree().
1164  *
1165  * This function initializes a pre-allocated struct ttm_buffer_object.
1166  * As this object may be part of a larger structure, this function,
1167  * together with the @destroy function, enables driver-specific objects
1168  * derived from a ttm_buffer_object.
1169  *
1170  * On successful return, the caller owns an object kref to @bo. The kref and
1171  * list_kref are usually set to 1, but note that in some situations, other
1172  * tasks may already be holding references to @bo as well.
1173  * Furthermore, if resv == NULL, the buffer's reservation lock will be held,
1174  * and it is the caller's responsibility to call ttm_bo_unreserve.
1175  *
1176  * If a failure occurs, the function will call the @destroy function. Thus,
1177  * after a failure, dereferencing @bo is illegal and will likely cause memory
1178  * corruption.
1179  *
1180  * Returns
1181  * -ENOMEM: Out of memory.
1182  * -EINVAL: Invalid placement flags.
1183  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
1184  */
1185 int ttm_bo_init_reserved(struct ttm_device *bdev, struct ttm_buffer_object *bo,
1186 			 enum ttm_bo_type type, struct ttm_placement *placement,
1187 			 uint32_t alignment, struct ttm_operation_ctx *ctx,
1188 			 struct sg_table *sg, struct dma_resv *resv,
1189 			 void (*destroy) (struct ttm_buffer_object *))
1190 {
1191 	int ret;
1192 
1193 	kref_init(&bo->kref);
1194 	bo->bdev = bdev;
1195 	bo->type = type;
1196 	bo->page_alignment = alignment;
1197 	bo->destroy = destroy;
1198 	bo->pin_count = 0;
1199 	bo->sg = sg;
1200 	bo->bulk_move = NULL;
1201 	if (resv)
1202 		bo->base.resv = resv;
1203 	else
1204 		bo->base.resv = &bo->base._resv;
1205 	atomic_inc(&ttm_glob.bo_count);
1206 
1207 	/*
1208 	 * For ttm_bo_type_device buffers, allocate
1209 	 * address space from the device.
1210 	 */
1211 	if (bo->type == ttm_bo_type_device || bo->type == ttm_bo_type_sg) {
1212 		ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
1213 					 PFN_UP(bo->base.size));
1214 		if (ret)
1215 			goto err_put;
1216 	}
1217 
1218 	/* passed reservation objects should already be locked,
1219 	 * since otherwise lockdep will be angered in radeon.
1220 	 */
1221 	if (!resv)
1222 		WARN_ON(!dma_resv_trylock(bo->base.resv));
1223 	else
1224 		dma_resv_assert_held(resv);
1225 
1226 	ret = ttm_bo_validate(bo, placement, ctx);
1227 	if (unlikely(ret))
1228 		goto err_unlock;
1229 
1230 	return 0;
1231 
1232 err_unlock:
1233 	if (!resv)
1234 		dma_resv_unlock(bo->base.resv);
1235 
1236 err_put:
1237 	ttm_bo_put(bo);
1238 	return ret;
1239 }
1240 EXPORT_SYMBOL(ttm_bo_init_reserved);
1241 
1242 /**
1243  * ttm_bo_init_validate
1244  *
1245  * @bdev: Pointer to a ttm_device struct.
1246  * @bo: Pointer to a ttm_buffer_object to be initialized.
1247  * @type: Requested type of buffer object.
1248  * @placement: Initial placement for buffer object.
1249  * @alignment: Data alignment in pages.
1250  * @interruptible: If needing to sleep to wait for GPU resources,
1251  * sleep interruptible.
1252  * pinned in physical memory. If this behaviour is not desired, this member
1253  * holds a pointer to a persistent shmem object. Typically, this would
1254  * point to the shmem object backing a GEM object if TTM is used to back a
1255  * GEM user interface.
1256  * @sg: Scatter-gather table.
1257  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
1258  * @destroy: Destroy function. Use NULL for kfree().
1259  *
1260  * This function initializes a pre-allocated struct ttm_buffer_object.
1261  * As this object may be part of a larger structure, this function,
1262  * together with the @destroy function,
1263  * enables driver-specific objects derived from a ttm_buffer_object.
1264  *
1265  * On successful return, the caller owns an object kref to @bo. The kref and
1266  * list_kref are usually set to 1, but note that in some situations, other
1267  * tasks may already be holding references to @bo as well.
1268  *
1269  * If a failure occurs, the function will call the @destroy function, Thus,
1270  * after a failure, dereferencing @bo is illegal and will likely cause memory
1271  * corruption.
1272  *
1273  * Returns
1274  * -ENOMEM: Out of memory.
1275  * -EINVAL: Invalid placement flags.
1276  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
1277  */
1278 int ttm_bo_init_validate(struct ttm_device *bdev, struct ttm_buffer_object *bo,
1279 			 enum ttm_bo_type type, struct ttm_placement *placement,
1280 			 uint32_t alignment, bool interruptible,
1281 			 struct sg_table *sg, struct dma_resv *resv,
1282 			 void (*destroy) (struct ttm_buffer_object *))
1283 {
1284 	struct ttm_operation_ctx ctx = { .interruptible = interruptible };
1285 	int ret;
1286 
1287 	ret = ttm_bo_init_reserved(bdev, bo, type, placement, alignment, &ctx,
1288 				   sg, resv, destroy);
1289 	if (ret)
1290 		return ret;
1291 
1292 	if (!resv)
1293 		ttm_bo_unreserve(bo);
1294 
1295 	return 0;
1296 }
1297 EXPORT_SYMBOL(ttm_bo_init_validate);
1298 
1299 /*
1300  * buffer object vm functions.
1301  */
1302 
1303 /**
1304  * ttm_bo_unmap_virtual
1305  *
1306  * @bo: tear down the virtual mappings for this BO
1307  */
1308 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1309 {
1310 	struct ttm_device *bdev = bo->bdev;
1311 
1312 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1313 	ttm_mem_io_free(bdev, bo->resource);
1314 }
1315 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1316 
1317 /**
1318  * ttm_bo_wait_ctx - wait for buffer idle.
1319  *
1320  * @bo:  The buffer object.
1321  * @ctx: defines how to wait
1322  *
1323  * Waits for the buffer to be idle. Used timeout depends on the context.
1324  * Returns -EBUSY if wait timed outt, -ERESTARTSYS if interrupted by a signal or
1325  * zero on success.
1326  */
1327 int ttm_bo_wait_ctx(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx)
1328 {
1329 	long ret;
1330 
1331 	if (ctx->no_wait_gpu) {
1332 		if (dma_resv_test_signaled(bo->base.resv,
1333 					   DMA_RESV_USAGE_BOOKKEEP))
1334 			return 0;
1335 		else
1336 			return -EBUSY;
1337 	}
1338 
1339 	ret = dma_resv_wait_timeout(bo->base.resv, DMA_RESV_USAGE_BOOKKEEP,
1340 				    ctx->interruptible, 15 * HZ);
1341 	if (unlikely(ret < 0))
1342 		return ret;
1343 	if (unlikely(ret == 0))
1344 		return -EBUSY;
1345 	return 0;
1346 }
1347 EXPORT_SYMBOL(ttm_bo_wait_ctx);
1348 
1349 /**
1350  * struct ttm_bo_swapout_walk - Parameters for the swapout walk
1351  */
1352 struct ttm_bo_swapout_walk {
1353 	/** @walk: The walk base parameters. */
1354 	struct ttm_lru_walk walk;
1355 	/** @gfp_flags: The gfp flags to use for ttm_tt_swapout() */
1356 	gfp_t gfp_flags;
1357 	/** @hit_low: Whether we should attempt to swap BO's with low watermark threshold */
1358 	/** @evict_low: If we cannot swap a bo when @try_low is false (first pass) */
1359 	bool hit_low, evict_low;
1360 };
1361 
1362 static s64
1363 ttm_bo_swapout_cb(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo)
1364 {
1365 	struct ttm_place place = { .mem_type = bo->resource->mem_type };
1366 	struct ttm_bo_swapout_walk *swapout_walk =
1367 		container_of(walk, typeof(*swapout_walk), walk);
1368 	struct ttm_operation_ctx *ctx = walk->arg.ctx;
1369 	struct ttm_device *bdev = bo->bdev;
1370 	struct ttm_tt *tt = bo->ttm;
1371 	s64 ret;
1372 
1373 	/*
1374 	 * While the bo may already reside in SYSTEM placement, set
1375 	 * SYSTEM as new placement to cover also the move further below.
1376 	 * The driver may use the fact that we're moving from SYSTEM
1377 	 * as an indication that we're about to swap out.
1378 	 */
1379 	if (bo->pin_count || !bdev->funcs->eviction_valuable(bo, &place)) {
1380 		ret = -EBUSY;
1381 		goto out;
1382 	}
1383 
1384 	if (!tt || !ttm_tt_is_populated(tt) ||
1385 	    tt->page_flags & (TTM_TT_FLAG_EXTERNAL | TTM_TT_FLAG_SWAPPED)) {
1386 		ret = -EBUSY;
1387 		goto out;
1388 	}
1389 
1390 	if (bo->deleted) {
1391 		pgoff_t num_pages = tt->num_pages;
1392 
1393 		ret = ttm_bo_wait_ctx(bo, ctx);
1394 		if (ret)
1395 			goto out;
1396 
1397 		ttm_bo_cleanup_memtype_use(bo);
1398 		ret = num_pages;
1399 		goto out;
1400 	}
1401 
1402 	/*
1403 	 * Move to system cached
1404 	 */
1405 	if (bo->resource->mem_type != TTM_PL_SYSTEM) {
1406 		struct ttm_resource *evict_mem;
1407 		struct ttm_place hop;
1408 
1409 		memset(&hop, 0, sizeof(hop));
1410 		place.mem_type = TTM_PL_SYSTEM;
1411 		ret = ttm_resource_alloc(bo, &place, &evict_mem, NULL);
1412 		if (ret)
1413 			goto out;
1414 
1415 		ret = ttm_bo_handle_move_mem(bo, evict_mem, true, ctx, &hop);
1416 		if (ret) {
1417 			WARN(ret == -EMULTIHOP,
1418 			     "Unexpected multihop in swapout - likely driver bug.\n");
1419 			ttm_resource_free(bo, &evict_mem);
1420 			goto out;
1421 		}
1422 	}
1423 
1424 	/*
1425 	 * Make sure BO is idle.
1426 	 */
1427 	ret = ttm_bo_wait_ctx(bo, ctx);
1428 	if (ret)
1429 		goto out;
1430 
1431 	ttm_bo_unmap_virtual(bo);
1432 	if (bdev->funcs->swap_notify)
1433 		bdev->funcs->swap_notify(bo);
1434 
1435 	if (ttm_tt_is_populated(tt)) {
1436 		ret = ttm_tt_swapout(bdev, tt, swapout_walk->gfp_flags);
1437 		if (!ret) {
1438 			spin_lock(&bdev->lru_lock);
1439 			ttm_resource_del_bulk_move_unevictable(bo->resource, bo);
1440 			ttm_resource_move_to_lru_tail(bo->resource);
1441 			spin_unlock(&bdev->lru_lock);
1442 		}
1443 	}
1444 
1445 out:
1446 	/* Consider -ENOMEM and -ENOSPC non-fatal. */
1447 	if (ret == -ENOMEM || ret == -ENOSPC)
1448 		ret = -EBUSY;
1449 
1450 	return ret;
1451 }
1452 
1453 const struct ttm_lru_walk_ops ttm_swap_ops = {
1454 	.process_bo = ttm_bo_swapout_cb,
1455 };
1456 
1457 /**
1458  * ttm_bo_swapout() - Swap out buffer objects on the LRU list to shmem.
1459  * @bdev: The ttm device.
1460  * @ctx: The ttm_operation_ctx governing the swapout operation.
1461  * @man: The resource manager whose resources / buffer objects are
1462  * goint to be swapped out.
1463  * @gfp_flags: The gfp flags used for shmem page allocations.
1464  * @target: The desired number of pages to swap out.
1465  *
1466  * Return: The number of pages actually swapped out, or negative error code
1467  * on error.
1468  */
1469 s64 ttm_bo_swapout(struct ttm_device *bdev, struct ttm_operation_ctx *ctx,
1470 		   struct ttm_resource_manager *man, gfp_t gfp_flags,
1471 		   s64 target)
1472 {
1473 	struct ttm_bo_swapout_walk swapout_walk = {
1474 		.walk = {
1475 			.ops = &ttm_swap_ops,
1476 			.arg = {
1477 				.ctx = ctx,
1478 				.trylock_only = true,
1479 			},
1480 		},
1481 		.gfp_flags = gfp_flags,
1482 	};
1483 
1484 	return ttm_lru_walk_for_evict(&swapout_walk.walk, bdev, man, target);
1485 }
1486 EXPORT_SYMBOL_FOR_TESTS_ONLY(ttm_bo_swapout);
1487 
1488 void ttm_bo_tt_destroy(struct ttm_buffer_object *bo)
1489 {
1490 	if (bo->ttm == NULL)
1491 		return;
1492 
1493 	ttm_tt_unpopulate(bo->bdev, bo->ttm);
1494 	ttm_tt_destroy(bo->bdev, bo->ttm);
1495 	bo->ttm = NULL;
1496 }
1497 
1498 /**
1499  * ttm_bo_populate() - Ensure that a buffer object has backing pages
1500  * @bo: The buffer object
1501  * @ctx: The ttm_operation_ctx governing the operation.
1502  *
1503  * For buffer objects in a memory type whose manager uses
1504  * struct ttm_tt for backing pages, ensure those backing pages
1505  * are present and with valid content. The bo's resource is also
1506  * placed on the correct LRU list if it was previously swapped
1507  * out.
1508  *
1509  * Return: 0 if successful, negative error code on failure.
1510  * Note: May return -EINTR or -ERESTARTSYS if @ctx::interruptible
1511  * is set to true.
1512  */
1513 int ttm_bo_populate(struct ttm_buffer_object *bo,
1514 		    struct ttm_operation_ctx *ctx)
1515 {
1516 	struct ttm_device *bdev = bo->bdev;
1517 	struct ttm_tt *tt = bo->ttm;
1518 	bool swapped;
1519 	int ret;
1520 
1521 	dma_resv_assert_held(bo->base.resv);
1522 
1523 	if (!tt)
1524 		return 0;
1525 
1526 	swapped = ttm_tt_is_swapped(tt);
1527 	ret = ttm_tt_populate(bdev, tt, ctx);
1528 	if (ret)
1529 		return ret;
1530 
1531 	if (swapped && !ttm_tt_is_swapped(tt) && !bo->pin_count &&
1532 	    bo->resource) {
1533 		spin_lock(&bdev->lru_lock);
1534 		ttm_resource_add_bulk_move(bo->resource, bo);
1535 		ttm_resource_move_to_lru_tail(bo->resource);
1536 		spin_unlock(&bdev->lru_lock);
1537 	}
1538 
1539 	return 0;
1540 }
1541 EXPORT_SYMBOL(ttm_bo_populate);
1542 
1543 int ttm_bo_setup_export(struct ttm_buffer_object *bo,
1544 			struct ttm_operation_ctx *ctx)
1545 {
1546 	int ret;
1547 
1548 	ret = ttm_bo_reserve(bo, false, false, NULL);
1549 	if (ret != 0)
1550 		return ret;
1551 
1552 	ret = ttm_bo_populate(bo, ctx);
1553 	ttm_bo_unreserve(bo);
1554 	return ret;
1555 }
1556 EXPORT_SYMBOL(ttm_bo_setup_export);
1557