xref: /linux/drivers/gpu/drm/ttm/ttm_bo.c (revision f14aa5ea415b8add245e976bfab96a12986c6843)
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_dbg_printer(NULL, DRM_UT_CORE, 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 	return 0;
299 }
300 
301 /*
302  * Block for the dma_resv object to become idle, lock the buffer and clean up
303  * the resource and tt object.
304  */
305 static void ttm_bo_delayed_delete(struct work_struct *work)
306 {
307 	struct ttm_buffer_object *bo;
308 
309 	bo = container_of(work, typeof(*bo), delayed_delete);
310 
311 	dma_resv_wait_timeout(bo->base.resv, DMA_RESV_USAGE_BOOKKEEP, false,
312 			      MAX_SCHEDULE_TIMEOUT);
313 	dma_resv_lock(bo->base.resv, NULL);
314 	ttm_bo_cleanup_memtype_use(bo);
315 	dma_resv_unlock(bo->base.resv);
316 	ttm_bo_put(bo);
317 }
318 
319 static void ttm_bo_release(struct kref *kref)
320 {
321 	struct ttm_buffer_object *bo =
322 	    container_of(kref, struct ttm_buffer_object, kref);
323 	struct ttm_device *bdev = bo->bdev;
324 	int ret;
325 
326 	WARN_ON_ONCE(bo->pin_count);
327 	WARN_ON_ONCE(bo->bulk_move);
328 
329 	if (!bo->deleted) {
330 		ret = ttm_bo_individualize_resv(bo);
331 		if (ret) {
332 			/* Last resort, if we fail to allocate memory for the
333 			 * fences block for the BO to become idle
334 			 */
335 			dma_resv_wait_timeout(bo->base.resv,
336 					      DMA_RESV_USAGE_BOOKKEEP, false,
337 					      30 * HZ);
338 		}
339 
340 		if (bo->bdev->funcs->release_notify)
341 			bo->bdev->funcs->release_notify(bo);
342 
343 		drm_vma_offset_remove(bdev->vma_manager, &bo->base.vma_node);
344 		ttm_mem_io_free(bdev, bo->resource);
345 
346 		if (!dma_resv_test_signaled(bo->base.resv,
347 					    DMA_RESV_USAGE_BOOKKEEP) ||
348 		    (want_init_on_free() && (bo->ttm != NULL)) ||
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 
374 			/* Schedule the worker on the closest NUMA node. This
375 			 * improves performance since system memory might be
376 			 * cleared on free and that is best done on a CPU core
377 			 * close to it.
378 			 */
379 			queue_work_node(bdev->pool.nid, bdev->wq, &bo->delayed_delete);
380 			return;
381 		}
382 
383 		ttm_bo_cleanup_memtype_use(bo);
384 		dma_resv_unlock(bo->base.resv);
385 	}
386 
387 	atomic_dec(&ttm_glob.bo_count);
388 	bo->destroy(bo);
389 }
390 
391 /**
392  * ttm_bo_put
393  *
394  * @bo: The buffer object.
395  *
396  * Unreference a buffer object.
397  */
398 void ttm_bo_put(struct ttm_buffer_object *bo)
399 {
400 	kref_put(&bo->kref, ttm_bo_release);
401 }
402 EXPORT_SYMBOL(ttm_bo_put);
403 
404 static int ttm_bo_bounce_temp_buffer(struct ttm_buffer_object *bo,
405 				     struct ttm_operation_ctx *ctx,
406 				     struct ttm_place *hop)
407 {
408 	struct ttm_placement hop_placement;
409 	struct ttm_resource *hop_mem;
410 	int ret;
411 
412 	hop_placement.num_placement = 1;
413 	hop_placement.placement = hop;
414 
415 	/* find space in the bounce domain */
416 	ret = ttm_bo_mem_space(bo, &hop_placement, &hop_mem, ctx);
417 	if (ret)
418 		return ret;
419 	/* move to the bounce domain */
420 	ret = ttm_bo_handle_move_mem(bo, hop_mem, false, ctx, NULL);
421 	if (ret) {
422 		ttm_resource_free(bo, &hop_mem);
423 		return ret;
424 	}
425 	return 0;
426 }
427 
428 static int ttm_bo_evict(struct ttm_buffer_object *bo,
429 			struct ttm_operation_ctx *ctx)
430 {
431 	struct ttm_device *bdev = bo->bdev;
432 	struct ttm_resource *evict_mem;
433 	struct ttm_placement placement;
434 	struct ttm_place hop;
435 	int ret = 0;
436 
437 	memset(&hop, 0, sizeof(hop));
438 
439 	dma_resv_assert_held(bo->base.resv);
440 
441 	placement.num_placement = 0;
442 	bdev->funcs->evict_flags(bo, &placement);
443 
444 	if (!placement.num_placement) {
445 		ret = ttm_bo_wait_ctx(bo, ctx);
446 		if (ret)
447 			return ret;
448 
449 		/*
450 		 * Since we've already synced, this frees backing store
451 		 * immediately.
452 		 */
453 		return ttm_bo_pipeline_gutting(bo);
454 	}
455 
456 	ret = ttm_bo_mem_space(bo, &placement, &evict_mem, ctx);
457 	if (ret) {
458 		if (ret != -ERESTARTSYS) {
459 			pr_err("Failed to find memory space for buffer 0x%p eviction\n",
460 			       bo);
461 			ttm_bo_mem_space_debug(bo, &placement);
462 		}
463 		goto out;
464 	}
465 
466 	do {
467 		ret = ttm_bo_handle_move_mem(bo, evict_mem, true, ctx, &hop);
468 		if (ret != -EMULTIHOP)
469 			break;
470 
471 		ret = ttm_bo_bounce_temp_buffer(bo, ctx, &hop);
472 	} while (!ret);
473 
474 	if (ret) {
475 		ttm_resource_free(bo, &evict_mem);
476 		if (ret != -ERESTARTSYS && ret != -EINTR)
477 			pr_err("Buffer eviction failed\n");
478 	}
479 out:
480 	return ret;
481 }
482 
483 /**
484  * ttm_bo_eviction_valuable
485  *
486  * @bo: The buffer object to evict
487  * @place: the placement we need to make room for
488  *
489  * Check if it is valuable to evict the BO to make room for the given placement.
490  */
491 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
492 			      const struct ttm_place *place)
493 {
494 	struct ttm_resource *res = bo->resource;
495 	struct ttm_device *bdev = bo->bdev;
496 
497 	dma_resv_assert_held(bo->base.resv);
498 	if (bo->resource->mem_type == TTM_PL_SYSTEM)
499 		return true;
500 
501 	/* Don't evict this BO if it's outside of the
502 	 * requested placement range
503 	 */
504 	return ttm_resource_intersects(bdev, res, place, bo->base.size);
505 }
506 EXPORT_SYMBOL(ttm_bo_eviction_valuable);
507 
508 /*
509  * Check the target bo is allowable to be evicted or swapout, including cases:
510  *
511  * a. if share same reservation object with ctx->resv, have assumption
512  * reservation objects should already be locked, so not lock again and
513  * return true directly when either the opreation allow_reserved_eviction
514  * or the target bo already is in delayed free list;
515  *
516  * b. Otherwise, trylock it.
517  */
518 static bool ttm_bo_evict_swapout_allowable(struct ttm_buffer_object *bo,
519 					   struct ttm_operation_ctx *ctx,
520 					   const struct ttm_place *place,
521 					   bool *locked, bool *busy)
522 {
523 	bool ret = false;
524 
525 	if (bo->pin_count) {
526 		*locked = false;
527 		if (busy)
528 			*busy = false;
529 		return false;
530 	}
531 
532 	if (bo->base.resv == ctx->resv) {
533 		dma_resv_assert_held(bo->base.resv);
534 		if (ctx->allow_res_evict)
535 			ret = true;
536 		*locked = false;
537 		if (busy)
538 			*busy = false;
539 	} else {
540 		ret = dma_resv_trylock(bo->base.resv);
541 		*locked = ret;
542 		if (busy)
543 			*busy = !ret;
544 	}
545 
546 	if (ret && place && (bo->resource->mem_type != place->mem_type ||
547 		!bo->bdev->funcs->eviction_valuable(bo, place))) {
548 		ret = false;
549 		if (*locked) {
550 			dma_resv_unlock(bo->base.resv);
551 			*locked = false;
552 		}
553 	}
554 
555 	return ret;
556 }
557 
558 /**
559  * ttm_mem_evict_wait_busy - wait for a busy BO to become available
560  *
561  * @busy_bo: BO which couldn't be locked with trylock
562  * @ctx: operation context
563  * @ticket: acquire ticket
564  *
565  * Try to lock a busy buffer object to avoid failing eviction.
566  */
567 static int ttm_mem_evict_wait_busy(struct ttm_buffer_object *busy_bo,
568 				   struct ttm_operation_ctx *ctx,
569 				   struct ww_acquire_ctx *ticket)
570 {
571 	int r;
572 
573 	if (!busy_bo || !ticket)
574 		return -EBUSY;
575 
576 	if (ctx->interruptible)
577 		r = dma_resv_lock_interruptible(busy_bo->base.resv,
578 							  ticket);
579 	else
580 		r = dma_resv_lock(busy_bo->base.resv, ticket);
581 
582 	/*
583 	 * TODO: It would be better to keep the BO locked until allocation is at
584 	 * least tried one more time, but that would mean a much larger rework
585 	 * of TTM.
586 	 */
587 	if (!r)
588 		dma_resv_unlock(busy_bo->base.resv);
589 
590 	return r == -EDEADLK ? -EBUSY : r;
591 }
592 
593 int ttm_mem_evict_first(struct ttm_device *bdev,
594 			struct ttm_resource_manager *man,
595 			const struct ttm_place *place,
596 			struct ttm_operation_ctx *ctx,
597 			struct ww_acquire_ctx *ticket)
598 {
599 	struct ttm_buffer_object *bo = NULL, *busy_bo = NULL;
600 	struct ttm_resource_cursor cursor;
601 	struct ttm_resource *res;
602 	bool locked = false;
603 	int ret;
604 
605 	spin_lock(&bdev->lru_lock);
606 	ttm_resource_manager_for_each_res(man, &cursor, res) {
607 		bool busy;
608 
609 		if (!ttm_bo_evict_swapout_allowable(res->bo, ctx, place,
610 						    &locked, &busy)) {
611 			if (busy && !busy_bo && ticket !=
612 			    dma_resv_locking_ctx(res->bo->base.resv))
613 				busy_bo = res->bo;
614 			continue;
615 		}
616 
617 		if (ttm_bo_get_unless_zero(res->bo)) {
618 			bo = res->bo;
619 			break;
620 		}
621 		if (locked)
622 			dma_resv_unlock(res->bo->base.resv);
623 	}
624 
625 	if (!bo) {
626 		if (busy_bo && !ttm_bo_get_unless_zero(busy_bo))
627 			busy_bo = NULL;
628 		spin_unlock(&bdev->lru_lock);
629 		ret = ttm_mem_evict_wait_busy(busy_bo, ctx, ticket);
630 		if (busy_bo)
631 			ttm_bo_put(busy_bo);
632 		return ret;
633 	}
634 
635 	if (bo->deleted) {
636 		ret = ttm_bo_cleanup_refs(bo, ctx->interruptible,
637 					  ctx->no_wait_gpu, locked);
638 		ttm_bo_put(bo);
639 		return ret;
640 	}
641 
642 	spin_unlock(&bdev->lru_lock);
643 
644 	ret = ttm_bo_evict(bo, ctx);
645 	if (locked)
646 		ttm_bo_unreserve(bo);
647 	else
648 		ttm_bo_move_to_lru_tail_unlocked(bo);
649 
650 	ttm_bo_put(bo);
651 	return ret;
652 }
653 
654 /**
655  * ttm_bo_pin - Pin the buffer object.
656  * @bo: The buffer object to pin
657  *
658  * Make sure the buffer is not evicted any more during memory pressure.
659  * @bo must be unpinned again by calling ttm_bo_unpin().
660  */
661 void ttm_bo_pin(struct ttm_buffer_object *bo)
662 {
663 	dma_resv_assert_held(bo->base.resv);
664 	WARN_ON_ONCE(!kref_read(&bo->kref));
665 	spin_lock(&bo->bdev->lru_lock);
666 	if (bo->resource)
667 		ttm_resource_del_bulk_move(bo->resource, bo);
668 	++bo->pin_count;
669 	spin_unlock(&bo->bdev->lru_lock);
670 }
671 EXPORT_SYMBOL(ttm_bo_pin);
672 
673 /**
674  * ttm_bo_unpin - Unpin the buffer object.
675  * @bo: The buffer object to unpin
676  *
677  * Allows the buffer object to be evicted again during memory pressure.
678  */
679 void ttm_bo_unpin(struct ttm_buffer_object *bo)
680 {
681 	dma_resv_assert_held(bo->base.resv);
682 	WARN_ON_ONCE(!kref_read(&bo->kref));
683 	if (WARN_ON_ONCE(!bo->pin_count))
684 		return;
685 
686 	spin_lock(&bo->bdev->lru_lock);
687 	--bo->pin_count;
688 	if (bo->resource)
689 		ttm_resource_add_bulk_move(bo->resource, bo);
690 	spin_unlock(&bo->bdev->lru_lock);
691 }
692 EXPORT_SYMBOL(ttm_bo_unpin);
693 
694 /*
695  * Add the last move fence to the BO as kernel dependency and reserve a new
696  * fence slot.
697  */
698 static int ttm_bo_add_move_fence(struct ttm_buffer_object *bo,
699 				 struct ttm_resource_manager *man,
700 				 bool no_wait_gpu)
701 {
702 	struct dma_fence *fence;
703 	int ret;
704 
705 	spin_lock(&man->move_lock);
706 	fence = dma_fence_get(man->move);
707 	spin_unlock(&man->move_lock);
708 
709 	if (!fence)
710 		return 0;
711 
712 	if (no_wait_gpu) {
713 		ret = dma_fence_is_signaled(fence) ? 0 : -EBUSY;
714 		dma_fence_put(fence);
715 		return ret;
716 	}
717 
718 	dma_resv_add_fence(bo->base.resv, fence, DMA_RESV_USAGE_KERNEL);
719 
720 	ret = dma_resv_reserve_fences(bo->base.resv, 1);
721 	dma_fence_put(fence);
722 	return ret;
723 }
724 
725 /**
726  * ttm_bo_alloc_resource - Allocate backing store for a BO
727  *
728  * @bo: Pointer to a struct ttm_buffer_object of which we want a resource for
729  * @placement: Proposed new placement for the buffer object
730  * @ctx: if and how to sleep, lock buffers and alloc memory
731  * @force_space: If we should evict buffers to force space
732  * @res: The resulting struct ttm_resource.
733  *
734  * Allocates a resource for the buffer object pointed to by @bo, using the
735  * placement flags in @placement, potentially evicting other buffer objects when
736  * @force_space is true.
737  * This function may sleep while waiting for resources to become available.
738  * Returns:
739  * -EBUSY: No space available (only if no_wait == true).
740  * -ENOSPC: Could not allocate space for the buffer object, either due to
741  * fragmentation or concurrent allocators.
742  * -ERESTARTSYS: An interruptible sleep was interrupted by a signal.
743  */
744 static int ttm_bo_alloc_resource(struct ttm_buffer_object *bo,
745 				 struct ttm_placement *placement,
746 				 struct ttm_operation_ctx *ctx,
747 				 bool force_space,
748 				 struct ttm_resource **res)
749 {
750 	struct ttm_device *bdev = bo->bdev;
751 	struct ww_acquire_ctx *ticket;
752 	int i, ret;
753 
754 	ticket = dma_resv_locking_ctx(bo->base.resv);
755 	ret = dma_resv_reserve_fences(bo->base.resv, 1);
756 	if (unlikely(ret))
757 		return ret;
758 
759 	for (i = 0; i < placement->num_placement; ++i) {
760 		const struct ttm_place *place = &placement->placement[i];
761 		struct ttm_resource_manager *man;
762 
763 		man = ttm_manager_type(bdev, place->mem_type);
764 		if (!man || !ttm_resource_manager_used(man))
765 			continue;
766 
767 		if (place->flags & (force_space ? TTM_PL_FLAG_DESIRED :
768 				    TTM_PL_FLAG_FALLBACK))
769 			continue;
770 
771 		do {
772 			ret = ttm_resource_alloc(bo, place, res);
773 			if (unlikely(ret && ret != -ENOSPC))
774 				return ret;
775 			if (likely(!ret) || !force_space)
776 				break;
777 
778 			ret = ttm_mem_evict_first(bdev, man, place, ctx,
779 						  ticket);
780 			if (unlikely(ret == -EBUSY))
781 				break;
782 			if (unlikely(ret))
783 				return ret;
784 		} while (1);
785 		if (ret)
786 			continue;
787 
788 		ret = ttm_bo_add_move_fence(bo, man, ctx->no_wait_gpu);
789 		if (unlikely(ret)) {
790 			ttm_resource_free(bo, res);
791 			if (ret == -EBUSY)
792 				continue;
793 
794 			return ret;
795 		}
796 		return 0;
797 	}
798 
799 	return -ENOSPC;
800 }
801 
802 /*
803  * ttm_bo_mem_space - Wrapper around ttm_bo_alloc_resource
804  *
805  * @bo: Pointer to a struct ttm_buffer_object of which we want a resource for
806  * @placement: Proposed new placement for the buffer object
807  * @res: The resulting struct ttm_resource.
808  * @ctx: if and how to sleep, lock buffers and alloc memory
809  *
810  * Tries both idle allocation and forcefully eviction of buffers. See
811  * ttm_bo_alloc_resource for details.
812  */
813 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
814 		     struct ttm_placement *placement,
815 		     struct ttm_resource **res,
816 		     struct ttm_operation_ctx *ctx)
817 {
818 	bool force_space = false;
819 	int ret;
820 
821 	do {
822 		ret = ttm_bo_alloc_resource(bo, placement, ctx,
823 					    force_space, res);
824 		force_space = !force_space;
825 	} while (ret == -ENOSPC && force_space);
826 
827 	return ret;
828 }
829 EXPORT_SYMBOL(ttm_bo_mem_space);
830 
831 /**
832  * ttm_bo_validate
833  *
834  * @bo: The buffer object.
835  * @placement: Proposed placement for the buffer object.
836  * @ctx: validation parameters.
837  *
838  * Changes placement and caching policy of the buffer object
839  * according proposed placement.
840  * Returns
841  * -EINVAL on invalid proposed placement.
842  * -ENOMEM on out-of-memory condition.
843  * -EBUSY if no_wait is true and buffer busy.
844  * -ERESTARTSYS if interrupted by a signal.
845  */
846 int ttm_bo_validate(struct ttm_buffer_object *bo,
847 		    struct ttm_placement *placement,
848 		    struct ttm_operation_ctx *ctx)
849 {
850 	struct ttm_resource *res;
851 	struct ttm_place hop;
852 	bool force_space;
853 	int ret;
854 
855 	dma_resv_assert_held(bo->base.resv);
856 
857 	/*
858 	 * Remove the backing store if no placement is given.
859 	 */
860 	if (!placement->num_placement)
861 		return ttm_bo_pipeline_gutting(bo);
862 
863 	force_space = false;
864 	do {
865 		/* Check whether we need to move buffer. */
866 		if (bo->resource &&
867 		    ttm_resource_compatible(bo->resource, placement,
868 					    force_space))
869 			return 0;
870 
871 		/* Moving of pinned BOs is forbidden */
872 		if (bo->pin_count)
873 			return -EINVAL;
874 
875 		/*
876 		 * Determine where to move the buffer.
877 		 *
878 		 * If driver determines move is going to need
879 		 * an extra step then it will return -EMULTIHOP
880 		 * and the buffer will be moved to the temporary
881 		 * stop and the driver will be called to make
882 		 * the second hop.
883 		 */
884 		ret = ttm_bo_alloc_resource(bo, placement, ctx, force_space,
885 					    &res);
886 		force_space = !force_space;
887 		if (ret == -ENOSPC)
888 			continue;
889 		if (ret)
890 			return ret;
891 
892 bounce:
893 		ret = ttm_bo_handle_move_mem(bo, res, false, ctx, &hop);
894 		if (ret == -EMULTIHOP) {
895 			ret = ttm_bo_bounce_temp_buffer(bo, ctx, &hop);
896 			/* try and move to final place now. */
897 			if (!ret)
898 				goto bounce;
899 		}
900 		if (ret) {
901 			ttm_resource_free(bo, &res);
902 			return ret;
903 		}
904 
905 	} while (ret && force_space);
906 
907 	/* For backward compatibility with userspace */
908 	if (ret == -ENOSPC)
909 		return -ENOMEM;
910 
911 	/*
912 	 * We might need to add a TTM.
913 	 */
914 	if (!bo->resource || bo->resource->mem_type == TTM_PL_SYSTEM) {
915 		ret = ttm_tt_create(bo, true);
916 		if (ret)
917 			return ret;
918 	}
919 	return 0;
920 }
921 EXPORT_SYMBOL(ttm_bo_validate);
922 
923 /**
924  * ttm_bo_init_reserved
925  *
926  * @bdev: Pointer to a ttm_device struct.
927  * @bo: Pointer to a ttm_buffer_object to be initialized.
928  * @type: Requested type of buffer object.
929  * @placement: Initial placement for buffer object.
930  * @alignment: Data alignment in pages.
931  * @ctx: TTM operation context for memory allocation.
932  * @sg: Scatter-gather table.
933  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
934  * @destroy: Destroy function. Use NULL for kfree().
935  *
936  * This function initializes a pre-allocated struct ttm_buffer_object.
937  * As this object may be part of a larger structure, this function,
938  * together with the @destroy function, enables driver-specific objects
939  * derived from a ttm_buffer_object.
940  *
941  * On successful return, the caller owns an object kref to @bo. The kref and
942  * list_kref are usually set to 1, but note that in some situations, other
943  * tasks may already be holding references to @bo as well.
944  * Furthermore, if resv == NULL, the buffer's reservation lock will be held,
945  * and it is the caller's responsibility to call ttm_bo_unreserve.
946  *
947  * If a failure occurs, the function will call the @destroy function. Thus,
948  * after a failure, dereferencing @bo is illegal and will likely cause memory
949  * corruption.
950  *
951  * Returns
952  * -ENOMEM: Out of memory.
953  * -EINVAL: Invalid placement flags.
954  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
955  */
956 int ttm_bo_init_reserved(struct ttm_device *bdev, struct ttm_buffer_object *bo,
957 			 enum ttm_bo_type type, struct ttm_placement *placement,
958 			 uint32_t alignment, struct ttm_operation_ctx *ctx,
959 			 struct sg_table *sg, struct dma_resv *resv,
960 			 void (*destroy) (struct ttm_buffer_object *))
961 {
962 	int ret;
963 
964 	kref_init(&bo->kref);
965 	bo->bdev = bdev;
966 	bo->type = type;
967 	bo->page_alignment = alignment;
968 	bo->destroy = destroy;
969 	bo->pin_count = 0;
970 	bo->sg = sg;
971 	bo->bulk_move = NULL;
972 	if (resv)
973 		bo->base.resv = resv;
974 	else
975 		bo->base.resv = &bo->base._resv;
976 	atomic_inc(&ttm_glob.bo_count);
977 
978 	/*
979 	 * For ttm_bo_type_device buffers, allocate
980 	 * address space from the device.
981 	 */
982 	if (bo->type == ttm_bo_type_device || bo->type == ttm_bo_type_sg) {
983 		ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
984 					 PFN_UP(bo->base.size));
985 		if (ret)
986 			goto err_put;
987 	}
988 
989 	/* passed reservation objects should already be locked,
990 	 * since otherwise lockdep will be angered in radeon.
991 	 */
992 	if (!resv)
993 		WARN_ON(!dma_resv_trylock(bo->base.resv));
994 	else
995 		dma_resv_assert_held(resv);
996 
997 	ret = ttm_bo_validate(bo, placement, ctx);
998 	if (unlikely(ret))
999 		goto err_unlock;
1000 
1001 	return 0;
1002 
1003 err_unlock:
1004 	if (!resv)
1005 		dma_resv_unlock(bo->base.resv);
1006 
1007 err_put:
1008 	ttm_bo_put(bo);
1009 	return ret;
1010 }
1011 EXPORT_SYMBOL(ttm_bo_init_reserved);
1012 
1013 /**
1014  * ttm_bo_init_validate
1015  *
1016  * @bdev: Pointer to a ttm_device struct.
1017  * @bo: Pointer to a ttm_buffer_object to be initialized.
1018  * @type: Requested type of buffer object.
1019  * @placement: Initial placement for buffer object.
1020  * @alignment: Data alignment in pages.
1021  * @interruptible: If needing to sleep to wait for GPU resources,
1022  * sleep interruptible.
1023  * pinned in physical memory. If this behaviour is not desired, this member
1024  * holds a pointer to a persistent shmem object. Typically, this would
1025  * point to the shmem object backing a GEM object if TTM is used to back a
1026  * GEM user interface.
1027  * @sg: Scatter-gather table.
1028  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
1029  * @destroy: Destroy function. Use NULL for kfree().
1030  *
1031  * This function initializes a pre-allocated struct ttm_buffer_object.
1032  * As this object may be part of a larger structure, this function,
1033  * together with the @destroy function,
1034  * enables driver-specific objects derived from a ttm_buffer_object.
1035  *
1036  * On successful return, the caller owns an object kref to @bo. The kref and
1037  * list_kref are usually set to 1, but note that in some situations, other
1038  * tasks may already be holding references to @bo as well.
1039  *
1040  * If a failure occurs, the function will call the @destroy function, Thus,
1041  * after a failure, dereferencing @bo is illegal and will likely cause memory
1042  * corruption.
1043  *
1044  * Returns
1045  * -ENOMEM: Out of memory.
1046  * -EINVAL: Invalid placement flags.
1047  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
1048  */
1049 int ttm_bo_init_validate(struct ttm_device *bdev, struct ttm_buffer_object *bo,
1050 			 enum ttm_bo_type type, struct ttm_placement *placement,
1051 			 uint32_t alignment, bool interruptible,
1052 			 struct sg_table *sg, struct dma_resv *resv,
1053 			 void (*destroy) (struct ttm_buffer_object *))
1054 {
1055 	struct ttm_operation_ctx ctx = { interruptible, false };
1056 	int ret;
1057 
1058 	ret = ttm_bo_init_reserved(bdev, bo, type, placement, alignment, &ctx,
1059 				   sg, resv, destroy);
1060 	if (ret)
1061 		return ret;
1062 
1063 	if (!resv)
1064 		ttm_bo_unreserve(bo);
1065 
1066 	return 0;
1067 }
1068 EXPORT_SYMBOL(ttm_bo_init_validate);
1069 
1070 /*
1071  * buffer object vm functions.
1072  */
1073 
1074 /**
1075  * ttm_bo_unmap_virtual
1076  *
1077  * @bo: tear down the virtual mappings for this BO
1078  */
1079 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1080 {
1081 	struct ttm_device *bdev = bo->bdev;
1082 
1083 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1084 	ttm_mem_io_free(bdev, bo->resource);
1085 }
1086 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1087 
1088 /**
1089  * ttm_bo_wait_ctx - wait for buffer idle.
1090  *
1091  * @bo:  The buffer object.
1092  * @ctx: defines how to wait
1093  *
1094  * Waits for the buffer to be idle. Used timeout depends on the context.
1095  * Returns -EBUSY if wait timed outt, -ERESTARTSYS if interrupted by a signal or
1096  * zero on success.
1097  */
1098 int ttm_bo_wait_ctx(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx)
1099 {
1100 	long ret;
1101 
1102 	if (ctx->no_wait_gpu) {
1103 		if (dma_resv_test_signaled(bo->base.resv,
1104 					   DMA_RESV_USAGE_BOOKKEEP))
1105 			return 0;
1106 		else
1107 			return -EBUSY;
1108 	}
1109 
1110 	ret = dma_resv_wait_timeout(bo->base.resv, DMA_RESV_USAGE_BOOKKEEP,
1111 				    ctx->interruptible, 15 * HZ);
1112 	if (unlikely(ret < 0))
1113 		return ret;
1114 	if (unlikely(ret == 0))
1115 		return -EBUSY;
1116 	return 0;
1117 }
1118 EXPORT_SYMBOL(ttm_bo_wait_ctx);
1119 
1120 int ttm_bo_swapout(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx,
1121 		   gfp_t gfp_flags)
1122 {
1123 	struct ttm_place place;
1124 	bool locked;
1125 	long ret;
1126 
1127 	/*
1128 	 * While the bo may already reside in SYSTEM placement, set
1129 	 * SYSTEM as new placement to cover also the move further below.
1130 	 * The driver may use the fact that we're moving from SYSTEM
1131 	 * as an indication that we're about to swap out.
1132 	 */
1133 	memset(&place, 0, sizeof(place));
1134 	place.mem_type = bo->resource->mem_type;
1135 	if (!ttm_bo_evict_swapout_allowable(bo, ctx, &place, &locked, NULL))
1136 		return -EBUSY;
1137 
1138 	if (!bo->ttm || !ttm_tt_is_populated(bo->ttm) ||
1139 	    bo->ttm->page_flags & TTM_TT_FLAG_EXTERNAL ||
1140 	    bo->ttm->page_flags & TTM_TT_FLAG_SWAPPED ||
1141 	    !ttm_bo_get_unless_zero(bo)) {
1142 		if (locked)
1143 			dma_resv_unlock(bo->base.resv);
1144 		return -EBUSY;
1145 	}
1146 
1147 	if (bo->deleted) {
1148 		ret = ttm_bo_cleanup_refs(bo, false, false, locked);
1149 		ttm_bo_put(bo);
1150 		return ret == -EBUSY ? -ENOSPC : ret;
1151 	}
1152 
1153 	/* TODO: Cleanup the locking */
1154 	spin_unlock(&bo->bdev->lru_lock);
1155 
1156 	/*
1157 	 * Move to system cached
1158 	 */
1159 	if (bo->resource->mem_type != TTM_PL_SYSTEM) {
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 			ttm_resource_free(bo, &evict_mem);
1173 			goto out;
1174 		}
1175 	}
1176 
1177 	/*
1178 	 * Make sure BO is idle.
1179 	 */
1180 	ret = ttm_bo_wait_ctx(bo, ctx);
1181 	if (unlikely(ret != 0))
1182 		goto out;
1183 
1184 	ttm_bo_unmap_virtual(bo);
1185 
1186 	/*
1187 	 * Swap out. Buffer will be swapped in again as soon as
1188 	 * anyone tries to access a ttm page.
1189 	 */
1190 	if (bo->bdev->funcs->swap_notify)
1191 		bo->bdev->funcs->swap_notify(bo);
1192 
1193 	if (ttm_tt_is_populated(bo->ttm))
1194 		ret = ttm_tt_swapout(bo->bdev, bo->ttm, gfp_flags);
1195 out:
1196 
1197 	/*
1198 	 * Unreserve without putting on LRU to avoid swapping out an
1199 	 * already swapped buffer.
1200 	 */
1201 	if (locked)
1202 		dma_resv_unlock(bo->base.resv);
1203 	ttm_bo_put(bo);
1204 	return ret == -EBUSY ? -ENOSPC : ret;
1205 }
1206 
1207 void ttm_bo_tt_destroy(struct ttm_buffer_object *bo)
1208 {
1209 	if (bo->ttm == NULL)
1210 		return;
1211 
1212 	ttm_tt_unpopulate(bo->bdev, bo->ttm);
1213 	ttm_tt_destroy(bo->bdev, bo->ttm);
1214 	bo->ttm = NULL;
1215 }
1216