xref: /openbmc/linux/drivers/gpu/drm/ttm/ttm_bo.c (revision d89775fc)
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 		dma_fence_put(fence);
885 		return -EBUSY;
886 	}
887 
888 	dma_resv_add_shared_fence(bo->base.resv, fence);
889 
890 	ret = dma_resv_reserve_shared(bo->base.resv, 1);
891 	if (unlikely(ret)) {
892 		dma_fence_put(fence);
893 		return ret;
894 	}
895 
896 	dma_fence_put(bo->moving);
897 	bo->moving = fence;
898 	return 0;
899 }
900 
901 /**
902  * Repeatedly evict memory from the LRU for @mem_type until we create enough
903  * space, or we've evicted everything and there isn't enough space.
904  */
905 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
906 				  const struct ttm_place *place,
907 				  struct ttm_mem_reg *mem,
908 				  struct ttm_operation_ctx *ctx)
909 {
910 	struct ttm_bo_device *bdev = bo->bdev;
911 	struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
912 	struct ww_acquire_ctx *ticket;
913 	int ret;
914 
915 	ticket = dma_resv_locking_ctx(bo->base.resv);
916 	do {
917 		ret = ttm_bo_mem_get(bo, place, mem);
918 		if (likely(!ret))
919 			break;
920 		if (unlikely(ret != -ENOSPC))
921 			return ret;
922 		ret = ttm_mem_evict_first(bdev, mem->mem_type, place, ctx,
923 					  ticket);
924 		if (unlikely(ret != 0))
925 			return ret;
926 	} while (1);
927 
928 	return ttm_bo_add_move_fence(bo, man, mem, ctx->no_wait_gpu);
929 }
930 
931 static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man,
932 				      uint32_t cur_placement,
933 				      uint32_t proposed_placement)
934 {
935 	uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
936 	uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
937 
938 	/**
939 	 * Keep current caching if possible.
940 	 */
941 
942 	if ((cur_placement & caching) != 0)
943 		result |= (cur_placement & caching);
944 	else if ((man->default_caching & caching) != 0)
945 		result |= man->default_caching;
946 	else if ((TTM_PL_FLAG_CACHED & caching) != 0)
947 		result |= TTM_PL_FLAG_CACHED;
948 	else if ((TTM_PL_FLAG_WC & caching) != 0)
949 		result |= TTM_PL_FLAG_WC;
950 	else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
951 		result |= TTM_PL_FLAG_UNCACHED;
952 
953 	return result;
954 }
955 
956 static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man,
957 				 uint32_t mem_type,
958 				 const struct ttm_place *place,
959 				 uint32_t *masked_placement)
960 {
961 	uint32_t cur_flags = ttm_bo_type_flags(mem_type);
962 
963 	if ((cur_flags & place->flags & TTM_PL_MASK_MEM) == 0)
964 		return false;
965 
966 	if ((place->flags & man->available_caching) == 0)
967 		return false;
968 
969 	cur_flags |= (place->flags & man->available_caching);
970 
971 	*masked_placement = cur_flags;
972 	return true;
973 }
974 
975 /**
976  * ttm_bo_mem_placement - check if placement is compatible
977  * @bo: BO to find memory for
978  * @place: where to search
979  * @mem: the memory object to fill in
980  * @ctx: operation context
981  *
982  * Check if placement is compatible and fill in mem structure.
983  * Returns -EBUSY if placement won't work or negative error code.
984  * 0 when placement can be used.
985  */
986 static int ttm_bo_mem_placement(struct ttm_buffer_object *bo,
987 				const struct ttm_place *place,
988 				struct ttm_mem_reg *mem,
989 				struct ttm_operation_ctx *ctx)
990 {
991 	struct ttm_bo_device *bdev = bo->bdev;
992 	uint32_t mem_type = TTM_PL_SYSTEM;
993 	struct ttm_mem_type_manager *man;
994 	uint32_t cur_flags = 0;
995 	int ret;
996 
997 	ret = ttm_mem_type_from_place(place, &mem_type);
998 	if (ret)
999 		return ret;
1000 
1001 	man = &bdev->man[mem_type];
1002 	if (!man->has_type || !man->use_type)
1003 		return -EBUSY;
1004 
1005 	if (!ttm_bo_mt_compatible(man, mem_type, place, &cur_flags))
1006 		return -EBUSY;
1007 
1008 	cur_flags = ttm_bo_select_caching(man, bo->mem.placement, cur_flags);
1009 	/*
1010 	 * Use the access and other non-mapping-related flag bits from
1011 	 * the memory placement flags to the current flags
1012 	 */
1013 	ttm_flag_masked(&cur_flags, place->flags, ~TTM_PL_MASK_MEMTYPE);
1014 
1015 	mem->mem_type = mem_type;
1016 	mem->placement = cur_flags;
1017 
1018 	spin_lock(&ttm_bo_glob.lru_lock);
1019 	ttm_bo_del_from_lru(bo);
1020 	ttm_bo_add_mem_to_lru(bo, mem);
1021 	spin_unlock(&ttm_bo_glob.lru_lock);
1022 
1023 	return 0;
1024 }
1025 
1026 /**
1027  * Creates space for memory region @mem according to its type.
1028  *
1029  * This function first searches for free space in compatible memory types in
1030  * the priority order defined by the driver.  If free space isn't found, then
1031  * ttm_bo_mem_force_space is attempted in priority order to evict and find
1032  * space.
1033  */
1034 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1035 			struct ttm_placement *placement,
1036 			struct ttm_mem_reg *mem,
1037 			struct ttm_operation_ctx *ctx)
1038 {
1039 	struct ttm_bo_device *bdev = bo->bdev;
1040 	bool type_found = false;
1041 	int i, ret;
1042 
1043 	ret = dma_resv_reserve_shared(bo->base.resv, 1);
1044 	if (unlikely(ret))
1045 		return ret;
1046 
1047 	for (i = 0; i < placement->num_placement; ++i) {
1048 		const struct ttm_place *place = &placement->placement[i];
1049 		struct ttm_mem_type_manager *man;
1050 
1051 		ret = ttm_bo_mem_placement(bo, place, mem, ctx);
1052 		if (ret == -EBUSY)
1053 			continue;
1054 		if (ret)
1055 			goto error;
1056 
1057 		type_found = true;
1058 		ret = ttm_bo_mem_get(bo, place, mem);
1059 		if (ret == -ENOSPC)
1060 			continue;
1061 		if (unlikely(ret))
1062 			goto error;
1063 
1064 		man = &bdev->man[mem->mem_type];
1065 		ret = ttm_bo_add_move_fence(bo, man, mem, ctx->no_wait_gpu);
1066 		if (unlikely(ret)) {
1067 			ttm_bo_mem_put(bo, mem);
1068 			if (ret == -EBUSY)
1069 				continue;
1070 
1071 			goto error;
1072 		}
1073 		return 0;
1074 	}
1075 
1076 	for (i = 0; i < placement->num_busy_placement; ++i) {
1077 		const struct ttm_place *place = &placement->busy_placement[i];
1078 
1079 		ret = ttm_bo_mem_placement(bo, place, mem, ctx);
1080 		if (ret == -EBUSY)
1081 			continue;
1082 		if (ret)
1083 			goto error;
1084 
1085 		type_found = true;
1086 		ret = ttm_bo_mem_force_space(bo, place, mem, ctx);
1087 		if (likely(!ret))
1088 			return 0;
1089 
1090 		if (ret && ret != -EBUSY)
1091 			goto error;
1092 	}
1093 
1094 	ret = -ENOMEM;
1095 	if (!type_found) {
1096 		pr_err(TTM_PFX "No compatible memory type found\n");
1097 		ret = -EINVAL;
1098 	}
1099 
1100 error:
1101 	if (bo->mem.mem_type == TTM_PL_SYSTEM && !list_empty(&bo->lru)) {
1102 		spin_lock(&ttm_bo_glob.lru_lock);
1103 		ttm_bo_move_to_lru_tail(bo, NULL);
1104 		spin_unlock(&ttm_bo_glob.lru_lock);
1105 	}
1106 
1107 	return ret;
1108 }
1109 EXPORT_SYMBOL(ttm_bo_mem_space);
1110 
1111 static int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
1112 			      struct ttm_placement *placement,
1113 			      struct ttm_operation_ctx *ctx)
1114 {
1115 	int ret = 0;
1116 	struct ttm_mem_reg mem;
1117 
1118 	dma_resv_assert_held(bo->base.resv);
1119 
1120 	mem.num_pages = bo->num_pages;
1121 	mem.size = mem.num_pages << PAGE_SHIFT;
1122 	mem.page_alignment = bo->mem.page_alignment;
1123 	mem.bus.io_reserved_vm = false;
1124 	mem.bus.io_reserved_count = 0;
1125 	mem.mm_node = NULL;
1126 
1127 	/*
1128 	 * Determine where to move the buffer.
1129 	 */
1130 	ret = ttm_bo_mem_space(bo, placement, &mem, ctx);
1131 	if (ret)
1132 		goto out_unlock;
1133 	ret = ttm_bo_handle_move_mem(bo, &mem, false, ctx);
1134 out_unlock:
1135 	if (ret)
1136 		ttm_bo_mem_put(bo, &mem);
1137 	return ret;
1138 }
1139 
1140 static bool ttm_bo_places_compat(const struct ttm_place *places,
1141 				 unsigned num_placement,
1142 				 struct ttm_mem_reg *mem,
1143 				 uint32_t *new_flags)
1144 {
1145 	unsigned i;
1146 
1147 	for (i = 0; i < num_placement; i++) {
1148 		const struct ttm_place *heap = &places[i];
1149 
1150 		if ((mem->start < heap->fpfn ||
1151 		     (heap->lpfn != 0 && (mem->start + mem->num_pages) > heap->lpfn)))
1152 			continue;
1153 
1154 		*new_flags = heap->flags;
1155 		if ((*new_flags & mem->placement & TTM_PL_MASK_CACHING) &&
1156 		    (*new_flags & mem->placement & TTM_PL_MASK_MEM) &&
1157 		    (!(*new_flags & TTM_PL_FLAG_CONTIGUOUS) ||
1158 		     (mem->placement & TTM_PL_FLAG_CONTIGUOUS)))
1159 			return true;
1160 	}
1161 	return false;
1162 }
1163 
1164 bool ttm_bo_mem_compat(struct ttm_placement *placement,
1165 		       struct ttm_mem_reg *mem,
1166 		       uint32_t *new_flags)
1167 {
1168 	if (ttm_bo_places_compat(placement->placement, placement->num_placement,
1169 				 mem, new_flags))
1170 		return true;
1171 
1172 	if ((placement->busy_placement != placement->placement ||
1173 	     placement->num_busy_placement > placement->num_placement) &&
1174 	    ttm_bo_places_compat(placement->busy_placement,
1175 				 placement->num_busy_placement,
1176 				 mem, new_flags))
1177 		return true;
1178 
1179 	return false;
1180 }
1181 EXPORT_SYMBOL(ttm_bo_mem_compat);
1182 
1183 int ttm_bo_validate(struct ttm_buffer_object *bo,
1184 		    struct ttm_placement *placement,
1185 		    struct ttm_operation_ctx *ctx)
1186 {
1187 	int ret;
1188 	uint32_t new_flags;
1189 
1190 	dma_resv_assert_held(bo->base.resv);
1191 
1192 	/*
1193 	 * Remove the backing store if no placement is given.
1194 	 */
1195 	if (!placement->num_placement && !placement->num_busy_placement)
1196 		return ttm_bo_pipeline_gutting(bo);
1197 
1198 	/*
1199 	 * Check whether we need to move buffer.
1200 	 */
1201 	if (!ttm_bo_mem_compat(placement, &bo->mem, &new_flags)) {
1202 		ret = ttm_bo_move_buffer(bo, placement, ctx);
1203 		if (ret)
1204 			return ret;
1205 	} else {
1206 		/*
1207 		 * Use the access and other non-mapping-related flag bits from
1208 		 * the compatible memory placement flags to the active flags
1209 		 */
1210 		ttm_flag_masked(&bo->mem.placement, new_flags,
1211 				~TTM_PL_MASK_MEMTYPE);
1212 	}
1213 	return 0;
1214 }
1215 EXPORT_SYMBOL(ttm_bo_validate);
1216 
1217 int ttm_bo_init_reserved(struct ttm_bo_device *bdev,
1218 			 struct ttm_buffer_object *bo,
1219 			 unsigned long size,
1220 			 enum ttm_bo_type type,
1221 			 struct ttm_placement *placement,
1222 			 uint32_t page_alignment,
1223 			 struct ttm_operation_ctx *ctx,
1224 			 size_t acc_size,
1225 			 struct sg_table *sg,
1226 			 struct dma_resv *resv,
1227 			 void (*destroy) (struct ttm_buffer_object *))
1228 {
1229 	struct ttm_mem_global *mem_glob = &ttm_mem_glob;
1230 	int ret = 0;
1231 	unsigned long num_pages;
1232 	bool locked;
1233 
1234 	ret = ttm_mem_global_alloc(mem_glob, acc_size, ctx);
1235 	if (ret) {
1236 		pr_err("Out of kernel memory\n");
1237 		if (destroy)
1238 			(*destroy)(bo);
1239 		else
1240 			kfree(bo);
1241 		return -ENOMEM;
1242 	}
1243 
1244 	num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1245 	if (num_pages == 0) {
1246 		pr_err("Illegal buffer object size\n");
1247 		if (destroy)
1248 			(*destroy)(bo);
1249 		else
1250 			kfree(bo);
1251 		ttm_mem_global_free(mem_glob, acc_size);
1252 		return -EINVAL;
1253 	}
1254 	bo->destroy = destroy ? destroy : ttm_bo_default_destroy;
1255 
1256 	kref_init(&bo->kref);
1257 	INIT_LIST_HEAD(&bo->lru);
1258 	INIT_LIST_HEAD(&bo->ddestroy);
1259 	INIT_LIST_HEAD(&bo->swap);
1260 	INIT_LIST_HEAD(&bo->io_reserve_lru);
1261 	bo->bdev = bdev;
1262 	bo->type = type;
1263 	bo->num_pages = num_pages;
1264 	bo->mem.size = num_pages << PAGE_SHIFT;
1265 	bo->mem.mem_type = TTM_PL_SYSTEM;
1266 	bo->mem.num_pages = bo->num_pages;
1267 	bo->mem.mm_node = NULL;
1268 	bo->mem.page_alignment = page_alignment;
1269 	bo->mem.bus.io_reserved_vm = false;
1270 	bo->mem.bus.io_reserved_count = 0;
1271 	bo->moving = NULL;
1272 	bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
1273 	bo->acc_size = acc_size;
1274 	bo->sg = sg;
1275 	if (resv) {
1276 		bo->base.resv = resv;
1277 		dma_resv_assert_held(bo->base.resv);
1278 	} else {
1279 		bo->base.resv = &bo->base._resv;
1280 	}
1281 	if (!ttm_bo_uses_embedded_gem_object(bo)) {
1282 		/*
1283 		 * bo.gem is not initialized, so we have to setup the
1284 		 * struct elements we want use regardless.
1285 		 */
1286 		dma_resv_init(&bo->base._resv);
1287 		drm_vma_node_reset(&bo->base.vma_node);
1288 	}
1289 	atomic_inc(&ttm_bo_glob.bo_count);
1290 
1291 	/*
1292 	 * For ttm_bo_type_device buffers, allocate
1293 	 * address space from the device.
1294 	 */
1295 	if (bo->type == ttm_bo_type_device ||
1296 	    bo->type == ttm_bo_type_sg)
1297 		ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
1298 					 bo->mem.num_pages);
1299 
1300 	/* passed reservation objects should already be locked,
1301 	 * since otherwise lockdep will be angered in radeon.
1302 	 */
1303 	if (!resv) {
1304 		locked = dma_resv_trylock(bo->base.resv);
1305 		WARN_ON(!locked);
1306 	}
1307 
1308 	if (likely(!ret))
1309 		ret = ttm_bo_validate(bo, placement, ctx);
1310 
1311 	if (unlikely(ret)) {
1312 		if (!resv)
1313 			ttm_bo_unreserve(bo);
1314 
1315 		ttm_bo_put(bo);
1316 		return ret;
1317 	}
1318 
1319 	spin_lock(&ttm_bo_glob.lru_lock);
1320 	ttm_bo_move_to_lru_tail(bo, NULL);
1321 	spin_unlock(&ttm_bo_glob.lru_lock);
1322 
1323 	return ret;
1324 }
1325 EXPORT_SYMBOL(ttm_bo_init_reserved);
1326 
1327 int ttm_bo_init(struct ttm_bo_device *bdev,
1328 		struct ttm_buffer_object *bo,
1329 		unsigned long size,
1330 		enum ttm_bo_type type,
1331 		struct ttm_placement *placement,
1332 		uint32_t page_alignment,
1333 		bool interruptible,
1334 		size_t acc_size,
1335 		struct sg_table *sg,
1336 		struct dma_resv *resv,
1337 		void (*destroy) (struct ttm_buffer_object *))
1338 {
1339 	struct ttm_operation_ctx ctx = { interruptible, false };
1340 	int ret;
1341 
1342 	ret = ttm_bo_init_reserved(bdev, bo, size, type, placement,
1343 				   page_alignment, &ctx, acc_size,
1344 				   sg, resv, destroy);
1345 	if (ret)
1346 		return ret;
1347 
1348 	if (!resv)
1349 		ttm_bo_unreserve(bo);
1350 
1351 	return 0;
1352 }
1353 EXPORT_SYMBOL(ttm_bo_init);
1354 
1355 size_t ttm_bo_acc_size(struct ttm_bo_device *bdev,
1356 		       unsigned long bo_size,
1357 		       unsigned struct_size)
1358 {
1359 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1360 	size_t size = 0;
1361 
1362 	size += ttm_round_pot(struct_size);
1363 	size += ttm_round_pot(npages * sizeof(void *));
1364 	size += ttm_round_pot(sizeof(struct ttm_tt));
1365 	return size;
1366 }
1367 EXPORT_SYMBOL(ttm_bo_acc_size);
1368 
1369 size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev,
1370 			   unsigned long bo_size,
1371 			   unsigned struct_size)
1372 {
1373 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1374 	size_t size = 0;
1375 
1376 	size += ttm_round_pot(struct_size);
1377 	size += ttm_round_pot(npages * (2*sizeof(void *) + sizeof(dma_addr_t)));
1378 	size += ttm_round_pot(sizeof(struct ttm_dma_tt));
1379 	return size;
1380 }
1381 EXPORT_SYMBOL(ttm_bo_dma_acc_size);
1382 
1383 int ttm_bo_create(struct ttm_bo_device *bdev,
1384 			unsigned long size,
1385 			enum ttm_bo_type type,
1386 			struct ttm_placement *placement,
1387 			uint32_t page_alignment,
1388 			bool interruptible,
1389 			struct ttm_buffer_object **p_bo)
1390 {
1391 	struct ttm_buffer_object *bo;
1392 	size_t acc_size;
1393 	int ret;
1394 
1395 	bo = kzalloc(sizeof(*bo), GFP_KERNEL);
1396 	if (unlikely(bo == NULL))
1397 		return -ENOMEM;
1398 
1399 	acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object));
1400 	ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
1401 			  interruptible, acc_size,
1402 			  NULL, NULL, NULL);
1403 	if (likely(ret == 0))
1404 		*p_bo = bo;
1405 
1406 	return ret;
1407 }
1408 EXPORT_SYMBOL(ttm_bo_create);
1409 
1410 static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev,
1411 				   unsigned mem_type)
1412 {
1413 	struct ttm_operation_ctx ctx = {
1414 		.interruptible = false,
1415 		.no_wait_gpu = false,
1416 		.flags = TTM_OPT_FLAG_FORCE_ALLOC
1417 	};
1418 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1419 	struct ttm_bo_global *glob = &ttm_bo_glob;
1420 	struct dma_fence *fence;
1421 	int ret;
1422 	unsigned i;
1423 
1424 	/*
1425 	 * Can't use standard list traversal since we're unlocking.
1426 	 */
1427 
1428 	spin_lock(&glob->lru_lock);
1429 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1430 		while (!list_empty(&man->lru[i])) {
1431 			spin_unlock(&glob->lru_lock);
1432 			ret = ttm_mem_evict_first(bdev, mem_type, NULL, &ctx,
1433 						  NULL);
1434 			if (ret)
1435 				return ret;
1436 			spin_lock(&glob->lru_lock);
1437 		}
1438 	}
1439 	spin_unlock(&glob->lru_lock);
1440 
1441 	spin_lock(&man->move_lock);
1442 	fence = dma_fence_get(man->move);
1443 	spin_unlock(&man->move_lock);
1444 
1445 	if (fence) {
1446 		ret = dma_fence_wait(fence, false);
1447 		dma_fence_put(fence);
1448 		if (ret)
1449 			return ret;
1450 	}
1451 
1452 	return 0;
1453 }
1454 
1455 int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1456 {
1457 	struct ttm_mem_type_manager *man;
1458 	int ret = -EINVAL;
1459 
1460 	if (mem_type >= TTM_NUM_MEM_TYPES) {
1461 		pr_err("Illegal memory type %d\n", mem_type);
1462 		return ret;
1463 	}
1464 	man = &bdev->man[mem_type];
1465 
1466 	if (!man->has_type) {
1467 		pr_err("Trying to take down uninitialized memory manager type %u\n",
1468 		       mem_type);
1469 		return ret;
1470 	}
1471 
1472 	man->use_type = false;
1473 	man->has_type = false;
1474 
1475 	ret = 0;
1476 	if (mem_type > 0) {
1477 		ret = ttm_bo_force_list_clean(bdev, mem_type);
1478 		if (ret) {
1479 			pr_err("Cleanup eviction failed\n");
1480 			return ret;
1481 		}
1482 
1483 		ret = (*man->func->takedown)(man);
1484 	}
1485 
1486 	dma_fence_put(man->move);
1487 	man->move = NULL;
1488 
1489 	return ret;
1490 }
1491 EXPORT_SYMBOL(ttm_bo_clean_mm);
1492 
1493 int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1494 {
1495 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1496 
1497 	if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
1498 		pr_err("Illegal memory manager memory type %u\n", mem_type);
1499 		return -EINVAL;
1500 	}
1501 
1502 	if (!man->has_type) {
1503 		pr_err("Memory type %u has not been initialized\n", mem_type);
1504 		return 0;
1505 	}
1506 
1507 	return ttm_bo_force_list_clean(bdev, mem_type);
1508 }
1509 EXPORT_SYMBOL(ttm_bo_evict_mm);
1510 
1511 int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type,
1512 			unsigned long p_size)
1513 {
1514 	int ret;
1515 	struct ttm_mem_type_manager *man;
1516 	unsigned i;
1517 
1518 	BUG_ON(type >= TTM_NUM_MEM_TYPES);
1519 	man = &bdev->man[type];
1520 	BUG_ON(man->has_type);
1521 	man->use_io_reserve_lru = false;
1522 	mutex_init(&man->io_reserve_mutex);
1523 	spin_lock_init(&man->move_lock);
1524 	INIT_LIST_HEAD(&man->io_reserve_lru);
1525 
1526 	ret = bdev->driver->init_mem_type(bdev, type, man);
1527 	if (ret)
1528 		return ret;
1529 	man->bdev = bdev;
1530 
1531 	if (type != TTM_PL_SYSTEM) {
1532 		ret = (*man->func->init)(man, p_size);
1533 		if (ret)
1534 			return ret;
1535 	}
1536 	man->has_type = true;
1537 	man->use_type = true;
1538 	man->size = p_size;
1539 
1540 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1541 		INIT_LIST_HEAD(&man->lru[i]);
1542 	man->move = NULL;
1543 
1544 	return 0;
1545 }
1546 EXPORT_SYMBOL(ttm_bo_init_mm);
1547 
1548 static void ttm_bo_global_kobj_release(struct kobject *kobj)
1549 {
1550 	struct ttm_bo_global *glob =
1551 		container_of(kobj, struct ttm_bo_global, kobj);
1552 
1553 	__free_page(glob->dummy_read_page);
1554 }
1555 
1556 static void ttm_bo_global_release(void)
1557 {
1558 	struct ttm_bo_global *glob = &ttm_bo_glob;
1559 
1560 	mutex_lock(&ttm_global_mutex);
1561 	if (--ttm_bo_glob_use_count > 0)
1562 		goto out;
1563 
1564 	kobject_del(&glob->kobj);
1565 	kobject_put(&glob->kobj);
1566 	ttm_mem_global_release(&ttm_mem_glob);
1567 	memset(glob, 0, sizeof(*glob));
1568 out:
1569 	mutex_unlock(&ttm_global_mutex);
1570 }
1571 
1572 static int ttm_bo_global_init(void)
1573 {
1574 	struct ttm_bo_global *glob = &ttm_bo_glob;
1575 	int ret = 0;
1576 	unsigned i;
1577 
1578 	mutex_lock(&ttm_global_mutex);
1579 	if (++ttm_bo_glob_use_count > 1)
1580 		goto out;
1581 
1582 	ret = ttm_mem_global_init(&ttm_mem_glob);
1583 	if (ret)
1584 		goto out;
1585 
1586 	spin_lock_init(&glob->lru_lock);
1587 	glob->dummy_read_page = alloc_page(__GFP_ZERO | GFP_DMA32);
1588 
1589 	if (unlikely(glob->dummy_read_page == NULL)) {
1590 		ret = -ENOMEM;
1591 		goto out;
1592 	}
1593 
1594 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1595 		INIT_LIST_HEAD(&glob->swap_lru[i]);
1596 	INIT_LIST_HEAD(&glob->device_list);
1597 	atomic_set(&glob->bo_count, 0);
1598 
1599 	ret = kobject_init_and_add(
1600 		&glob->kobj, &ttm_bo_glob_kobj_type, ttm_get_kobj(), "buffer_objects");
1601 	if (unlikely(ret != 0))
1602 		kobject_put(&glob->kobj);
1603 out:
1604 	mutex_unlock(&ttm_global_mutex);
1605 	return ret;
1606 }
1607 
1608 int ttm_bo_device_release(struct ttm_bo_device *bdev)
1609 {
1610 	struct ttm_bo_global *glob = &ttm_bo_glob;
1611 	int ret = 0;
1612 	unsigned i = TTM_NUM_MEM_TYPES;
1613 	struct ttm_mem_type_manager *man;
1614 
1615 	while (i--) {
1616 		man = &bdev->man[i];
1617 		if (man->has_type) {
1618 			man->use_type = false;
1619 			if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) {
1620 				ret = -EBUSY;
1621 				pr_err("DRM memory manager type %d is not clean\n",
1622 				       i);
1623 			}
1624 			man->has_type = false;
1625 		}
1626 	}
1627 
1628 	mutex_lock(&ttm_global_mutex);
1629 	list_del(&bdev->device_list);
1630 	mutex_unlock(&ttm_global_mutex);
1631 
1632 	cancel_delayed_work_sync(&bdev->wq);
1633 
1634 	if (ttm_bo_delayed_delete(bdev, true))
1635 		pr_debug("Delayed destroy list was clean\n");
1636 
1637 	spin_lock(&glob->lru_lock);
1638 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1639 		if (list_empty(&bdev->man[0].lru[0]))
1640 			pr_debug("Swap list %d was clean\n", i);
1641 	spin_unlock(&glob->lru_lock);
1642 
1643 	if (!ret)
1644 		ttm_bo_global_release();
1645 
1646 	return ret;
1647 }
1648 EXPORT_SYMBOL(ttm_bo_device_release);
1649 
1650 int ttm_bo_device_init(struct ttm_bo_device *bdev,
1651 		       struct ttm_bo_driver *driver,
1652 		       struct address_space *mapping,
1653 		       struct drm_vma_offset_manager *vma_manager,
1654 		       bool need_dma32)
1655 {
1656 	struct ttm_bo_global *glob = &ttm_bo_glob;
1657 	int ret;
1658 
1659 	if (WARN_ON(vma_manager == NULL))
1660 		return -EINVAL;
1661 
1662 	ret = ttm_bo_global_init();
1663 	if (ret)
1664 		return ret;
1665 
1666 	bdev->driver = driver;
1667 
1668 	memset(bdev->man, 0, sizeof(bdev->man));
1669 
1670 	/*
1671 	 * Initialize the system memory buffer type.
1672 	 * Other types need to be driver / IOCTL initialized.
1673 	 */
1674 	ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0);
1675 	if (unlikely(ret != 0))
1676 		goto out_no_sys;
1677 
1678 	bdev->vma_manager = vma_manager;
1679 	INIT_DELAYED_WORK(&bdev->wq, ttm_bo_delayed_workqueue);
1680 	INIT_LIST_HEAD(&bdev->ddestroy);
1681 	bdev->dev_mapping = mapping;
1682 	bdev->need_dma32 = need_dma32;
1683 	mutex_lock(&ttm_global_mutex);
1684 	list_add_tail(&bdev->device_list, &glob->device_list);
1685 	mutex_unlock(&ttm_global_mutex);
1686 
1687 	return 0;
1688 out_no_sys:
1689 	ttm_bo_global_release();
1690 	return ret;
1691 }
1692 EXPORT_SYMBOL(ttm_bo_device_init);
1693 
1694 /*
1695  * buffer object vm functions.
1696  */
1697 
1698 void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
1699 {
1700 	struct ttm_bo_device *bdev = bo->bdev;
1701 
1702 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1703 	ttm_mem_io_free_vm(bo);
1704 }
1705 
1706 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1707 {
1708 	struct ttm_bo_device *bdev = bo->bdev;
1709 	struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
1710 
1711 	ttm_mem_io_lock(man, false);
1712 	ttm_bo_unmap_virtual_locked(bo);
1713 	ttm_mem_io_unlock(man);
1714 }
1715 
1716 
1717 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1718 
1719 int ttm_bo_wait(struct ttm_buffer_object *bo,
1720 		bool interruptible, bool no_wait)
1721 {
1722 	long timeout = 15 * HZ;
1723 
1724 	if (no_wait) {
1725 		if (dma_resv_test_signaled_rcu(bo->base.resv, true))
1726 			return 0;
1727 		else
1728 			return -EBUSY;
1729 	}
1730 
1731 	timeout = dma_resv_wait_timeout_rcu(bo->base.resv, true,
1732 						      interruptible, timeout);
1733 	if (timeout < 0)
1734 		return timeout;
1735 
1736 	if (timeout == 0)
1737 		return -EBUSY;
1738 
1739 	dma_resv_add_excl_fence(bo->base.resv, NULL);
1740 	return 0;
1741 }
1742 EXPORT_SYMBOL(ttm_bo_wait);
1743 
1744 /**
1745  * A buffer object shrink method that tries to swap out the first
1746  * buffer object on the bo_global::swap_lru list.
1747  */
1748 int ttm_bo_swapout(struct ttm_bo_global *glob, struct ttm_operation_ctx *ctx)
1749 {
1750 	struct ttm_buffer_object *bo;
1751 	int ret = -EBUSY;
1752 	bool locked;
1753 	unsigned i;
1754 
1755 	spin_lock(&glob->lru_lock);
1756 	for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1757 		list_for_each_entry(bo, &glob->swap_lru[i], swap) {
1758 			if (!ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
1759 							    NULL))
1760 				continue;
1761 
1762 			if (!ttm_bo_get_unless_zero(bo)) {
1763 				if (locked)
1764 					dma_resv_unlock(bo->base.resv);
1765 				continue;
1766 			}
1767 
1768 			ret = 0;
1769 			break;
1770 		}
1771 		if (!ret)
1772 			break;
1773 	}
1774 
1775 	if (ret) {
1776 		spin_unlock(&glob->lru_lock);
1777 		return ret;
1778 	}
1779 
1780 	if (bo->deleted) {
1781 		ret = ttm_bo_cleanup_refs(bo, false, false, locked);
1782 		ttm_bo_put(bo);
1783 		return ret;
1784 	}
1785 
1786 	ttm_bo_del_from_lru(bo);
1787 	spin_unlock(&glob->lru_lock);
1788 
1789 	/**
1790 	 * Move to system cached
1791 	 */
1792 
1793 	if (bo->mem.mem_type != TTM_PL_SYSTEM ||
1794 	    bo->ttm->caching_state != tt_cached) {
1795 		struct ttm_operation_ctx ctx = { false, false };
1796 		struct ttm_mem_reg evict_mem;
1797 
1798 		evict_mem = bo->mem;
1799 		evict_mem.mm_node = NULL;
1800 		evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
1801 		evict_mem.mem_type = TTM_PL_SYSTEM;
1802 
1803 		ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, &ctx);
1804 		if (unlikely(ret != 0))
1805 			goto out;
1806 	}
1807 
1808 	/**
1809 	 * Make sure BO is idle.
1810 	 */
1811 
1812 	ret = ttm_bo_wait(bo, false, false);
1813 	if (unlikely(ret != 0))
1814 		goto out;
1815 
1816 	ttm_bo_unmap_virtual(bo);
1817 
1818 	/**
1819 	 * Swap out. Buffer will be swapped in again as soon as
1820 	 * anyone tries to access a ttm page.
1821 	 */
1822 
1823 	if (bo->bdev->driver->swap_notify)
1824 		bo->bdev->driver->swap_notify(bo);
1825 
1826 	ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
1827 out:
1828 
1829 	/**
1830 	 *
1831 	 * Unreserve without putting on LRU to avoid swapping out an
1832 	 * already swapped buffer.
1833 	 */
1834 	if (locked)
1835 		dma_resv_unlock(bo->base.resv);
1836 	ttm_bo_put(bo);
1837 	return ret;
1838 }
1839 EXPORT_SYMBOL(ttm_bo_swapout);
1840 
1841 void ttm_bo_swapout_all(void)
1842 {
1843 	struct ttm_operation_ctx ctx = {
1844 		.interruptible = false,
1845 		.no_wait_gpu = false
1846 	};
1847 
1848 	while (ttm_bo_swapout(&ttm_bo_glob, &ctx) == 0);
1849 }
1850 EXPORT_SYMBOL(ttm_bo_swapout_all);
1851