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