xref: /linux/drivers/gpu/drm/ttm/ttm_bo.c (revision b0a3a811634aa7422f8a92196db47a06a70bda16)
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  * @force_space: If we should evict buffers to force space
510  * @res: On allocation success, the resulting struct ttm_resource.
511  * @alloc_state: Object holding allocation state such as charged cgroups.
512  *
513  * Returns:
514  * -EBUSY: No space available, but allocation should be retried with ttm_bo_evict_alloc.
515  * -ENOSPC: No space available, allocation should not be retried.
516  * -ERESTARTSYS: An interruptible sleep was interrupted by a signal.
517  *
518  */
519 static int ttm_bo_alloc_at_place(struct ttm_buffer_object *bo,
520 				 const struct ttm_place *place,
521 				 bool force_space,
522 				 struct ttm_resource **res,
523 				 struct ttm_bo_alloc_state *alloc_state)
524 {
525 	bool may_evict;
526 	int ret;
527 
528 	may_evict = !alloc_state->in_evict && force_space &&
529 		    place->mem_type != TTM_PL_SYSTEM;
530 	if (!alloc_state->charge_pool) {
531 		ret = ttm_resource_try_charge(bo, place, &alloc_state->charge_pool,
532 					      force_space ? &alloc_state->limit_pool
533 							  : NULL);
534 		if (ret) {
535 			/*
536 			 * -EAGAIN means the charge failed, which we treat
537 			 * like an allocation failure. Therefore, return an
538 			 * error code indicating the allocation failed -
539 			 * either -EBUSY if the allocation should be
540 			 * retried with eviction, or -ENOSPC if there should
541 			 * be no second attempt.
542 			 */
543 			if (!alloc_state->in_evict)
544 				alloc_state->may_try_low = may_evict;
545 			if (ret == -EAGAIN)
546 				ret = may_evict ? -EBUSY : -ENOSPC;
547 			return ret;
548 		}
549 	}
550 
551 	/*
552 	 * cgroup protection plays a special role in eviction.
553 	 * Conceptually, protection of memory via the dmem cgroup controller
554 	 * entitles the protected cgroup to use a certain amount of memory.
555 	 * There are two types of protection - the 'low' limit is a
556 	 * "best-effort" protection, whereas the 'min' limit provides a hard
557 	 * guarantee that memory within the cgroup's allowance will not be
558 	 * evicted under any circumstance.
559 	 *
560 	 * To faithfully model this concept in TTM, we also need to take cgroup
561 	 * protection into account when allocating. When allocation in one
562 	 * place fails, TTM will default to trying other places first before
563 	 * evicting.
564 	 * If the allocation is covered by dmem cgroup protection, however,
565 	 * this prevents the allocation from using the memory it is "entitled"
566 	 * to. To make sure unprotected allocations cannot push new protected
567 	 * allocations out of places they are "entitled" to use, we should
568 	 * evict buffers not covered by any cgroup protection, if this
569 	 * allocation is covered by cgroup protection.
570 	 *
571 	 * Buffers covered by 'min' protection are a special case - the 'min'
572 	 * limit is a stronger guarantee than 'low', and thus buffers protected
573 	 * by 'low' but not 'min' should also be considered for eviction.
574 	 * Buffers protected by 'min' will never be considered for eviction
575 	 * anyway, so the regular eviction path should be triggered here.
576 	 * Buffers protected by 'low' but not 'min' will take a special
577 	 * eviction path that only evicts buffers covered by neither 'low' or
578 	 * 'min' protections.
579 	 */
580 	if (!alloc_state->in_evict) {
581 		may_evict |= dmem_cgroup_below_min(NULL, alloc_state->charge_pool);
582 		alloc_state->may_try_low = may_evict;
583 
584 		may_evict |= dmem_cgroup_below_low(NULL, alloc_state->charge_pool);
585 	}
586 
587 	ret = ttm_resource_alloc(bo, place, res, alloc_state->charge_pool);
588 	if (ret) {
589 		if (ret == -ENOSPC && may_evict)
590 			ret = -EBUSY;
591 		return ret;
592 	}
593 
594 	/*
595 	 * Ownership of charge_pool has been transferred to the TTM resource,
596 	 * don't make the caller think we still hold a reference to it.
597 	 */
598 	alloc_state->charge_pool = NULL;
599 	return 0;
600 }
601 
602 /**
603  * struct ttm_bo_evict_walk - Parameters for the evict walk.
604  */
605 struct ttm_bo_evict_walk {
606 	/** @walk: The walk base parameters. */
607 	struct ttm_lru_walk walk;
608 	/** @place: The place passed to the resource allocation. */
609 	const struct ttm_place *place;
610 	/** @evictor: The buffer object we're trying to make room for. */
611 	struct ttm_buffer_object *evictor;
612 	/** @res: The allocated resource if any. */
613 	struct ttm_resource **res;
614 	/** @evicted: Number of successful evictions. */
615 	unsigned long evicted;
616 
617 	/** @try_low: Whether we should attempt to evict BO's with low watermark threshold */
618 	bool try_low;
619 	/** @hit_low: If we cannot evict a bo when @try_low is false (first pass) */
620 	bool hit_low;
621 
622 	/** @alloc_state: State associated with the allocation attempt. */
623 	struct ttm_bo_alloc_state *alloc_state;
624 };
625 
626 static s64 ttm_bo_evict_cb(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo)
627 {
628 	struct ttm_bo_evict_walk *evict_walk =
629 		container_of(walk, typeof(*evict_walk), walk);
630 	struct dmem_cgroup_pool_state *limit_pool, *ancestor = NULL;
631 	s64 bo_size = bo->base.size;
632 	bool evict_valuable;
633 	s64 lret;
634 
635 	/*
636 	 * If may_try_low is not set, then we're trying to evict unprotected
637 	 * buffers in favor of a protected allocation for charge_pool. Explicitly skip
638 	 * buffers belonging to the same cgroup here - that cgroup is definitely protected,
639 	 * even though dmem_cgroup_state_evict_valuable would allow the eviction because a
640 	 * cgroup is always allowed to evict from itself even if it is protected.
641 	 */
642 	if (!evict_walk->alloc_state->may_try_low &&
643 			bo->resource->css == evict_walk->alloc_state->charge_pool)
644 		return 0;
645 
646 	limit_pool = evict_walk->alloc_state->limit_pool;
647 	/*
648 	 * If there is no explicit limit pool, find the root of the shared subtree between
649 	 * evictor and evictee. This is important so that recursive protection rules can
650 	 * apply properly: Recursive protection distributes cgroup protection afforded
651 	 * to a parent cgroup but not used explicitly by a child cgroup between all child
652 	 * cgroups (see docs of effective_protection in mm/page_counter.c). However, when
653 	 * direct siblings compete for memory, siblings that were explicitly protected
654 	 * should get prioritized over siblings that weren't. This only happens correctly
655 	 * when the root of the shared subtree is passed to
656 	 * dmem_cgroup_state_evict_valuable. Otherwise, the effective-protection
657 	 * calculation cannot distinguish direct siblings from unrelated subtrees and the
658 	 * calculated protection ends up wrong.
659 	 */
660 	if (!limit_pool) {
661 		ancestor = dmem_cgroup_get_common_ancestor(bo->resource->css,
662 							   evict_walk->alloc_state->charge_pool);
663 		limit_pool = ancestor;
664 	}
665 
666 	evict_valuable = dmem_cgroup_state_evict_valuable(limit_pool, bo->resource->css,
667 							  evict_walk->try_low,
668 							  &evict_walk->hit_low);
669 	if (ancestor)
670 		dmem_cgroup_pool_state_put(ancestor);
671 
672 	if (!evict_valuable)
673 		return 0;
674 
675 	/*
676 	 * evict_walk->place is NULL in cgroup drain mode.  Drivers'
677 	 * eviction_valuable() callbacks must handle a NULL place, treating it
678 	 * as "any placement": the TTM base implementation already does so via
679 	 * ttm_resource_intersects().
680 	 */
681 	if (bo->pin_count || !bo->bdev->funcs->eviction_valuable(bo, evict_walk->place))
682 		return 0;
683 
684 	if (bo->deleted) {
685 		lret = ttm_bo_wait_ctx(bo, walk->arg.ctx);
686 		if (!lret)
687 			ttm_bo_cleanup_memtype_use(bo);
688 	} else {
689 		lret = ttm_bo_evict(bo, walk->arg.ctx);
690 	}
691 
692 	if (lret)
693 		goto out;
694 
695 	evict_walk->evicted++;
696 	if (evict_walk->res) {
697 		lret = ttm_bo_alloc_at_place(evict_walk->evictor,
698 					     evict_walk->place, false,
699 					     evict_walk->res,
700 					     evict_walk->alloc_state);
701 		if (lret == 0)
702 			return 1;
703 	} else {
704 		/* Cgroup drain: return bytes freed for byte-denominated progress. */
705 		return bo_size;
706 	}
707 out:
708 	/* Errors that should terminate the walk. */
709 	if (lret == -ENOSPC)
710 		return -EBUSY;
711 
712 	return lret;
713 }
714 
715 static const struct ttm_lru_walk_ops ttm_evict_walk_ops = {
716 	.process_bo = ttm_bo_evict_cb,
717 };
718 
719 static int ttm_bo_evict_alloc(struct ttm_device *bdev,
720 			      struct ttm_resource_manager *man,
721 			      const struct ttm_place *place,
722 			      struct ttm_buffer_object *evictor,
723 			      struct ttm_operation_ctx *ctx,
724 			      struct ww_acquire_ctx *ticket,
725 			      struct ttm_resource **res,
726 			      struct ttm_bo_alloc_state *state)
727 {
728 	struct ttm_bo_evict_walk evict_walk = {
729 		.walk = {
730 			.ops = &ttm_evict_walk_ops,
731 			.arg = {
732 				.ctx = ctx,
733 				.ticket = ticket,
734 			}
735 		},
736 		.place = place,
737 		.evictor = evictor,
738 		.res = res,
739 		.alloc_state = state,
740 	};
741 	s64 lret;
742 
743 	state->in_evict = true;
744 
745 	evict_walk.walk.arg.trylock_only = true;
746 	lret = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man, 1);
747 
748 	/* If we failed to find enough BOs to evict, but we skipped over
749 	 * some BOs because they were covered by dmem low protection, retry
750 	 * evicting these protected BOs too, except if we're told not to
751 	 * consider protected BOs at all.
752 	 */
753 	if (!lret && evict_walk.hit_low && state->may_try_low) {
754 		evict_walk.try_low = true;
755 		lret = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man, 1);
756 	}
757 	if (lret || !ticket)
758 		goto out;
759 
760 	/* Reset low limit */
761 	evict_walk.try_low = evict_walk.hit_low = false;
762 	/* If ticket-locking, repeat while making progress. */
763 	evict_walk.walk.arg.trylock_only = false;
764 
765 retry:
766 	do {
767 		/* The walk may clear the evict_walk.walk.ticket field */
768 		evict_walk.walk.arg.ticket = ticket;
769 		evict_walk.evicted = 0;
770 		lret = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man, 1);
771 	} while (!lret && evict_walk.evicted);
772 
773 	/* We hit the low limit? Try once more */
774 	if (!lret && evict_walk.hit_low && !evict_walk.try_low &&
775 			state->may_try_low) {
776 		evict_walk.try_low = true;
777 		goto retry;
778 	}
779 out:
780 	state->in_evict = false;
781 	if (lret < 0)
782 		return lret;
783 	if (lret == 0)
784 		return -EBUSY;
785 	return 0;
786 }
787 
788 /**
789  * ttm_bo_evict_cgroup() - Evict buffer objects charged to a specific cgroup.
790  * @bdev: The TTM device.
791  * @man: The resource manager whose LRU to walk.
792  * @limit_pool: The cgroup pool state whose members should be evicted.
793  * @target_bytes: Number of bytes to free.
794  * @ctx: The TTM operation context.
795  *
796  * Walk the LRU of @man and evict buffer objects that are charged to the
797  * cgroup identified by @limit_pool, until at least @target_bytes have been
798  * freed.  Mirrors the two-pass (trylock -> sleeping-lock, low-watermark)
799  * strategy used by ttm_bo_evict_alloc().
800  *
801  * Return: >= @target_bytes on full success, 0..target_bytes-1 if partial,
802  *         negative error code on fatal error.
803  */
804 s64 ttm_bo_evict_cgroup(struct ttm_device *bdev,
805 			struct ttm_resource_manager *man,
806 			struct dmem_cgroup_pool_state *limit_pool,
807 			s64 target_bytes,
808 			struct ttm_operation_ctx *ctx)
809 {
810 	struct ttm_bo_evict_walk evict_walk = {
811 		.walk = {
812 			.ops = &ttm_evict_walk_ops,
813 			.arg = { .ctx = ctx },
814 		},
815 		.alloc_state = &(struct ttm_bo_alloc_state) {
816 			.limit_pool = limit_pool,
817 			.in_evict = true,
818 		},
819 		/* place, evictor, res left NULL: selects cgroup drain mode */
820 	};
821 	s64 lret, pass;
822 
823 	evict_walk.walk.arg.trylock_only = true;
824 	lret = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man, target_bytes);
825 	if (lret < 0 || lret >= target_bytes)
826 		return lret;
827 
828 	/* Second pass: also evict BOs at the low watermark. */
829 	if (evict_walk.hit_low) {
830 		evict_walk.try_low = true;
831 		pass = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man,
832 					      target_bytes - lret);
833 		if (pass < 0)
834 			return pass;
835 		lret += pass;
836 		if (lret >= target_bytes)
837 			return lret;
838 	}
839 
840 	/* Full sleeping-lock pass for remaining target. */
841 	evict_walk.try_low = evict_walk.hit_low = false;
842 	evict_walk.walk.arg.trylock_only = false;
843 
844 retry:
845 	evict_walk.walk.arg.sleeping_lock = true;
846 	do {
847 		evict_walk.evicted = 0;
848 		pass = ttm_lru_walk_for_evict(&evict_walk.walk, bdev, man,
849 					      target_bytes - lret);
850 		if (pass < 0) {
851 			lret = pass;
852 			goto out;
853 		}
854 		lret += pass;
855 	} while (lret < target_bytes && evict_walk.evicted);
856 
857 	/* One more attempt if we hit the low limit during sleeping-lock pass. */
858 	if (lret < target_bytes && evict_walk.hit_low && !evict_walk.try_low) {
859 		evict_walk.try_low = true;
860 		goto retry;
861 	}
862 
863 out:
864 	return lret;
865 }
866 EXPORT_SYMBOL(ttm_bo_evict_cgroup);
867 
868 /**
869  * ttm_bo_pin - Pin the buffer object.
870  * @bo: The buffer object to pin
871  *
872  * Make sure the buffer is not evicted any more during memory pressure.
873  * @bo must be unpinned again by calling ttm_bo_unpin().
874  */
875 void ttm_bo_pin(struct ttm_buffer_object *bo)
876 {
877 	dma_resv_assert_held(bo->base.resv);
878 	WARN_ON_ONCE(!kref_read(&bo->kref));
879 	spin_lock(&bo->bdev->lru_lock);
880 	if (bo->resource)
881 		ttm_resource_del_bulk_move(bo->resource, bo);
882 	if (!bo->pin_count++ && bo->resource)
883 		ttm_resource_move_to_lru_tail(bo->resource);
884 	spin_unlock(&bo->bdev->lru_lock);
885 }
886 EXPORT_SYMBOL(ttm_bo_pin);
887 
888 /**
889  * ttm_bo_unpin - Unpin the buffer object.
890  * @bo: The buffer object to unpin
891  *
892  * Allows the buffer object to be evicted again during memory pressure.
893  */
894 void ttm_bo_unpin(struct ttm_buffer_object *bo)
895 {
896 	dma_resv_assert_held(bo->base.resv);
897 	WARN_ON_ONCE(!kref_read(&bo->kref));
898 	if (WARN_ON_ONCE(!bo->pin_count))
899 		return;
900 
901 	spin_lock(&bo->bdev->lru_lock);
902 	if (!--bo->pin_count && bo->resource) {
903 		ttm_resource_add_bulk_move(bo->resource, bo);
904 		ttm_resource_move_to_lru_tail(bo->resource);
905 	}
906 	spin_unlock(&bo->bdev->lru_lock);
907 }
908 EXPORT_SYMBOL(ttm_bo_unpin);
909 
910 /*
911  * Add the pipelined eviction fencesto the BO as kernel dependency and reserve new
912  * fence slots.
913  */
914 static int ttm_bo_add_pipelined_eviction_fences(struct ttm_buffer_object *bo,
915 						struct ttm_resource_manager *man,
916 						bool no_wait_gpu)
917 {
918 	struct dma_fence *fence;
919 	int i;
920 
921 	spin_lock(&man->eviction_lock);
922 	for (i = 0; i < TTM_NUM_MOVE_FENCES; i++) {
923 		fence = man->eviction_fences[i];
924 		if (!fence)
925 			continue;
926 
927 		if (no_wait_gpu) {
928 			if (!dma_fence_is_signaled(fence)) {
929 				spin_unlock(&man->eviction_lock);
930 				return -EBUSY;
931 			}
932 		} else {
933 			dma_resv_add_fence(bo->base.resv, fence, DMA_RESV_USAGE_KERNEL);
934 		}
935 	}
936 	spin_unlock(&man->eviction_lock);
937 
938 	/* TODO: this call should be removed. */
939 	return dma_resv_reserve_fences(bo->base.resv, 1);
940 }
941 
942 /**
943  * ttm_bo_alloc_resource - Allocate backing store for a BO
944  *
945  * @bo: Pointer to a struct ttm_buffer_object of which we want a resource for
946  * @placement: Proposed new placement for the buffer object
947  * @ctx: if and how to sleep, lock buffers and alloc memory
948  * @force_space: If we should evict buffers to force space
949  * @res: The resulting struct ttm_resource.
950  *
951  * Allocates a resource for the buffer object pointed to by @bo, using the
952  * placement flags in @placement, potentially evicting other buffer objects when
953  * @force_space is true.
954  * This function may sleep while waiting for resources to become available.
955  * Returns:
956  * -EBUSY: No space available (only if no_wait == true).
957  * -ENOSPC: Could not allocate space for the buffer object, either due to
958  * fragmentation or concurrent allocators.
959  * -ERESTARTSYS: An interruptible sleep was interrupted by a signal.
960  */
961 static int ttm_bo_alloc_resource(struct ttm_buffer_object *bo,
962 				 struct ttm_placement *placement,
963 				 struct ttm_operation_ctx *ctx,
964 				 bool force_space,
965 				 struct ttm_resource **res)
966 {
967 	struct ttm_device *bdev = bo->bdev;
968 	struct ww_acquire_ctx *ticket;
969 	int i, ret;
970 
971 	ticket = dma_resv_locking_ctx(bo->base.resv);
972 	ret = dma_resv_reserve_fences(bo->base.resv, TTM_NUM_MOVE_FENCES);
973 	if (unlikely(ret))
974 		return ret;
975 
976 	for (i = 0; i < placement->num_placement; ++i) {
977 		const struct ttm_place *place = &placement->placement[i];
978 		struct ttm_bo_alloc_state alloc_state = {};
979 		struct ttm_resource_manager *man;
980 
981 		man = ttm_manager_type(bdev, place->mem_type);
982 		if (!man || !ttm_resource_manager_used(man))
983 			continue;
984 
985 		if (place->flags & (force_space ? TTM_PL_FLAG_DESIRED :
986 				    TTM_PL_FLAG_FALLBACK))
987 			continue;
988 
989 		ret = ttm_bo_alloc_at_place(bo, place, force_space, res,
990 					    &alloc_state);
991 
992 		if (ret == -ENOSPC) {
993 			dmem_cgroup_uncharge(alloc_state.charge_pool, bo->base.size);
994 			dmem_cgroup_pool_state_put(alloc_state.limit_pool);
995 			continue;
996 		} else if (ret == -EBUSY) {
997 			ret = ttm_bo_evict_alloc(bdev, man, place, bo, ctx,
998 						 ticket, res, &alloc_state);
999 
1000 			dmem_cgroup_pool_state_put(alloc_state.limit_pool);
1001 
1002 			if (ret) {
1003 				dmem_cgroup_uncharge(alloc_state.charge_pool,
1004 						bo->base.size);
1005 				if (ret == -EBUSY)
1006 					continue;
1007 				return ret;
1008 			}
1009 		} else if (ret) {
1010 			dmem_cgroup_uncharge(alloc_state.charge_pool, bo->base.size);
1011 			dmem_cgroup_pool_state_put(alloc_state.limit_pool);
1012 			return ret;
1013 		}
1014 
1015 		ret = ttm_bo_add_pipelined_eviction_fences(bo, man, ctx->no_wait_gpu);
1016 		if (unlikely(ret)) {
1017 			ttm_resource_free(bo, res);
1018 			if (ret == -EBUSY)
1019 				continue;
1020 
1021 			return ret;
1022 		}
1023 		return 0;
1024 	}
1025 
1026 	return -ENOSPC;
1027 }
1028 
1029 /*
1030  * ttm_bo_mem_space - Wrapper around ttm_bo_alloc_resource
1031  *
1032  * @bo: Pointer to a struct ttm_buffer_object of which we want a resource for
1033  * @placement: Proposed new placement for the buffer object
1034  * @res: The resulting struct ttm_resource.
1035  * @ctx: if and how to sleep, lock buffers and alloc memory
1036  *
1037  * Tries both idle allocation and forcefully eviction of buffers. See
1038  * ttm_bo_alloc_resource for details.
1039  */
1040 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1041 		     struct ttm_placement *placement,
1042 		     struct ttm_resource **res,
1043 		     struct ttm_operation_ctx *ctx)
1044 {
1045 	bool force_space = false;
1046 	int ret;
1047 
1048 	do {
1049 		ret = ttm_bo_alloc_resource(bo, placement, ctx,
1050 					    force_space, res);
1051 		force_space = !force_space;
1052 	} while (ret == -ENOSPC && force_space);
1053 
1054 	return ret;
1055 }
1056 EXPORT_SYMBOL(ttm_bo_mem_space);
1057 
1058 /**
1059  * ttm_bo_validate
1060  *
1061  * @bo: The buffer object.
1062  * @placement: Proposed placement for the buffer object.
1063  * @ctx: validation parameters.
1064  *
1065  * Changes placement and caching policy of the buffer object
1066  * according proposed placement.
1067  * Returns
1068  * -EINVAL on invalid proposed placement.
1069  * -ENOMEM on out-of-memory condition.
1070  * -EBUSY if no_wait is true and buffer busy.
1071  * -ERESTARTSYS if interrupted by a signal.
1072  */
1073 int ttm_bo_validate(struct ttm_buffer_object *bo,
1074 		    struct ttm_placement *placement,
1075 		    struct ttm_operation_ctx *ctx)
1076 {
1077 	struct ttm_resource *res;
1078 	struct ttm_place hop;
1079 	bool force_space;
1080 	int ret;
1081 
1082 	dma_resv_assert_held(bo->base.resv);
1083 
1084 	/*
1085 	 * Remove the backing store if no placement is given.
1086 	 */
1087 	if (!placement->num_placement)
1088 		return ttm_bo_pipeline_gutting(bo);
1089 
1090 	force_space = false;
1091 	do {
1092 		/* Check whether we need to move buffer. */
1093 		if (bo->resource &&
1094 		    ttm_resource_compatible(bo->resource, placement,
1095 					    force_space))
1096 			return 0;
1097 
1098 		/* Moving of pinned BOs is forbidden */
1099 		if (bo->pin_count)
1100 			return -EINVAL;
1101 
1102 		/*
1103 		 * Determine where to move the buffer.
1104 		 *
1105 		 * If driver determines move is going to need
1106 		 * an extra step then it will return -EMULTIHOP
1107 		 * and the buffer will be moved to the temporary
1108 		 * stop and the driver will be called to make
1109 		 * the second hop.
1110 		 */
1111 		ret = ttm_bo_alloc_resource(bo, placement, ctx, force_space,
1112 					    &res);
1113 		force_space = !force_space;
1114 		if (ret == -ENOSPC)
1115 			continue;
1116 		if (ret)
1117 			return ret;
1118 
1119 bounce:
1120 		ret = ttm_bo_handle_move_mem(bo, res, false, ctx, &hop);
1121 		if (ret == -EMULTIHOP) {
1122 			ret = ttm_bo_bounce_temp_buffer(bo, ctx, &hop);
1123 			/* try and move to final place now. */
1124 			if (!ret)
1125 				goto bounce;
1126 		}
1127 		if (ret) {
1128 			ttm_resource_free(bo, &res);
1129 			return ret;
1130 		}
1131 
1132 	} while (ret && force_space);
1133 
1134 	/* For backward compatibility with userspace */
1135 	if (ret == -ENOSPC)
1136 		return bo->bdev->alloc_flags & TTM_ALLOCATION_PROPAGATE_ENOSPC ?
1137 		       ret : -ENOMEM;
1138 
1139 	/*
1140 	 * We might need to add a TTM.
1141 	 */
1142 	if (!bo->resource || bo->resource->mem_type == TTM_PL_SYSTEM) {
1143 		ret = ttm_tt_create(bo, true);
1144 		if (ret)
1145 			return ret;
1146 	}
1147 	return 0;
1148 }
1149 EXPORT_SYMBOL(ttm_bo_validate);
1150 
1151 /**
1152  * ttm_bo_init_reserved
1153  *
1154  * @bdev: Pointer to a ttm_device struct.
1155  * @bo: Pointer to a ttm_buffer_object to be initialized.
1156  * @type: Requested type of buffer object.
1157  * @placement: Initial placement for buffer object.
1158  * @alignment: Data alignment in pages.
1159  * @ctx: TTM operation context for memory allocation.
1160  * @sg: Scatter-gather table.
1161  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
1162  * @destroy: Destroy function. Use NULL for kfree().
1163  *
1164  * This function initializes a pre-allocated struct ttm_buffer_object.
1165  * As this object may be part of a larger structure, this function,
1166  * together with the @destroy function, enables driver-specific objects
1167  * derived from a ttm_buffer_object.
1168  *
1169  * On successful return, the caller owns an object kref to @bo. The kref and
1170  * list_kref are usually set to 1, but note that in some situations, other
1171  * tasks may already be holding references to @bo as well.
1172  * Furthermore, if resv == NULL, the buffer's reservation lock will be held,
1173  * and it is the caller's responsibility to call ttm_bo_unreserve.
1174  *
1175  * If a failure occurs, the function will call the @destroy function. Thus,
1176  * after a failure, dereferencing @bo is illegal and will likely cause memory
1177  * corruption.
1178  *
1179  * Returns
1180  * -ENOMEM: Out of memory.
1181  * -EINVAL: Invalid placement flags.
1182  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
1183  */
1184 int ttm_bo_init_reserved(struct ttm_device *bdev, struct ttm_buffer_object *bo,
1185 			 enum ttm_bo_type type, struct ttm_placement *placement,
1186 			 uint32_t alignment, struct ttm_operation_ctx *ctx,
1187 			 struct sg_table *sg, struct dma_resv *resv,
1188 			 void (*destroy) (struct ttm_buffer_object *))
1189 {
1190 	int ret;
1191 
1192 	kref_init(&bo->kref);
1193 	bo->bdev = bdev;
1194 	bo->type = type;
1195 	bo->page_alignment = alignment;
1196 	bo->destroy = destroy;
1197 	bo->pin_count = 0;
1198 	bo->sg = sg;
1199 	bo->bulk_move = NULL;
1200 	if (resv)
1201 		bo->base.resv = resv;
1202 	else
1203 		bo->base.resv = &bo->base._resv;
1204 	atomic_inc(&ttm_glob.bo_count);
1205 
1206 	/*
1207 	 * For ttm_bo_type_device buffers, allocate
1208 	 * address space from the device.
1209 	 */
1210 	if (bo->type == ttm_bo_type_device || bo->type == ttm_bo_type_sg) {
1211 		ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
1212 					 PFN_UP(bo->base.size));
1213 		if (ret)
1214 			goto err_put;
1215 	}
1216 
1217 	/* passed reservation objects should already be locked,
1218 	 * since otherwise lockdep will be angered in radeon.
1219 	 */
1220 	if (!resv)
1221 		WARN_ON(!dma_resv_trylock(bo->base.resv));
1222 	else
1223 		dma_resv_assert_held(resv);
1224 
1225 	ret = ttm_bo_validate(bo, placement, ctx);
1226 	if (unlikely(ret))
1227 		goto err_unlock;
1228 
1229 	return 0;
1230 
1231 err_unlock:
1232 	if (!resv)
1233 		dma_resv_unlock(bo->base.resv);
1234 
1235 err_put:
1236 	ttm_bo_put(bo);
1237 	return ret;
1238 }
1239 EXPORT_SYMBOL(ttm_bo_init_reserved);
1240 
1241 /**
1242  * ttm_bo_init_validate
1243  *
1244  * @bdev: Pointer to a ttm_device struct.
1245  * @bo: Pointer to a ttm_buffer_object to be initialized.
1246  * @type: Requested type of buffer object.
1247  * @placement: Initial placement for buffer object.
1248  * @alignment: Data alignment in pages.
1249  * @interruptible: If needing to sleep to wait for GPU resources,
1250  * sleep interruptible.
1251  * pinned in physical memory. If this behaviour is not desired, this member
1252  * holds a pointer to a persistent shmem object. Typically, this would
1253  * point to the shmem object backing a GEM object if TTM is used to back a
1254  * GEM user interface.
1255  * @sg: Scatter-gather table.
1256  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
1257  * @destroy: Destroy function. Use NULL for kfree().
1258  *
1259  * This function initializes a pre-allocated struct ttm_buffer_object.
1260  * As this object may be part of a larger structure, this function,
1261  * together with the @destroy function,
1262  * enables driver-specific objects derived from a ttm_buffer_object.
1263  *
1264  * On successful return, the caller owns an object kref to @bo. The kref and
1265  * list_kref are usually set to 1, but note that in some situations, other
1266  * tasks may already be holding references to @bo as well.
1267  *
1268  * If a failure occurs, the function will call the @destroy function, Thus,
1269  * after a failure, dereferencing @bo is illegal and will likely cause memory
1270  * corruption.
1271  *
1272  * Returns
1273  * -ENOMEM: Out of memory.
1274  * -EINVAL: Invalid placement flags.
1275  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
1276  */
1277 int ttm_bo_init_validate(struct ttm_device *bdev, struct ttm_buffer_object *bo,
1278 			 enum ttm_bo_type type, struct ttm_placement *placement,
1279 			 uint32_t alignment, bool interruptible,
1280 			 struct sg_table *sg, struct dma_resv *resv,
1281 			 void (*destroy) (struct ttm_buffer_object *))
1282 {
1283 	struct ttm_operation_ctx ctx = { .interruptible = interruptible };
1284 	int ret;
1285 
1286 	ret = ttm_bo_init_reserved(bdev, bo, type, placement, alignment, &ctx,
1287 				   sg, resv, destroy);
1288 	if (ret)
1289 		return ret;
1290 
1291 	if (!resv)
1292 		ttm_bo_unreserve(bo);
1293 
1294 	return 0;
1295 }
1296 EXPORT_SYMBOL(ttm_bo_init_validate);
1297 
1298 /*
1299  * buffer object vm functions.
1300  */
1301 
1302 /**
1303  * ttm_bo_unmap_virtual
1304  *
1305  * @bo: tear down the virtual mappings for this BO
1306  */
1307 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1308 {
1309 	struct ttm_device *bdev = bo->bdev;
1310 
1311 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1312 	ttm_mem_io_free(bdev, bo->resource);
1313 }
1314 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1315 
1316 /**
1317  * ttm_bo_wait_ctx - wait for buffer idle.
1318  *
1319  * @bo:  The buffer object.
1320  * @ctx: defines how to wait
1321  *
1322  * Waits for the buffer to be idle. Used timeout depends on the context.
1323  * Returns -EBUSY if wait timed outt, -ERESTARTSYS if interrupted by a signal or
1324  * zero on success.
1325  */
1326 int ttm_bo_wait_ctx(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx)
1327 {
1328 	long ret;
1329 
1330 	if (ctx->no_wait_gpu) {
1331 		if (dma_resv_test_signaled(bo->base.resv,
1332 					   DMA_RESV_USAGE_BOOKKEEP))
1333 			return 0;
1334 		else
1335 			return -EBUSY;
1336 	}
1337 
1338 	ret = dma_resv_wait_timeout(bo->base.resv, DMA_RESV_USAGE_BOOKKEEP,
1339 				    ctx->interruptible, 15 * HZ);
1340 	if (unlikely(ret < 0))
1341 		return ret;
1342 	if (unlikely(ret == 0))
1343 		return -EBUSY;
1344 	return 0;
1345 }
1346 EXPORT_SYMBOL(ttm_bo_wait_ctx);
1347 
1348 /**
1349  * struct ttm_bo_swapout_walk - Parameters for the swapout walk
1350  */
1351 struct ttm_bo_swapout_walk {
1352 	/** @walk: The walk base parameters. */
1353 	struct ttm_lru_walk walk;
1354 	/** @gfp_flags: The gfp flags to use for ttm_tt_swapout() */
1355 	gfp_t gfp_flags;
1356 	/** @hit_low: Whether we should attempt to swap BO's with low watermark threshold */
1357 	/** @evict_low: If we cannot swap a bo when @try_low is false (first pass) */
1358 	bool hit_low, evict_low;
1359 };
1360 
1361 static s64
1362 ttm_bo_swapout_cb(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo)
1363 {
1364 	struct ttm_place place = { .mem_type = bo->resource->mem_type };
1365 	struct ttm_bo_swapout_walk *swapout_walk =
1366 		container_of(walk, typeof(*swapout_walk), walk);
1367 	struct ttm_operation_ctx *ctx = walk->arg.ctx;
1368 	struct ttm_device *bdev = bo->bdev;
1369 	struct ttm_tt *tt = bo->ttm;
1370 	s64 ret;
1371 
1372 	/*
1373 	 * While the bo may already reside in SYSTEM placement, set
1374 	 * SYSTEM as new placement to cover also the move further below.
1375 	 * The driver may use the fact that we're moving from SYSTEM
1376 	 * as an indication that we're about to swap out.
1377 	 */
1378 	if (bo->pin_count || !bdev->funcs->eviction_valuable(bo, &place)) {
1379 		ret = -EBUSY;
1380 		goto out;
1381 	}
1382 
1383 	if (!tt || !ttm_tt_is_populated(tt) ||
1384 	    tt->page_flags & (TTM_TT_FLAG_EXTERNAL | TTM_TT_FLAG_SWAPPED)) {
1385 		ret = -EBUSY;
1386 		goto out;
1387 	}
1388 
1389 	if (bo->deleted) {
1390 		pgoff_t num_pages = tt->num_pages;
1391 
1392 		ret = ttm_bo_wait_ctx(bo, ctx);
1393 		if (ret)
1394 			goto out;
1395 
1396 		ttm_bo_cleanup_memtype_use(bo);
1397 		ret = num_pages;
1398 		goto out;
1399 	}
1400 
1401 	/*
1402 	 * Move to system cached
1403 	 */
1404 	if (bo->resource->mem_type != TTM_PL_SYSTEM) {
1405 		struct ttm_resource *evict_mem;
1406 		struct ttm_place hop;
1407 
1408 		memset(&hop, 0, sizeof(hop));
1409 		place.mem_type = TTM_PL_SYSTEM;
1410 		ret = ttm_resource_alloc(bo, &place, &evict_mem, NULL);
1411 		if (ret)
1412 			goto out;
1413 
1414 		ret = ttm_bo_handle_move_mem(bo, evict_mem, true, ctx, &hop);
1415 		if (ret) {
1416 			WARN(ret == -EMULTIHOP,
1417 			     "Unexpected multihop in swapout - likely driver bug.\n");
1418 			ttm_resource_free(bo, &evict_mem);
1419 			goto out;
1420 		}
1421 	}
1422 
1423 	/*
1424 	 * Make sure BO is idle.
1425 	 */
1426 	ret = ttm_bo_wait_ctx(bo, ctx);
1427 	if (ret)
1428 		goto out;
1429 
1430 	ttm_bo_unmap_virtual(bo);
1431 	if (bdev->funcs->swap_notify)
1432 		bdev->funcs->swap_notify(bo);
1433 
1434 	if (ttm_tt_is_populated(tt)) {
1435 		ret = ttm_tt_swapout(bdev, tt, swapout_walk->gfp_flags);
1436 		if (ret > 0) {
1437 			spin_lock(&bdev->lru_lock);
1438 			ttm_resource_del_bulk_move_unevictable(bo->resource, bo);
1439 			ttm_resource_move_to_lru_tail(bo->resource);
1440 			spin_unlock(&bdev->lru_lock);
1441 		}
1442 	}
1443 
1444 out:
1445 	/* Consider -ENOMEM and -ENOSPC non-fatal. */
1446 	if (ret == -ENOMEM || ret == -ENOSPC)
1447 		ret = -EBUSY;
1448 
1449 	return ret;
1450 }
1451 
1452 static const struct ttm_lru_walk_ops ttm_swap_ops = {
1453 	.process_bo = ttm_bo_swapout_cb,
1454 };
1455 
1456 /**
1457  * ttm_bo_swapout() - Swap out buffer objects on the LRU list to shmem.
1458  * @bdev: The ttm device.
1459  * @ctx: The ttm_operation_ctx governing the swapout operation.
1460  * @man: The resource manager whose resources / buffer objects are
1461  * goint to be swapped out.
1462  * @gfp_flags: The gfp flags used for shmem page allocations.
1463  * @target: The desired number of pages to swap out.
1464  *
1465  * Return: The number of pages actually swapped out, or negative error code
1466  * on error.
1467  */
1468 s64 ttm_bo_swapout(struct ttm_device *bdev, struct ttm_operation_ctx *ctx,
1469 		   struct ttm_resource_manager *man, gfp_t gfp_flags,
1470 		   s64 target)
1471 {
1472 	struct ttm_bo_swapout_walk swapout_walk = {
1473 		.walk = {
1474 			.ops = &ttm_swap_ops,
1475 			.arg = {
1476 				.ctx = ctx,
1477 				.trylock_only = true,
1478 			},
1479 		},
1480 		.gfp_flags = gfp_flags,
1481 	};
1482 
1483 	return ttm_lru_walk_for_evict(&swapout_walk.walk, bdev, man, target);
1484 }
1485 EXPORT_SYMBOL_FOR_TESTS_ONLY(ttm_bo_swapout);
1486 
1487 void ttm_bo_tt_destroy(struct ttm_buffer_object *bo)
1488 {
1489 	if (bo->ttm == NULL)
1490 		return;
1491 
1492 	ttm_tt_unpopulate(bo->bdev, bo->ttm);
1493 	ttm_tt_destroy(bo->bdev, bo->ttm);
1494 	bo->ttm = NULL;
1495 }
1496 
1497 /**
1498  * ttm_bo_populate() - Ensure that a buffer object has backing pages
1499  * @bo: The buffer object
1500  * @ctx: The ttm_operation_ctx governing the operation.
1501  *
1502  * For buffer objects in a memory type whose manager uses
1503  * struct ttm_tt for backing pages, ensure those backing pages
1504  * are present and with valid content. The bo's resource is also
1505  * placed on the correct LRU list if it was previously swapped
1506  * out.
1507  *
1508  * Return: 0 if successful, negative error code on failure.
1509  * Note: May return -EINTR or -ERESTARTSYS if @ctx::interruptible
1510  * is set to true.
1511  */
1512 int ttm_bo_populate(struct ttm_buffer_object *bo,
1513 		    struct ttm_operation_ctx *ctx)
1514 {
1515 	struct ttm_device *bdev = bo->bdev;
1516 	struct ttm_tt *tt = bo->ttm;
1517 	bool swapped;
1518 	int ret;
1519 
1520 	dma_resv_assert_held(bo->base.resv);
1521 
1522 	if (!tt)
1523 		return 0;
1524 
1525 	swapped = ttm_tt_is_swapped(tt);
1526 	ret = ttm_tt_populate(bdev, tt, ctx);
1527 	if (ret)
1528 		return ret;
1529 
1530 	if (swapped && !ttm_tt_is_swapped(tt) && !bo->pin_count &&
1531 	    bo->resource) {
1532 		spin_lock(&bdev->lru_lock);
1533 		ttm_resource_add_bulk_move(bo->resource, bo);
1534 		ttm_resource_move_to_lru_tail(bo->resource);
1535 		spin_unlock(&bdev->lru_lock);
1536 	}
1537 
1538 	return 0;
1539 }
1540 EXPORT_SYMBOL(ttm_bo_populate);
1541 
1542 int ttm_bo_setup_export(struct ttm_buffer_object *bo,
1543 			struct ttm_operation_ctx *ctx)
1544 {
1545 	int ret;
1546 
1547 	ret = ttm_bo_reserve(bo, false, false, NULL);
1548 	if (ret != 0)
1549 		return ret;
1550 
1551 	ret = ttm_bo_populate(bo, ctx);
1552 	ttm_bo_unreserve(bo);
1553 	return ret;
1554 }
1555 EXPORT_SYMBOL(ttm_bo_setup_export);
1556