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