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