xref: /openbmc/linux/drivers/gpu/drm/ttm/ttm_bo.c (revision 46f28427)
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/ttm/ttm_bo.h>
35 #include <drm/ttm/ttm_placement.h>
36 #include <drm/ttm/ttm_tt.h>
37 
38 #include <linux/jiffies.h>
39 #include <linux/slab.h>
40 #include <linux/sched.h>
41 #include <linux/mm.h>
42 #include <linux/file.h>
43 #include <linux/module.h>
44 #include <linux/atomic.h>
45 #include <linux/dma-resv.h>
46 
47 #include "ttm_module.h"
48 
49 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
50 					struct ttm_placement *placement)
51 {
52 	struct drm_printer p = drm_debug_printer(TTM_PFX);
53 	struct ttm_resource_manager *man;
54 	int i, mem_type;
55 
56 	for (i = 0; i < placement->num_placement; i++) {
57 		mem_type = placement->placement[i].mem_type;
58 		drm_printf(&p, "  placement[%d]=0x%08X (%d)\n",
59 			   i, placement->placement[i].flags, mem_type);
60 		man = ttm_manager_type(bo->bdev, mem_type);
61 		ttm_resource_manager_debug(man, &p);
62 	}
63 }
64 
65 /**
66  * ttm_bo_move_to_lru_tail
67  *
68  * @bo: The buffer object.
69  *
70  * Move this BO to the tail of all lru lists used to lookup and reserve an
71  * object. This function must be called with struct ttm_global::lru_lock
72  * held, and is used to make a BO less likely to be considered for eviction.
73  */
74 void ttm_bo_move_to_lru_tail(struct ttm_buffer_object *bo)
75 {
76 	dma_resv_assert_held(bo->base.resv);
77 
78 	if (bo->resource)
79 		ttm_resource_move_to_lru_tail(bo->resource);
80 }
81 EXPORT_SYMBOL(ttm_bo_move_to_lru_tail);
82 
83 /**
84  * ttm_bo_set_bulk_move - update BOs bulk move object
85  *
86  * @bo: The buffer object.
87  * @bulk: bulk move structure
88  *
89  * Update the BOs bulk move object, making sure that resources are added/removed
90  * as well. A bulk move allows to move many resource on the LRU at once,
91  * resulting in much less overhead of maintaining the LRU.
92  * The only requirement is that the resources stay together on the LRU and are
93  * never separated. This is enforces by setting the bulk_move structure on a BO.
94  * ttm_lru_bulk_move_tail() should be used to move all resources to the tail of
95  * their LRU list.
96  */
97 void ttm_bo_set_bulk_move(struct ttm_buffer_object *bo,
98 			  struct ttm_lru_bulk_move *bulk)
99 {
100 	dma_resv_assert_held(bo->base.resv);
101 
102 	if (bo->bulk_move == bulk)
103 		return;
104 
105 	spin_lock(&bo->bdev->lru_lock);
106 	if (bo->resource)
107 		ttm_resource_del_bulk_move(bo->resource, bo);
108 	bo->bulk_move = bulk;
109 	if (bo->resource)
110 		ttm_resource_add_bulk_move(bo->resource, bo);
111 	spin_unlock(&bo->bdev->lru_lock);
112 }
113 EXPORT_SYMBOL(ttm_bo_set_bulk_move);
114 
115 static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo,
116 				  struct ttm_resource *mem, bool evict,
117 				  struct ttm_operation_ctx *ctx,
118 				  struct ttm_place *hop)
119 {
120 	struct ttm_device *bdev = bo->bdev;
121 	bool old_use_tt, new_use_tt;
122 	int ret;
123 
124 	old_use_tt = !bo->resource || ttm_manager_type(bdev, bo->resource->mem_type)->use_tt;
125 	new_use_tt = ttm_manager_type(bdev, mem->mem_type)->use_tt;
126 
127 	ttm_bo_unmap_virtual(bo);
128 
129 	/*
130 	 * Create and bind a ttm if required.
131 	 */
132 
133 	if (new_use_tt) {
134 		/* Zero init the new TTM structure if the old location should
135 		 * have used one as well.
136 		 */
137 		ret = ttm_tt_create(bo, old_use_tt);
138 		if (ret)
139 			goto out_err;
140 
141 		if (mem->mem_type != TTM_PL_SYSTEM) {
142 			ret = ttm_tt_populate(bo->bdev, bo->ttm, ctx);
143 			if (ret)
144 				goto out_err;
145 		}
146 	}
147 
148 	ret = dma_resv_reserve_fences(bo->base.resv, 1);
149 	if (ret)
150 		goto out_err;
151 
152 	ret = bdev->funcs->move(bo, evict, ctx, mem, hop);
153 	if (ret) {
154 		if (ret == -EMULTIHOP)
155 			return ret;
156 		goto out_err;
157 	}
158 
159 	ctx->bytes_moved += bo->base.size;
160 	return 0;
161 
162 out_err:
163 	if (!old_use_tt)
164 		ttm_bo_tt_destroy(bo);
165 
166 	return ret;
167 }
168 
169 /*
170  * Call bo::reserved.
171  * Will release GPU memory type usage on destruction.
172  * This is the place to put in driver specific hooks to release
173  * driver private resources.
174  * Will release the bo::reserved lock.
175  */
176 
177 static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo)
178 {
179 	if (bo->bdev->funcs->delete_mem_notify)
180 		bo->bdev->funcs->delete_mem_notify(bo);
181 
182 	ttm_bo_tt_destroy(bo);
183 	ttm_resource_free(bo, &bo->resource);
184 }
185 
186 static int ttm_bo_individualize_resv(struct ttm_buffer_object *bo)
187 {
188 	int r;
189 
190 	if (bo->base.resv == &bo->base._resv)
191 		return 0;
192 
193 	BUG_ON(!dma_resv_trylock(&bo->base._resv));
194 
195 	r = dma_resv_copy_fences(&bo->base._resv, bo->base.resv);
196 	dma_resv_unlock(&bo->base._resv);
197 	if (r)
198 		return r;
199 
200 	if (bo->type != ttm_bo_type_sg) {
201 		/* This works because the BO is about to be destroyed and nobody
202 		 * reference it any more. The only tricky case is the trylock on
203 		 * the resv object while holding the lru_lock.
204 		 */
205 		spin_lock(&bo->bdev->lru_lock);
206 		bo->base.resv = &bo->base._resv;
207 		spin_unlock(&bo->bdev->lru_lock);
208 	}
209 
210 	return r;
211 }
212 
213 static void ttm_bo_flush_all_fences(struct ttm_buffer_object *bo)
214 {
215 	struct dma_resv *resv = &bo->base._resv;
216 	struct dma_resv_iter cursor;
217 	struct dma_fence *fence;
218 
219 	dma_resv_iter_begin(&cursor, resv, DMA_RESV_USAGE_BOOKKEEP);
220 	dma_resv_for_each_fence_unlocked(&cursor, fence) {
221 		if (!fence->ops->signaled)
222 			dma_fence_enable_sw_signaling(fence);
223 	}
224 	dma_resv_iter_end(&cursor);
225 }
226 
227 /**
228  * ttm_bo_cleanup_refs
229  * If bo idle, remove from lru lists, and unref.
230  * If not idle, block if possible.
231  *
232  * Must be called with lru_lock and reservation held, this function
233  * will drop the lru lock and optionally the reservation lock before returning.
234  *
235  * @bo:                    The buffer object to clean-up
236  * @interruptible:         Any sleeps should occur interruptibly.
237  * @no_wait_gpu:           Never wait for gpu. Return -EBUSY instead.
238  * @unlock_resv:           Unlock the reservation lock as well.
239  */
240 
241 static int ttm_bo_cleanup_refs(struct ttm_buffer_object *bo,
242 			       bool interruptible, bool no_wait_gpu,
243 			       bool unlock_resv)
244 {
245 	struct dma_resv *resv = &bo->base._resv;
246 	int ret;
247 
248 	if (dma_resv_test_signaled(resv, DMA_RESV_USAGE_BOOKKEEP))
249 		ret = 0;
250 	else
251 		ret = -EBUSY;
252 
253 	if (ret && !no_wait_gpu) {
254 		long lret;
255 
256 		if (unlock_resv)
257 			dma_resv_unlock(bo->base.resv);
258 		spin_unlock(&bo->bdev->lru_lock);
259 
260 		lret = dma_resv_wait_timeout(resv, DMA_RESV_USAGE_BOOKKEEP,
261 					     interruptible,
262 					     30 * HZ);
263 
264 		if (lret < 0)
265 			return lret;
266 		else if (lret == 0)
267 			return -EBUSY;
268 
269 		spin_lock(&bo->bdev->lru_lock);
270 		if (unlock_resv && !dma_resv_trylock(bo->base.resv)) {
271 			/*
272 			 * We raced, and lost, someone else holds the reservation now,
273 			 * and is probably busy in ttm_bo_cleanup_memtype_use.
274 			 *
275 			 * Even if it's not the case, because we finished waiting any
276 			 * delayed destruction would succeed, so just return success
277 			 * here.
278 			 */
279 			spin_unlock(&bo->bdev->lru_lock);
280 			return 0;
281 		}
282 		ret = 0;
283 	}
284 
285 	if (ret) {
286 		if (unlock_resv)
287 			dma_resv_unlock(bo->base.resv);
288 		spin_unlock(&bo->bdev->lru_lock);
289 		return ret;
290 	}
291 
292 	spin_unlock(&bo->bdev->lru_lock);
293 	ttm_bo_cleanup_memtype_use(bo);
294 
295 	if (unlock_resv)
296 		dma_resv_unlock(bo->base.resv);
297 
298 	ttm_bo_put(bo);
299 
300 	return 0;
301 }
302 
303 /*
304  * Block for the dma_resv object to become idle, lock the buffer and clean up
305  * the resource and tt object.
306  */
307 static void ttm_bo_delayed_delete(struct work_struct *work)
308 {
309 	struct ttm_buffer_object *bo;
310 
311 	bo = container_of(work, typeof(*bo), delayed_delete);
312 
313 	dma_resv_wait_timeout(bo->base.resv, DMA_RESV_USAGE_BOOKKEEP, false,
314 			      MAX_SCHEDULE_TIMEOUT);
315 	dma_resv_lock(bo->base.resv, NULL);
316 	ttm_bo_cleanup_memtype_use(bo);
317 	dma_resv_unlock(bo->base.resv);
318 	ttm_bo_put(bo);
319 }
320 
321 static void ttm_bo_release(struct kref *kref)
322 {
323 	struct ttm_buffer_object *bo =
324 	    container_of(kref, struct ttm_buffer_object, kref);
325 	struct ttm_device *bdev = bo->bdev;
326 	int ret;
327 
328 	WARN_ON_ONCE(bo->pin_count);
329 	WARN_ON_ONCE(bo->bulk_move);
330 
331 	if (!bo->deleted) {
332 		ret = ttm_bo_individualize_resv(bo);
333 		if (ret) {
334 			/* Last resort, if we fail to allocate memory for the
335 			 * fences block for the BO to become idle
336 			 */
337 			dma_resv_wait_timeout(bo->base.resv,
338 					      DMA_RESV_USAGE_BOOKKEEP, false,
339 					      30 * HZ);
340 		}
341 
342 		if (bo->bdev->funcs->release_notify)
343 			bo->bdev->funcs->release_notify(bo);
344 
345 		drm_vma_offset_remove(bdev->vma_manager, &bo->base.vma_node);
346 		ttm_mem_io_free(bdev, bo->resource);
347 
348 		if (!dma_resv_test_signaled(bo->base.resv,
349 					    DMA_RESV_USAGE_BOOKKEEP) ||
350 		    !dma_resv_trylock(bo->base.resv)) {
351 			/* The BO is not idle, resurrect it for delayed destroy */
352 			ttm_bo_flush_all_fences(bo);
353 			bo->deleted = true;
354 
355 			spin_lock(&bo->bdev->lru_lock);
356 
357 			/*
358 			 * Make pinned bos immediately available to
359 			 * shrinkers, now that they are queued for
360 			 * destruction.
361 			 *
362 			 * FIXME: QXL is triggering this. Can be removed when the
363 			 * driver is fixed.
364 			 */
365 			if (bo->pin_count) {
366 				bo->pin_count = 0;
367 				ttm_resource_move_to_lru_tail(bo->resource);
368 			}
369 
370 			kref_init(&bo->kref);
371 			spin_unlock(&bo->bdev->lru_lock);
372 
373 			INIT_WORK(&bo->delayed_delete, ttm_bo_delayed_delete);
374 			queue_work(bdev->wq, &bo->delayed_delete);
375 			return;
376 		}
377 
378 		ttm_bo_cleanup_memtype_use(bo);
379 		dma_resv_unlock(bo->base.resv);
380 	}
381 
382 	atomic_dec(&ttm_glob.bo_count);
383 	bo->destroy(bo);
384 }
385 
386 /**
387  * ttm_bo_put
388  *
389  * @bo: The buffer object.
390  *
391  * Unreference a buffer object.
392  */
393 void ttm_bo_put(struct ttm_buffer_object *bo)
394 {
395 	kref_put(&bo->kref, ttm_bo_release);
396 }
397 EXPORT_SYMBOL(ttm_bo_put);
398 
399 static int ttm_bo_bounce_temp_buffer(struct ttm_buffer_object *bo,
400 				     struct ttm_resource **mem,
401 				     struct ttm_operation_ctx *ctx,
402 				     struct ttm_place *hop)
403 {
404 	struct ttm_placement hop_placement;
405 	struct ttm_resource *hop_mem;
406 	int ret;
407 
408 	hop_placement.num_placement = hop_placement.num_busy_placement = 1;
409 	hop_placement.placement = hop_placement.busy_placement = hop;
410 
411 	/* find space in the bounce domain */
412 	ret = ttm_bo_mem_space(bo, &hop_placement, &hop_mem, ctx);
413 	if (ret)
414 		return ret;
415 	/* move to the bounce domain */
416 	ret = ttm_bo_handle_move_mem(bo, hop_mem, false, ctx, NULL);
417 	if (ret) {
418 		ttm_resource_free(bo, &hop_mem);
419 		return ret;
420 	}
421 	return 0;
422 }
423 
424 static int ttm_bo_evict(struct ttm_buffer_object *bo,
425 			struct ttm_operation_ctx *ctx)
426 {
427 	struct ttm_device *bdev = bo->bdev;
428 	struct ttm_resource *evict_mem;
429 	struct ttm_placement placement;
430 	struct ttm_place hop;
431 	int ret = 0;
432 
433 	memset(&hop, 0, sizeof(hop));
434 
435 	dma_resv_assert_held(bo->base.resv);
436 
437 	placement.num_placement = 0;
438 	placement.num_busy_placement = 0;
439 	bdev->funcs->evict_flags(bo, &placement);
440 
441 	if (!placement.num_placement && !placement.num_busy_placement) {
442 		ret = ttm_bo_wait_ctx(bo, ctx);
443 		if (ret)
444 			return ret;
445 
446 		/*
447 		 * Since we've already synced, this frees backing store
448 		 * immediately.
449 		 */
450 		return ttm_bo_pipeline_gutting(bo);
451 	}
452 
453 	ret = ttm_bo_mem_space(bo, &placement, &evict_mem, ctx);
454 	if (ret) {
455 		if (ret != -ERESTARTSYS) {
456 			pr_err("Failed to find memory space for buffer 0x%p eviction\n",
457 			       bo);
458 			ttm_bo_mem_space_debug(bo, &placement);
459 		}
460 		goto out;
461 	}
462 
463 bounce:
464 	ret = ttm_bo_handle_move_mem(bo, evict_mem, true, ctx, &hop);
465 	if (ret == -EMULTIHOP) {
466 		ret = ttm_bo_bounce_temp_buffer(bo, &evict_mem, ctx, &hop);
467 		if (ret) {
468 			if (ret != -ERESTARTSYS && ret != -EINTR)
469 				pr_err("Buffer eviction failed\n");
470 			ttm_resource_free(bo, &evict_mem);
471 			goto out;
472 		}
473 		/* try and move to final place now. */
474 		goto bounce;
475 	}
476 out:
477 	return ret;
478 }
479 
480 /**
481  * ttm_bo_eviction_valuable
482  *
483  * @bo: The buffer object to evict
484  * @place: the placement we need to make room for
485  *
486  * Check if it is valuable to evict the BO to make room for the given placement.
487  */
488 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
489 			      const struct ttm_place *place)
490 {
491 	struct ttm_resource *res = bo->resource;
492 	struct ttm_device *bdev = bo->bdev;
493 
494 	dma_resv_assert_held(bo->base.resv);
495 	if (bo->resource->mem_type == TTM_PL_SYSTEM)
496 		return true;
497 
498 	/* Don't evict this BO if it's outside of the
499 	 * requested placement range
500 	 */
501 	return ttm_resource_intersects(bdev, res, place, bo->base.size);
502 }
503 EXPORT_SYMBOL(ttm_bo_eviction_valuable);
504 
505 /*
506  * Check the target bo is allowable to be evicted or swapout, including cases:
507  *
508  * a. if share same reservation object with ctx->resv, have assumption
509  * reservation objects should already be locked, so not lock again and
510  * return true directly when either the opreation allow_reserved_eviction
511  * or the target bo already is in delayed free list;
512  *
513  * b. Otherwise, trylock it.
514  */
515 static bool ttm_bo_evict_swapout_allowable(struct ttm_buffer_object *bo,
516 					   struct ttm_operation_ctx *ctx,
517 					   const struct ttm_place *place,
518 					   bool *locked, bool *busy)
519 {
520 	bool ret = false;
521 
522 	if (bo->base.resv == ctx->resv) {
523 		dma_resv_assert_held(bo->base.resv);
524 		if (ctx->allow_res_evict)
525 			ret = true;
526 		*locked = false;
527 		if (busy)
528 			*busy = false;
529 	} else {
530 		ret = dma_resv_trylock(bo->base.resv);
531 		*locked = ret;
532 		if (busy)
533 			*busy = !ret;
534 	}
535 
536 	if (ret && place && (bo->resource->mem_type != place->mem_type ||
537 		!bo->bdev->funcs->eviction_valuable(bo, place))) {
538 		ret = false;
539 		if (*locked) {
540 			dma_resv_unlock(bo->base.resv);
541 			*locked = false;
542 		}
543 	}
544 
545 	return ret;
546 }
547 
548 /**
549  * ttm_mem_evict_wait_busy - wait for a busy BO to become available
550  *
551  * @busy_bo: BO which couldn't be locked with trylock
552  * @ctx: operation context
553  * @ticket: acquire ticket
554  *
555  * Try to lock a busy buffer object to avoid failing eviction.
556  */
557 static int ttm_mem_evict_wait_busy(struct ttm_buffer_object *busy_bo,
558 				   struct ttm_operation_ctx *ctx,
559 				   struct ww_acquire_ctx *ticket)
560 {
561 	int r;
562 
563 	if (!busy_bo || !ticket)
564 		return -EBUSY;
565 
566 	if (ctx->interruptible)
567 		r = dma_resv_lock_interruptible(busy_bo->base.resv,
568 							  ticket);
569 	else
570 		r = dma_resv_lock(busy_bo->base.resv, ticket);
571 
572 	/*
573 	 * TODO: It would be better to keep the BO locked until allocation is at
574 	 * least tried one more time, but that would mean a much larger rework
575 	 * of TTM.
576 	 */
577 	if (!r)
578 		dma_resv_unlock(busy_bo->base.resv);
579 
580 	return r == -EDEADLK ? -EBUSY : r;
581 }
582 
583 int ttm_mem_evict_first(struct ttm_device *bdev,
584 			struct ttm_resource_manager *man,
585 			const struct ttm_place *place,
586 			struct ttm_operation_ctx *ctx,
587 			struct ww_acquire_ctx *ticket)
588 {
589 	struct ttm_buffer_object *bo = NULL, *busy_bo = NULL;
590 	struct ttm_resource_cursor cursor;
591 	struct ttm_resource *res;
592 	bool locked = false;
593 	int ret;
594 
595 	spin_lock(&bdev->lru_lock);
596 	ttm_resource_manager_for_each_res(man, &cursor, res) {
597 		bool busy;
598 
599 		if (!ttm_bo_evict_swapout_allowable(res->bo, ctx, place,
600 						    &locked, &busy)) {
601 			if (busy && !busy_bo && ticket !=
602 			    dma_resv_locking_ctx(res->bo->base.resv))
603 				busy_bo = res->bo;
604 			continue;
605 		}
606 
607 		if (ttm_bo_get_unless_zero(res->bo)) {
608 			bo = res->bo;
609 			break;
610 		}
611 		if (locked)
612 			dma_resv_unlock(res->bo->base.resv);
613 	}
614 
615 	if (!bo) {
616 		if (busy_bo && !ttm_bo_get_unless_zero(busy_bo))
617 			busy_bo = NULL;
618 		spin_unlock(&bdev->lru_lock);
619 		ret = ttm_mem_evict_wait_busy(busy_bo, ctx, ticket);
620 		if (busy_bo)
621 			ttm_bo_put(busy_bo);
622 		return ret;
623 	}
624 
625 	if (bo->deleted) {
626 		ret = ttm_bo_cleanup_refs(bo, ctx->interruptible,
627 					  ctx->no_wait_gpu, locked);
628 		ttm_bo_put(bo);
629 		return ret;
630 	}
631 
632 	spin_unlock(&bdev->lru_lock);
633 
634 	ret = ttm_bo_evict(bo, ctx);
635 	if (locked)
636 		ttm_bo_unreserve(bo);
637 	else
638 		ttm_bo_move_to_lru_tail_unlocked(bo);
639 
640 	ttm_bo_put(bo);
641 	return ret;
642 }
643 
644 /**
645  * ttm_bo_pin - Pin the buffer object.
646  * @bo: The buffer object to pin
647  *
648  * Make sure the buffer is not evicted any more during memory pressure.
649  * @bo must be unpinned again by calling ttm_bo_unpin().
650  */
651 void ttm_bo_pin(struct ttm_buffer_object *bo)
652 {
653 	dma_resv_assert_held(bo->base.resv);
654 	WARN_ON_ONCE(!kref_read(&bo->kref));
655 	spin_lock(&bo->bdev->lru_lock);
656 	if (bo->resource)
657 		ttm_resource_del_bulk_move(bo->resource, bo);
658 	++bo->pin_count;
659 	spin_unlock(&bo->bdev->lru_lock);
660 }
661 EXPORT_SYMBOL(ttm_bo_pin);
662 
663 /**
664  * ttm_bo_unpin - Unpin the buffer object.
665  * @bo: The buffer object to unpin
666  *
667  * Allows the buffer object to be evicted again during memory pressure.
668  */
669 void ttm_bo_unpin(struct ttm_buffer_object *bo)
670 {
671 	dma_resv_assert_held(bo->base.resv);
672 	WARN_ON_ONCE(!kref_read(&bo->kref));
673 	if (WARN_ON_ONCE(!bo->pin_count))
674 		return;
675 
676 	spin_lock(&bo->bdev->lru_lock);
677 	--bo->pin_count;
678 	if (bo->resource)
679 		ttm_resource_add_bulk_move(bo->resource, bo);
680 	spin_unlock(&bo->bdev->lru_lock);
681 }
682 EXPORT_SYMBOL(ttm_bo_unpin);
683 
684 /*
685  * Add the last move fence to the BO as kernel dependency and reserve a new
686  * fence slot.
687  */
688 static int ttm_bo_add_move_fence(struct ttm_buffer_object *bo,
689 				 struct ttm_resource_manager *man,
690 				 struct ttm_resource *mem,
691 				 bool no_wait_gpu)
692 {
693 	struct dma_fence *fence;
694 	int ret;
695 
696 	spin_lock(&man->move_lock);
697 	fence = dma_fence_get(man->move);
698 	spin_unlock(&man->move_lock);
699 
700 	if (!fence)
701 		return 0;
702 
703 	if (no_wait_gpu) {
704 		ret = dma_fence_is_signaled(fence) ? 0 : -EBUSY;
705 		dma_fence_put(fence);
706 		return ret;
707 	}
708 
709 	dma_resv_add_fence(bo->base.resv, fence, DMA_RESV_USAGE_KERNEL);
710 
711 	ret = dma_resv_reserve_fences(bo->base.resv, 1);
712 	dma_fence_put(fence);
713 	return ret;
714 }
715 
716 /*
717  * Repeatedly evict memory from the LRU for @mem_type until we create enough
718  * space, or we've evicted everything and there isn't enough space.
719  */
720 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
721 				  const struct ttm_place *place,
722 				  struct ttm_resource **mem,
723 				  struct ttm_operation_ctx *ctx)
724 {
725 	struct ttm_device *bdev = bo->bdev;
726 	struct ttm_resource_manager *man;
727 	struct ww_acquire_ctx *ticket;
728 	int ret;
729 
730 	man = ttm_manager_type(bdev, place->mem_type);
731 	ticket = dma_resv_locking_ctx(bo->base.resv);
732 	do {
733 		ret = ttm_resource_alloc(bo, place, mem);
734 		if (likely(!ret))
735 			break;
736 		if (unlikely(ret != -ENOSPC))
737 			return ret;
738 		ret = ttm_mem_evict_first(bdev, man, place, ctx,
739 					  ticket);
740 		if (unlikely(ret != 0))
741 			return ret;
742 	} while (1);
743 
744 	return ttm_bo_add_move_fence(bo, man, *mem, ctx->no_wait_gpu);
745 }
746 
747 /**
748  * ttm_bo_mem_space
749  *
750  * @bo: Pointer to a struct ttm_buffer_object. the data of which
751  * we want to allocate space for.
752  * @placement: Proposed new placement for the buffer object.
753  * @mem: A struct ttm_resource.
754  * @ctx: if and how to sleep, lock buffers and alloc memory
755  *
756  * Allocate memory space for the buffer object pointed to by @bo, using
757  * the placement flags in @placement, potentially evicting other idle buffer objects.
758  * This function may sleep while waiting for space to become available.
759  * Returns:
760  * -EBUSY: No space available (only if no_wait == 1).
761  * -ENOMEM: Could not allocate memory for the buffer object, either due to
762  * fragmentation or concurrent allocators.
763  * -ERESTARTSYS: An interruptible sleep was interrupted by a signal.
764  */
765 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
766 			struct ttm_placement *placement,
767 			struct ttm_resource **mem,
768 			struct ttm_operation_ctx *ctx)
769 {
770 	struct ttm_device *bdev = bo->bdev;
771 	bool type_found = false;
772 	int i, ret;
773 
774 	ret = dma_resv_reserve_fences(bo->base.resv, 1);
775 	if (unlikely(ret))
776 		return ret;
777 
778 	for (i = 0; i < placement->num_placement; ++i) {
779 		const struct ttm_place *place = &placement->placement[i];
780 		struct ttm_resource_manager *man;
781 
782 		man = ttm_manager_type(bdev, place->mem_type);
783 		if (!man || !ttm_resource_manager_used(man))
784 			continue;
785 
786 		type_found = true;
787 		ret = ttm_resource_alloc(bo, place, mem);
788 		if (ret == -ENOSPC)
789 			continue;
790 		if (unlikely(ret))
791 			goto error;
792 
793 		ret = ttm_bo_add_move_fence(bo, man, *mem, ctx->no_wait_gpu);
794 		if (unlikely(ret)) {
795 			ttm_resource_free(bo, mem);
796 			if (ret == -EBUSY)
797 				continue;
798 
799 			goto error;
800 		}
801 		return 0;
802 	}
803 
804 	for (i = 0; i < placement->num_busy_placement; ++i) {
805 		const struct ttm_place *place = &placement->busy_placement[i];
806 		struct ttm_resource_manager *man;
807 
808 		man = ttm_manager_type(bdev, place->mem_type);
809 		if (!man || !ttm_resource_manager_used(man))
810 			continue;
811 
812 		type_found = true;
813 		ret = ttm_bo_mem_force_space(bo, place, mem, ctx);
814 		if (likely(!ret))
815 			return 0;
816 
817 		if (ret && ret != -EBUSY)
818 			goto error;
819 	}
820 
821 	ret = -ENOMEM;
822 	if (!type_found) {
823 		pr_err(TTM_PFX "No compatible memory type found\n");
824 		ret = -EINVAL;
825 	}
826 
827 error:
828 	return ret;
829 }
830 EXPORT_SYMBOL(ttm_bo_mem_space);
831 
832 static int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
833 			      struct ttm_placement *placement,
834 			      struct ttm_operation_ctx *ctx)
835 {
836 	struct ttm_resource *mem;
837 	struct ttm_place hop;
838 	int ret;
839 
840 	dma_resv_assert_held(bo->base.resv);
841 
842 	/*
843 	 * Determine where to move the buffer.
844 	 *
845 	 * If driver determines move is going to need
846 	 * an extra step then it will return -EMULTIHOP
847 	 * and the buffer will be moved to the temporary
848 	 * stop and the driver will be called to make
849 	 * the second hop.
850 	 */
851 	ret = ttm_bo_mem_space(bo, placement, &mem, ctx);
852 	if (ret)
853 		return ret;
854 bounce:
855 	ret = ttm_bo_handle_move_mem(bo, mem, false, ctx, &hop);
856 	if (ret == -EMULTIHOP) {
857 		ret = ttm_bo_bounce_temp_buffer(bo, &mem, ctx, &hop);
858 		if (ret)
859 			goto out;
860 		/* try and move to final place now. */
861 		goto bounce;
862 	}
863 out:
864 	if (ret)
865 		ttm_resource_free(bo, &mem);
866 	return ret;
867 }
868 
869 /**
870  * ttm_bo_validate
871  *
872  * @bo: The buffer object.
873  * @placement: Proposed placement for the buffer object.
874  * @ctx: validation parameters.
875  *
876  * Changes placement and caching policy of the buffer object
877  * according proposed placement.
878  * Returns
879  * -EINVAL on invalid proposed placement.
880  * -ENOMEM on out-of-memory condition.
881  * -EBUSY if no_wait is true and buffer busy.
882  * -ERESTARTSYS if interrupted by a signal.
883  */
884 int ttm_bo_validate(struct ttm_buffer_object *bo,
885 		    struct ttm_placement *placement,
886 		    struct ttm_operation_ctx *ctx)
887 {
888 	int ret;
889 
890 	dma_resv_assert_held(bo->base.resv);
891 
892 	/*
893 	 * Remove the backing store if no placement is given.
894 	 */
895 	if (!placement->num_placement && !placement->num_busy_placement)
896 		return ttm_bo_pipeline_gutting(bo);
897 
898 	/* Check whether we need to move buffer. */
899 	if (bo->resource && ttm_resource_compat(bo->resource, placement))
900 		return 0;
901 
902 	/* Moving of pinned BOs is forbidden */
903 	if (bo->pin_count)
904 		return -EINVAL;
905 
906 	ret = ttm_bo_move_buffer(bo, placement, ctx);
907 	if (ret)
908 		return ret;
909 
910 	/*
911 	 * We might need to add a TTM.
912 	 */
913 	if (!bo->resource || bo->resource->mem_type == TTM_PL_SYSTEM) {
914 		ret = ttm_tt_create(bo, true);
915 		if (ret)
916 			return ret;
917 	}
918 	return 0;
919 }
920 EXPORT_SYMBOL(ttm_bo_validate);
921 
922 /**
923  * ttm_bo_init_reserved
924  *
925  * @bdev: Pointer to a ttm_device struct.
926  * @bo: Pointer to a ttm_buffer_object to be initialized.
927  * @type: Requested type of buffer object.
928  * @placement: Initial placement for buffer object.
929  * @alignment: Data alignment in pages.
930  * @ctx: TTM operation context for memory allocation.
931  * @sg: Scatter-gather table.
932  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
933  * @destroy: Destroy function. Use NULL for kfree().
934  *
935  * This function initializes a pre-allocated struct ttm_buffer_object.
936  * As this object may be part of a larger structure, this function,
937  * together with the @destroy function, enables driver-specific objects
938  * derived from a ttm_buffer_object.
939  *
940  * On successful return, the caller owns an object kref to @bo. The kref and
941  * list_kref are usually set to 1, but note that in some situations, other
942  * tasks may already be holding references to @bo as well.
943  * Furthermore, if resv == NULL, the buffer's reservation lock will be held,
944  * and it is the caller's responsibility to call ttm_bo_unreserve.
945  *
946  * If a failure occurs, the function will call the @destroy function. Thus,
947  * after a failure, dereferencing @bo is illegal and will likely cause memory
948  * corruption.
949  *
950  * Returns
951  * -ENOMEM: Out of memory.
952  * -EINVAL: Invalid placement flags.
953  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
954  */
955 int ttm_bo_init_reserved(struct ttm_device *bdev, struct ttm_buffer_object *bo,
956 			 enum ttm_bo_type type, struct ttm_placement *placement,
957 			 uint32_t alignment, struct ttm_operation_ctx *ctx,
958 			 struct sg_table *sg, struct dma_resv *resv,
959 			 void (*destroy) (struct ttm_buffer_object *))
960 {
961 	int ret;
962 
963 	kref_init(&bo->kref);
964 	bo->bdev = bdev;
965 	bo->type = type;
966 	bo->page_alignment = alignment;
967 	bo->destroy = destroy;
968 	bo->pin_count = 0;
969 	bo->sg = sg;
970 	bo->bulk_move = NULL;
971 	if (resv)
972 		bo->base.resv = resv;
973 	else
974 		bo->base.resv = &bo->base._resv;
975 	atomic_inc(&ttm_glob.bo_count);
976 
977 	/*
978 	 * For ttm_bo_type_device buffers, allocate
979 	 * address space from the device.
980 	 */
981 	if (bo->type == ttm_bo_type_device || bo->type == ttm_bo_type_sg) {
982 		ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
983 					 PFN_UP(bo->base.size));
984 		if (ret)
985 			goto err_put;
986 	}
987 
988 	/* passed reservation objects should already be locked,
989 	 * since otherwise lockdep will be angered in radeon.
990 	 */
991 	if (!resv)
992 		WARN_ON(!dma_resv_trylock(bo->base.resv));
993 	else
994 		dma_resv_assert_held(resv);
995 
996 	ret = ttm_bo_validate(bo, placement, ctx);
997 	if (unlikely(ret))
998 		goto err_unlock;
999 
1000 	return 0;
1001 
1002 err_unlock:
1003 	if (!resv)
1004 		dma_resv_unlock(bo->base.resv);
1005 
1006 err_put:
1007 	ttm_bo_put(bo);
1008 	return ret;
1009 }
1010 EXPORT_SYMBOL(ttm_bo_init_reserved);
1011 
1012 /**
1013  * ttm_bo_init_validate
1014  *
1015  * @bdev: Pointer to a ttm_device struct.
1016  * @bo: Pointer to a ttm_buffer_object to be initialized.
1017  * @type: Requested type of buffer object.
1018  * @placement: Initial placement for buffer object.
1019  * @alignment: Data alignment in pages.
1020  * @interruptible: If needing to sleep to wait for GPU resources,
1021  * sleep interruptible.
1022  * pinned in physical memory. If this behaviour is not desired, this member
1023  * holds a pointer to a persistent shmem object. Typically, this would
1024  * point to the shmem object backing a GEM object if TTM is used to back a
1025  * GEM user interface.
1026  * @sg: Scatter-gather table.
1027  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
1028  * @destroy: Destroy function. Use NULL for kfree().
1029  *
1030  * This function initializes a pre-allocated struct ttm_buffer_object.
1031  * As this object may be part of a larger structure, this function,
1032  * together with the @destroy function,
1033  * enables driver-specific objects derived from a ttm_buffer_object.
1034  *
1035  * On successful return, the caller owns an object kref to @bo. The kref and
1036  * list_kref are usually set to 1, but note that in some situations, other
1037  * tasks may already be holding references to @bo as well.
1038  *
1039  * If a failure occurs, the function will call the @destroy function, Thus,
1040  * after a failure, dereferencing @bo is illegal and will likely cause memory
1041  * corruption.
1042  *
1043  * Returns
1044  * -ENOMEM: Out of memory.
1045  * -EINVAL: Invalid placement flags.
1046  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
1047  */
1048 int ttm_bo_init_validate(struct ttm_device *bdev, struct ttm_buffer_object *bo,
1049 			 enum ttm_bo_type type, struct ttm_placement *placement,
1050 			 uint32_t alignment, bool interruptible,
1051 			 struct sg_table *sg, struct dma_resv *resv,
1052 			 void (*destroy) (struct ttm_buffer_object *))
1053 {
1054 	struct ttm_operation_ctx ctx = { interruptible, false };
1055 	int ret;
1056 
1057 	ret = ttm_bo_init_reserved(bdev, bo, type, placement, alignment, &ctx,
1058 				   sg, resv, destroy);
1059 	if (ret)
1060 		return ret;
1061 
1062 	if (!resv)
1063 		ttm_bo_unreserve(bo);
1064 
1065 	return 0;
1066 }
1067 EXPORT_SYMBOL(ttm_bo_init_validate);
1068 
1069 /*
1070  * buffer object vm functions.
1071  */
1072 
1073 /**
1074  * ttm_bo_unmap_virtual
1075  *
1076  * @bo: tear down the virtual mappings for this BO
1077  */
1078 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1079 {
1080 	struct ttm_device *bdev = bo->bdev;
1081 
1082 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1083 	ttm_mem_io_free(bdev, bo->resource);
1084 }
1085 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1086 
1087 /**
1088  * ttm_bo_wait_ctx - wait for buffer idle.
1089  *
1090  * @bo:  The buffer object.
1091  * @ctx: defines how to wait
1092  *
1093  * Waits for the buffer to be idle. Used timeout depends on the context.
1094  * Returns -EBUSY if wait timed outt, -ERESTARTSYS if interrupted by a signal or
1095  * zero on success.
1096  */
1097 int ttm_bo_wait_ctx(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx)
1098 {
1099 	long ret;
1100 
1101 	if (ctx->no_wait_gpu) {
1102 		if (dma_resv_test_signaled(bo->base.resv,
1103 					   DMA_RESV_USAGE_BOOKKEEP))
1104 			return 0;
1105 		else
1106 			return -EBUSY;
1107 	}
1108 
1109 	ret = dma_resv_wait_timeout(bo->base.resv, DMA_RESV_USAGE_BOOKKEEP,
1110 				    ctx->interruptible, 15 * HZ);
1111 	if (unlikely(ret < 0))
1112 		return ret;
1113 	if (unlikely(ret == 0))
1114 		return -EBUSY;
1115 	return 0;
1116 }
1117 EXPORT_SYMBOL(ttm_bo_wait_ctx);
1118 
1119 int ttm_bo_swapout(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx,
1120 		   gfp_t gfp_flags)
1121 {
1122 	struct ttm_place place;
1123 	bool locked;
1124 	long ret;
1125 
1126 	/*
1127 	 * While the bo may already reside in SYSTEM placement, set
1128 	 * SYSTEM as new placement to cover also the move further below.
1129 	 * The driver may use the fact that we're moving from SYSTEM
1130 	 * as an indication that we're about to swap out.
1131 	 */
1132 	memset(&place, 0, sizeof(place));
1133 	place.mem_type = bo->resource->mem_type;
1134 	if (!ttm_bo_evict_swapout_allowable(bo, ctx, &place, &locked, NULL))
1135 		return -EBUSY;
1136 
1137 	if (!bo->ttm || !ttm_tt_is_populated(bo->ttm) ||
1138 	    bo->ttm->page_flags & TTM_TT_FLAG_EXTERNAL ||
1139 	    bo->ttm->page_flags & TTM_TT_FLAG_SWAPPED ||
1140 	    !ttm_bo_get_unless_zero(bo)) {
1141 		if (locked)
1142 			dma_resv_unlock(bo->base.resv);
1143 		return -EBUSY;
1144 	}
1145 
1146 	if (bo->deleted) {
1147 		ret = ttm_bo_cleanup_refs(bo, false, false, locked);
1148 		ttm_bo_put(bo);
1149 		return ret == -EBUSY ? -ENOSPC : ret;
1150 	}
1151 
1152 	/* TODO: Cleanup the locking */
1153 	spin_unlock(&bo->bdev->lru_lock);
1154 
1155 	/*
1156 	 * Move to system cached
1157 	 */
1158 	if (bo->resource->mem_type != TTM_PL_SYSTEM) {
1159 		struct ttm_operation_ctx ctx = { false, false };
1160 		struct ttm_resource *evict_mem;
1161 		struct ttm_place hop;
1162 
1163 		memset(&hop, 0, sizeof(hop));
1164 		place.mem_type = TTM_PL_SYSTEM;
1165 		ret = ttm_resource_alloc(bo, &place, &evict_mem);
1166 		if (unlikely(ret))
1167 			goto out;
1168 
1169 		ret = ttm_bo_handle_move_mem(bo, evict_mem, true, &ctx, &hop);
1170 		if (unlikely(ret != 0)) {
1171 			WARN(ret == -EMULTIHOP, "Unexpected multihop in swaput - likely driver bug.\n");
1172 			goto out;
1173 		}
1174 	}
1175 
1176 	/*
1177 	 * Make sure BO is idle.
1178 	 */
1179 	ret = ttm_bo_wait_ctx(bo, ctx);
1180 	if (unlikely(ret != 0))
1181 		goto out;
1182 
1183 	ttm_bo_unmap_virtual(bo);
1184 
1185 	/*
1186 	 * Swap out. Buffer will be swapped in again as soon as
1187 	 * anyone tries to access a ttm page.
1188 	 */
1189 	if (bo->bdev->funcs->swap_notify)
1190 		bo->bdev->funcs->swap_notify(bo);
1191 
1192 	if (ttm_tt_is_populated(bo->ttm))
1193 		ret = ttm_tt_swapout(bo->bdev, bo->ttm, gfp_flags);
1194 out:
1195 
1196 	/*
1197 	 * Unreserve without putting on LRU to avoid swapping out an
1198 	 * already swapped buffer.
1199 	 */
1200 	if (locked)
1201 		dma_resv_unlock(bo->base.resv);
1202 	ttm_bo_put(bo);
1203 	return ret == -EBUSY ? -ENOSPC : ret;
1204 }
1205 
1206 void ttm_bo_tt_destroy(struct ttm_buffer_object *bo)
1207 {
1208 	if (bo->ttm == NULL)
1209 		return;
1210 
1211 	ttm_tt_unpopulate(bo->bdev, bo->ttm);
1212 	ttm_tt_destroy(bo->bdev, bo->ttm);
1213 	bo->ttm = NULL;
1214 }
1215