xref: /openbmc/linux/drivers/gpu/drm/ttm/ttm_bo.c (revision 8b0d47e8)
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_module.h>
35 #include <drm/ttm/ttm_bo_driver.h>
36 #include <drm/ttm/ttm_placement.h>
37 #include <linux/jiffies.h>
38 #include <linux/slab.h>
39 #include <linux/sched.h>
40 #include <linux/mm.h>
41 #include <linux/file.h>
42 #include <linux/module.h>
43 #include <linux/atomic.h>
44 #include <linux/dma-resv.h>
45 
46 static void ttm_bo_global_kobj_release(struct kobject *kobj);
47 
48 /**
49  * ttm_global_mutex - protecting the global BO state
50  */
51 DEFINE_MUTEX(ttm_global_mutex);
52 unsigned ttm_bo_glob_use_count;
53 struct ttm_bo_global ttm_bo_glob;
54 EXPORT_SYMBOL(ttm_bo_glob);
55 
56 static struct attribute ttm_bo_count = {
57 	.name = "bo_count",
58 	.mode = S_IRUGO
59 };
60 
61 /* default destructor */
62 static void ttm_bo_default_destroy(struct ttm_buffer_object *bo)
63 {
64 	kfree(bo);
65 }
66 
67 static inline int ttm_mem_type_from_place(const struct ttm_place *place,
68 					  uint32_t *mem_type)
69 {
70 	int pos;
71 
72 	pos = ffs(place->flags & TTM_PL_MASK_MEM);
73 	if (unlikely(!pos))
74 		return -EINVAL;
75 
76 	*mem_type = pos - 1;
77 	return 0;
78 }
79 
80 void ttm_resource_manager_debug(struct ttm_resource_manager *man,
81 				struct drm_printer *p)
82 {
83 	drm_printf(p, "    use_type: %d\n", man->use_type);
84 	drm_printf(p, "    use_tt: %d\n", man->use_tt);
85 	drm_printf(p, "    size: %llu\n", man->size);
86 	drm_printf(p, "    available_caching: 0x%08X\n", man->available_caching);
87 	drm_printf(p, "    default_caching: 0x%08X\n", man->default_caching);
88 	if (man->func && man->func->debug)
89 		(*man->func->debug)(man, p);
90 }
91 EXPORT_SYMBOL(ttm_resource_manager_debug);
92 
93 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
94 					struct ttm_placement *placement)
95 {
96 	struct drm_printer p = drm_debug_printer(TTM_PFX);
97 	int i, ret, mem_type;
98 	struct ttm_resource_manager *man;
99 
100 	drm_printf(&p, "No space for %p (%lu pages, %luK, %luM)\n",
101 		   bo, bo->mem.num_pages, bo->mem.size >> 10,
102 		   bo->mem.size >> 20);
103 	for (i = 0; i < placement->num_placement; i++) {
104 		ret = ttm_mem_type_from_place(&placement->placement[i],
105 						&mem_type);
106 		if (ret)
107 			return;
108 		drm_printf(&p, "  placement[%d]=0x%08X (%d)\n",
109 			   i, placement->placement[i].flags, mem_type);
110 		man = ttm_manager_type(bo->bdev, mem_type);
111 		ttm_resource_manager_debug(man, &p);
112 	}
113 }
114 
115 static ssize_t ttm_bo_global_show(struct kobject *kobj,
116 				  struct attribute *attr,
117 				  char *buffer)
118 {
119 	struct ttm_bo_global *glob =
120 		container_of(kobj, struct ttm_bo_global, kobj);
121 
122 	return snprintf(buffer, PAGE_SIZE, "%d\n",
123 				atomic_read(&glob->bo_count));
124 }
125 
126 static struct attribute *ttm_bo_global_attrs[] = {
127 	&ttm_bo_count,
128 	NULL
129 };
130 
131 static const struct sysfs_ops ttm_bo_global_ops = {
132 	.show = &ttm_bo_global_show
133 };
134 
135 static struct kobj_type ttm_bo_glob_kobj_type  = {
136 	.release = &ttm_bo_global_kobj_release,
137 	.sysfs_ops = &ttm_bo_global_ops,
138 	.default_attrs = ttm_bo_global_attrs
139 };
140 
141 
142 static inline uint32_t ttm_bo_type_flags(unsigned type)
143 {
144 	return 1 << (type);
145 }
146 
147 static void ttm_bo_add_mem_to_lru(struct ttm_buffer_object *bo,
148 				  struct ttm_resource *mem)
149 {
150 	struct ttm_bo_device *bdev = bo->bdev;
151 	struct ttm_resource_manager *man;
152 
153 	if (!list_empty(&bo->lru))
154 		return;
155 
156 	if (mem->placement & TTM_PL_FLAG_NO_EVICT)
157 		return;
158 
159 	man = ttm_manager_type(bdev, mem->mem_type);
160 	list_add_tail(&bo->lru, &man->lru[bo->priority]);
161 
162 	if (man->use_tt && bo->ttm &&
163 	    !(bo->ttm->page_flags & (TTM_PAGE_FLAG_SG |
164 				     TTM_PAGE_FLAG_SWAPPED))) {
165 		list_add_tail(&bo->swap, &ttm_bo_glob.swap_lru[bo->priority]);
166 	}
167 }
168 
169 static void ttm_bo_del_from_lru(struct ttm_buffer_object *bo)
170 {
171 	struct ttm_bo_device *bdev = bo->bdev;
172 	bool notify = false;
173 
174 	if (!list_empty(&bo->swap)) {
175 		list_del_init(&bo->swap);
176 		notify = true;
177 	}
178 	if (!list_empty(&bo->lru)) {
179 		list_del_init(&bo->lru);
180 		notify = true;
181 	}
182 
183 	if (notify && bdev->driver->del_from_lru_notify)
184 		bdev->driver->del_from_lru_notify(bo);
185 }
186 
187 static void ttm_bo_bulk_move_set_pos(struct ttm_lru_bulk_move_pos *pos,
188 				     struct ttm_buffer_object *bo)
189 {
190 	if (!pos->first)
191 		pos->first = bo;
192 	pos->last = bo;
193 }
194 
195 void ttm_bo_move_to_lru_tail(struct ttm_buffer_object *bo,
196 			     struct ttm_lru_bulk_move *bulk)
197 {
198 	dma_resv_assert_held(bo->base.resv);
199 
200 	ttm_bo_del_from_lru(bo);
201 	ttm_bo_add_mem_to_lru(bo, &bo->mem);
202 
203 	if (bulk && !(bo->mem.placement & TTM_PL_FLAG_NO_EVICT)) {
204 		switch (bo->mem.mem_type) {
205 		case TTM_PL_TT:
206 			ttm_bo_bulk_move_set_pos(&bulk->tt[bo->priority], bo);
207 			break;
208 
209 		case TTM_PL_VRAM:
210 			ttm_bo_bulk_move_set_pos(&bulk->vram[bo->priority], bo);
211 			break;
212 		}
213 		if (bo->ttm && !(bo->ttm->page_flags &
214 				 (TTM_PAGE_FLAG_SG | TTM_PAGE_FLAG_SWAPPED)))
215 			ttm_bo_bulk_move_set_pos(&bulk->swap[bo->priority], bo);
216 	}
217 }
218 EXPORT_SYMBOL(ttm_bo_move_to_lru_tail);
219 
220 void ttm_bo_bulk_move_lru_tail(struct ttm_lru_bulk_move *bulk)
221 {
222 	unsigned i;
223 
224 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
225 		struct ttm_lru_bulk_move_pos *pos = &bulk->tt[i];
226 		struct ttm_resource_manager *man;
227 
228 		if (!pos->first)
229 			continue;
230 
231 		dma_resv_assert_held(pos->first->base.resv);
232 		dma_resv_assert_held(pos->last->base.resv);
233 
234 		man = ttm_manager_type(pos->first->bdev, TTM_PL_TT);
235 		list_bulk_move_tail(&man->lru[i], &pos->first->lru,
236 				    &pos->last->lru);
237 	}
238 
239 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
240 		struct ttm_lru_bulk_move_pos *pos = &bulk->vram[i];
241 		struct ttm_resource_manager *man;
242 
243 		if (!pos->first)
244 			continue;
245 
246 		dma_resv_assert_held(pos->first->base.resv);
247 		dma_resv_assert_held(pos->last->base.resv);
248 
249 		man = ttm_manager_type(pos->first->bdev, TTM_PL_VRAM);
250 		list_bulk_move_tail(&man->lru[i], &pos->first->lru,
251 				    &pos->last->lru);
252 	}
253 
254 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
255 		struct ttm_lru_bulk_move_pos *pos = &bulk->swap[i];
256 		struct list_head *lru;
257 
258 		if (!pos->first)
259 			continue;
260 
261 		dma_resv_assert_held(pos->first->base.resv);
262 		dma_resv_assert_held(pos->last->base.resv);
263 
264 		lru = &ttm_bo_glob.swap_lru[i];
265 		list_bulk_move_tail(lru, &pos->first->swap, &pos->last->swap);
266 	}
267 }
268 EXPORT_SYMBOL(ttm_bo_bulk_move_lru_tail);
269 
270 static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo,
271 				  struct ttm_resource *mem, bool evict,
272 				  struct ttm_operation_ctx *ctx)
273 {
274 	struct ttm_bo_device *bdev = bo->bdev;
275 	struct ttm_resource_manager *old_man = ttm_manager_type(bdev, bo->mem.mem_type);
276 	struct ttm_resource_manager *new_man = ttm_manager_type(bdev, mem->mem_type);
277 	int ret;
278 
279 	ret = ttm_mem_io_lock(old_man, true);
280 	if (unlikely(ret != 0))
281 		goto out_err;
282 	ttm_bo_unmap_virtual_locked(bo);
283 	ttm_mem_io_unlock(old_man);
284 
285 	/*
286 	 * Create and bind a ttm if required.
287 	 */
288 
289 	if (new_man->use_tt) {
290 		/* Zero init the new TTM structure if the old location should
291 		 * have used one as well.
292 		 */
293 		ret = ttm_tt_create(bo, old_man->use_tt);
294 		if (ret)
295 			goto out_err;
296 
297 		ret = ttm_tt_set_placement_caching(bo->ttm, mem->placement);
298 		if (ret)
299 			goto out_err;
300 
301 		if (mem->mem_type != TTM_PL_SYSTEM) {
302 			ret = ttm_tt_bind(bo->ttm, mem, ctx);
303 			if (ret)
304 				goto out_err;
305 		}
306 
307 		if (bo->mem.mem_type == TTM_PL_SYSTEM) {
308 			if (bdev->driver->move_notify)
309 				bdev->driver->move_notify(bo, evict, mem);
310 			bo->mem = *mem;
311 			goto moved;
312 		}
313 	}
314 
315 	if (bdev->driver->move_notify)
316 		bdev->driver->move_notify(bo, evict, mem);
317 
318 	if (old_man->use_tt && new_man->use_tt)
319 		ret = ttm_bo_move_ttm(bo, ctx, mem);
320 	else if (bdev->driver->move)
321 		ret = bdev->driver->move(bo, evict, ctx, mem);
322 	else
323 		ret = ttm_bo_move_memcpy(bo, ctx, mem);
324 
325 	if (ret) {
326 		if (bdev->driver->move_notify) {
327 			swap(*mem, bo->mem);
328 			bdev->driver->move_notify(bo, false, mem);
329 			swap(*mem, bo->mem);
330 		}
331 
332 		goto out_err;
333 	}
334 
335 moved:
336 	bo->evicted = false;
337 
338 	ctx->bytes_moved += bo->num_pages << PAGE_SHIFT;
339 	return 0;
340 
341 out_err:
342 	new_man = ttm_manager_type(bdev, bo->mem.mem_type);
343 	if (!new_man->use_tt) {
344 		ttm_tt_destroy(bo->ttm);
345 		bo->ttm = NULL;
346 	}
347 
348 	return ret;
349 }
350 
351 /**
352  * Call bo::reserved.
353  * Will release GPU memory type usage on destruction.
354  * This is the place to put in driver specific hooks to release
355  * driver private resources.
356  * Will release the bo::reserved lock.
357  */
358 
359 static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo)
360 {
361 	if (bo->bdev->driver->move_notify)
362 		bo->bdev->driver->move_notify(bo, false, NULL);
363 
364 	ttm_tt_destroy(bo->ttm);
365 	bo->ttm = NULL;
366 	ttm_bo_mem_put(bo, &bo->mem);
367 }
368 
369 static int ttm_bo_individualize_resv(struct ttm_buffer_object *bo)
370 {
371 	int r;
372 
373 	if (bo->base.resv == &bo->base._resv)
374 		return 0;
375 
376 	BUG_ON(!dma_resv_trylock(&bo->base._resv));
377 
378 	r = dma_resv_copy_fences(&bo->base._resv, bo->base.resv);
379 	dma_resv_unlock(&bo->base._resv);
380 	if (r)
381 		return r;
382 
383 	if (bo->type != ttm_bo_type_sg) {
384 		/* This works because the BO is about to be destroyed and nobody
385 		 * reference it any more. The only tricky case is the trylock on
386 		 * the resv object while holding the lru_lock.
387 		 */
388 		spin_lock(&ttm_bo_glob.lru_lock);
389 		bo->base.resv = &bo->base._resv;
390 		spin_unlock(&ttm_bo_glob.lru_lock);
391 	}
392 
393 	return r;
394 }
395 
396 static void ttm_bo_flush_all_fences(struct ttm_buffer_object *bo)
397 {
398 	struct dma_resv *resv = &bo->base._resv;
399 	struct dma_resv_list *fobj;
400 	struct dma_fence *fence;
401 	int i;
402 
403 	rcu_read_lock();
404 	fobj = rcu_dereference(resv->fence);
405 	fence = rcu_dereference(resv->fence_excl);
406 	if (fence && !fence->ops->signaled)
407 		dma_fence_enable_sw_signaling(fence);
408 
409 	for (i = 0; fobj && i < fobj->shared_count; ++i) {
410 		fence = rcu_dereference(fobj->shared[i]);
411 
412 		if (!fence->ops->signaled)
413 			dma_fence_enable_sw_signaling(fence);
414 	}
415 	rcu_read_unlock();
416 }
417 
418 /**
419  * function ttm_bo_cleanup_refs
420  * If bo idle, remove from lru lists, and unref.
421  * If not idle, block if possible.
422  *
423  * Must be called with lru_lock and reservation held, this function
424  * will drop the lru lock and optionally the reservation lock before returning.
425  *
426  * @interruptible         Any sleeps should occur interruptibly.
427  * @no_wait_gpu           Never wait for gpu. Return -EBUSY instead.
428  * @unlock_resv           Unlock the reservation lock as well.
429  */
430 
431 static int ttm_bo_cleanup_refs(struct ttm_buffer_object *bo,
432 			       bool interruptible, bool no_wait_gpu,
433 			       bool unlock_resv)
434 {
435 	struct dma_resv *resv = &bo->base._resv;
436 	int ret;
437 
438 	if (dma_resv_test_signaled_rcu(resv, true))
439 		ret = 0;
440 	else
441 		ret = -EBUSY;
442 
443 	if (ret && !no_wait_gpu) {
444 		long lret;
445 
446 		if (unlock_resv)
447 			dma_resv_unlock(bo->base.resv);
448 		spin_unlock(&ttm_bo_glob.lru_lock);
449 
450 		lret = dma_resv_wait_timeout_rcu(resv, true, interruptible,
451 						 30 * HZ);
452 
453 		if (lret < 0)
454 			return lret;
455 		else if (lret == 0)
456 			return -EBUSY;
457 
458 		spin_lock(&ttm_bo_glob.lru_lock);
459 		if (unlock_resv && !dma_resv_trylock(bo->base.resv)) {
460 			/*
461 			 * We raced, and lost, someone else holds the reservation now,
462 			 * and is probably busy in ttm_bo_cleanup_memtype_use.
463 			 *
464 			 * Even if it's not the case, because we finished waiting any
465 			 * delayed destruction would succeed, so just return success
466 			 * here.
467 			 */
468 			spin_unlock(&ttm_bo_glob.lru_lock);
469 			return 0;
470 		}
471 		ret = 0;
472 	}
473 
474 	if (ret || unlikely(list_empty(&bo->ddestroy))) {
475 		if (unlock_resv)
476 			dma_resv_unlock(bo->base.resv);
477 		spin_unlock(&ttm_bo_glob.lru_lock);
478 		return ret;
479 	}
480 
481 	ttm_bo_del_from_lru(bo);
482 	list_del_init(&bo->ddestroy);
483 	spin_unlock(&ttm_bo_glob.lru_lock);
484 	ttm_bo_cleanup_memtype_use(bo);
485 
486 	if (unlock_resv)
487 		dma_resv_unlock(bo->base.resv);
488 
489 	ttm_bo_put(bo);
490 
491 	return 0;
492 }
493 
494 /**
495  * Traverse the delayed list, and call ttm_bo_cleanup_refs on all
496  * encountered buffers.
497  */
498 static bool ttm_bo_delayed_delete(struct ttm_bo_device *bdev, bool remove_all)
499 {
500 	struct ttm_bo_global *glob = &ttm_bo_glob;
501 	struct list_head removed;
502 	bool empty;
503 
504 	INIT_LIST_HEAD(&removed);
505 
506 	spin_lock(&glob->lru_lock);
507 	while (!list_empty(&bdev->ddestroy)) {
508 		struct ttm_buffer_object *bo;
509 
510 		bo = list_first_entry(&bdev->ddestroy, struct ttm_buffer_object,
511 				      ddestroy);
512 		list_move_tail(&bo->ddestroy, &removed);
513 		if (!ttm_bo_get_unless_zero(bo))
514 			continue;
515 
516 		if (remove_all || bo->base.resv != &bo->base._resv) {
517 			spin_unlock(&glob->lru_lock);
518 			dma_resv_lock(bo->base.resv, NULL);
519 
520 			spin_lock(&glob->lru_lock);
521 			ttm_bo_cleanup_refs(bo, false, !remove_all, true);
522 
523 		} else if (dma_resv_trylock(bo->base.resv)) {
524 			ttm_bo_cleanup_refs(bo, false, !remove_all, true);
525 		} else {
526 			spin_unlock(&glob->lru_lock);
527 		}
528 
529 		ttm_bo_put(bo);
530 		spin_lock(&glob->lru_lock);
531 	}
532 	list_splice_tail(&removed, &bdev->ddestroy);
533 	empty = list_empty(&bdev->ddestroy);
534 	spin_unlock(&glob->lru_lock);
535 
536 	return empty;
537 }
538 
539 static void ttm_bo_delayed_workqueue(struct work_struct *work)
540 {
541 	struct ttm_bo_device *bdev =
542 	    container_of(work, struct ttm_bo_device, wq.work);
543 
544 	if (!ttm_bo_delayed_delete(bdev, false))
545 		schedule_delayed_work(&bdev->wq,
546 				      ((HZ / 100) < 1) ? 1 : HZ / 100);
547 }
548 
549 static void ttm_bo_release(struct kref *kref)
550 {
551 	struct ttm_buffer_object *bo =
552 	    container_of(kref, struct ttm_buffer_object, kref);
553 	struct ttm_bo_device *bdev = bo->bdev;
554 	struct ttm_resource_manager *man = ttm_manager_type(bdev, bo->mem.mem_type);
555 	size_t acc_size = bo->acc_size;
556 	int ret;
557 
558 	if (!bo->deleted) {
559 		ret = ttm_bo_individualize_resv(bo);
560 		if (ret) {
561 			/* Last resort, if we fail to allocate memory for the
562 			 * fences block for the BO to become idle
563 			 */
564 			dma_resv_wait_timeout_rcu(bo->base.resv, true, false,
565 						  30 * HZ);
566 		}
567 
568 		if (bo->bdev->driver->release_notify)
569 			bo->bdev->driver->release_notify(bo);
570 
571 		drm_vma_offset_remove(bdev->vma_manager, &bo->base.vma_node);
572 		ttm_mem_io_lock(man, false);
573 		ttm_mem_io_free_vm(bo);
574 		ttm_mem_io_unlock(man);
575 	}
576 
577 	if (!dma_resv_test_signaled_rcu(bo->base.resv, true) ||
578 	    !dma_resv_trylock(bo->base.resv)) {
579 		/* The BO is not idle, resurrect it for delayed destroy */
580 		ttm_bo_flush_all_fences(bo);
581 		bo->deleted = true;
582 
583 		spin_lock(&ttm_bo_glob.lru_lock);
584 
585 		/*
586 		 * Make NO_EVICT bos immediately available to
587 		 * shrinkers, now that they are queued for
588 		 * destruction.
589 		 */
590 		if (bo->mem.placement & TTM_PL_FLAG_NO_EVICT) {
591 			bo->mem.placement &= ~TTM_PL_FLAG_NO_EVICT;
592 			ttm_bo_del_from_lru(bo);
593 			ttm_bo_add_mem_to_lru(bo, &bo->mem);
594 		}
595 
596 		kref_init(&bo->kref);
597 		list_add_tail(&bo->ddestroy, &bdev->ddestroy);
598 		spin_unlock(&ttm_bo_glob.lru_lock);
599 
600 		schedule_delayed_work(&bdev->wq,
601 				      ((HZ / 100) < 1) ? 1 : HZ / 100);
602 		return;
603 	}
604 
605 	spin_lock(&ttm_bo_glob.lru_lock);
606 	ttm_bo_del_from_lru(bo);
607 	list_del(&bo->ddestroy);
608 	spin_unlock(&ttm_bo_glob.lru_lock);
609 
610 	ttm_bo_cleanup_memtype_use(bo);
611 	dma_resv_unlock(bo->base.resv);
612 
613 	atomic_dec(&ttm_bo_glob.bo_count);
614 	dma_fence_put(bo->moving);
615 	if (!ttm_bo_uses_embedded_gem_object(bo))
616 		dma_resv_fini(&bo->base._resv);
617 	bo->destroy(bo);
618 	ttm_mem_global_free(&ttm_mem_glob, acc_size);
619 }
620 
621 void ttm_bo_put(struct ttm_buffer_object *bo)
622 {
623 	kref_put(&bo->kref, ttm_bo_release);
624 }
625 EXPORT_SYMBOL(ttm_bo_put);
626 
627 int ttm_bo_lock_delayed_workqueue(struct ttm_bo_device *bdev)
628 {
629 	return cancel_delayed_work_sync(&bdev->wq);
630 }
631 EXPORT_SYMBOL(ttm_bo_lock_delayed_workqueue);
632 
633 void ttm_bo_unlock_delayed_workqueue(struct ttm_bo_device *bdev, int resched)
634 {
635 	if (resched)
636 		schedule_delayed_work(&bdev->wq,
637 				      ((HZ / 100) < 1) ? 1 : HZ / 100);
638 }
639 EXPORT_SYMBOL(ttm_bo_unlock_delayed_workqueue);
640 
641 static int ttm_bo_evict(struct ttm_buffer_object *bo,
642 			struct ttm_operation_ctx *ctx)
643 {
644 	struct ttm_bo_device *bdev = bo->bdev;
645 	struct ttm_resource evict_mem;
646 	struct ttm_placement placement;
647 	int ret = 0;
648 
649 	dma_resv_assert_held(bo->base.resv);
650 
651 	placement.num_placement = 0;
652 	placement.num_busy_placement = 0;
653 	bdev->driver->evict_flags(bo, &placement);
654 
655 	if (!placement.num_placement && !placement.num_busy_placement) {
656 		ttm_bo_wait(bo, false, false);
657 
658 		ttm_bo_cleanup_memtype_use(bo);
659 		return 0;
660 	}
661 
662 	evict_mem = bo->mem;
663 	evict_mem.mm_node = NULL;
664 	evict_mem.bus.io_reserved_vm = false;
665 	evict_mem.bus.io_reserved_count = 0;
666 
667 	ret = ttm_bo_mem_space(bo, &placement, &evict_mem, ctx);
668 	if (ret) {
669 		if (ret != -ERESTARTSYS) {
670 			pr_err("Failed to find memory space for buffer 0x%p eviction\n",
671 			       bo);
672 			ttm_bo_mem_space_debug(bo, &placement);
673 		}
674 		goto out;
675 	}
676 
677 	ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, ctx);
678 	if (unlikely(ret)) {
679 		if (ret != -ERESTARTSYS)
680 			pr_err("Buffer eviction failed\n");
681 		ttm_bo_mem_put(bo, &evict_mem);
682 		goto out;
683 	}
684 	bo->evicted = true;
685 out:
686 	return ret;
687 }
688 
689 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
690 			      const struct ttm_place *place)
691 {
692 	/* Don't evict this BO if it's outside of the
693 	 * requested placement range
694 	 */
695 	if (place->fpfn >= (bo->mem.start + bo->mem.size) ||
696 	    (place->lpfn && place->lpfn <= bo->mem.start))
697 		return false;
698 
699 	return true;
700 }
701 EXPORT_SYMBOL(ttm_bo_eviction_valuable);
702 
703 /**
704  * Check the target bo is allowable to be evicted or swapout, including cases:
705  *
706  * a. if share same reservation object with ctx->resv, have assumption
707  * reservation objects should already be locked, so not lock again and
708  * return true directly when either the opreation allow_reserved_eviction
709  * or the target bo already is in delayed free list;
710  *
711  * b. Otherwise, trylock it.
712  */
713 static bool ttm_bo_evict_swapout_allowable(struct ttm_buffer_object *bo,
714 			struct ttm_operation_ctx *ctx, bool *locked, bool *busy)
715 {
716 	bool ret = false;
717 
718 	if (bo->base.resv == ctx->resv) {
719 		dma_resv_assert_held(bo->base.resv);
720 		if (ctx->flags & TTM_OPT_FLAG_ALLOW_RES_EVICT)
721 			ret = true;
722 		*locked = false;
723 		if (busy)
724 			*busy = false;
725 	} else {
726 		ret = dma_resv_trylock(bo->base.resv);
727 		*locked = ret;
728 		if (busy)
729 			*busy = !ret;
730 	}
731 
732 	return ret;
733 }
734 
735 /**
736  * ttm_mem_evict_wait_busy - wait for a busy BO to become available
737  *
738  * @busy_bo: BO which couldn't be locked with trylock
739  * @ctx: operation context
740  * @ticket: acquire ticket
741  *
742  * Try to lock a busy buffer object to avoid failing eviction.
743  */
744 static int ttm_mem_evict_wait_busy(struct ttm_buffer_object *busy_bo,
745 				   struct ttm_operation_ctx *ctx,
746 				   struct ww_acquire_ctx *ticket)
747 {
748 	int r;
749 
750 	if (!busy_bo || !ticket)
751 		return -EBUSY;
752 
753 	if (ctx->interruptible)
754 		r = dma_resv_lock_interruptible(busy_bo->base.resv,
755 							  ticket);
756 	else
757 		r = dma_resv_lock(busy_bo->base.resv, ticket);
758 
759 	/*
760 	 * TODO: It would be better to keep the BO locked until allocation is at
761 	 * least tried one more time, but that would mean a much larger rework
762 	 * of TTM.
763 	 */
764 	if (!r)
765 		dma_resv_unlock(busy_bo->base.resv);
766 
767 	return r == -EDEADLK ? -EBUSY : r;
768 }
769 
770 static int ttm_mem_evict_first(struct ttm_bo_device *bdev,
771 			       struct ttm_resource_manager *man,
772 			       const struct ttm_place *place,
773 			       struct ttm_operation_ctx *ctx,
774 			       struct ww_acquire_ctx *ticket)
775 {
776 	struct ttm_buffer_object *bo = NULL, *busy_bo = NULL;
777 	bool locked = false;
778 	unsigned i;
779 	int ret;
780 
781 	spin_lock(&ttm_bo_glob.lru_lock);
782 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
783 		list_for_each_entry(bo, &man->lru[i], lru) {
784 			bool busy;
785 
786 			if (!ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
787 							    &busy)) {
788 				if (busy && !busy_bo && ticket !=
789 				    dma_resv_locking_ctx(bo->base.resv))
790 					busy_bo = bo;
791 				continue;
792 			}
793 
794 			if (place && !bdev->driver->eviction_valuable(bo,
795 								      place)) {
796 				if (locked)
797 					dma_resv_unlock(bo->base.resv);
798 				continue;
799 			}
800 			if (!ttm_bo_get_unless_zero(bo)) {
801 				if (locked)
802 					dma_resv_unlock(bo->base.resv);
803 				continue;
804 			}
805 			break;
806 		}
807 
808 		/* If the inner loop terminated early, we have our candidate */
809 		if (&bo->lru != &man->lru[i])
810 			break;
811 
812 		bo = NULL;
813 	}
814 
815 	if (!bo) {
816 		if (busy_bo && !ttm_bo_get_unless_zero(busy_bo))
817 			busy_bo = NULL;
818 		spin_unlock(&ttm_bo_glob.lru_lock);
819 		ret = ttm_mem_evict_wait_busy(busy_bo, ctx, ticket);
820 		if (busy_bo)
821 			ttm_bo_put(busy_bo);
822 		return ret;
823 	}
824 
825 	if (bo->deleted) {
826 		ret = ttm_bo_cleanup_refs(bo, ctx->interruptible,
827 					  ctx->no_wait_gpu, locked);
828 		ttm_bo_put(bo);
829 		return ret;
830 	}
831 
832 	spin_unlock(&ttm_bo_glob.lru_lock);
833 
834 	ret = ttm_bo_evict(bo, ctx);
835 	if (locked)
836 		ttm_bo_unreserve(bo);
837 
838 	ttm_bo_put(bo);
839 	return ret;
840 }
841 
842 static int ttm_bo_mem_get(struct ttm_buffer_object *bo,
843 			  const struct ttm_place *place,
844 			  struct ttm_resource *mem)
845 {
846 	struct ttm_resource_manager *man = ttm_manager_type(bo->bdev, mem->mem_type);
847 
848 	mem->mm_node = NULL;
849 	if (!man->func || !man->func->get_node)
850 		return 0;
851 
852 	return man->func->get_node(man, bo, place, mem);
853 }
854 
855 void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_resource *mem)
856 {
857 	struct ttm_resource_manager *man = ttm_manager_type(bo->bdev, mem->mem_type);
858 
859 	if (!man->func || !man->func->put_node)
860 		return;
861 
862 	man->func->put_node(man, mem);
863 	mem->mm_node = NULL;
864 	mem->mem_type = TTM_PL_SYSTEM;
865 }
866 EXPORT_SYMBOL(ttm_bo_mem_put);
867 
868 /**
869  * Add the last move fence to the BO and reserve a new shared slot.
870  */
871 static int ttm_bo_add_move_fence(struct ttm_buffer_object *bo,
872 				 struct ttm_resource_manager *man,
873 				 struct ttm_resource *mem,
874 				 bool no_wait_gpu)
875 {
876 	struct dma_fence *fence;
877 	int ret;
878 
879 	spin_lock(&man->move_lock);
880 	fence = dma_fence_get(man->move);
881 	spin_unlock(&man->move_lock);
882 
883 	if (!fence)
884 		return 0;
885 
886 	if (no_wait_gpu)
887 		return -EBUSY;
888 
889 	dma_resv_add_shared_fence(bo->base.resv, fence);
890 
891 	ret = dma_resv_reserve_shared(bo->base.resv, 1);
892 	if (unlikely(ret)) {
893 		dma_fence_put(fence);
894 		return ret;
895 	}
896 
897 	dma_fence_put(bo->moving);
898 	bo->moving = fence;
899 	return 0;
900 }
901 
902 /**
903  * Repeatedly evict memory from the LRU for @mem_type until we create enough
904  * space, or we've evicted everything and there isn't enough space.
905  */
906 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
907 				  const struct ttm_place *place,
908 				  struct ttm_resource *mem,
909 				  struct ttm_operation_ctx *ctx)
910 {
911 	struct ttm_bo_device *bdev = bo->bdev;
912 	struct ttm_resource_manager *man = ttm_manager_type(bdev, mem->mem_type);
913 	struct ww_acquire_ctx *ticket;
914 	int ret;
915 
916 	ticket = dma_resv_locking_ctx(bo->base.resv);
917 	do {
918 		ret = ttm_bo_mem_get(bo, place, mem);
919 		if (likely(!ret))
920 			break;
921 		if (unlikely(ret != -ENOSPC))
922 			return ret;
923 		ret = ttm_mem_evict_first(bdev, man, place, ctx,
924 					  ticket);
925 		if (unlikely(ret != 0))
926 			return ret;
927 	} while (1);
928 
929 	return ttm_bo_add_move_fence(bo, man, mem, ctx->no_wait_gpu);
930 }
931 
932 static uint32_t ttm_bo_select_caching(struct ttm_resource_manager *man,
933 				      uint32_t cur_placement,
934 				      uint32_t proposed_placement)
935 {
936 	uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
937 	uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
938 
939 	/**
940 	 * Keep current caching if possible.
941 	 */
942 
943 	if ((cur_placement & caching) != 0)
944 		result |= (cur_placement & caching);
945 	else if ((man->default_caching & caching) != 0)
946 		result |= man->default_caching;
947 	else if ((TTM_PL_FLAG_CACHED & caching) != 0)
948 		result |= TTM_PL_FLAG_CACHED;
949 	else if ((TTM_PL_FLAG_WC & caching) != 0)
950 		result |= TTM_PL_FLAG_WC;
951 	else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
952 		result |= TTM_PL_FLAG_UNCACHED;
953 
954 	return result;
955 }
956 
957 static bool ttm_bo_mt_compatible(struct ttm_resource_manager *man,
958 				 uint32_t mem_type,
959 				 const struct ttm_place *place,
960 				 uint32_t *masked_placement)
961 {
962 	uint32_t cur_flags = ttm_bo_type_flags(mem_type);
963 
964 	if ((cur_flags & place->flags & TTM_PL_MASK_MEM) == 0)
965 		return false;
966 
967 	if ((place->flags & man->available_caching) == 0)
968 		return false;
969 
970 	cur_flags |= (place->flags & man->available_caching);
971 
972 	*masked_placement = cur_flags;
973 	return true;
974 }
975 
976 /**
977  * ttm_bo_mem_placement - check if placement is compatible
978  * @bo: BO to find memory for
979  * @place: where to search
980  * @mem: the memory object to fill in
981  * @ctx: operation context
982  *
983  * Check if placement is compatible and fill in mem structure.
984  * Returns -EBUSY if placement won't work or negative error code.
985  * 0 when placement can be used.
986  */
987 static int ttm_bo_mem_placement(struct ttm_buffer_object *bo,
988 				const struct ttm_place *place,
989 				struct ttm_resource *mem,
990 				struct ttm_operation_ctx *ctx)
991 {
992 	struct ttm_bo_device *bdev = bo->bdev;
993 	uint32_t mem_type = TTM_PL_SYSTEM;
994 	struct ttm_resource_manager *man;
995 	uint32_t cur_flags = 0;
996 	int ret;
997 
998 	ret = ttm_mem_type_from_place(place, &mem_type);
999 	if (ret)
1000 		return ret;
1001 
1002 	man = ttm_manager_type(bdev, mem_type);
1003 	if (!man || !ttm_resource_manager_used(man))
1004 		return -EBUSY;
1005 
1006 	if (!ttm_bo_mt_compatible(man, mem_type, place, &cur_flags))
1007 		return -EBUSY;
1008 
1009 	cur_flags = ttm_bo_select_caching(man, bo->mem.placement, cur_flags);
1010 	/*
1011 	 * Use the access and other non-mapping-related flag bits from
1012 	 * the memory placement flags to the current flags
1013 	 */
1014 	ttm_flag_masked(&cur_flags, place->flags, ~TTM_PL_MASK_MEMTYPE);
1015 
1016 	mem->mem_type = mem_type;
1017 	mem->placement = cur_flags;
1018 
1019 	spin_lock(&ttm_bo_glob.lru_lock);
1020 	ttm_bo_del_from_lru(bo);
1021 	ttm_bo_add_mem_to_lru(bo, mem);
1022 	spin_unlock(&ttm_bo_glob.lru_lock);
1023 
1024 	return 0;
1025 }
1026 
1027 /**
1028  * Creates space for memory region @mem according to its type.
1029  *
1030  * This function first searches for free space in compatible memory types in
1031  * the priority order defined by the driver.  If free space isn't found, then
1032  * ttm_bo_mem_force_space is attempted in priority order to evict and find
1033  * space.
1034  */
1035 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1036 			struct ttm_placement *placement,
1037 			struct ttm_resource *mem,
1038 			struct ttm_operation_ctx *ctx)
1039 {
1040 	struct ttm_bo_device *bdev = bo->bdev;
1041 	bool type_found = false;
1042 	int i, ret;
1043 
1044 	ret = dma_resv_reserve_shared(bo->base.resv, 1);
1045 	if (unlikely(ret))
1046 		return ret;
1047 
1048 	for (i = 0; i < placement->num_placement; ++i) {
1049 		const struct ttm_place *place = &placement->placement[i];
1050 		struct ttm_resource_manager *man;
1051 
1052 		ret = ttm_bo_mem_placement(bo, place, mem, ctx);
1053 		if (ret == -EBUSY)
1054 			continue;
1055 		if (ret)
1056 			goto error;
1057 
1058 		type_found = true;
1059 		ret = ttm_bo_mem_get(bo, place, mem);
1060 		if (ret == -ENOSPC)
1061 			continue;
1062 		if (unlikely(ret))
1063 			goto error;
1064 
1065 		man = ttm_manager_type(bdev, mem->mem_type);
1066 		ret = ttm_bo_add_move_fence(bo, man, mem, ctx->no_wait_gpu);
1067 		if (unlikely(ret)) {
1068 			ttm_bo_mem_put(bo, mem);
1069 			if (ret == -EBUSY)
1070 				continue;
1071 
1072 			goto error;
1073 		}
1074 		return 0;
1075 	}
1076 
1077 	for (i = 0; i < placement->num_busy_placement; ++i) {
1078 		const struct ttm_place *place = &placement->busy_placement[i];
1079 
1080 		ret = ttm_bo_mem_placement(bo, place, mem, ctx);
1081 		if (ret == -EBUSY)
1082 			continue;
1083 		if (ret)
1084 			goto error;
1085 
1086 		type_found = true;
1087 		ret = ttm_bo_mem_force_space(bo, place, mem, ctx);
1088 		if (likely(!ret))
1089 			return 0;
1090 
1091 		if (ret && ret != -EBUSY)
1092 			goto error;
1093 	}
1094 
1095 	ret = -ENOMEM;
1096 	if (!type_found) {
1097 		pr_err(TTM_PFX "No compatible memory type found\n");
1098 		ret = -EINVAL;
1099 	}
1100 
1101 error:
1102 	if (bo->mem.mem_type == TTM_PL_SYSTEM && !list_empty(&bo->lru)) {
1103 		ttm_bo_move_to_lru_tail_unlocked(bo);
1104 	}
1105 
1106 	return ret;
1107 }
1108 EXPORT_SYMBOL(ttm_bo_mem_space);
1109 
1110 static int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
1111 			      struct ttm_placement *placement,
1112 			      struct ttm_operation_ctx *ctx)
1113 {
1114 	int ret = 0;
1115 	struct ttm_resource mem;
1116 
1117 	dma_resv_assert_held(bo->base.resv);
1118 
1119 	mem.num_pages = bo->num_pages;
1120 	mem.size = mem.num_pages << PAGE_SHIFT;
1121 	mem.page_alignment = bo->mem.page_alignment;
1122 	mem.bus.io_reserved_vm = false;
1123 	mem.bus.io_reserved_count = 0;
1124 	mem.mm_node = NULL;
1125 
1126 	/*
1127 	 * Determine where to move the buffer.
1128 	 */
1129 	ret = ttm_bo_mem_space(bo, placement, &mem, ctx);
1130 	if (ret)
1131 		goto out_unlock;
1132 	ret = ttm_bo_handle_move_mem(bo, &mem, false, ctx);
1133 out_unlock:
1134 	if (ret)
1135 		ttm_bo_mem_put(bo, &mem);
1136 	return ret;
1137 }
1138 
1139 static bool ttm_bo_places_compat(const struct ttm_place *places,
1140 				 unsigned num_placement,
1141 				 struct ttm_resource *mem,
1142 				 uint32_t *new_flags)
1143 {
1144 	unsigned i;
1145 
1146 	for (i = 0; i < num_placement; i++) {
1147 		const struct ttm_place *heap = &places[i];
1148 
1149 		if ((mem->start < heap->fpfn ||
1150 		     (heap->lpfn != 0 && (mem->start + mem->num_pages) > heap->lpfn)))
1151 			continue;
1152 
1153 		*new_flags = heap->flags;
1154 		if ((*new_flags & mem->placement & TTM_PL_MASK_CACHING) &&
1155 		    (*new_flags & mem->placement & TTM_PL_MASK_MEM) &&
1156 		    (!(*new_flags & TTM_PL_FLAG_CONTIGUOUS) ||
1157 		     (mem->placement & TTM_PL_FLAG_CONTIGUOUS)))
1158 			return true;
1159 	}
1160 	return false;
1161 }
1162 
1163 bool ttm_bo_mem_compat(struct ttm_placement *placement,
1164 		       struct ttm_resource *mem,
1165 		       uint32_t *new_flags)
1166 {
1167 	if (ttm_bo_places_compat(placement->placement, placement->num_placement,
1168 				 mem, new_flags))
1169 		return true;
1170 
1171 	if ((placement->busy_placement != placement->placement ||
1172 	     placement->num_busy_placement > placement->num_placement) &&
1173 	    ttm_bo_places_compat(placement->busy_placement,
1174 				 placement->num_busy_placement,
1175 				 mem, new_flags))
1176 		return true;
1177 
1178 	return false;
1179 }
1180 EXPORT_SYMBOL(ttm_bo_mem_compat);
1181 
1182 int ttm_bo_validate(struct ttm_buffer_object *bo,
1183 		    struct ttm_placement *placement,
1184 		    struct ttm_operation_ctx *ctx)
1185 {
1186 	int ret;
1187 	uint32_t new_flags;
1188 
1189 	dma_resv_assert_held(bo->base.resv);
1190 
1191 	/*
1192 	 * Remove the backing store if no placement is given.
1193 	 */
1194 	if (!placement->num_placement && !placement->num_busy_placement)
1195 		return ttm_bo_pipeline_gutting(bo);
1196 
1197 	/*
1198 	 * Check whether we need to move buffer.
1199 	 */
1200 	if (!ttm_bo_mem_compat(placement, &bo->mem, &new_flags)) {
1201 		ret = ttm_bo_move_buffer(bo, placement, ctx);
1202 		if (ret)
1203 			return ret;
1204 	} else {
1205 		/*
1206 		 * Use the access and other non-mapping-related flag bits from
1207 		 * the compatible memory placement flags to the active flags
1208 		 */
1209 		ttm_flag_masked(&bo->mem.placement, new_flags,
1210 				~TTM_PL_MASK_MEMTYPE);
1211 	}
1212 	return 0;
1213 }
1214 EXPORT_SYMBOL(ttm_bo_validate);
1215 
1216 int ttm_bo_init_reserved(struct ttm_bo_device *bdev,
1217 			 struct ttm_buffer_object *bo,
1218 			 unsigned long size,
1219 			 enum ttm_bo_type type,
1220 			 struct ttm_placement *placement,
1221 			 uint32_t page_alignment,
1222 			 struct ttm_operation_ctx *ctx,
1223 			 size_t acc_size,
1224 			 struct sg_table *sg,
1225 			 struct dma_resv *resv,
1226 			 void (*destroy) (struct ttm_buffer_object *))
1227 {
1228 	struct ttm_mem_global *mem_glob = &ttm_mem_glob;
1229 	int ret = 0;
1230 	unsigned long num_pages;
1231 	bool locked;
1232 
1233 	ret = ttm_mem_global_alloc(mem_glob, acc_size, ctx);
1234 	if (ret) {
1235 		pr_err("Out of kernel memory\n");
1236 		if (destroy)
1237 			(*destroy)(bo);
1238 		else
1239 			kfree(bo);
1240 		return -ENOMEM;
1241 	}
1242 
1243 	num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1244 	if (num_pages == 0) {
1245 		pr_err("Illegal buffer object size\n");
1246 		if (destroy)
1247 			(*destroy)(bo);
1248 		else
1249 			kfree(bo);
1250 		ttm_mem_global_free(mem_glob, acc_size);
1251 		return -EINVAL;
1252 	}
1253 	bo->destroy = destroy ? destroy : ttm_bo_default_destroy;
1254 
1255 	kref_init(&bo->kref);
1256 	INIT_LIST_HEAD(&bo->lru);
1257 	INIT_LIST_HEAD(&bo->ddestroy);
1258 	INIT_LIST_HEAD(&bo->swap);
1259 	INIT_LIST_HEAD(&bo->io_reserve_lru);
1260 	bo->bdev = bdev;
1261 	bo->type = type;
1262 	bo->num_pages = num_pages;
1263 	bo->mem.size = num_pages << PAGE_SHIFT;
1264 	bo->mem.mem_type = TTM_PL_SYSTEM;
1265 	bo->mem.num_pages = bo->num_pages;
1266 	bo->mem.mm_node = NULL;
1267 	bo->mem.page_alignment = page_alignment;
1268 	bo->mem.bus.io_reserved_vm = false;
1269 	bo->mem.bus.io_reserved_count = 0;
1270 	bo->moving = NULL;
1271 	bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
1272 	bo->acc_size = acc_size;
1273 	bo->sg = sg;
1274 	if (resv) {
1275 		bo->base.resv = resv;
1276 		dma_resv_assert_held(bo->base.resv);
1277 	} else {
1278 		bo->base.resv = &bo->base._resv;
1279 	}
1280 	if (!ttm_bo_uses_embedded_gem_object(bo)) {
1281 		/*
1282 		 * bo.gem is not initialized, so we have to setup the
1283 		 * struct elements we want use regardless.
1284 		 */
1285 		dma_resv_init(&bo->base._resv);
1286 		drm_vma_node_reset(&bo->base.vma_node);
1287 	}
1288 	atomic_inc(&ttm_bo_glob.bo_count);
1289 
1290 	/*
1291 	 * For ttm_bo_type_device buffers, allocate
1292 	 * address space from the device.
1293 	 */
1294 	if (bo->type == ttm_bo_type_device ||
1295 	    bo->type == ttm_bo_type_sg)
1296 		ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
1297 					 bo->mem.num_pages);
1298 
1299 	/* passed reservation objects should already be locked,
1300 	 * since otherwise lockdep will be angered in radeon.
1301 	 */
1302 	if (!resv) {
1303 		locked = dma_resv_trylock(bo->base.resv);
1304 		WARN_ON(!locked);
1305 	}
1306 
1307 	if (likely(!ret))
1308 		ret = ttm_bo_validate(bo, placement, ctx);
1309 
1310 	if (unlikely(ret)) {
1311 		if (!resv)
1312 			ttm_bo_unreserve(bo);
1313 
1314 		ttm_bo_put(bo);
1315 		return ret;
1316 	}
1317 
1318 	ttm_bo_move_to_lru_tail_unlocked(bo);
1319 
1320 	return ret;
1321 }
1322 EXPORT_SYMBOL(ttm_bo_init_reserved);
1323 
1324 int ttm_bo_init(struct ttm_bo_device *bdev,
1325 		struct ttm_buffer_object *bo,
1326 		unsigned long size,
1327 		enum ttm_bo_type type,
1328 		struct ttm_placement *placement,
1329 		uint32_t page_alignment,
1330 		bool interruptible,
1331 		size_t acc_size,
1332 		struct sg_table *sg,
1333 		struct dma_resv *resv,
1334 		void (*destroy) (struct ttm_buffer_object *))
1335 {
1336 	struct ttm_operation_ctx ctx = { interruptible, false };
1337 	int ret;
1338 
1339 	ret = ttm_bo_init_reserved(bdev, bo, size, type, placement,
1340 				   page_alignment, &ctx, acc_size,
1341 				   sg, resv, destroy);
1342 	if (ret)
1343 		return ret;
1344 
1345 	if (!resv)
1346 		ttm_bo_unreserve(bo);
1347 
1348 	return 0;
1349 }
1350 EXPORT_SYMBOL(ttm_bo_init);
1351 
1352 size_t ttm_bo_acc_size(struct ttm_bo_device *bdev,
1353 		       unsigned long bo_size,
1354 		       unsigned struct_size)
1355 {
1356 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1357 	size_t size = 0;
1358 
1359 	size += ttm_round_pot(struct_size);
1360 	size += ttm_round_pot(npages * sizeof(void *));
1361 	size += ttm_round_pot(sizeof(struct ttm_tt));
1362 	return size;
1363 }
1364 EXPORT_SYMBOL(ttm_bo_acc_size);
1365 
1366 size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev,
1367 			   unsigned long bo_size,
1368 			   unsigned struct_size)
1369 {
1370 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1371 	size_t size = 0;
1372 
1373 	size += ttm_round_pot(struct_size);
1374 	size += ttm_round_pot(npages * (2*sizeof(void *) + sizeof(dma_addr_t)));
1375 	size += ttm_round_pot(sizeof(struct ttm_dma_tt));
1376 	return size;
1377 }
1378 EXPORT_SYMBOL(ttm_bo_dma_acc_size);
1379 
1380 int ttm_bo_create(struct ttm_bo_device *bdev,
1381 			unsigned long size,
1382 			enum ttm_bo_type type,
1383 			struct ttm_placement *placement,
1384 			uint32_t page_alignment,
1385 			bool interruptible,
1386 			struct ttm_buffer_object **p_bo)
1387 {
1388 	struct ttm_buffer_object *bo;
1389 	size_t acc_size;
1390 	int ret;
1391 
1392 	bo = kzalloc(sizeof(*bo), GFP_KERNEL);
1393 	if (unlikely(bo == NULL))
1394 		return -ENOMEM;
1395 
1396 	acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object));
1397 	ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
1398 			  interruptible, acc_size,
1399 			  NULL, NULL, NULL);
1400 	if (likely(ret == 0))
1401 		*p_bo = bo;
1402 
1403 	return ret;
1404 }
1405 EXPORT_SYMBOL(ttm_bo_create);
1406 
1407 int ttm_resource_manager_force_list_clean(struct ttm_bo_device *bdev,
1408 					  struct ttm_resource_manager *man)
1409 {
1410 	struct ttm_operation_ctx ctx = {
1411 		.interruptible = false,
1412 		.no_wait_gpu = false,
1413 		.flags = TTM_OPT_FLAG_FORCE_ALLOC
1414 	};
1415 	struct ttm_bo_global *glob = &ttm_bo_glob;
1416 	struct dma_fence *fence;
1417 	int ret;
1418 	unsigned i;
1419 
1420 	/*
1421 	 * Can't use standard list traversal since we're unlocking.
1422 	 */
1423 
1424 	spin_lock(&glob->lru_lock);
1425 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1426 		while (!list_empty(&man->lru[i])) {
1427 			spin_unlock(&glob->lru_lock);
1428 			ret = ttm_mem_evict_first(bdev, man, NULL, &ctx,
1429 						  NULL);
1430 			if (ret)
1431 				return ret;
1432 			spin_lock(&glob->lru_lock);
1433 		}
1434 	}
1435 	spin_unlock(&glob->lru_lock);
1436 
1437 	spin_lock(&man->move_lock);
1438 	fence = dma_fence_get(man->move);
1439 	spin_unlock(&man->move_lock);
1440 
1441 	if (fence) {
1442 		ret = dma_fence_wait(fence, false);
1443 		dma_fence_put(fence);
1444 		if (ret)
1445 			return ret;
1446 	}
1447 
1448 	return 0;
1449 }
1450 EXPORT_SYMBOL(ttm_resource_manager_force_list_clean);
1451 
1452 
1453 int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1454 {
1455 	struct ttm_resource_manager *man = ttm_manager_type(bdev, mem_type);
1456 
1457 	if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
1458 		pr_err("Illegal memory manager memory type %u\n", mem_type);
1459 		return -EINVAL;
1460 	}
1461 
1462 	if (!man) {
1463 		pr_err("Memory type %u has not been initialized\n", mem_type);
1464 		return 0;
1465 	}
1466 
1467 	return ttm_resource_manager_force_list_clean(bdev, man);
1468 }
1469 EXPORT_SYMBOL(ttm_bo_evict_mm);
1470 
1471 void ttm_resource_manager_init(struct ttm_resource_manager *man,
1472 			       unsigned long p_size)
1473 {
1474 	unsigned i;
1475 
1476 	man->use_io_reserve_lru = false;
1477 	mutex_init(&man->io_reserve_mutex);
1478 	spin_lock_init(&man->move_lock);
1479 	INIT_LIST_HEAD(&man->io_reserve_lru);
1480 	man->size = p_size;
1481 
1482 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1483 		INIT_LIST_HEAD(&man->lru[i]);
1484 	man->move = NULL;
1485 }
1486 EXPORT_SYMBOL(ttm_resource_manager_init);
1487 
1488 static void ttm_bo_global_kobj_release(struct kobject *kobj)
1489 {
1490 	struct ttm_bo_global *glob =
1491 		container_of(kobj, struct ttm_bo_global, kobj);
1492 
1493 	__free_page(glob->dummy_read_page);
1494 }
1495 
1496 static void ttm_bo_global_release(void)
1497 {
1498 	struct ttm_bo_global *glob = &ttm_bo_glob;
1499 
1500 	mutex_lock(&ttm_global_mutex);
1501 	if (--ttm_bo_glob_use_count > 0)
1502 		goto out;
1503 
1504 	kobject_del(&glob->kobj);
1505 	kobject_put(&glob->kobj);
1506 	ttm_mem_global_release(&ttm_mem_glob);
1507 	memset(glob, 0, sizeof(*glob));
1508 out:
1509 	mutex_unlock(&ttm_global_mutex);
1510 }
1511 
1512 static int ttm_bo_global_init(void)
1513 {
1514 	struct ttm_bo_global *glob = &ttm_bo_glob;
1515 	int ret = 0;
1516 	unsigned i;
1517 
1518 	mutex_lock(&ttm_global_mutex);
1519 	if (++ttm_bo_glob_use_count > 1)
1520 		goto out;
1521 
1522 	ret = ttm_mem_global_init(&ttm_mem_glob);
1523 	if (ret)
1524 		goto out;
1525 
1526 	spin_lock_init(&glob->lru_lock);
1527 	glob->dummy_read_page = alloc_page(__GFP_ZERO | GFP_DMA32);
1528 
1529 	if (unlikely(glob->dummy_read_page == NULL)) {
1530 		ret = -ENOMEM;
1531 		goto out;
1532 	}
1533 
1534 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1535 		INIT_LIST_HEAD(&glob->swap_lru[i]);
1536 	INIT_LIST_HEAD(&glob->device_list);
1537 	atomic_set(&glob->bo_count, 0);
1538 
1539 	ret = kobject_init_and_add(
1540 		&glob->kobj, &ttm_bo_glob_kobj_type, ttm_get_kobj(), "buffer_objects");
1541 	if (unlikely(ret != 0))
1542 		kobject_put(&glob->kobj);
1543 out:
1544 	mutex_unlock(&ttm_global_mutex);
1545 	return ret;
1546 }
1547 
1548 int ttm_bo_device_release(struct ttm_bo_device *bdev)
1549 {
1550 	struct ttm_bo_global *glob = &ttm_bo_glob;
1551 	int ret = 0;
1552 	unsigned i;
1553 	struct ttm_resource_manager *man;
1554 
1555 	man = ttm_manager_type(bdev, TTM_PL_SYSTEM);
1556 	ttm_resource_manager_set_used(man, false);
1557 	ttm_set_driver_manager(bdev, TTM_PL_SYSTEM, NULL);
1558 
1559 	mutex_lock(&ttm_global_mutex);
1560 	list_del(&bdev->device_list);
1561 	mutex_unlock(&ttm_global_mutex);
1562 
1563 	cancel_delayed_work_sync(&bdev->wq);
1564 
1565 	if (ttm_bo_delayed_delete(bdev, true))
1566 		pr_debug("Delayed destroy list was clean\n");
1567 
1568 	spin_lock(&glob->lru_lock);
1569 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1570 		if (list_empty(&man->lru[0]))
1571 			pr_debug("Swap list %d was clean\n", i);
1572 	spin_unlock(&glob->lru_lock);
1573 
1574 	if (!ret)
1575 		ttm_bo_global_release();
1576 
1577 	return ret;
1578 }
1579 EXPORT_SYMBOL(ttm_bo_device_release);
1580 
1581 static void ttm_bo_init_sysman(struct ttm_bo_device *bdev)
1582 {
1583 	struct ttm_resource_manager *man = &bdev->sysman;
1584 
1585 	/*
1586 	 * Initialize the system memory buffer type.
1587 	 * Other types need to be driver / IOCTL initialized.
1588 	 */
1589 	man->use_tt = true;
1590 	man->available_caching = TTM_PL_MASK_CACHING;
1591 	man->default_caching = TTM_PL_FLAG_CACHED;
1592 
1593 	ttm_resource_manager_init(man, 0);
1594 	ttm_set_driver_manager(bdev, TTM_PL_SYSTEM, man);
1595 	ttm_resource_manager_set_used(man, true);
1596 }
1597 
1598 int ttm_bo_device_init(struct ttm_bo_device *bdev,
1599 		       struct ttm_bo_driver *driver,
1600 		       struct address_space *mapping,
1601 		       struct drm_vma_offset_manager *vma_manager,
1602 		       bool need_dma32)
1603 {
1604 	struct ttm_bo_global *glob = &ttm_bo_glob;
1605 	int ret;
1606 
1607 	if (WARN_ON(vma_manager == NULL))
1608 		return -EINVAL;
1609 
1610 	ret = ttm_bo_global_init();
1611 	if (ret)
1612 		return ret;
1613 
1614 	bdev->driver = driver;
1615 
1616 	ttm_bo_init_sysman(bdev);
1617 
1618 	bdev->vma_manager = vma_manager;
1619 	INIT_DELAYED_WORK(&bdev->wq, ttm_bo_delayed_workqueue);
1620 	INIT_LIST_HEAD(&bdev->ddestroy);
1621 	bdev->dev_mapping = mapping;
1622 	bdev->need_dma32 = need_dma32;
1623 	mutex_lock(&ttm_global_mutex);
1624 	list_add_tail(&bdev->device_list, &glob->device_list);
1625 	mutex_unlock(&ttm_global_mutex);
1626 
1627 	return 0;
1628 }
1629 EXPORT_SYMBOL(ttm_bo_device_init);
1630 
1631 /*
1632  * buffer object vm functions.
1633  */
1634 
1635 void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
1636 {
1637 	struct ttm_bo_device *bdev = bo->bdev;
1638 
1639 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1640 	ttm_mem_io_free_vm(bo);
1641 }
1642 
1643 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1644 {
1645 	struct ttm_bo_device *bdev = bo->bdev;
1646 	struct ttm_resource_manager *man = ttm_manager_type(bdev, bo->mem.mem_type);
1647 
1648 	ttm_mem_io_lock(man, false);
1649 	ttm_bo_unmap_virtual_locked(bo);
1650 	ttm_mem_io_unlock(man);
1651 }
1652 
1653 
1654 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1655 
1656 int ttm_bo_wait(struct ttm_buffer_object *bo,
1657 		bool interruptible, bool no_wait)
1658 {
1659 	long timeout = 15 * HZ;
1660 
1661 	if (no_wait) {
1662 		if (dma_resv_test_signaled_rcu(bo->base.resv, true))
1663 			return 0;
1664 		else
1665 			return -EBUSY;
1666 	}
1667 
1668 	timeout = dma_resv_wait_timeout_rcu(bo->base.resv, true,
1669 						      interruptible, timeout);
1670 	if (timeout < 0)
1671 		return timeout;
1672 
1673 	if (timeout == 0)
1674 		return -EBUSY;
1675 
1676 	dma_resv_add_excl_fence(bo->base.resv, NULL);
1677 	return 0;
1678 }
1679 EXPORT_SYMBOL(ttm_bo_wait);
1680 
1681 /**
1682  * A buffer object shrink method that tries to swap out the first
1683  * buffer object on the bo_global::swap_lru list.
1684  */
1685 int ttm_bo_swapout(struct ttm_bo_global *glob, struct ttm_operation_ctx *ctx)
1686 {
1687 	struct ttm_buffer_object *bo;
1688 	int ret = -EBUSY;
1689 	bool locked;
1690 	unsigned i;
1691 
1692 	spin_lock(&glob->lru_lock);
1693 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1694 		list_for_each_entry(bo, &glob->swap_lru[i], swap) {
1695 			if (!ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
1696 							    NULL))
1697 				continue;
1698 
1699 			if (!ttm_bo_get_unless_zero(bo)) {
1700 				if (locked)
1701 					dma_resv_unlock(bo->base.resv);
1702 				continue;
1703 			}
1704 
1705 			ret = 0;
1706 			break;
1707 		}
1708 		if (!ret)
1709 			break;
1710 	}
1711 
1712 	if (ret) {
1713 		spin_unlock(&glob->lru_lock);
1714 		return ret;
1715 	}
1716 
1717 	if (bo->deleted) {
1718 		ret = ttm_bo_cleanup_refs(bo, false, false, locked);
1719 		ttm_bo_put(bo);
1720 		return ret;
1721 	}
1722 
1723 	ttm_bo_del_from_lru(bo);
1724 	spin_unlock(&glob->lru_lock);
1725 
1726 	/**
1727 	 * Move to system cached
1728 	 */
1729 
1730 	if (bo->mem.mem_type != TTM_PL_SYSTEM ||
1731 	    bo->ttm->caching_state != tt_cached) {
1732 		struct ttm_operation_ctx ctx = { false, false };
1733 		struct ttm_resource evict_mem;
1734 
1735 		evict_mem = bo->mem;
1736 		evict_mem.mm_node = NULL;
1737 		evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
1738 		evict_mem.mem_type = TTM_PL_SYSTEM;
1739 
1740 		ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, &ctx);
1741 		if (unlikely(ret != 0))
1742 			goto out;
1743 	}
1744 
1745 	/**
1746 	 * Make sure BO is idle.
1747 	 */
1748 
1749 	ret = ttm_bo_wait(bo, false, false);
1750 	if (unlikely(ret != 0))
1751 		goto out;
1752 
1753 	ttm_bo_unmap_virtual(bo);
1754 
1755 	/**
1756 	 * Swap out. Buffer will be swapped in again as soon as
1757 	 * anyone tries to access a ttm page.
1758 	 */
1759 
1760 	if (bo->bdev->driver->swap_notify)
1761 		bo->bdev->driver->swap_notify(bo);
1762 
1763 	ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
1764 out:
1765 
1766 	/**
1767 	 *
1768 	 * Unreserve without putting on LRU to avoid swapping out an
1769 	 * already swapped buffer.
1770 	 */
1771 	if (locked)
1772 		dma_resv_unlock(bo->base.resv);
1773 	ttm_bo_put(bo);
1774 	return ret;
1775 }
1776 EXPORT_SYMBOL(ttm_bo_swapout);
1777 
1778 void ttm_bo_swapout_all(struct ttm_bo_device *bdev)
1779 {
1780 	struct ttm_operation_ctx ctx = {
1781 		.interruptible = false,
1782 		.no_wait_gpu = false
1783 	};
1784 
1785 	while (ttm_bo_swapout(&ttm_bo_glob, &ctx) == 0);
1786 }
1787 EXPORT_SYMBOL(ttm_bo_swapout_all);
1788