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