xref: /openbmc/linux/drivers/gpu/drm/ttm/ttm_bo.c (revision 724884c3)
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 static void ttm_mem_type_debug(struct ttm_bo_device *bdev, struct drm_printer *p,
81 			       int mem_type)
82 {
83 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
84 
85 	drm_printf(p, "    has_type: %d\n", man->has_type);
86 	drm_printf(p, "    use_type: %d\n", man->use_type);
87 	drm_printf(p, "    flags: 0x%08X\n", man->flags);
88 	drm_printf(p, "    size: %llu\n", man->size);
89 	drm_printf(p, "    available_caching: 0x%08X\n", man->available_caching);
90 	drm_printf(p, "    default_caching: 0x%08X\n", man->default_caching);
91 	if (mem_type != TTM_PL_SYSTEM)
92 		(*man->func->debug)(man, p);
93 }
94 
95 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
96 					struct ttm_placement *placement)
97 {
98 	struct drm_printer p = drm_debug_printer(TTM_PFX);
99 	int i, ret, mem_type;
100 
101 	drm_printf(&p, "No space for %p (%lu pages, %luK, %luM)\n",
102 		   bo, bo->mem.num_pages, bo->mem.size >> 10,
103 		   bo->mem.size >> 20);
104 	for (i = 0; i < placement->num_placement; i++) {
105 		ret = ttm_mem_type_from_place(&placement->placement[i],
106 						&mem_type);
107 		if (ret)
108 			return;
109 		drm_printf(&p, "  placement[%d]=0x%08X (%d)\n",
110 			   i, placement->placement[i].flags, mem_type);
111 		ttm_mem_type_debug(bo->bdev, &p, mem_type);
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_mem_reg *mem)
149 {
150 	struct ttm_bo_device *bdev = bo->bdev;
151 	struct ttm_mem_type_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 = &bdev->man[mem->mem_type];
160 	list_add_tail(&bo->lru, &man->lru[bo->priority]);
161 
162 	if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED) && 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_mem_type_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 = &pos->first->bdev->man[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_mem_type_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 = &pos->first->bdev->man[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_mem_reg *mem, bool evict,
272 				  struct ttm_operation_ctx *ctx)
273 {
274 	struct ttm_bo_device *bdev = bo->bdev;
275 	struct ttm_mem_type_manager *old_man = &bdev->man[bo->mem.mem_type];
276 	struct ttm_mem_type_manager *new_man = &bdev->man[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->flags & TTM_MEMTYPE_FLAG_FIXED)) {
290 		bool zero = !(old_man->flags & TTM_MEMTYPE_FLAG_FIXED);
291 
292 		ret = ttm_tt_create(bo, zero);
293 		if (ret)
294 			goto out_err;
295 
296 		ret = ttm_tt_set_placement_caching(bo->ttm, mem->placement);
297 		if (ret)
298 			goto out_err;
299 
300 		if (mem->mem_type != TTM_PL_SYSTEM) {
301 			ret = ttm_tt_bind(bo->ttm, mem, ctx);
302 			if (ret)
303 				goto out_err;
304 		}
305 
306 		if (bo->mem.mem_type == TTM_PL_SYSTEM) {
307 			if (bdev->driver->move_notify)
308 				bdev->driver->move_notify(bo, evict, mem);
309 			bo->mem = *mem;
310 			goto moved;
311 		}
312 	}
313 
314 	if (bdev->driver->move_notify)
315 		bdev->driver->move_notify(bo, evict, mem);
316 
317 	if (!(old_man->flags & TTM_MEMTYPE_FLAG_FIXED) &&
318 	    !(new_man->flags & TTM_MEMTYPE_FLAG_FIXED))
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 = &bdev->man[bo->mem.mem_type];
343 	if (new_man->flags & TTM_MEMTYPE_FLAG_FIXED) {
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_mem_type_manager *man = &bdev->man[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_mem_reg 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 		return ttm_bo_pipeline_gutting(bo);
657 
658 	evict_mem = bo->mem;
659 	evict_mem.mm_node = NULL;
660 	evict_mem.bus.io_reserved_vm = false;
661 	evict_mem.bus.io_reserved_count = 0;
662 
663 	ret = ttm_bo_mem_space(bo, &placement, &evict_mem, ctx);
664 	if (ret) {
665 		if (ret != -ERESTARTSYS) {
666 			pr_err("Failed to find memory space for buffer 0x%p eviction\n",
667 			       bo);
668 			ttm_bo_mem_space_debug(bo, &placement);
669 		}
670 		goto out;
671 	}
672 
673 	ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, ctx);
674 	if (unlikely(ret)) {
675 		if (ret != -ERESTARTSYS)
676 			pr_err("Buffer eviction failed\n");
677 		ttm_bo_mem_put(bo, &evict_mem);
678 		goto out;
679 	}
680 	bo->evicted = true;
681 out:
682 	return ret;
683 }
684 
685 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
686 			      const struct ttm_place *place)
687 {
688 	/* Don't evict this BO if it's outside of the
689 	 * requested placement range
690 	 */
691 	if (place->fpfn >= (bo->mem.start + bo->mem.size) ||
692 	    (place->lpfn && place->lpfn <= bo->mem.start))
693 		return false;
694 
695 	return true;
696 }
697 EXPORT_SYMBOL(ttm_bo_eviction_valuable);
698 
699 /**
700  * Check the target bo is allowable to be evicted or swapout, including cases:
701  *
702  * a. if share same reservation object with ctx->resv, have assumption
703  * reservation objects should already be locked, so not lock again and
704  * return true directly when either the opreation allow_reserved_eviction
705  * or the target bo already is in delayed free list;
706  *
707  * b. Otherwise, trylock it.
708  */
709 static bool ttm_bo_evict_swapout_allowable(struct ttm_buffer_object *bo,
710 			struct ttm_operation_ctx *ctx, bool *locked, bool *busy)
711 {
712 	bool ret = false;
713 
714 	if (bo->base.resv == ctx->resv) {
715 		dma_resv_assert_held(bo->base.resv);
716 		if (ctx->flags & TTM_OPT_FLAG_ALLOW_RES_EVICT)
717 			ret = true;
718 		*locked = false;
719 		if (busy)
720 			*busy = false;
721 	} else {
722 		ret = dma_resv_trylock(bo->base.resv);
723 		*locked = ret;
724 		if (busy)
725 			*busy = !ret;
726 	}
727 
728 	return ret;
729 }
730 
731 /**
732  * ttm_mem_evict_wait_busy - wait for a busy BO to become available
733  *
734  * @busy_bo: BO which couldn't be locked with trylock
735  * @ctx: operation context
736  * @ticket: acquire ticket
737  *
738  * Try to lock a busy buffer object to avoid failing eviction.
739  */
740 static int ttm_mem_evict_wait_busy(struct ttm_buffer_object *busy_bo,
741 				   struct ttm_operation_ctx *ctx,
742 				   struct ww_acquire_ctx *ticket)
743 {
744 	int r;
745 
746 	if (!busy_bo || !ticket)
747 		return -EBUSY;
748 
749 	if (ctx->interruptible)
750 		r = dma_resv_lock_interruptible(busy_bo->base.resv,
751 							  ticket);
752 	else
753 		r = dma_resv_lock(busy_bo->base.resv, ticket);
754 
755 	/*
756 	 * TODO: It would be better to keep the BO locked until allocation is at
757 	 * least tried one more time, but that would mean a much larger rework
758 	 * of TTM.
759 	 */
760 	if (!r)
761 		dma_resv_unlock(busy_bo->base.resv);
762 
763 	return r == -EDEADLK ? -EBUSY : r;
764 }
765 
766 static int ttm_mem_evict_first(struct ttm_bo_device *bdev,
767 			       uint32_t mem_type,
768 			       const struct ttm_place *place,
769 			       struct ttm_operation_ctx *ctx,
770 			       struct ww_acquire_ctx *ticket)
771 {
772 	struct ttm_buffer_object *bo = NULL, *busy_bo = NULL;
773 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
774 	bool locked = false;
775 	unsigned i;
776 	int ret;
777 
778 	spin_lock(&ttm_bo_glob.lru_lock);
779 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
780 		list_for_each_entry(bo, &man->lru[i], lru) {
781 			bool busy;
782 
783 			if (!ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
784 							    &busy)) {
785 				if (busy && !busy_bo && ticket !=
786 				    dma_resv_locking_ctx(bo->base.resv))
787 					busy_bo = bo;
788 				continue;
789 			}
790 
791 			if (place && !bdev->driver->eviction_valuable(bo,
792 								      place)) {
793 				if (locked)
794 					dma_resv_unlock(bo->base.resv);
795 				continue;
796 			}
797 			if (!ttm_bo_get_unless_zero(bo)) {
798 				if (locked)
799 					dma_resv_unlock(bo->base.resv);
800 				continue;
801 			}
802 			break;
803 		}
804 
805 		/* If the inner loop terminated early, we have our candidate */
806 		if (&bo->lru != &man->lru[i])
807 			break;
808 
809 		bo = NULL;
810 	}
811 
812 	if (!bo) {
813 		if (busy_bo && !ttm_bo_get_unless_zero(busy_bo))
814 			busy_bo = NULL;
815 		spin_unlock(&ttm_bo_glob.lru_lock);
816 		ret = ttm_mem_evict_wait_busy(busy_bo, ctx, ticket);
817 		if (busy_bo)
818 			ttm_bo_put(busy_bo);
819 		return ret;
820 	}
821 
822 	if (bo->deleted) {
823 		ret = ttm_bo_cleanup_refs(bo, ctx->interruptible,
824 					  ctx->no_wait_gpu, locked);
825 		ttm_bo_put(bo);
826 		return ret;
827 	}
828 
829 	spin_unlock(&ttm_bo_glob.lru_lock);
830 
831 	ret = ttm_bo_evict(bo, ctx);
832 	if (locked)
833 		ttm_bo_unreserve(bo);
834 
835 	ttm_bo_put(bo);
836 	return ret;
837 }
838 
839 static int ttm_bo_mem_get(struct ttm_buffer_object *bo,
840 			  const struct ttm_place *place,
841 			  struct ttm_mem_reg *mem)
842 {
843 	struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type];
844 
845 	mem->mm_node = NULL;
846 	if (!man->func || !man->func->get_node)
847 		return 0;
848 
849 	return man->func->get_node(man, bo, place, mem);
850 }
851 
852 void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem)
853 {
854 	struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type];
855 
856 	if (!man->func || !man->func->put_node)
857 		return;
858 
859 	man->func->put_node(man, mem);
860 	mem->mm_node = NULL;
861 	mem->mem_type = TTM_PL_SYSTEM;
862 }
863 EXPORT_SYMBOL(ttm_bo_mem_put);
864 
865 /**
866  * Add the last move fence to the BO and reserve a new shared slot.
867  */
868 static int ttm_bo_add_move_fence(struct ttm_buffer_object *bo,
869 				 struct ttm_mem_type_manager *man,
870 				 struct ttm_mem_reg *mem,
871 				 bool no_wait_gpu)
872 {
873 	struct dma_fence *fence;
874 	int ret;
875 
876 	spin_lock(&man->move_lock);
877 	fence = dma_fence_get(man->move);
878 	spin_unlock(&man->move_lock);
879 
880 	if (!fence)
881 		return 0;
882 
883 	if (no_wait_gpu)
884 		return -EBUSY;
885 
886 	dma_resv_add_shared_fence(bo->base.resv, fence);
887 
888 	ret = dma_resv_reserve_shared(bo->base.resv, 1);
889 	if (unlikely(ret)) {
890 		dma_fence_put(fence);
891 		return ret;
892 	}
893 
894 	dma_fence_put(bo->moving);
895 	bo->moving = fence;
896 	return 0;
897 }
898 
899 /**
900  * Repeatedly evict memory from the LRU for @mem_type until we create enough
901  * space, or we've evicted everything and there isn't enough space.
902  */
903 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
904 				  const struct ttm_place *place,
905 				  struct ttm_mem_reg *mem,
906 				  struct ttm_operation_ctx *ctx)
907 {
908 	struct ttm_bo_device *bdev = bo->bdev;
909 	struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
910 	struct ww_acquire_ctx *ticket;
911 	int ret;
912 
913 	ticket = dma_resv_locking_ctx(bo->base.resv);
914 	do {
915 		ret = ttm_bo_mem_get(bo, place, mem);
916 		if (likely(!ret))
917 			break;
918 		if (unlikely(ret != -ENOSPC))
919 			return ret;
920 		ret = ttm_mem_evict_first(bdev, mem->mem_type, place, ctx,
921 					  ticket);
922 		if (unlikely(ret != 0))
923 			return ret;
924 	} while (1);
925 
926 	return ttm_bo_add_move_fence(bo, man, mem, ctx->no_wait_gpu);
927 }
928 
929 static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man,
930 				      uint32_t cur_placement,
931 				      uint32_t proposed_placement)
932 {
933 	uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
934 	uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
935 
936 	/**
937 	 * Keep current caching if possible.
938 	 */
939 
940 	if ((cur_placement & caching) != 0)
941 		result |= (cur_placement & caching);
942 	else if ((man->default_caching & caching) != 0)
943 		result |= man->default_caching;
944 	else if ((TTM_PL_FLAG_CACHED & caching) != 0)
945 		result |= TTM_PL_FLAG_CACHED;
946 	else if ((TTM_PL_FLAG_WC & caching) != 0)
947 		result |= TTM_PL_FLAG_WC;
948 	else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
949 		result |= TTM_PL_FLAG_UNCACHED;
950 
951 	return result;
952 }
953 
954 static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man,
955 				 uint32_t mem_type,
956 				 const struct ttm_place *place,
957 				 uint32_t *masked_placement)
958 {
959 	uint32_t cur_flags = ttm_bo_type_flags(mem_type);
960 
961 	if ((cur_flags & place->flags & TTM_PL_MASK_MEM) == 0)
962 		return false;
963 
964 	if ((place->flags & man->available_caching) == 0)
965 		return false;
966 
967 	cur_flags |= (place->flags & man->available_caching);
968 
969 	*masked_placement = cur_flags;
970 	return true;
971 }
972 
973 /**
974  * ttm_bo_mem_placement - check if placement is compatible
975  * @bo: BO to find memory for
976  * @place: where to search
977  * @mem: the memory object to fill in
978  * @ctx: operation context
979  *
980  * Check if placement is compatible and fill in mem structure.
981  * Returns -EBUSY if placement won't work or negative error code.
982  * 0 when placement can be used.
983  */
984 static int ttm_bo_mem_placement(struct ttm_buffer_object *bo,
985 				const struct ttm_place *place,
986 				struct ttm_mem_reg *mem,
987 				struct ttm_operation_ctx *ctx)
988 {
989 	struct ttm_bo_device *bdev = bo->bdev;
990 	uint32_t mem_type = TTM_PL_SYSTEM;
991 	struct ttm_mem_type_manager *man;
992 	uint32_t cur_flags = 0;
993 	int ret;
994 
995 	ret = ttm_mem_type_from_place(place, &mem_type);
996 	if (ret)
997 		return ret;
998 
999 	man = &bdev->man[mem_type];
1000 	if (!man->has_type || !man->use_type)
1001 		return -EBUSY;
1002 
1003 	if (!ttm_bo_mt_compatible(man, mem_type, place, &cur_flags))
1004 		return -EBUSY;
1005 
1006 	cur_flags = ttm_bo_select_caching(man, bo->mem.placement, cur_flags);
1007 	/*
1008 	 * Use the access and other non-mapping-related flag bits from
1009 	 * the memory placement flags to the current flags
1010 	 */
1011 	ttm_flag_masked(&cur_flags, place->flags, ~TTM_PL_MASK_MEMTYPE);
1012 
1013 	mem->mem_type = mem_type;
1014 	mem->placement = cur_flags;
1015 
1016 	spin_lock(&ttm_bo_glob.lru_lock);
1017 	ttm_bo_del_from_lru(bo);
1018 	ttm_bo_add_mem_to_lru(bo, mem);
1019 	spin_unlock(&ttm_bo_glob.lru_lock);
1020 
1021 	return 0;
1022 }
1023 
1024 /**
1025  * Creates space for memory region @mem according to its type.
1026  *
1027  * This function first searches for free space in compatible memory types in
1028  * the priority order defined by the driver.  If free space isn't found, then
1029  * ttm_bo_mem_force_space is attempted in priority order to evict and find
1030  * space.
1031  */
1032 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1033 			struct ttm_placement *placement,
1034 			struct ttm_mem_reg *mem,
1035 			struct ttm_operation_ctx *ctx)
1036 {
1037 	struct ttm_bo_device *bdev = bo->bdev;
1038 	bool type_found = false;
1039 	int i, ret;
1040 
1041 	ret = dma_resv_reserve_shared(bo->base.resv, 1);
1042 	if (unlikely(ret))
1043 		return ret;
1044 
1045 	for (i = 0; i < placement->num_placement; ++i) {
1046 		const struct ttm_place *place = &placement->placement[i];
1047 		struct ttm_mem_type_manager *man;
1048 
1049 		ret = ttm_bo_mem_placement(bo, place, mem, ctx);
1050 		if (ret == -EBUSY)
1051 			continue;
1052 		if (ret)
1053 			goto error;
1054 
1055 		type_found = true;
1056 		ret = ttm_bo_mem_get(bo, place, mem);
1057 		if (ret == -ENOSPC)
1058 			continue;
1059 		if (unlikely(ret))
1060 			goto error;
1061 
1062 		man = &bdev->man[mem->mem_type];
1063 		ret = ttm_bo_add_move_fence(bo, man, mem, ctx->no_wait_gpu);
1064 		if (unlikely(ret)) {
1065 			ttm_bo_mem_put(bo, mem);
1066 			if (ret == -EBUSY)
1067 				continue;
1068 
1069 			goto error;
1070 		}
1071 		return 0;
1072 	}
1073 
1074 	for (i = 0; i < placement->num_busy_placement; ++i) {
1075 		const struct ttm_place *place = &placement->busy_placement[i];
1076 
1077 		ret = ttm_bo_mem_placement(bo, place, mem, ctx);
1078 		if (ret == -EBUSY)
1079 			continue;
1080 		if (ret)
1081 			goto error;
1082 
1083 		type_found = true;
1084 		ret = ttm_bo_mem_force_space(bo, place, mem, ctx);
1085 		if (likely(!ret))
1086 			return 0;
1087 
1088 		if (ret && ret != -EBUSY)
1089 			goto error;
1090 	}
1091 
1092 	ret = -ENOMEM;
1093 	if (!type_found) {
1094 		pr_err(TTM_PFX "No compatible memory type found\n");
1095 		ret = -EINVAL;
1096 	}
1097 
1098 error:
1099 	if (bo->mem.mem_type == TTM_PL_SYSTEM && !list_empty(&bo->lru)) {
1100 		spin_lock(&ttm_bo_glob.lru_lock);
1101 		ttm_bo_move_to_lru_tail(bo, NULL);
1102 		spin_unlock(&ttm_bo_glob.lru_lock);
1103 	}
1104 
1105 	return ret;
1106 }
1107 EXPORT_SYMBOL(ttm_bo_mem_space);
1108 
1109 static int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
1110 			      struct ttm_placement *placement,
1111 			      struct ttm_operation_ctx *ctx)
1112 {
1113 	int ret = 0;
1114 	struct ttm_mem_reg mem;
1115 
1116 	dma_resv_assert_held(bo->base.resv);
1117 
1118 	mem.num_pages = bo->num_pages;
1119 	mem.size = mem.num_pages << PAGE_SHIFT;
1120 	mem.page_alignment = bo->mem.page_alignment;
1121 	mem.bus.io_reserved_vm = false;
1122 	mem.bus.io_reserved_count = 0;
1123 	mem.mm_node = NULL;
1124 
1125 	/*
1126 	 * Determine where to move the buffer.
1127 	 */
1128 	ret = ttm_bo_mem_space(bo, placement, &mem, ctx);
1129 	if (ret)
1130 		goto out_unlock;
1131 	ret = ttm_bo_handle_move_mem(bo, &mem, false, ctx);
1132 out_unlock:
1133 	if (ret)
1134 		ttm_bo_mem_put(bo, &mem);
1135 	return ret;
1136 }
1137 
1138 static bool ttm_bo_places_compat(const struct ttm_place *places,
1139 				 unsigned num_placement,
1140 				 struct ttm_mem_reg *mem,
1141 				 uint32_t *new_flags)
1142 {
1143 	unsigned i;
1144 
1145 	for (i = 0; i < num_placement; i++) {
1146 		const struct ttm_place *heap = &places[i];
1147 
1148 		if ((mem->start < heap->fpfn ||
1149 		     (heap->lpfn != 0 && (mem->start + mem->num_pages) > heap->lpfn)))
1150 			continue;
1151 
1152 		*new_flags = heap->flags;
1153 		if ((*new_flags & mem->placement & TTM_PL_MASK_CACHING) &&
1154 		    (*new_flags & mem->placement & TTM_PL_MASK_MEM) &&
1155 		    (!(*new_flags & TTM_PL_FLAG_CONTIGUOUS) ||
1156 		     (mem->placement & TTM_PL_FLAG_CONTIGUOUS)))
1157 			return true;
1158 	}
1159 	return false;
1160 }
1161 
1162 bool ttm_bo_mem_compat(struct ttm_placement *placement,
1163 		       struct ttm_mem_reg *mem,
1164 		       uint32_t *new_flags)
1165 {
1166 	if (ttm_bo_places_compat(placement->placement, placement->num_placement,
1167 				 mem, new_flags))
1168 		return true;
1169 
1170 	if ((placement->busy_placement != placement->placement ||
1171 	     placement->num_busy_placement > placement->num_placement) &&
1172 	    ttm_bo_places_compat(placement->busy_placement,
1173 				 placement->num_busy_placement,
1174 				 mem, new_flags))
1175 		return true;
1176 
1177 	return false;
1178 }
1179 EXPORT_SYMBOL(ttm_bo_mem_compat);
1180 
1181 int ttm_bo_validate(struct ttm_buffer_object *bo,
1182 		    struct ttm_placement *placement,
1183 		    struct ttm_operation_ctx *ctx)
1184 {
1185 	int ret;
1186 	uint32_t new_flags;
1187 
1188 	dma_resv_assert_held(bo->base.resv);
1189 
1190 	/*
1191 	 * Remove the backing store if no placement is given.
1192 	 */
1193 	if (!placement->num_placement && !placement->num_busy_placement)
1194 		return ttm_bo_pipeline_gutting(bo);
1195 
1196 	/*
1197 	 * Check whether we need to move buffer.
1198 	 */
1199 	if (!ttm_bo_mem_compat(placement, &bo->mem, &new_flags)) {
1200 		ret = ttm_bo_move_buffer(bo, placement, ctx);
1201 		if (ret)
1202 			return ret;
1203 	} else {
1204 		/*
1205 		 * Use the access and other non-mapping-related flag bits from
1206 		 * the compatible memory placement flags to the active flags
1207 		 */
1208 		ttm_flag_masked(&bo->mem.placement, new_flags,
1209 				~TTM_PL_MASK_MEMTYPE);
1210 	}
1211 	return 0;
1212 }
1213 EXPORT_SYMBOL(ttm_bo_validate);
1214 
1215 int ttm_bo_init_reserved(struct ttm_bo_device *bdev,
1216 			 struct ttm_buffer_object *bo,
1217 			 unsigned long size,
1218 			 enum ttm_bo_type type,
1219 			 struct ttm_placement *placement,
1220 			 uint32_t page_alignment,
1221 			 struct ttm_operation_ctx *ctx,
1222 			 size_t acc_size,
1223 			 struct sg_table *sg,
1224 			 struct dma_resv *resv,
1225 			 void (*destroy) (struct ttm_buffer_object *))
1226 {
1227 	struct ttm_mem_global *mem_glob = &ttm_mem_glob;
1228 	int ret = 0;
1229 	unsigned long num_pages;
1230 	bool locked;
1231 
1232 	ret = ttm_mem_global_alloc(mem_glob, acc_size, ctx);
1233 	if (ret) {
1234 		pr_err("Out of kernel memory\n");
1235 		if (destroy)
1236 			(*destroy)(bo);
1237 		else
1238 			kfree(bo);
1239 		return -ENOMEM;
1240 	}
1241 
1242 	num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1243 	if (num_pages == 0) {
1244 		pr_err("Illegal buffer object size\n");
1245 		if (destroy)
1246 			(*destroy)(bo);
1247 		else
1248 			kfree(bo);
1249 		ttm_mem_global_free(mem_glob, acc_size);
1250 		return -EINVAL;
1251 	}
1252 	bo->destroy = destroy ? destroy : ttm_bo_default_destroy;
1253 
1254 	kref_init(&bo->kref);
1255 	INIT_LIST_HEAD(&bo->lru);
1256 	INIT_LIST_HEAD(&bo->ddestroy);
1257 	INIT_LIST_HEAD(&bo->swap);
1258 	INIT_LIST_HEAD(&bo->io_reserve_lru);
1259 	bo->bdev = bdev;
1260 	bo->type = type;
1261 	bo->num_pages = num_pages;
1262 	bo->mem.size = num_pages << PAGE_SHIFT;
1263 	bo->mem.mem_type = TTM_PL_SYSTEM;
1264 	bo->mem.num_pages = bo->num_pages;
1265 	bo->mem.mm_node = NULL;
1266 	bo->mem.page_alignment = page_alignment;
1267 	bo->mem.bus.io_reserved_vm = false;
1268 	bo->mem.bus.io_reserved_count = 0;
1269 	bo->moving = NULL;
1270 	bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
1271 	bo->acc_size = acc_size;
1272 	bo->sg = sg;
1273 	if (resv) {
1274 		bo->base.resv = resv;
1275 		dma_resv_assert_held(bo->base.resv);
1276 	} else {
1277 		bo->base.resv = &bo->base._resv;
1278 	}
1279 	if (!ttm_bo_uses_embedded_gem_object(bo)) {
1280 		/*
1281 		 * bo.gem is not initialized, so we have to setup the
1282 		 * struct elements we want use regardless.
1283 		 */
1284 		dma_resv_init(&bo->base._resv);
1285 		drm_vma_node_reset(&bo->base.vma_node);
1286 	}
1287 	atomic_inc(&ttm_bo_glob.bo_count);
1288 
1289 	/*
1290 	 * For ttm_bo_type_device buffers, allocate
1291 	 * address space from the device.
1292 	 */
1293 	if (bo->type == ttm_bo_type_device ||
1294 	    bo->type == ttm_bo_type_sg)
1295 		ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
1296 					 bo->mem.num_pages);
1297 
1298 	/* passed reservation objects should already be locked,
1299 	 * since otherwise lockdep will be angered in radeon.
1300 	 */
1301 	if (!resv) {
1302 		locked = dma_resv_trylock(bo->base.resv);
1303 		WARN_ON(!locked);
1304 	}
1305 
1306 	if (likely(!ret))
1307 		ret = ttm_bo_validate(bo, placement, ctx);
1308 
1309 	if (unlikely(ret)) {
1310 		if (!resv)
1311 			ttm_bo_unreserve(bo);
1312 
1313 		ttm_bo_put(bo);
1314 		return ret;
1315 	}
1316 
1317 	spin_lock(&ttm_bo_glob.lru_lock);
1318 	ttm_bo_move_to_lru_tail(bo, NULL);
1319 	spin_unlock(&ttm_bo_glob.lru_lock);
1320 
1321 	return ret;
1322 }
1323 EXPORT_SYMBOL(ttm_bo_init_reserved);
1324 
1325 int ttm_bo_init(struct ttm_bo_device *bdev,
1326 		struct ttm_buffer_object *bo,
1327 		unsigned long size,
1328 		enum ttm_bo_type type,
1329 		struct ttm_placement *placement,
1330 		uint32_t page_alignment,
1331 		bool interruptible,
1332 		size_t acc_size,
1333 		struct sg_table *sg,
1334 		struct dma_resv *resv,
1335 		void (*destroy) (struct ttm_buffer_object *))
1336 {
1337 	struct ttm_operation_ctx ctx = { interruptible, false };
1338 	int ret;
1339 
1340 	ret = ttm_bo_init_reserved(bdev, bo, size, type, placement,
1341 				   page_alignment, &ctx, acc_size,
1342 				   sg, resv, destroy);
1343 	if (ret)
1344 		return ret;
1345 
1346 	if (!resv)
1347 		ttm_bo_unreserve(bo);
1348 
1349 	return 0;
1350 }
1351 EXPORT_SYMBOL(ttm_bo_init);
1352 
1353 size_t ttm_bo_acc_size(struct ttm_bo_device *bdev,
1354 		       unsigned long bo_size,
1355 		       unsigned struct_size)
1356 {
1357 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1358 	size_t size = 0;
1359 
1360 	size += ttm_round_pot(struct_size);
1361 	size += ttm_round_pot(npages * sizeof(void *));
1362 	size += ttm_round_pot(sizeof(struct ttm_tt));
1363 	return size;
1364 }
1365 EXPORT_SYMBOL(ttm_bo_acc_size);
1366 
1367 size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev,
1368 			   unsigned long bo_size,
1369 			   unsigned struct_size)
1370 {
1371 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1372 	size_t size = 0;
1373 
1374 	size += ttm_round_pot(struct_size);
1375 	size += ttm_round_pot(npages * (2*sizeof(void *) + sizeof(dma_addr_t)));
1376 	size += ttm_round_pot(sizeof(struct ttm_dma_tt));
1377 	return size;
1378 }
1379 EXPORT_SYMBOL(ttm_bo_dma_acc_size);
1380 
1381 int ttm_bo_create(struct ttm_bo_device *bdev,
1382 			unsigned long size,
1383 			enum ttm_bo_type type,
1384 			struct ttm_placement *placement,
1385 			uint32_t page_alignment,
1386 			bool interruptible,
1387 			struct ttm_buffer_object **p_bo)
1388 {
1389 	struct ttm_buffer_object *bo;
1390 	size_t acc_size;
1391 	int ret;
1392 
1393 	bo = kzalloc(sizeof(*bo), GFP_KERNEL);
1394 	if (unlikely(bo == NULL))
1395 		return -ENOMEM;
1396 
1397 	acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object));
1398 	ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
1399 			  interruptible, acc_size,
1400 			  NULL, NULL, NULL);
1401 	if (likely(ret == 0))
1402 		*p_bo = bo;
1403 
1404 	return ret;
1405 }
1406 EXPORT_SYMBOL(ttm_bo_create);
1407 
1408 static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev,
1409 				   unsigned mem_type)
1410 {
1411 	struct ttm_operation_ctx ctx = {
1412 		.interruptible = false,
1413 		.no_wait_gpu = false,
1414 		.flags = TTM_OPT_FLAG_FORCE_ALLOC
1415 	};
1416 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1417 	struct ttm_bo_global *glob = &ttm_bo_glob;
1418 	struct dma_fence *fence;
1419 	int ret;
1420 	unsigned i;
1421 
1422 	/*
1423 	 * Can't use standard list traversal since we're unlocking.
1424 	 */
1425 
1426 	spin_lock(&glob->lru_lock);
1427 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1428 		while (!list_empty(&man->lru[i])) {
1429 			spin_unlock(&glob->lru_lock);
1430 			ret = ttm_mem_evict_first(bdev, mem_type, NULL, &ctx,
1431 						  NULL);
1432 			if (ret)
1433 				return ret;
1434 			spin_lock(&glob->lru_lock);
1435 		}
1436 	}
1437 	spin_unlock(&glob->lru_lock);
1438 
1439 	spin_lock(&man->move_lock);
1440 	fence = dma_fence_get(man->move);
1441 	spin_unlock(&man->move_lock);
1442 
1443 	if (fence) {
1444 		ret = dma_fence_wait(fence, false);
1445 		dma_fence_put(fence);
1446 		if (ret)
1447 			return ret;
1448 	}
1449 
1450 	return 0;
1451 }
1452 
1453 int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1454 {
1455 	struct ttm_mem_type_manager *man;
1456 	int ret = -EINVAL;
1457 
1458 	if (mem_type >= TTM_NUM_MEM_TYPES) {
1459 		pr_err("Illegal memory type %d\n", mem_type);
1460 		return ret;
1461 	}
1462 	man = &bdev->man[mem_type];
1463 
1464 	if (!man->has_type) {
1465 		pr_err("Trying to take down uninitialized memory manager type %u\n",
1466 		       mem_type);
1467 		return ret;
1468 	}
1469 
1470 	man->use_type = false;
1471 	man->has_type = false;
1472 
1473 	ret = 0;
1474 	if (mem_type > 0) {
1475 		ret = ttm_bo_force_list_clean(bdev, mem_type);
1476 		if (ret) {
1477 			pr_err("Cleanup eviction failed\n");
1478 			return ret;
1479 		}
1480 
1481 		ret = (*man->func->takedown)(man);
1482 	}
1483 
1484 	dma_fence_put(man->move);
1485 	man->move = NULL;
1486 
1487 	return ret;
1488 }
1489 EXPORT_SYMBOL(ttm_bo_clean_mm);
1490 
1491 int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1492 {
1493 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1494 
1495 	if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
1496 		pr_err("Illegal memory manager memory type %u\n", mem_type);
1497 		return -EINVAL;
1498 	}
1499 
1500 	if (!man->has_type) {
1501 		pr_err("Memory type %u has not been initialized\n", mem_type);
1502 		return 0;
1503 	}
1504 
1505 	return ttm_bo_force_list_clean(bdev, mem_type);
1506 }
1507 EXPORT_SYMBOL(ttm_bo_evict_mm);
1508 
1509 int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type,
1510 			unsigned long p_size)
1511 {
1512 	int ret;
1513 	struct ttm_mem_type_manager *man;
1514 	unsigned i;
1515 
1516 	BUG_ON(type >= TTM_NUM_MEM_TYPES);
1517 	man = &bdev->man[type];
1518 	BUG_ON(man->has_type);
1519 	man->use_io_reserve_lru = false;
1520 	mutex_init(&man->io_reserve_mutex);
1521 	spin_lock_init(&man->move_lock);
1522 	INIT_LIST_HEAD(&man->io_reserve_lru);
1523 
1524 	ret = bdev->driver->init_mem_type(bdev, type, man);
1525 	if (ret)
1526 		return ret;
1527 	man->bdev = bdev;
1528 
1529 	if (type != TTM_PL_SYSTEM) {
1530 		ret = (*man->func->init)(man, p_size);
1531 		if (ret)
1532 			return ret;
1533 	}
1534 	man->has_type = true;
1535 	man->use_type = true;
1536 	man->size = p_size;
1537 
1538 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1539 		INIT_LIST_HEAD(&man->lru[i]);
1540 	man->move = NULL;
1541 
1542 	return 0;
1543 }
1544 EXPORT_SYMBOL(ttm_bo_init_mm);
1545 
1546 static void ttm_bo_global_kobj_release(struct kobject *kobj)
1547 {
1548 	struct ttm_bo_global *glob =
1549 		container_of(kobj, struct ttm_bo_global, kobj);
1550 
1551 	__free_page(glob->dummy_read_page);
1552 }
1553 
1554 static void ttm_bo_global_release(void)
1555 {
1556 	struct ttm_bo_global *glob = &ttm_bo_glob;
1557 
1558 	mutex_lock(&ttm_global_mutex);
1559 	if (--ttm_bo_glob_use_count > 0)
1560 		goto out;
1561 
1562 	kobject_del(&glob->kobj);
1563 	kobject_put(&glob->kobj);
1564 	ttm_mem_global_release(&ttm_mem_glob);
1565 	memset(glob, 0, sizeof(*glob));
1566 out:
1567 	mutex_unlock(&ttm_global_mutex);
1568 }
1569 
1570 static int ttm_bo_global_init(void)
1571 {
1572 	struct ttm_bo_global *glob = &ttm_bo_glob;
1573 	int ret = 0;
1574 	unsigned i;
1575 
1576 	mutex_lock(&ttm_global_mutex);
1577 	if (++ttm_bo_glob_use_count > 1)
1578 		goto out;
1579 
1580 	ret = ttm_mem_global_init(&ttm_mem_glob);
1581 	if (ret)
1582 		goto out;
1583 
1584 	spin_lock_init(&glob->lru_lock);
1585 	glob->dummy_read_page = alloc_page(__GFP_ZERO | GFP_DMA32);
1586 
1587 	if (unlikely(glob->dummy_read_page == NULL)) {
1588 		ret = -ENOMEM;
1589 		goto out;
1590 	}
1591 
1592 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1593 		INIT_LIST_HEAD(&glob->swap_lru[i]);
1594 	INIT_LIST_HEAD(&glob->device_list);
1595 	atomic_set(&glob->bo_count, 0);
1596 
1597 	ret = kobject_init_and_add(
1598 		&glob->kobj, &ttm_bo_glob_kobj_type, ttm_get_kobj(), "buffer_objects");
1599 	if (unlikely(ret != 0))
1600 		kobject_put(&glob->kobj);
1601 out:
1602 	mutex_unlock(&ttm_global_mutex);
1603 	return ret;
1604 }
1605 
1606 int ttm_bo_device_release(struct ttm_bo_device *bdev)
1607 {
1608 	struct ttm_bo_global *glob = &ttm_bo_glob;
1609 	int ret = 0;
1610 	unsigned i = TTM_NUM_MEM_TYPES;
1611 	struct ttm_mem_type_manager *man;
1612 
1613 	while (i--) {
1614 		man = &bdev->man[i];
1615 		if (man->has_type) {
1616 			man->use_type = false;
1617 			if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) {
1618 				ret = -EBUSY;
1619 				pr_err("DRM memory manager type %d is not clean\n",
1620 				       i);
1621 			}
1622 			man->has_type = false;
1623 		}
1624 	}
1625 
1626 	mutex_lock(&ttm_global_mutex);
1627 	list_del(&bdev->device_list);
1628 	mutex_unlock(&ttm_global_mutex);
1629 
1630 	cancel_delayed_work_sync(&bdev->wq);
1631 
1632 	if (ttm_bo_delayed_delete(bdev, true))
1633 		pr_debug("Delayed destroy list was clean\n");
1634 
1635 	spin_lock(&glob->lru_lock);
1636 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1637 		if (list_empty(&bdev->man[0].lru[0]))
1638 			pr_debug("Swap list %d was clean\n", i);
1639 	spin_unlock(&glob->lru_lock);
1640 
1641 	if (!ret)
1642 		ttm_bo_global_release();
1643 
1644 	return ret;
1645 }
1646 EXPORT_SYMBOL(ttm_bo_device_release);
1647 
1648 int ttm_bo_device_init(struct ttm_bo_device *bdev,
1649 		       struct ttm_bo_driver *driver,
1650 		       struct address_space *mapping,
1651 		       struct drm_vma_offset_manager *vma_manager,
1652 		       bool need_dma32)
1653 {
1654 	struct ttm_bo_global *glob = &ttm_bo_glob;
1655 	int ret;
1656 
1657 	if (WARN_ON(vma_manager == NULL))
1658 		return -EINVAL;
1659 
1660 	ret = ttm_bo_global_init();
1661 	if (ret)
1662 		return ret;
1663 
1664 	bdev->driver = driver;
1665 
1666 	memset(bdev->man, 0, sizeof(bdev->man));
1667 
1668 	/*
1669 	 * Initialize the system memory buffer type.
1670 	 * Other types need to be driver / IOCTL initialized.
1671 	 */
1672 	ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0);
1673 	if (unlikely(ret != 0))
1674 		goto out_no_sys;
1675 
1676 	bdev->vma_manager = vma_manager;
1677 	INIT_DELAYED_WORK(&bdev->wq, ttm_bo_delayed_workqueue);
1678 	INIT_LIST_HEAD(&bdev->ddestroy);
1679 	bdev->dev_mapping = mapping;
1680 	bdev->need_dma32 = need_dma32;
1681 	mutex_lock(&ttm_global_mutex);
1682 	list_add_tail(&bdev->device_list, &glob->device_list);
1683 	mutex_unlock(&ttm_global_mutex);
1684 
1685 	return 0;
1686 out_no_sys:
1687 	ttm_bo_global_release();
1688 	return ret;
1689 }
1690 EXPORT_SYMBOL(ttm_bo_device_init);
1691 
1692 /*
1693  * buffer object vm functions.
1694  */
1695 
1696 void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
1697 {
1698 	struct ttm_bo_device *bdev = bo->bdev;
1699 
1700 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1701 	ttm_mem_io_free_vm(bo);
1702 }
1703 
1704 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1705 {
1706 	struct ttm_bo_device *bdev = bo->bdev;
1707 	struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
1708 
1709 	ttm_mem_io_lock(man, false);
1710 	ttm_bo_unmap_virtual_locked(bo);
1711 	ttm_mem_io_unlock(man);
1712 }
1713 
1714 
1715 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1716 
1717 int ttm_bo_wait(struct ttm_buffer_object *bo,
1718 		bool interruptible, bool no_wait)
1719 {
1720 	long timeout = 15 * HZ;
1721 
1722 	if (no_wait) {
1723 		if (dma_resv_test_signaled_rcu(bo->base.resv, true))
1724 			return 0;
1725 		else
1726 			return -EBUSY;
1727 	}
1728 
1729 	timeout = dma_resv_wait_timeout_rcu(bo->base.resv, true,
1730 						      interruptible, timeout);
1731 	if (timeout < 0)
1732 		return timeout;
1733 
1734 	if (timeout == 0)
1735 		return -EBUSY;
1736 
1737 	dma_resv_add_excl_fence(bo->base.resv, NULL);
1738 	return 0;
1739 }
1740 EXPORT_SYMBOL(ttm_bo_wait);
1741 
1742 /**
1743  * A buffer object shrink method that tries to swap out the first
1744  * buffer object on the bo_global::swap_lru list.
1745  */
1746 int ttm_bo_swapout(struct ttm_bo_global *glob, struct ttm_operation_ctx *ctx)
1747 {
1748 	struct ttm_buffer_object *bo;
1749 	int ret = -EBUSY;
1750 	bool locked;
1751 	unsigned i;
1752 
1753 	spin_lock(&glob->lru_lock);
1754 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1755 		list_for_each_entry(bo, &glob->swap_lru[i], swap) {
1756 			if (!ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
1757 							    NULL))
1758 				continue;
1759 
1760 			if (!ttm_bo_get_unless_zero(bo)) {
1761 				if (locked)
1762 					dma_resv_unlock(bo->base.resv);
1763 				continue;
1764 			}
1765 
1766 			ret = 0;
1767 			break;
1768 		}
1769 		if (!ret)
1770 			break;
1771 	}
1772 
1773 	if (ret) {
1774 		spin_unlock(&glob->lru_lock);
1775 		return ret;
1776 	}
1777 
1778 	if (bo->deleted) {
1779 		ret = ttm_bo_cleanup_refs(bo, false, false, locked);
1780 		ttm_bo_put(bo);
1781 		return ret;
1782 	}
1783 
1784 	ttm_bo_del_from_lru(bo);
1785 	spin_unlock(&glob->lru_lock);
1786 
1787 	/**
1788 	 * Move to system cached
1789 	 */
1790 
1791 	if (bo->mem.mem_type != TTM_PL_SYSTEM ||
1792 	    bo->ttm->caching_state != tt_cached) {
1793 		struct ttm_operation_ctx ctx = { false, false };
1794 		struct ttm_mem_reg evict_mem;
1795 
1796 		evict_mem = bo->mem;
1797 		evict_mem.mm_node = NULL;
1798 		evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
1799 		evict_mem.mem_type = TTM_PL_SYSTEM;
1800 
1801 		ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, &ctx);
1802 		if (unlikely(ret != 0))
1803 			goto out;
1804 	}
1805 
1806 	/**
1807 	 * Make sure BO is idle.
1808 	 */
1809 
1810 	ret = ttm_bo_wait(bo, false, false);
1811 	if (unlikely(ret != 0))
1812 		goto out;
1813 
1814 	ttm_bo_unmap_virtual(bo);
1815 
1816 	/**
1817 	 * Swap out. Buffer will be swapped in again as soon as
1818 	 * anyone tries to access a ttm page.
1819 	 */
1820 
1821 	if (bo->bdev->driver->swap_notify)
1822 		bo->bdev->driver->swap_notify(bo);
1823 
1824 	ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
1825 out:
1826 
1827 	/**
1828 	 *
1829 	 * Unreserve without putting on LRU to avoid swapping out an
1830 	 * already swapped buffer.
1831 	 */
1832 	if (locked)
1833 		dma_resv_unlock(bo->base.resv);
1834 	ttm_bo_put(bo);
1835 	return ret;
1836 }
1837 EXPORT_SYMBOL(ttm_bo_swapout);
1838 
1839 void ttm_bo_swapout_all(struct ttm_bo_device *bdev)
1840 {
1841 	struct ttm_operation_ctx ctx = {
1842 		.interruptible = false,
1843 		.no_wait_gpu = false
1844 	};
1845 
1846 	while (ttm_bo_swapout(&ttm_bo_glob, &ctx) == 0);
1847 }
1848 EXPORT_SYMBOL(ttm_bo_swapout_all);
1849