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