xref: /freebsd/sys/dev/drm2/ttm/ttm_bo.c (revision ec273ebf3b6aed5fba8c56b6ece5ad8693a48ea7)
1 /**************************************************************************
2  *
3  * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
22  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24  * USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  **************************************************************************/
27 /*
28  * Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <dev/drm2/drmP.h>
35 #include <dev/drm2/ttm/ttm_module.h>
36 #include <dev/drm2/ttm/ttm_bo_driver.h>
37 #include <dev/drm2/ttm/ttm_placement.h>
38 #include <vm/vm_pageout.h>
39 
40 #define TTM_ASSERT_LOCKED(param)
41 #define TTM_DEBUG(fmt, arg...)
42 #define TTM_BO_HASH_ORDER 13
43 
44 static int ttm_bo_setup_vm(struct ttm_buffer_object *bo);
45 static int ttm_bo_swapout(struct ttm_mem_shrink *shrink);
46 static void ttm_bo_global_kobj_release(struct ttm_bo_global *glob);
47 
48 MALLOC_DEFINE(M_TTM_BO, "ttm_bo", "TTM Buffer Objects");
49 
50 static inline int ttm_mem_type_from_flags(uint32_t flags, uint32_t *mem_type)
51 {
52 	int i;
53 
54 	for (i = 0; i <= TTM_PL_PRIV5; i++)
55 		if (flags & (1 << i)) {
56 			*mem_type = i;
57 			return 0;
58 		}
59 	return -EINVAL;
60 }
61 
62 static void ttm_mem_type_debug(struct ttm_bo_device *bdev, int mem_type)
63 {
64 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
65 
66 	printf("    has_type: %d\n", man->has_type);
67 	printf("    use_type: %d\n", man->use_type);
68 	printf("    flags: 0x%08X\n", man->flags);
69 	printf("    gpu_offset: 0x%08lX\n", man->gpu_offset);
70 	printf("    size: %ju\n", (uintmax_t)man->size);
71 	printf("    available_caching: 0x%08X\n", man->available_caching);
72 	printf("    default_caching: 0x%08X\n", man->default_caching);
73 	if (mem_type != TTM_PL_SYSTEM)
74 		(*man->func->debug)(man, TTM_PFX);
75 }
76 
77 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
78 					struct ttm_placement *placement)
79 {
80 	int i, ret, mem_type;
81 
82 	printf("No space for %p (%lu pages, %luK, %luM)\n",
83 	       bo, bo->mem.num_pages, bo->mem.size >> 10,
84 	       bo->mem.size >> 20);
85 	for (i = 0; i < placement->num_placement; i++) {
86 		ret = ttm_mem_type_from_flags(placement->placement[i],
87 						&mem_type);
88 		if (ret)
89 			return;
90 		printf("  placement[%d]=0x%08X (%d)\n",
91 		       i, placement->placement[i], mem_type);
92 		ttm_mem_type_debug(bo->bdev, mem_type);
93 	}
94 }
95 
96 #if 0
97 static ssize_t ttm_bo_global_show(struct ttm_bo_global *glob,
98     char *buffer)
99 {
100 
101 	return snprintf(buffer, PAGE_SIZE, "%lu\n",
102 			(unsigned long) atomic_read(&glob->bo_count));
103 }
104 #endif
105 
106 static inline uint32_t ttm_bo_type_flags(unsigned type)
107 {
108 	return 1 << (type);
109 }
110 
111 static void ttm_bo_release_list(struct ttm_buffer_object *bo)
112 {
113 	struct ttm_bo_device *bdev = bo->bdev;
114 	size_t acc_size = bo->acc_size;
115 
116 	MPASS(atomic_read(&bo->list_kref) == 0);
117 	MPASS(atomic_read(&bo->kref) == 0);
118 	MPASS(atomic_read(&bo->cpu_writers) == 0);
119 	MPASS(bo->sync_obj == NULL);
120 	MPASS(bo->mem.mm_node == NULL);
121 	MPASS(list_empty(&bo->lru));
122 	MPASS(list_empty(&bo->ddestroy));
123 
124 	if (bo->ttm)
125 		ttm_tt_destroy(bo->ttm);
126 	atomic_dec(&bo->glob->bo_count);
127 	if (bo->destroy)
128 		bo->destroy(bo);
129 	else {
130 		free(bo, M_TTM_BO);
131 	}
132 	ttm_mem_global_free(bdev->glob->mem_glob, acc_size);
133 }
134 
135 static int
136 ttm_bo_wait_unreserved_locked(struct ttm_buffer_object *bo, bool interruptible)
137 {
138 	const char *wmsg;
139 	int flags, ret;
140 
141 	ret = 0;
142 	if (interruptible) {
143 		flags = PCATCH;
144 		wmsg = "ttbowi";
145 	} else {
146 		flags = 0;
147 		wmsg = "ttbowu";
148 	}
149 	while (ttm_bo_is_reserved(bo)) {
150 		ret = -msleep(bo, &bo->glob->lru_lock, flags, wmsg, 0);
151 		if (ret == -EINTR)
152 			ret = -ERESTARTSYS;
153 		if (ret != 0)
154 			break;
155 	}
156 	return (ret);
157 }
158 
159 void ttm_bo_add_to_lru(struct ttm_buffer_object *bo)
160 {
161 	struct ttm_bo_device *bdev = bo->bdev;
162 	struct ttm_mem_type_manager *man;
163 
164 	MPASS(ttm_bo_is_reserved(bo));
165 
166 	if (!(bo->mem.placement & TTM_PL_FLAG_NO_EVICT)) {
167 
168 		MPASS(list_empty(&bo->lru));
169 
170 		man = &bdev->man[bo->mem.mem_type];
171 		list_add_tail(&bo->lru, &man->lru);
172 		refcount_acquire(&bo->list_kref);
173 
174 		if (bo->ttm != NULL) {
175 			list_add_tail(&bo->swap, &bo->glob->swap_lru);
176 			refcount_acquire(&bo->list_kref);
177 		}
178 	}
179 }
180 
181 int ttm_bo_del_from_lru(struct ttm_buffer_object *bo)
182 {
183 	int put_count = 0;
184 
185 	if (!list_empty(&bo->swap)) {
186 		list_del_init(&bo->swap);
187 		++put_count;
188 	}
189 	if (!list_empty(&bo->lru)) {
190 		list_del_init(&bo->lru);
191 		++put_count;
192 	}
193 
194 	/*
195 	 * TODO: Add a driver hook to delete from
196 	 * driver-specific LRU's here.
197 	 */
198 
199 	return put_count;
200 }
201 
202 int ttm_bo_reserve_nolru(struct ttm_buffer_object *bo,
203 			  bool interruptible,
204 			  bool no_wait, bool use_sequence, uint32_t sequence)
205 {
206 	int ret;
207 
208 	while (unlikely(atomic_xchg(&bo->reserved, 1) != 0)) {
209 		/**
210 		 * Deadlock avoidance for multi-bo reserving.
211 		 */
212 		if (use_sequence && bo->seq_valid) {
213 			/**
214 			 * We've already reserved this one.
215 			 */
216 			if (unlikely(sequence == bo->val_seq))
217 				return -EDEADLK;
218 			/**
219 			 * Already reserved by a thread that will not back
220 			 * off for us. We need to back off.
221 			 */
222 			if (unlikely(sequence - bo->val_seq < (1U << 31)))
223 				return -EAGAIN;
224 		}
225 
226 		if (no_wait)
227 			return -EBUSY;
228 
229 		ret = ttm_bo_wait_unreserved_locked(bo, interruptible);
230 
231 		if (unlikely(ret))
232 			return ret;
233 	}
234 
235 	if (use_sequence) {
236 		bool wake_up = false;
237 		/**
238 		 * Wake up waiters that may need to recheck for deadlock,
239 		 * if we decreased the sequence number.
240 		 */
241 		if (unlikely((bo->val_seq - sequence < (1U << 31))
242 			     || !bo->seq_valid))
243 			wake_up = true;
244 
245 		/*
246 		 * In the worst case with memory ordering these values can be
247 		 * seen in the wrong order. However since we call wake_up_all
248 		 * in that case, this will hopefully not pose a problem,
249 		 * and the worst case would only cause someone to accidentally
250 		 * hit -EAGAIN in ttm_bo_reserve when they see old value of
251 		 * val_seq. However this would only happen if seq_valid was
252 		 * written before val_seq was, and just means some slightly
253 		 * increased cpu usage
254 		 */
255 		bo->val_seq = sequence;
256 		bo->seq_valid = true;
257 		if (wake_up)
258 			wakeup(bo);
259 	} else {
260 		bo->seq_valid = false;
261 	}
262 
263 	return 0;
264 }
265 
266 void ttm_bo_list_ref_sub(struct ttm_buffer_object *bo, int count,
267 			 bool never_free)
268 {
269 	u_int old;
270 
271 	old = atomic_fetchadd_int(&bo->list_kref, -count);
272 	if (old <= count) {
273 		if (never_free)
274 			panic("ttm_bo_ref_buf");
275 		ttm_bo_release_list(bo);
276 	}
277 }
278 
279 int ttm_bo_reserve(struct ttm_buffer_object *bo,
280 		   bool interruptible,
281 		   bool no_wait, bool use_sequence, uint32_t sequence)
282 {
283 	struct ttm_bo_global *glob = bo->glob;
284 	int put_count = 0;
285 	int ret;
286 
287 	mtx_lock(&bo->glob->lru_lock);
288 	ret = ttm_bo_reserve_nolru(bo, interruptible, no_wait, use_sequence,
289 				   sequence);
290 	if (likely(ret == 0)) {
291 		put_count = ttm_bo_del_from_lru(bo);
292 		mtx_unlock(&glob->lru_lock);
293 		ttm_bo_list_ref_sub(bo, put_count, true);
294 	} else
295 		mtx_unlock(&bo->glob->lru_lock);
296 
297 	return ret;
298 }
299 
300 int ttm_bo_reserve_slowpath_nolru(struct ttm_buffer_object *bo,
301 				  bool interruptible, uint32_t sequence)
302 {
303 	bool wake_up = false;
304 	int ret;
305 
306 	while (unlikely(atomic_xchg(&bo->reserved, 1) != 0)) {
307 		if (bo->seq_valid && sequence == bo->val_seq) {
308 			DRM_ERROR(
309 			    "%s: bo->seq_valid && sequence == bo->val_seq",
310 			    __func__);
311 		}
312 
313 		ret = ttm_bo_wait_unreserved_locked(bo, interruptible);
314 
315 		if (unlikely(ret))
316 			return ret;
317 	}
318 
319 	if ((bo->val_seq - sequence < (1U << 31)) || !bo->seq_valid)
320 		wake_up = true;
321 
322 	/**
323 	 * Wake up waiters that may need to recheck for deadlock,
324 	 * if we decreased the sequence number.
325 	 */
326 	bo->val_seq = sequence;
327 	bo->seq_valid = true;
328 	if (wake_up)
329 		wakeup(bo);
330 
331 	return 0;
332 }
333 
334 int ttm_bo_reserve_slowpath(struct ttm_buffer_object *bo,
335 			    bool interruptible, uint32_t sequence)
336 {
337 	struct ttm_bo_global *glob = bo->glob;
338 	int put_count, ret;
339 
340 	mtx_lock(&glob->lru_lock);
341 	ret = ttm_bo_reserve_slowpath_nolru(bo, interruptible, sequence);
342 	if (likely(!ret)) {
343 		put_count = ttm_bo_del_from_lru(bo);
344 		mtx_unlock(&glob->lru_lock);
345 		ttm_bo_list_ref_sub(bo, put_count, true);
346 	} else
347 		mtx_unlock(&glob->lru_lock);
348 	return ret;
349 }
350 
351 void ttm_bo_unreserve_locked(struct ttm_buffer_object *bo)
352 {
353 	ttm_bo_add_to_lru(bo);
354 	atomic_set(&bo->reserved, 0);
355 	wakeup(bo);
356 }
357 
358 void ttm_bo_unreserve(struct ttm_buffer_object *bo)
359 {
360 	struct ttm_bo_global *glob = bo->glob;
361 
362 	mtx_lock(&glob->lru_lock);
363 	ttm_bo_unreserve_locked(bo);
364 	mtx_unlock(&glob->lru_lock);
365 }
366 
367 /*
368  * Call bo->mutex locked.
369  */
370 static int ttm_bo_add_ttm(struct ttm_buffer_object *bo, bool zero_alloc)
371 {
372 	struct ttm_bo_device *bdev = bo->bdev;
373 	struct ttm_bo_global *glob = bo->glob;
374 	int ret = 0;
375 	uint32_t page_flags = 0;
376 
377 	TTM_ASSERT_LOCKED(&bo->mutex);
378 	bo->ttm = NULL;
379 
380 	if (bdev->need_dma32)
381 		page_flags |= TTM_PAGE_FLAG_DMA32;
382 
383 	switch (bo->type) {
384 	case ttm_bo_type_device:
385 		if (zero_alloc)
386 			page_flags |= TTM_PAGE_FLAG_ZERO_ALLOC;
387 	case ttm_bo_type_kernel:
388 		bo->ttm = bdev->driver->ttm_tt_create(bdev, bo->num_pages << PAGE_SHIFT,
389 						      page_flags, glob->dummy_read_page);
390 		if (unlikely(bo->ttm == NULL))
391 			ret = -ENOMEM;
392 		break;
393 	case ttm_bo_type_sg:
394 		bo->ttm = bdev->driver->ttm_tt_create(bdev, bo->num_pages << PAGE_SHIFT,
395 						      page_flags | TTM_PAGE_FLAG_SG,
396 						      glob->dummy_read_page);
397 		if (unlikely(bo->ttm == NULL)) {
398 			ret = -ENOMEM;
399 			break;
400 		}
401 		bo->ttm->sg = bo->sg;
402 		break;
403 	default:
404 		printf("[TTM] Illegal buffer object type\n");
405 		ret = -EINVAL;
406 		break;
407 	}
408 
409 	return ret;
410 }
411 
412 static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo,
413 				  struct ttm_mem_reg *mem,
414 				  bool evict, bool interruptible,
415 				  bool no_wait_gpu)
416 {
417 	struct ttm_bo_device *bdev = bo->bdev;
418 	bool old_is_pci = ttm_mem_reg_is_pci(bdev, &bo->mem);
419 	bool new_is_pci = ttm_mem_reg_is_pci(bdev, mem);
420 	struct ttm_mem_type_manager *old_man = &bdev->man[bo->mem.mem_type];
421 	struct ttm_mem_type_manager *new_man = &bdev->man[mem->mem_type];
422 	int ret = 0;
423 
424 	if (old_is_pci || new_is_pci ||
425 	    ((mem->placement & bo->mem.placement & TTM_PL_MASK_CACHING) == 0)) {
426 		ret = ttm_mem_io_lock(old_man, true);
427 		if (unlikely(ret != 0))
428 			goto out_err;
429 		ttm_bo_unmap_virtual_locked(bo);
430 		ttm_mem_io_unlock(old_man);
431 	}
432 
433 	/*
434 	 * Create and bind a ttm if required.
435 	 */
436 
437 	if (!(new_man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
438 		if (bo->ttm == NULL) {
439 			bool zero = !(old_man->flags & TTM_MEMTYPE_FLAG_FIXED);
440 			ret = ttm_bo_add_ttm(bo, zero);
441 			if (ret)
442 				goto out_err;
443 		}
444 
445 		ret = ttm_tt_set_placement_caching(bo->ttm, mem->placement);
446 		if (ret)
447 			goto out_err;
448 
449 		if (mem->mem_type != TTM_PL_SYSTEM) {
450 			ret = ttm_tt_bind(bo->ttm, mem);
451 			if (ret)
452 				goto out_err;
453 		}
454 
455 		if (bo->mem.mem_type == TTM_PL_SYSTEM) {
456 			if (bdev->driver->move_notify)
457 				bdev->driver->move_notify(bo, mem);
458 			bo->mem = *mem;
459 			mem->mm_node = NULL;
460 			goto moved;
461 		}
462 	}
463 
464 	if (bdev->driver->move_notify)
465 		bdev->driver->move_notify(bo, mem);
466 
467 	if (!(old_man->flags & TTM_MEMTYPE_FLAG_FIXED) &&
468 	    !(new_man->flags & TTM_MEMTYPE_FLAG_FIXED))
469 		ret = ttm_bo_move_ttm(bo, evict, no_wait_gpu, mem);
470 	else if (bdev->driver->move)
471 		ret = bdev->driver->move(bo, evict, interruptible,
472 					 no_wait_gpu, mem);
473 	else
474 		ret = ttm_bo_move_memcpy(bo, evict, no_wait_gpu, mem);
475 
476 	if (ret) {
477 		if (bdev->driver->move_notify) {
478 			struct ttm_mem_reg tmp_mem = *mem;
479 			*mem = bo->mem;
480 			bo->mem = tmp_mem;
481 			bdev->driver->move_notify(bo, mem);
482 			bo->mem = *mem;
483 			*mem = tmp_mem;
484 		}
485 
486 		goto out_err;
487 	}
488 
489 moved:
490 	if (bo->evicted) {
491 		ret = bdev->driver->invalidate_caches(bdev, bo->mem.placement);
492 		if (ret)
493 			printf("[TTM] Can not flush read caches\n");
494 		bo->evicted = false;
495 	}
496 
497 	if (bo->mem.mm_node) {
498 		bo->offset = (bo->mem.start << PAGE_SHIFT) +
499 		    bdev->man[bo->mem.mem_type].gpu_offset;
500 		bo->cur_placement = bo->mem.placement;
501 	} else
502 		bo->offset = 0;
503 
504 	return 0;
505 
506 out_err:
507 	new_man = &bdev->man[bo->mem.mem_type];
508 	if ((new_man->flags & TTM_MEMTYPE_FLAG_FIXED) && bo->ttm) {
509 		ttm_tt_unbind(bo->ttm);
510 		ttm_tt_destroy(bo->ttm);
511 		bo->ttm = NULL;
512 	}
513 
514 	return ret;
515 }
516 
517 /**
518  * Call bo::reserved.
519  * Will release GPU memory type usage on destruction.
520  * This is the place to put in driver specific hooks to release
521  * driver private resources.
522  * Will release the bo::reserved lock.
523  */
524 
525 static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo)
526 {
527 	if (bo->bdev->driver->move_notify)
528 		bo->bdev->driver->move_notify(bo, NULL);
529 
530 	if (bo->ttm) {
531 		ttm_tt_unbind(bo->ttm);
532 		ttm_tt_destroy(bo->ttm);
533 		bo->ttm = NULL;
534 	}
535 	ttm_bo_mem_put(bo, &bo->mem);
536 
537 	atomic_set(&bo->reserved, 0);
538 	wakeup(&bo);
539 
540 	/*
541 	 * Since the final reference to this bo may not be dropped by
542 	 * the current task we have to put a memory barrier here to make
543 	 * sure the changes done in this function are always visible.
544 	 *
545 	 * This function only needs protection against the final kref_put.
546 	 */
547 	mb();
548 }
549 
550 static void ttm_bo_cleanup_refs_or_queue(struct ttm_buffer_object *bo)
551 {
552 	struct ttm_bo_device *bdev = bo->bdev;
553 	struct ttm_bo_global *glob = bo->glob;
554 	struct ttm_bo_driver *driver = bdev->driver;
555 	void *sync_obj = NULL;
556 	int put_count;
557 	int ret;
558 
559 	mtx_lock(&glob->lru_lock);
560 	ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
561 
562 	mtx_lock(&bdev->fence_lock);
563 	(void) ttm_bo_wait(bo, false, false, true);
564 	if (!ret && !bo->sync_obj) {
565 		mtx_unlock(&bdev->fence_lock);
566 		put_count = ttm_bo_del_from_lru(bo);
567 
568 		mtx_unlock(&glob->lru_lock);
569 		ttm_bo_cleanup_memtype_use(bo);
570 
571 		ttm_bo_list_ref_sub(bo, put_count, true);
572 
573 		return;
574 	}
575 	if (bo->sync_obj)
576 		sync_obj = driver->sync_obj_ref(bo->sync_obj);
577 	mtx_unlock(&bdev->fence_lock);
578 
579 	if (!ret) {
580 		atomic_set(&bo->reserved, 0);
581 		wakeup(bo);
582 	}
583 
584 	refcount_acquire(&bo->list_kref);
585 	list_add_tail(&bo->ddestroy, &bdev->ddestroy);
586 	mtx_unlock(&glob->lru_lock);
587 
588 	if (sync_obj) {
589 		driver->sync_obj_flush(sync_obj);
590 		driver->sync_obj_unref(&sync_obj);
591 	}
592 	taskqueue_enqueue_timeout(taskqueue_thread, &bdev->wq,
593 	    ((hz / 100) < 1) ? 1 : hz / 100);
594 }
595 
596 /**
597  * function ttm_bo_cleanup_refs_and_unlock
598  * If bo idle, remove from delayed- and lru lists, and unref.
599  * If not idle, do nothing.
600  *
601  * Must be called with lru_lock and reservation held, this function
602  * will drop both before returning.
603  *
604  * @interruptible         Any sleeps should occur interruptibly.
605  * @no_wait_gpu           Never wait for gpu. Return -EBUSY instead.
606  */
607 
608 static int ttm_bo_cleanup_refs_and_unlock(struct ttm_buffer_object *bo,
609 					  bool interruptible,
610 					  bool no_wait_gpu)
611 {
612 	struct ttm_bo_device *bdev = bo->bdev;
613 	struct ttm_bo_driver *driver = bdev->driver;
614 	struct ttm_bo_global *glob = bo->glob;
615 	int put_count;
616 	int ret;
617 
618 	mtx_lock(&bdev->fence_lock);
619 	ret = ttm_bo_wait(bo, false, false, true);
620 
621 	if (ret && !no_wait_gpu) {
622 		void *sync_obj;
623 
624 		/*
625 		 * Take a reference to the fence and unreserve,
626 		 * at this point the buffer should be dead, so
627 		 * no new sync objects can be attached.
628 		 */
629 		sync_obj = driver->sync_obj_ref(bo->sync_obj);
630 		mtx_unlock(&bdev->fence_lock);
631 
632 		atomic_set(&bo->reserved, 0);
633 		wakeup(bo);
634 		mtx_unlock(&glob->lru_lock);
635 
636 		ret = driver->sync_obj_wait(sync_obj, false, interruptible);
637 		driver->sync_obj_unref(&sync_obj);
638 		if (ret)
639 			return ret;
640 
641 		/*
642 		 * remove sync_obj with ttm_bo_wait, the wait should be
643 		 * finished, and no new wait object should have been added.
644 		 */
645 		mtx_lock(&bdev->fence_lock);
646 		ret = ttm_bo_wait(bo, false, false, true);
647 		mtx_unlock(&bdev->fence_lock);
648 		if (ret)
649 			return ret;
650 
651 		mtx_lock(&glob->lru_lock);
652 		ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
653 
654 		/*
655 		 * We raced, and lost, someone else holds the reservation now,
656 		 * and is probably busy in ttm_bo_cleanup_memtype_use.
657 		 *
658 		 * Even if it's not the case, because we finished waiting any
659 		 * delayed destruction would succeed, so just return success
660 		 * here.
661 		 */
662 		if (ret) {
663 			mtx_unlock(&glob->lru_lock);
664 			return 0;
665 		}
666 	} else
667 		mtx_unlock(&bdev->fence_lock);
668 
669 	if (ret || unlikely(list_empty(&bo->ddestroy))) {
670 		atomic_set(&bo->reserved, 0);
671 		wakeup(bo);
672 		mtx_unlock(&glob->lru_lock);
673 		return ret;
674 	}
675 
676 	put_count = ttm_bo_del_from_lru(bo);
677 	list_del_init(&bo->ddestroy);
678 	++put_count;
679 
680 	mtx_unlock(&glob->lru_lock);
681 	ttm_bo_cleanup_memtype_use(bo);
682 
683 	ttm_bo_list_ref_sub(bo, put_count, true);
684 
685 	return 0;
686 }
687 
688 /**
689  * Traverse the delayed list, and call ttm_bo_cleanup_refs on all
690  * encountered buffers.
691  */
692 
693 static int ttm_bo_delayed_delete(struct ttm_bo_device *bdev, bool remove_all)
694 {
695 	struct ttm_bo_global *glob = bdev->glob;
696 	struct ttm_buffer_object *entry = NULL;
697 	int ret = 0;
698 
699 	mtx_lock(&glob->lru_lock);
700 	if (list_empty(&bdev->ddestroy))
701 		goto out_unlock;
702 
703 	entry = list_first_entry(&bdev->ddestroy,
704 		struct ttm_buffer_object, ddestroy);
705 	refcount_acquire(&entry->list_kref);
706 
707 	for (;;) {
708 		struct ttm_buffer_object *nentry = NULL;
709 
710 		if (entry->ddestroy.next != &bdev->ddestroy) {
711 			nentry = list_first_entry(&entry->ddestroy,
712 				struct ttm_buffer_object, ddestroy);
713 			refcount_acquire(&nentry->list_kref);
714 		}
715 
716 		ret = ttm_bo_reserve_nolru(entry, false, true, false, 0);
717 		if (remove_all && ret) {
718 			ret = ttm_bo_reserve_nolru(entry, false, false,
719 						   false, 0);
720 		}
721 
722 		if (!ret)
723 			ret = ttm_bo_cleanup_refs_and_unlock(entry, false,
724 							     !remove_all);
725 		else
726 			mtx_unlock(&glob->lru_lock);
727 
728 		if (refcount_release(&entry->list_kref))
729 			ttm_bo_release_list(entry);
730 		entry = nentry;
731 
732 		if (ret || !entry)
733 			goto out;
734 
735 		mtx_lock(&glob->lru_lock);
736 		if (list_empty(&entry->ddestroy))
737 			break;
738 	}
739 
740 out_unlock:
741 	mtx_unlock(&glob->lru_lock);
742 out:
743 	if (entry && refcount_release(&entry->list_kref))
744 		ttm_bo_release_list(entry);
745 	return ret;
746 }
747 
748 static void ttm_bo_delayed_workqueue(void *arg, int pending __unused)
749 {
750 	struct ttm_bo_device *bdev = arg;
751 
752 	if (ttm_bo_delayed_delete(bdev, false)) {
753 		taskqueue_enqueue_timeout(taskqueue_thread, &bdev->wq,
754 		    ((hz / 100) < 1) ? 1 : hz / 100);
755 	}
756 }
757 
758 static void ttm_bo_release(struct ttm_buffer_object *bo)
759 {
760 	struct ttm_bo_device *bdev = bo->bdev;
761 	struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
762 
763 	rw_wlock(&bdev->vm_lock);
764 	if (likely(bo->vm_node != NULL)) {
765 		RB_REMOVE(ttm_bo_device_buffer_objects,
766 		    &bdev->addr_space_rb, bo);
767 		drm_mm_put_block(bo->vm_node);
768 		bo->vm_node = NULL;
769 	}
770 	rw_wunlock(&bdev->vm_lock);
771 	ttm_mem_io_lock(man, false);
772 	ttm_mem_io_free_vm(bo);
773 	ttm_mem_io_unlock(man);
774 	ttm_bo_cleanup_refs_or_queue(bo);
775 	if (refcount_release(&bo->list_kref))
776 		ttm_bo_release_list(bo);
777 }
778 
779 void ttm_bo_unref(struct ttm_buffer_object **p_bo)
780 {
781 	struct ttm_buffer_object *bo = *p_bo;
782 
783 	*p_bo = NULL;
784 	if (refcount_release(&bo->kref))
785 		ttm_bo_release(bo);
786 }
787 
788 int ttm_bo_lock_delayed_workqueue(struct ttm_bo_device *bdev)
789 {
790 	int pending;
791 
792 	taskqueue_cancel_timeout(taskqueue_thread, &bdev->wq, &pending);
793 	if (pending)
794 		taskqueue_drain_timeout(taskqueue_thread, &bdev->wq);
795 	return (pending);
796 }
797 
798 void ttm_bo_unlock_delayed_workqueue(struct ttm_bo_device *bdev, int resched)
799 {
800 	if (resched) {
801 		taskqueue_enqueue_timeout(taskqueue_thread, &bdev->wq,
802 		    ((hz / 100) < 1) ? 1 : hz / 100);
803 	}
804 }
805 
806 static int ttm_bo_evict(struct ttm_buffer_object *bo, bool interruptible,
807 			bool no_wait_gpu)
808 {
809 	struct ttm_bo_device *bdev = bo->bdev;
810 	struct ttm_mem_reg evict_mem;
811 	struct ttm_placement placement;
812 	int ret = 0;
813 
814 	mtx_lock(&bdev->fence_lock);
815 	ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
816 	mtx_unlock(&bdev->fence_lock);
817 
818 	if (unlikely(ret != 0)) {
819 		if (ret != -ERESTART) {
820 			printf("[TTM] Failed to expire sync object before buffer eviction\n");
821 		}
822 		goto out;
823 	}
824 
825 	MPASS(ttm_bo_is_reserved(bo));
826 
827 	evict_mem = bo->mem;
828 	evict_mem.mm_node = NULL;
829 	evict_mem.bus.io_reserved_vm = false;
830 	evict_mem.bus.io_reserved_count = 0;
831 
832 	placement.fpfn = 0;
833 	placement.lpfn = 0;
834 	placement.num_placement = 0;
835 	placement.num_busy_placement = 0;
836 	bdev->driver->evict_flags(bo, &placement);
837 	ret = ttm_bo_mem_space(bo, &placement, &evict_mem, interruptible,
838 				no_wait_gpu);
839 	if (ret) {
840 		if (ret != -ERESTART) {
841 			printf("[TTM] Failed to find memory space for buffer 0x%p eviction\n",
842 			       bo);
843 			ttm_bo_mem_space_debug(bo, &placement);
844 		}
845 		goto out;
846 	}
847 
848 	ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, interruptible,
849 				     no_wait_gpu);
850 	if (ret) {
851 		if (ret != -ERESTART)
852 			printf("[TTM] Buffer eviction failed\n");
853 		ttm_bo_mem_put(bo, &evict_mem);
854 		goto out;
855 	}
856 	bo->evicted = true;
857 out:
858 	return ret;
859 }
860 
861 static int ttm_mem_evict_first(struct ttm_bo_device *bdev,
862 				uint32_t mem_type,
863 				bool interruptible,
864 				bool no_wait_gpu)
865 {
866 	struct ttm_bo_global *glob = bdev->glob;
867 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
868 	struct ttm_buffer_object *bo;
869 	int ret = -EBUSY, put_count;
870 
871 	mtx_lock(&glob->lru_lock);
872 	list_for_each_entry(bo, &man->lru, lru) {
873 		ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
874 		if (!ret)
875 			break;
876 	}
877 
878 	if (ret) {
879 		mtx_unlock(&glob->lru_lock);
880 		return ret;
881 	}
882 
883 	refcount_acquire(&bo->list_kref);
884 
885 	if (!list_empty(&bo->ddestroy)) {
886 		ret = ttm_bo_cleanup_refs_and_unlock(bo, interruptible,
887 						     no_wait_gpu);
888 		if (refcount_release(&bo->list_kref))
889 			ttm_bo_release_list(bo);
890 		return ret;
891 	}
892 
893 	put_count = ttm_bo_del_from_lru(bo);
894 	mtx_unlock(&glob->lru_lock);
895 
896 	MPASS(ret == 0);
897 
898 	ttm_bo_list_ref_sub(bo, put_count, true);
899 
900 	ret = ttm_bo_evict(bo, interruptible, no_wait_gpu);
901 	ttm_bo_unreserve(bo);
902 
903 	if (refcount_release(&bo->list_kref))
904 		ttm_bo_release_list(bo);
905 	return ret;
906 }
907 
908 void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem)
909 {
910 	struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type];
911 
912 	if (mem->mm_node)
913 		(*man->func->put_node)(man, mem);
914 }
915 
916 /**
917  * Repeatedly evict memory from the LRU for @mem_type until we create enough
918  * space, or we've evicted everything and there isn't enough space.
919  */
920 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
921 					uint32_t mem_type,
922 					struct ttm_placement *placement,
923 					struct ttm_mem_reg *mem,
924 					bool interruptible,
925 					bool no_wait_gpu)
926 {
927 	struct ttm_bo_device *bdev = bo->bdev;
928 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
929 	int ret;
930 
931 	do {
932 		ret = (*man->func->get_node)(man, bo, placement, mem);
933 		if (unlikely(ret != 0))
934 			return ret;
935 		if (mem->mm_node)
936 			break;
937 		ret = ttm_mem_evict_first(bdev, mem_type,
938 					  interruptible, no_wait_gpu);
939 		if (unlikely(ret != 0))
940 			return ret;
941 	} while (1);
942 	if (mem->mm_node == NULL)
943 		return -ENOMEM;
944 	mem->mem_type = mem_type;
945 	return 0;
946 }
947 
948 static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man,
949 				      uint32_t cur_placement,
950 				      uint32_t proposed_placement)
951 {
952 	uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
953 	uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
954 
955 	/**
956 	 * Keep current caching if possible.
957 	 */
958 
959 	if ((cur_placement & caching) != 0)
960 		result |= (cur_placement & caching);
961 	else if ((man->default_caching & caching) != 0)
962 		result |= man->default_caching;
963 	else if ((TTM_PL_FLAG_CACHED & caching) != 0)
964 		result |= TTM_PL_FLAG_CACHED;
965 	else if ((TTM_PL_FLAG_WC & caching) != 0)
966 		result |= TTM_PL_FLAG_WC;
967 	else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
968 		result |= TTM_PL_FLAG_UNCACHED;
969 
970 	return result;
971 }
972 
973 static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man,
974 				 uint32_t mem_type,
975 				 uint32_t proposed_placement,
976 				 uint32_t *masked_placement)
977 {
978 	uint32_t cur_flags = ttm_bo_type_flags(mem_type);
979 
980 	if ((cur_flags & proposed_placement & TTM_PL_MASK_MEM) == 0)
981 		return false;
982 
983 	if ((proposed_placement & man->available_caching) == 0)
984 		return false;
985 
986 	cur_flags |= (proposed_placement & man->available_caching);
987 
988 	*masked_placement = cur_flags;
989 	return true;
990 }
991 
992 /**
993  * Creates space for memory region @mem according to its type.
994  *
995  * This function first searches for free space in compatible memory types in
996  * the priority order defined by the driver.  If free space isn't found, then
997  * ttm_bo_mem_force_space is attempted in priority order to evict and find
998  * space.
999  */
1000 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1001 			struct ttm_placement *placement,
1002 			struct ttm_mem_reg *mem,
1003 			bool interruptible,
1004 			bool no_wait_gpu)
1005 {
1006 	struct ttm_bo_device *bdev = bo->bdev;
1007 	struct ttm_mem_type_manager *man;
1008 	uint32_t mem_type = TTM_PL_SYSTEM;
1009 	uint32_t cur_flags = 0;
1010 	bool type_found = false;
1011 	bool type_ok = false;
1012 	bool has_erestartsys = false;
1013 	int i, ret;
1014 
1015 	mem->mm_node = NULL;
1016 	for (i = 0; i < placement->num_placement; ++i) {
1017 		ret = ttm_mem_type_from_flags(placement->placement[i],
1018 						&mem_type);
1019 		if (ret)
1020 			return ret;
1021 		man = &bdev->man[mem_type];
1022 
1023 		type_ok = ttm_bo_mt_compatible(man,
1024 						mem_type,
1025 						placement->placement[i],
1026 						&cur_flags);
1027 
1028 		if (!type_ok)
1029 			continue;
1030 
1031 		cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
1032 						  cur_flags);
1033 		/*
1034 		 * Use the access and other non-mapping-related flag bits from
1035 		 * the memory placement flags to the current flags
1036 		 */
1037 		ttm_flag_masked(&cur_flags, placement->placement[i],
1038 				~TTM_PL_MASK_MEMTYPE);
1039 
1040 		if (mem_type == TTM_PL_SYSTEM)
1041 			break;
1042 
1043 		if (man->has_type && man->use_type) {
1044 			type_found = true;
1045 			ret = (*man->func->get_node)(man, bo, placement, mem);
1046 			if (unlikely(ret))
1047 				return ret;
1048 		}
1049 		if (mem->mm_node)
1050 			break;
1051 	}
1052 
1053 	if ((type_ok && (mem_type == TTM_PL_SYSTEM)) || mem->mm_node) {
1054 		mem->mem_type = mem_type;
1055 		mem->placement = cur_flags;
1056 		return 0;
1057 	}
1058 
1059 	if (!type_found)
1060 		return -EINVAL;
1061 
1062 	for (i = 0; i < placement->num_busy_placement; ++i) {
1063 		ret = ttm_mem_type_from_flags(placement->busy_placement[i],
1064 						&mem_type);
1065 		if (ret)
1066 			return ret;
1067 		man = &bdev->man[mem_type];
1068 		if (!man->has_type)
1069 			continue;
1070 		if (!ttm_bo_mt_compatible(man,
1071 						mem_type,
1072 						placement->busy_placement[i],
1073 						&cur_flags))
1074 			continue;
1075 
1076 		cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
1077 						  cur_flags);
1078 		/*
1079 		 * Use the access and other non-mapping-related flag bits from
1080 		 * the memory placement flags to the current flags
1081 		 */
1082 		ttm_flag_masked(&cur_flags, placement->busy_placement[i],
1083 				~TTM_PL_MASK_MEMTYPE);
1084 
1085 
1086 		if (mem_type == TTM_PL_SYSTEM) {
1087 			mem->mem_type = mem_type;
1088 			mem->placement = cur_flags;
1089 			mem->mm_node = NULL;
1090 			return 0;
1091 		}
1092 
1093 		ret = ttm_bo_mem_force_space(bo, mem_type, placement, mem,
1094 						interruptible, no_wait_gpu);
1095 		if (ret == 0 && mem->mm_node) {
1096 			mem->placement = cur_flags;
1097 			return 0;
1098 		}
1099 		if (ret == -ERESTART)
1100 			has_erestartsys = true;
1101 	}
1102 	ret = (has_erestartsys) ? -ERESTART : -ENOMEM;
1103 	return ret;
1104 }
1105 
1106 static
1107 int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
1108 			struct ttm_placement *placement,
1109 			bool interruptible,
1110 			bool no_wait_gpu)
1111 {
1112 	int ret = 0;
1113 	struct ttm_mem_reg mem;
1114 	struct ttm_bo_device *bdev = bo->bdev;
1115 
1116 	MPASS(ttm_bo_is_reserved(bo));
1117 
1118 	/*
1119 	 * FIXME: It's possible to pipeline buffer moves.
1120 	 * Have the driver move function wait for idle when necessary,
1121 	 * instead of doing it here.
1122 	 */
1123 	mtx_lock(&bdev->fence_lock);
1124 	ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
1125 	mtx_unlock(&bdev->fence_lock);
1126 	if (ret)
1127 		return ret;
1128 	mem.num_pages = bo->num_pages;
1129 	mem.size = mem.num_pages << PAGE_SHIFT;
1130 	mem.page_alignment = bo->mem.page_alignment;
1131 	mem.bus.io_reserved_vm = false;
1132 	mem.bus.io_reserved_count = 0;
1133 	/*
1134 	 * Determine where to move the buffer.
1135 	 */
1136 	ret = ttm_bo_mem_space(bo, placement, &mem,
1137 			       interruptible, no_wait_gpu);
1138 	if (ret)
1139 		goto out_unlock;
1140 	ret = ttm_bo_handle_move_mem(bo, &mem, false,
1141 				     interruptible, no_wait_gpu);
1142 out_unlock:
1143 	if (ret && mem.mm_node)
1144 		ttm_bo_mem_put(bo, &mem);
1145 	return ret;
1146 }
1147 
1148 static int ttm_bo_mem_compat(struct ttm_placement *placement,
1149 			     struct ttm_mem_reg *mem)
1150 {
1151 	int i;
1152 
1153 	if (mem->mm_node && placement->lpfn != 0 &&
1154 	    (mem->start < placement->fpfn ||
1155 	     mem->start + mem->num_pages > placement->lpfn))
1156 		return -1;
1157 
1158 	for (i = 0; i < placement->num_placement; i++) {
1159 		if ((placement->placement[i] & mem->placement &
1160 			TTM_PL_MASK_CACHING) &&
1161 			(placement->placement[i] & mem->placement &
1162 			TTM_PL_MASK_MEM))
1163 			return i;
1164 	}
1165 	return -1;
1166 }
1167 
1168 int ttm_bo_validate(struct ttm_buffer_object *bo,
1169 			struct ttm_placement *placement,
1170 			bool interruptible,
1171 			bool no_wait_gpu)
1172 {
1173 	int ret;
1174 
1175 	MPASS(ttm_bo_is_reserved(bo));
1176 	/* Check that range is valid */
1177 	if (placement->lpfn || placement->fpfn)
1178 		if (placement->fpfn > placement->lpfn ||
1179 			(placement->lpfn - placement->fpfn) < bo->num_pages)
1180 			return -EINVAL;
1181 	/*
1182 	 * Check whether we need to move buffer.
1183 	 */
1184 	ret = ttm_bo_mem_compat(placement, &bo->mem);
1185 	if (ret < 0) {
1186 		ret = ttm_bo_move_buffer(bo, placement, interruptible,
1187 					 no_wait_gpu);
1188 		if (ret)
1189 			return ret;
1190 	} else {
1191 		/*
1192 		 * Use the access and other non-mapping-related flag bits from
1193 		 * the compatible memory placement flags to the active flags
1194 		 */
1195 		ttm_flag_masked(&bo->mem.placement, placement->placement[ret],
1196 				~TTM_PL_MASK_MEMTYPE);
1197 	}
1198 	/*
1199 	 * We might need to add a TTM.
1200 	 */
1201 	if (bo->mem.mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
1202 		ret = ttm_bo_add_ttm(bo, true);
1203 		if (ret)
1204 			return ret;
1205 	}
1206 	return 0;
1207 }
1208 
1209 int ttm_bo_check_placement(struct ttm_buffer_object *bo,
1210 				struct ttm_placement *placement)
1211 {
1212 	MPASS(!((placement->fpfn || placement->lpfn) &&
1213 	    (bo->mem.num_pages > (placement->lpfn - placement->fpfn))));
1214 
1215 	return 0;
1216 }
1217 
1218 int ttm_bo_init(struct ttm_bo_device *bdev,
1219 		struct ttm_buffer_object *bo,
1220 		unsigned long size,
1221 		enum ttm_bo_type type,
1222 		struct ttm_placement *placement,
1223 		uint32_t page_alignment,
1224 		bool interruptible,
1225 		struct vm_object *persistent_swap_storage,
1226 		size_t acc_size,
1227 		struct sg_table *sg,
1228 		void (*destroy) (struct ttm_buffer_object *))
1229 {
1230 	int ret = 0;
1231 	unsigned long num_pages;
1232 	struct ttm_mem_global *mem_glob = bdev->glob->mem_glob;
1233 
1234 	ret = ttm_mem_global_alloc(mem_glob, acc_size, false, false);
1235 	if (ret) {
1236 		printf("[TTM] Out of kernel memory\n");
1237 		if (destroy)
1238 			(*destroy)(bo);
1239 		else
1240 			free(bo, M_TTM_BO);
1241 		return -ENOMEM;
1242 	}
1243 
1244 	num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1245 	if (num_pages == 0) {
1246 		printf("[TTM] Illegal buffer object size\n");
1247 		if (destroy)
1248 			(*destroy)(bo);
1249 		else
1250 			free(bo, M_TTM_BO);
1251 		ttm_mem_global_free(mem_glob, acc_size);
1252 		return -EINVAL;
1253 	}
1254 	bo->destroy = destroy;
1255 
1256 	refcount_init(&bo->kref, 1);
1257 	refcount_init(&bo->list_kref, 1);
1258 	atomic_set(&bo->cpu_writers, 0);
1259 	atomic_set(&bo->reserved, 1);
1260 	INIT_LIST_HEAD(&bo->lru);
1261 	INIT_LIST_HEAD(&bo->ddestroy);
1262 	INIT_LIST_HEAD(&bo->swap);
1263 	INIT_LIST_HEAD(&bo->io_reserve_lru);
1264 	bo->bdev = bdev;
1265 	bo->glob = bdev->glob;
1266 	bo->type = type;
1267 	bo->num_pages = num_pages;
1268 	bo->mem.size = num_pages << PAGE_SHIFT;
1269 	bo->mem.mem_type = TTM_PL_SYSTEM;
1270 	bo->mem.num_pages = bo->num_pages;
1271 	bo->mem.mm_node = NULL;
1272 	bo->mem.page_alignment = page_alignment;
1273 	bo->mem.bus.io_reserved_vm = false;
1274 	bo->mem.bus.io_reserved_count = 0;
1275 	bo->priv_flags = 0;
1276 	bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
1277 	bo->seq_valid = false;
1278 	bo->persistent_swap_storage = persistent_swap_storage;
1279 	bo->acc_size = acc_size;
1280 	bo->sg = sg;
1281 	atomic_inc(&bo->glob->bo_count);
1282 
1283 	ret = ttm_bo_check_placement(bo, placement);
1284 	if (unlikely(ret != 0))
1285 		goto out_err;
1286 
1287 	/*
1288 	 * For ttm_bo_type_device buffers, allocate
1289 	 * address space from the device.
1290 	 */
1291 	if (bo->type == ttm_bo_type_device ||
1292 	    bo->type == ttm_bo_type_sg) {
1293 		ret = ttm_bo_setup_vm(bo);
1294 		if (ret)
1295 			goto out_err;
1296 	}
1297 
1298 	ret = ttm_bo_validate(bo, placement, interruptible, false);
1299 	if (ret)
1300 		goto out_err;
1301 
1302 	ttm_bo_unreserve(bo);
1303 	return 0;
1304 
1305 out_err:
1306 	ttm_bo_unreserve(bo);
1307 	ttm_bo_unref(&bo);
1308 
1309 	return ret;
1310 }
1311 
1312 size_t ttm_bo_acc_size(struct ttm_bo_device *bdev,
1313 		       unsigned long bo_size,
1314 		       unsigned struct_size)
1315 {
1316 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1317 	size_t size = 0;
1318 
1319 	size += ttm_round_pot(struct_size);
1320 	size += PAGE_ALIGN(npages * sizeof(void *));
1321 	size += ttm_round_pot(sizeof(struct ttm_tt));
1322 	return size;
1323 }
1324 
1325 size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev,
1326 			   unsigned long bo_size,
1327 			   unsigned struct_size)
1328 {
1329 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1330 	size_t size = 0;
1331 
1332 	size += ttm_round_pot(struct_size);
1333 	size += PAGE_ALIGN(npages * sizeof(void *));
1334 	size += PAGE_ALIGN(npages * sizeof(dma_addr_t));
1335 	size += ttm_round_pot(sizeof(struct ttm_dma_tt));
1336 	return size;
1337 }
1338 
1339 int ttm_bo_create(struct ttm_bo_device *bdev,
1340 			unsigned long size,
1341 			enum ttm_bo_type type,
1342 			struct ttm_placement *placement,
1343 			uint32_t page_alignment,
1344 			bool interruptible,
1345 			struct vm_object *persistent_swap_storage,
1346 			struct ttm_buffer_object **p_bo)
1347 {
1348 	struct ttm_buffer_object *bo;
1349 	size_t acc_size;
1350 	int ret;
1351 
1352 	bo = malloc(sizeof(*bo), M_TTM_BO, M_WAITOK | M_ZERO);
1353 	acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object));
1354 	ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
1355 			  interruptible, persistent_swap_storage, acc_size,
1356 			  NULL, NULL);
1357 	if (likely(ret == 0))
1358 		*p_bo = bo;
1359 
1360 	return ret;
1361 }
1362 
1363 static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev,
1364 					unsigned mem_type, bool allow_errors)
1365 {
1366 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1367 	struct ttm_bo_global *glob = bdev->glob;
1368 	int ret;
1369 
1370 	/*
1371 	 * Can't use standard list traversal since we're unlocking.
1372 	 */
1373 
1374 	mtx_lock(&glob->lru_lock);
1375 	while (!list_empty(&man->lru)) {
1376 		mtx_unlock(&glob->lru_lock);
1377 		ret = ttm_mem_evict_first(bdev, mem_type, false, false);
1378 		if (ret) {
1379 			if (allow_errors) {
1380 				return ret;
1381 			} else {
1382 				printf("[TTM] Cleanup eviction failed\n");
1383 			}
1384 		}
1385 		mtx_lock(&glob->lru_lock);
1386 	}
1387 	mtx_unlock(&glob->lru_lock);
1388 	return 0;
1389 }
1390 
1391 int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1392 {
1393 	struct ttm_mem_type_manager *man;
1394 	int ret = -EINVAL;
1395 
1396 	if (mem_type >= TTM_NUM_MEM_TYPES) {
1397 		printf("[TTM] Illegal memory type %d\n", mem_type);
1398 		return ret;
1399 	}
1400 	man = &bdev->man[mem_type];
1401 
1402 	if (!man->has_type) {
1403 		printf("[TTM] Trying to take down uninitialized memory manager type %u\n",
1404 		       mem_type);
1405 		return ret;
1406 	}
1407 
1408 	man->use_type = false;
1409 	man->has_type = false;
1410 
1411 	ret = 0;
1412 	if (mem_type > 0) {
1413 		ttm_bo_force_list_clean(bdev, mem_type, false);
1414 
1415 		ret = (*man->func->takedown)(man);
1416 	}
1417 
1418 	return ret;
1419 }
1420 
1421 int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1422 {
1423 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1424 
1425 	if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
1426 		printf("[TTM] Illegal memory manager memory type %u\n", mem_type);
1427 		return -EINVAL;
1428 	}
1429 
1430 	if (!man->has_type) {
1431 		printf("[TTM] Memory type %u has not been initialized\n", mem_type);
1432 		return 0;
1433 	}
1434 
1435 	return ttm_bo_force_list_clean(bdev, mem_type, true);
1436 }
1437 
1438 int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type,
1439 			unsigned long p_size)
1440 {
1441 	int ret = -EINVAL;
1442 	struct ttm_mem_type_manager *man;
1443 
1444 	MPASS(type < TTM_NUM_MEM_TYPES);
1445 	man = &bdev->man[type];
1446 	MPASS(!man->has_type);
1447 	man->io_reserve_fastpath = true;
1448 	man->use_io_reserve_lru = false;
1449 	sx_init(&man->io_reserve_mutex, "ttmman");
1450 	INIT_LIST_HEAD(&man->io_reserve_lru);
1451 
1452 	ret = bdev->driver->init_mem_type(bdev, type, man);
1453 	if (ret)
1454 		return ret;
1455 	man->bdev = bdev;
1456 
1457 	ret = 0;
1458 	if (type != TTM_PL_SYSTEM) {
1459 		ret = (*man->func->init)(man, p_size);
1460 		if (ret)
1461 			return ret;
1462 	}
1463 	man->has_type = true;
1464 	man->use_type = true;
1465 	man->size = p_size;
1466 
1467 	INIT_LIST_HEAD(&man->lru);
1468 
1469 	return 0;
1470 }
1471 
1472 static void ttm_bo_global_kobj_release(struct ttm_bo_global *glob)
1473 {
1474 
1475 	ttm_mem_unregister_shrink(glob->mem_glob, &glob->shrink);
1476 	vm_page_free(glob->dummy_read_page);
1477 }
1478 
1479 void ttm_bo_global_release(struct drm_global_reference *ref)
1480 {
1481 	struct ttm_bo_global *glob = ref->object;
1482 
1483 	if (refcount_release(&glob->kobj_ref))
1484 		ttm_bo_global_kobj_release(glob);
1485 }
1486 
1487 int ttm_bo_global_init(struct drm_global_reference *ref)
1488 {
1489 	struct ttm_bo_global_ref *bo_ref =
1490 		container_of(ref, struct ttm_bo_global_ref, ref);
1491 	struct ttm_bo_global *glob = ref->object;
1492 	int ret;
1493 	int tries;
1494 
1495 	sx_init(&glob->device_list_mutex, "ttmdlm");
1496 	mtx_init(&glob->lru_lock, "ttmlru", NULL, MTX_DEF);
1497 	glob->mem_glob = bo_ref->mem_glob;
1498 	tries = 0;
1499 retry:
1500 	glob->dummy_read_page = vm_page_alloc_contig(NULL, 0,
1501 	    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ,
1502 	    1, 0, VM_MAX_ADDRESS, PAGE_SIZE, 0, VM_MEMATTR_UNCACHEABLE);
1503 
1504 	if (unlikely(glob->dummy_read_page == NULL)) {
1505 		if (tries < 1) {
1506 			vm_pageout_grow_cache(tries, 0, VM_MAX_ADDRESS);
1507 			tries++;
1508 			goto retry;
1509 		}
1510 		ret = -ENOMEM;
1511 		goto out_no_drp;
1512 	}
1513 
1514 	INIT_LIST_HEAD(&glob->swap_lru);
1515 	INIT_LIST_HEAD(&glob->device_list);
1516 
1517 	ttm_mem_init_shrink(&glob->shrink, ttm_bo_swapout);
1518 	ret = ttm_mem_register_shrink(glob->mem_glob, &glob->shrink);
1519 	if (unlikely(ret != 0)) {
1520 		printf("[TTM] Could not register buffer object swapout\n");
1521 		goto out_no_shrink;
1522 	}
1523 
1524 	atomic_set(&glob->bo_count, 0);
1525 
1526 	refcount_init(&glob->kobj_ref, 1);
1527 	return (0);
1528 
1529 out_no_shrink:
1530 	vm_page_free(glob->dummy_read_page);
1531 out_no_drp:
1532 	free(glob, M_DRM_GLOBAL);
1533 	return ret;
1534 }
1535 
1536 int ttm_bo_device_release(struct ttm_bo_device *bdev)
1537 {
1538 	int ret = 0;
1539 	unsigned i = TTM_NUM_MEM_TYPES;
1540 	struct ttm_mem_type_manager *man;
1541 	struct ttm_bo_global *glob = bdev->glob;
1542 
1543 	while (i--) {
1544 		man = &bdev->man[i];
1545 		if (man->has_type) {
1546 			man->use_type = false;
1547 			if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) {
1548 				ret = -EBUSY;
1549 				printf("[TTM] DRM memory manager type %d is not clean\n",
1550 				       i);
1551 			}
1552 			man->has_type = false;
1553 		}
1554 	}
1555 
1556 	sx_xlock(&glob->device_list_mutex);
1557 	list_del(&bdev->device_list);
1558 	sx_xunlock(&glob->device_list_mutex);
1559 
1560 	if (taskqueue_cancel_timeout(taskqueue_thread, &bdev->wq, NULL))
1561 		taskqueue_drain_timeout(taskqueue_thread, &bdev->wq);
1562 
1563 	while (ttm_bo_delayed_delete(bdev, true))
1564 		;
1565 
1566 	mtx_lock(&glob->lru_lock);
1567 	if (list_empty(&bdev->ddestroy))
1568 		TTM_DEBUG("Delayed destroy list was clean\n");
1569 
1570 	if (list_empty(&bdev->man[0].lru))
1571 		TTM_DEBUG("Swap list was clean\n");
1572 	mtx_unlock(&glob->lru_lock);
1573 
1574 	MPASS(drm_mm_clean(&bdev->addr_space_mm));
1575 	rw_wlock(&bdev->vm_lock);
1576 	drm_mm_takedown(&bdev->addr_space_mm);
1577 	rw_wunlock(&bdev->vm_lock);
1578 
1579 	return ret;
1580 }
1581 
1582 int ttm_bo_device_init(struct ttm_bo_device *bdev,
1583 		       struct ttm_bo_global *glob,
1584 		       struct ttm_bo_driver *driver,
1585 		       uint64_t file_page_offset,
1586 		       bool need_dma32)
1587 {
1588 	int ret = -EINVAL;
1589 
1590 	rw_init(&bdev->vm_lock, "ttmvml");
1591 	bdev->driver = driver;
1592 
1593 	memset(bdev->man, 0, sizeof(bdev->man));
1594 
1595 	/*
1596 	 * Initialize the system memory buffer type.
1597 	 * Other types need to be driver / IOCTL initialized.
1598 	 */
1599 	ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0);
1600 	if (unlikely(ret != 0))
1601 		goto out_no_sys;
1602 
1603 	RB_INIT(&bdev->addr_space_rb);
1604 	ret = drm_mm_init(&bdev->addr_space_mm, file_page_offset, 0x10000000);
1605 	if (unlikely(ret != 0))
1606 		goto out_no_addr_mm;
1607 
1608 	TIMEOUT_TASK_INIT(taskqueue_thread, &bdev->wq, 0,
1609 	    ttm_bo_delayed_workqueue, bdev);
1610 	INIT_LIST_HEAD(&bdev->ddestroy);
1611 	bdev->dev_mapping = NULL;
1612 	bdev->glob = glob;
1613 	bdev->need_dma32 = need_dma32;
1614 	bdev->val_seq = 0;
1615 	mtx_init(&bdev->fence_lock, "ttmfence", NULL, MTX_DEF);
1616 	sx_xlock(&glob->device_list_mutex);
1617 	list_add_tail(&bdev->device_list, &glob->device_list);
1618 	sx_xunlock(&glob->device_list_mutex);
1619 
1620 	return 0;
1621 out_no_addr_mm:
1622 	ttm_bo_clean_mm(bdev, 0);
1623 out_no_sys:
1624 	return ret;
1625 }
1626 
1627 /*
1628  * buffer object vm functions.
1629  */
1630 
1631 bool ttm_mem_reg_is_pci(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
1632 {
1633 	struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
1634 
1635 	if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
1636 		if (mem->mem_type == TTM_PL_SYSTEM)
1637 			return false;
1638 
1639 		if (man->flags & TTM_MEMTYPE_FLAG_CMA)
1640 			return false;
1641 
1642 		if (mem->placement & TTM_PL_FLAG_CACHED)
1643 			return false;
1644 	}
1645 	return true;
1646 }
1647 
1648 void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
1649 {
1650 
1651 	ttm_bo_release_mmap(bo);
1652 	ttm_mem_io_free_vm(bo);
1653 }
1654 
1655 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1656 {
1657 	struct ttm_bo_device *bdev = bo->bdev;
1658 	struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
1659 
1660 	ttm_mem_io_lock(man, false);
1661 	ttm_bo_unmap_virtual_locked(bo);
1662 	ttm_mem_io_unlock(man);
1663 }
1664 
1665 static void ttm_bo_vm_insert_rb(struct ttm_buffer_object *bo)
1666 {
1667 	struct ttm_bo_device *bdev = bo->bdev;
1668 
1669 	/* The caller acquired bdev->vm_lock. */
1670 	RB_INSERT(ttm_bo_device_buffer_objects, &bdev->addr_space_rb, bo);
1671 }
1672 
1673 /**
1674  * ttm_bo_setup_vm:
1675  *
1676  * @bo: the buffer to allocate address space for
1677  *
1678  * Allocate address space in the drm device so that applications
1679  * can mmap the buffer and access the contents. This only
1680  * applies to ttm_bo_type_device objects as others are not
1681  * placed in the drm device address space.
1682  */
1683 
1684 static int ttm_bo_setup_vm(struct ttm_buffer_object *bo)
1685 {
1686 	struct ttm_bo_device *bdev = bo->bdev;
1687 	int ret;
1688 
1689 retry_pre_get:
1690 	ret = drm_mm_pre_get(&bdev->addr_space_mm);
1691 	if (unlikely(ret != 0))
1692 		return ret;
1693 
1694 	rw_wlock(&bdev->vm_lock);
1695 	bo->vm_node = drm_mm_search_free(&bdev->addr_space_mm,
1696 					 bo->mem.num_pages, 0, 0);
1697 
1698 	if (unlikely(bo->vm_node == NULL)) {
1699 		ret = -ENOMEM;
1700 		goto out_unlock;
1701 	}
1702 
1703 	bo->vm_node = drm_mm_get_block_atomic(bo->vm_node,
1704 					      bo->mem.num_pages, 0);
1705 
1706 	if (unlikely(bo->vm_node == NULL)) {
1707 		rw_wunlock(&bdev->vm_lock);
1708 		goto retry_pre_get;
1709 	}
1710 
1711 	ttm_bo_vm_insert_rb(bo);
1712 	rw_wunlock(&bdev->vm_lock);
1713 	bo->addr_space_offset = ((uint64_t) bo->vm_node->start) << PAGE_SHIFT;
1714 
1715 	return 0;
1716 out_unlock:
1717 	rw_wunlock(&bdev->vm_lock);
1718 	return ret;
1719 }
1720 
1721 int ttm_bo_wait(struct ttm_buffer_object *bo,
1722 		bool lazy, bool interruptible, bool no_wait)
1723 {
1724 	struct ttm_bo_driver *driver = bo->bdev->driver;
1725 	struct ttm_bo_device *bdev = bo->bdev;
1726 	void *sync_obj;
1727 	int ret = 0;
1728 
1729 	if (likely(bo->sync_obj == NULL))
1730 		return 0;
1731 
1732 	while (bo->sync_obj) {
1733 
1734 		if (driver->sync_obj_signaled(bo->sync_obj)) {
1735 			void *tmp_obj = bo->sync_obj;
1736 			bo->sync_obj = NULL;
1737 			clear_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags);
1738 			mtx_unlock(&bdev->fence_lock);
1739 			driver->sync_obj_unref(&tmp_obj);
1740 			mtx_lock(&bdev->fence_lock);
1741 			continue;
1742 		}
1743 
1744 		if (no_wait)
1745 			return -EBUSY;
1746 
1747 		sync_obj = driver->sync_obj_ref(bo->sync_obj);
1748 		mtx_unlock(&bdev->fence_lock);
1749 		ret = driver->sync_obj_wait(sync_obj,
1750 					    lazy, interruptible);
1751 		if (unlikely(ret != 0)) {
1752 			driver->sync_obj_unref(&sync_obj);
1753 			mtx_lock(&bdev->fence_lock);
1754 			return ret;
1755 		}
1756 		mtx_lock(&bdev->fence_lock);
1757 		if (likely(bo->sync_obj == sync_obj)) {
1758 			void *tmp_obj = bo->sync_obj;
1759 			bo->sync_obj = NULL;
1760 			clear_bit(TTM_BO_PRIV_FLAG_MOVING,
1761 				  &bo->priv_flags);
1762 			mtx_unlock(&bdev->fence_lock);
1763 			driver->sync_obj_unref(&sync_obj);
1764 			driver->sync_obj_unref(&tmp_obj);
1765 			mtx_lock(&bdev->fence_lock);
1766 		} else {
1767 			mtx_unlock(&bdev->fence_lock);
1768 			driver->sync_obj_unref(&sync_obj);
1769 			mtx_lock(&bdev->fence_lock);
1770 		}
1771 	}
1772 	return 0;
1773 }
1774 
1775 int ttm_bo_synccpu_write_grab(struct ttm_buffer_object *bo, bool no_wait)
1776 {
1777 	struct ttm_bo_device *bdev = bo->bdev;
1778 	int ret = 0;
1779 
1780 	/*
1781 	 * Using ttm_bo_reserve makes sure the lru lists are updated.
1782 	 */
1783 
1784 	ret = ttm_bo_reserve(bo, true, no_wait, false, 0);
1785 	if (unlikely(ret != 0))
1786 		return ret;
1787 	mtx_lock(&bdev->fence_lock);
1788 	ret = ttm_bo_wait(bo, false, true, no_wait);
1789 	mtx_unlock(&bdev->fence_lock);
1790 	if (likely(ret == 0))
1791 		atomic_inc(&bo->cpu_writers);
1792 	ttm_bo_unreserve(bo);
1793 	return ret;
1794 }
1795 
1796 void ttm_bo_synccpu_write_release(struct ttm_buffer_object *bo)
1797 {
1798 	atomic_dec(&bo->cpu_writers);
1799 }
1800 
1801 /**
1802  * A buffer object shrink method that tries to swap out the first
1803  * buffer object on the bo_global::swap_lru list.
1804  */
1805 
1806 static int ttm_bo_swapout(struct ttm_mem_shrink *shrink)
1807 {
1808 	struct ttm_bo_global *glob =
1809 	    container_of(shrink, struct ttm_bo_global, shrink);
1810 	struct ttm_buffer_object *bo;
1811 	int ret = -EBUSY;
1812 	int put_count;
1813 	uint32_t swap_placement = (TTM_PL_FLAG_CACHED | TTM_PL_FLAG_SYSTEM);
1814 
1815 	mtx_lock(&glob->lru_lock);
1816 	list_for_each_entry(bo, &glob->swap_lru, swap) {
1817 		ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
1818 		if (!ret)
1819 			break;
1820 	}
1821 
1822 	if (ret) {
1823 		mtx_unlock(&glob->lru_lock);
1824 		return ret;
1825 	}
1826 
1827 	refcount_acquire(&bo->list_kref);
1828 
1829 	if (!list_empty(&bo->ddestroy)) {
1830 		ret = ttm_bo_cleanup_refs_and_unlock(bo, false, false);
1831 		if (refcount_release(&bo->list_kref))
1832 			ttm_bo_release_list(bo);
1833 		return ret;
1834 	}
1835 
1836 	put_count = ttm_bo_del_from_lru(bo);
1837 	mtx_unlock(&glob->lru_lock);
1838 
1839 	ttm_bo_list_ref_sub(bo, put_count, true);
1840 
1841 	/**
1842 	 * Wait for GPU, then move to system cached.
1843 	 */
1844 
1845 	mtx_lock(&bo->bdev->fence_lock);
1846 	ret = ttm_bo_wait(bo, false, false, false);
1847 	mtx_unlock(&bo->bdev->fence_lock);
1848 
1849 	if (unlikely(ret != 0))
1850 		goto out;
1851 
1852 	if ((bo->mem.placement & swap_placement) != swap_placement) {
1853 		struct ttm_mem_reg evict_mem;
1854 
1855 		evict_mem = bo->mem;
1856 		evict_mem.mm_node = NULL;
1857 		evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
1858 		evict_mem.mem_type = TTM_PL_SYSTEM;
1859 
1860 		ret = ttm_bo_handle_move_mem(bo, &evict_mem, true,
1861 					     false, false);
1862 		if (unlikely(ret != 0))
1863 			goto out;
1864 	}
1865 
1866 	ttm_bo_unmap_virtual(bo);
1867 
1868 	/**
1869 	 * Swap out. Buffer will be swapped in again as soon as
1870 	 * anyone tries to access a ttm page.
1871 	 */
1872 
1873 	if (bo->bdev->driver->swap_notify)
1874 		bo->bdev->driver->swap_notify(bo);
1875 
1876 	ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
1877 out:
1878 
1879 	/**
1880 	 *
1881 	 * Unreserve without putting on LRU to avoid swapping out an
1882 	 * already swapped buffer.
1883 	 */
1884 
1885 	atomic_set(&bo->reserved, 0);
1886 	wakeup(bo);
1887 	if (refcount_release(&bo->list_kref))
1888 		ttm_bo_release_list(bo);
1889 	return ret;
1890 }
1891 
1892 void ttm_bo_swapout_all(struct ttm_bo_device *bdev)
1893 {
1894 	while (ttm_bo_swapout(&bdev->glob->shrink) == 0)
1895 		;
1896 }
1897