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