xref: /openbsd-src/sys/dev/pci/drm/ttm/ttm_bo.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: ttm_bo.c,v 1.19 2015/10/23 08:21:58 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 	write_lock(&bdev->vm_lock);
732 	if (likely(bo->vm_node != NULL)) {
733 		RB_REMOVE(ttm_bo_device_buffer_objects,
734 		    &bdev->addr_space_rb, bo);
735 		drm_mm_put_block(bo->vm_node);
736 		bo->vm_node = NULL;
737 	}
738 	write_unlock(&bdev->vm_lock);
739 	ttm_mem_io_lock(man, false);
740 	ttm_mem_io_free_vm(bo);
741 	ttm_mem_io_unlock(man);
742 	ttm_bo_cleanup_refs_or_queue(bo);
743 	kref_put(&bo->list_kref, ttm_bo_release_list);
744 }
745 
746 void ttm_bo_unref(struct ttm_buffer_object **p_bo)
747 {
748 	struct ttm_buffer_object *bo = *p_bo;
749 
750 	*p_bo = NULL;
751 	kref_put(&bo->kref, ttm_bo_release);
752 }
753 EXPORT_SYMBOL(ttm_bo_unref);
754 
755 int ttm_bo_lock_delayed_workqueue(struct ttm_bo_device *bdev)
756 {
757 	return cancel_delayed_work_sync(&bdev->wq);
758 }
759 EXPORT_SYMBOL(ttm_bo_lock_delayed_workqueue);
760 
761 void ttm_bo_unlock_delayed_workqueue(struct ttm_bo_device *bdev, int resched)
762 {
763 	if (resched)
764 		schedule_delayed_work(&bdev->wq,
765 				      ((HZ / 100) < 1) ? 1 : HZ / 100);
766 }
767 EXPORT_SYMBOL(ttm_bo_unlock_delayed_workqueue);
768 
769 static int ttm_bo_evict(struct ttm_buffer_object *bo, bool interruptible,
770 			bool no_wait_gpu)
771 {
772 	struct ttm_bo_device *bdev = bo->bdev;
773 	struct ttm_mem_reg evict_mem;
774 	struct ttm_placement placement;
775 	int ret = 0;
776 
777 	spin_lock(&bdev->fence_lock);
778 	ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
779 	spin_unlock(&bdev->fence_lock);
780 
781 	if (unlikely(ret != 0)) {
782 		if (ret != -ERESTARTSYS) {
783 			pr_err("Failed to expire sync object before buffer eviction\n");
784 		}
785 		goto out;
786 	}
787 
788 	BUG_ON(!ttm_bo_is_reserved(bo));
789 
790 	evict_mem = bo->mem;
791 	evict_mem.mm_node = NULL;
792 	evict_mem.bus.io_reserved_vm = false;
793 	evict_mem.bus.io_reserved_count = 0;
794 
795 	placement.fpfn = 0;
796 	placement.lpfn = 0;
797 	placement.num_placement = 0;
798 	placement.num_busy_placement = 0;
799 	bdev->driver->evict_flags(bo, &placement);
800 	ret = ttm_bo_mem_space(bo, &placement, &evict_mem, interruptible,
801 				no_wait_gpu);
802 	if (ret) {
803 		if (ret != -ERESTARTSYS) {
804 			pr_err("Failed to find memory space for buffer 0x%p eviction\n",
805 			       bo);
806 			ttm_bo_mem_space_debug(bo, &placement);
807 		}
808 		goto out;
809 	}
810 
811 	ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, interruptible,
812 				     no_wait_gpu);
813 	if (ret) {
814 		if (ret != -ERESTARTSYS)
815 			pr_err("Buffer eviction failed\n");
816 		ttm_bo_mem_put(bo, &evict_mem);
817 		goto out;
818 	}
819 	bo->evicted = true;
820 out:
821 	return ret;
822 }
823 
824 static int ttm_mem_evict_first(struct ttm_bo_device *bdev,
825 				uint32_t mem_type,
826 				bool interruptible,
827 				bool no_wait_gpu)
828 {
829 	struct ttm_bo_global *glob = bdev->glob;
830 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
831 	struct ttm_buffer_object *bo;
832 	int ret = -EBUSY, put_count;
833 
834 	spin_lock(&glob->lru_lock);
835 	list_for_each_entry(bo, &man->lru, lru) {
836 		ret = ttm_bo_reserve_locked(bo, false, true, false, 0);
837 		if (!ret)
838 			break;
839 	}
840 
841 	if (ret) {
842 		spin_unlock(&glob->lru_lock);
843 		return ret;
844 	}
845 
846 	kref_get(&bo->list_kref);
847 
848 	if (!list_empty(&bo->ddestroy)) {
849 		ret = ttm_bo_cleanup_refs_and_unlock(bo, interruptible,
850 						     no_wait_gpu);
851 		kref_put(&bo->list_kref, ttm_bo_release_list);
852 		return ret;
853 	}
854 
855 	put_count = ttm_bo_del_from_lru(bo);
856 	spin_unlock(&glob->lru_lock);
857 
858 	BUG_ON(ret != 0);
859 
860 	ttm_bo_list_ref_sub(bo, put_count, true);
861 
862 	ret = ttm_bo_evict(bo, interruptible, no_wait_gpu);
863 	ttm_bo_unreserve(bo);
864 
865 	kref_put(&bo->list_kref, ttm_bo_release_list);
866 	return ret;
867 }
868 
869 void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem)
870 {
871 	struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type];
872 
873 	if (mem->mm_node)
874 		(*man->func->put_node)(man, mem);
875 }
876 EXPORT_SYMBOL(ttm_bo_mem_put);
877 
878 /**
879  * Repeatedly evict memory from the LRU for @mem_type until we create enough
880  * space, or we've evicted everything and there isn't enough space.
881  */
882 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
883 					uint32_t mem_type,
884 					struct ttm_placement *placement,
885 					struct ttm_mem_reg *mem,
886 					bool interruptible,
887 					bool no_wait_gpu)
888 {
889 	struct ttm_bo_device *bdev = bo->bdev;
890 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
891 	int ret;
892 
893 	do {
894 		ret = (*man->func->get_node)(man, bo, placement, mem);
895 		if (unlikely(ret != 0))
896 			return ret;
897 		if (mem->mm_node)
898 			break;
899 		ret = ttm_mem_evict_first(bdev, mem_type,
900 					  interruptible, no_wait_gpu);
901 		if (unlikely(ret != 0))
902 			return ret;
903 	} while (1);
904 	if (mem->mm_node == NULL)
905 		return -ENOMEM;
906 	mem->mem_type = mem_type;
907 	return 0;
908 }
909 
910 static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man,
911 				      uint32_t cur_placement,
912 				      uint32_t proposed_placement)
913 {
914 	uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
915 	uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
916 
917 	/**
918 	 * Keep current caching if possible.
919 	 */
920 
921 	if ((cur_placement & caching) != 0)
922 		result |= (cur_placement & caching);
923 	else if ((man->default_caching & caching) != 0)
924 		result |= man->default_caching;
925 	else if ((TTM_PL_FLAG_CACHED & caching) != 0)
926 		result |= TTM_PL_FLAG_CACHED;
927 	else if ((TTM_PL_FLAG_WC & caching) != 0)
928 		result |= TTM_PL_FLAG_WC;
929 	else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
930 		result |= TTM_PL_FLAG_UNCACHED;
931 
932 	return result;
933 }
934 
935 static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man,
936 				 uint32_t mem_type,
937 				 uint32_t proposed_placement,
938 				 uint32_t *masked_placement)
939 {
940 	uint32_t cur_flags = ttm_bo_type_flags(mem_type);
941 
942 	if ((cur_flags & proposed_placement & TTM_PL_MASK_MEM) == 0)
943 		return false;
944 
945 	if ((proposed_placement & man->available_caching) == 0)
946 		return false;
947 
948 	cur_flags |= (proposed_placement & man->available_caching);
949 
950 	*masked_placement = cur_flags;
951 	return true;
952 }
953 
954 /**
955  * Creates space for memory region @mem according to its type.
956  *
957  * This function first searches for free space in compatible memory types in
958  * the priority order defined by the driver.  If free space isn't found, then
959  * ttm_bo_mem_force_space is attempted in priority order to evict and find
960  * space.
961  */
962 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
963 			struct ttm_placement *placement,
964 			struct ttm_mem_reg *mem,
965 			bool interruptible,
966 			bool no_wait_gpu)
967 {
968 	struct ttm_bo_device *bdev = bo->bdev;
969 	struct ttm_mem_type_manager *man;
970 	uint32_t mem_type = TTM_PL_SYSTEM;
971 	uint32_t cur_flags = 0;
972 	bool type_found = false;
973 	bool type_ok = false;
974 	bool has_erestartsys = false;
975 	int i, ret;
976 
977 	mem->mm_node = NULL;
978 	for (i = 0; i < placement->num_placement; ++i) {
979 		ret = ttm_mem_type_from_flags(placement->placement[i],
980 						&mem_type);
981 		if (ret)
982 			return ret;
983 		man = &bdev->man[mem_type];
984 
985 		type_ok = ttm_bo_mt_compatible(man,
986 						mem_type,
987 						placement->placement[i],
988 						&cur_flags);
989 
990 		if (!type_ok)
991 			continue;
992 
993 		cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
994 						  cur_flags);
995 		/*
996 		 * Use the access and other non-mapping-related flag bits from
997 		 * the memory placement flags to the current flags
998 		 */
999 		ttm_flag_masked(&cur_flags, placement->placement[i],
1000 				~TTM_PL_MASK_MEMTYPE);
1001 
1002 		if (mem_type == TTM_PL_SYSTEM)
1003 			break;
1004 
1005 		if (man->has_type && man->use_type) {
1006 			type_found = true;
1007 			ret = (*man->func->get_node)(man, bo, placement, mem);
1008 			if (unlikely(ret))
1009 				return ret;
1010 		}
1011 		if (mem->mm_node)
1012 			break;
1013 	}
1014 
1015 	if ((type_ok && (mem_type == TTM_PL_SYSTEM)) || mem->mm_node) {
1016 		mem->mem_type = mem_type;
1017 		mem->placement = cur_flags;
1018 		return 0;
1019 	}
1020 
1021 	if (!type_found)
1022 		return -EINVAL;
1023 
1024 	for (i = 0; i < placement->num_busy_placement; ++i) {
1025 		ret = ttm_mem_type_from_flags(placement->busy_placement[i],
1026 						&mem_type);
1027 		if (ret)
1028 			return ret;
1029 		man = &bdev->man[mem_type];
1030 		if (!man->has_type)
1031 			continue;
1032 		if (!ttm_bo_mt_compatible(man,
1033 						mem_type,
1034 						placement->busy_placement[i],
1035 						&cur_flags))
1036 			continue;
1037 
1038 		cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
1039 						  cur_flags);
1040 		/*
1041 		 * Use the access and other non-mapping-related flag bits from
1042 		 * the memory placement flags to the current flags
1043 		 */
1044 		ttm_flag_masked(&cur_flags, placement->busy_placement[i],
1045 				~TTM_PL_MASK_MEMTYPE);
1046 
1047 
1048 		if (mem_type == TTM_PL_SYSTEM) {
1049 			mem->mem_type = mem_type;
1050 			mem->placement = cur_flags;
1051 			mem->mm_node = NULL;
1052 			return 0;
1053 		}
1054 
1055 		ret = ttm_bo_mem_force_space(bo, mem_type, placement, mem,
1056 						interruptible, no_wait_gpu);
1057 		if (ret == 0 && mem->mm_node) {
1058 			mem->placement = cur_flags;
1059 			return 0;
1060 		}
1061 		if (ret == -ERESTART)
1062 			has_erestartsys = true;
1063 	}
1064 	ret = (has_erestartsys) ? -ERESTART: -ENOMEM;
1065 	return ret;
1066 }
1067 EXPORT_SYMBOL(ttm_bo_mem_space);
1068 
1069 int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
1070 			struct ttm_placement *placement,
1071 			bool interruptible,
1072 			bool no_wait_gpu)
1073 {
1074 	int ret = 0;
1075 	struct ttm_mem_reg mem;
1076 	struct ttm_bo_device *bdev = bo->bdev;
1077 
1078 	BUG_ON(!ttm_bo_is_reserved(bo));
1079 
1080 	/*
1081 	 * FIXME: It's possible to pipeline buffer moves.
1082 	 * Have the driver move function wait for idle when necessary,
1083 	 * instead of doing it here.
1084 	 */
1085 	spin_lock(&bdev->fence_lock);
1086 	ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
1087 	spin_unlock(&bdev->fence_lock);
1088 	if (ret)
1089 		return ret;
1090 	mem.num_pages = bo->num_pages;
1091 	mem.size = mem.num_pages << PAGE_SHIFT;
1092 	mem.page_alignment = bo->mem.page_alignment;
1093 	mem.bus.io_reserved_vm = false;
1094 	mem.bus.io_reserved_count = 0;
1095 	/*
1096 	 * Determine where to move the buffer.
1097 	 */
1098 	ret = ttm_bo_mem_space(bo, placement, &mem,
1099 			       interruptible, no_wait_gpu);
1100 	if (ret)
1101 		goto out_unlock;
1102 	ret = ttm_bo_handle_move_mem(bo, &mem, false,
1103 				     interruptible, no_wait_gpu);
1104 out_unlock:
1105 	if (ret && mem.mm_node)
1106 		ttm_bo_mem_put(bo, &mem);
1107 	return ret;
1108 }
1109 
1110 static bool ttm_bo_mem_compat(struct ttm_placement *placement,
1111 			      struct ttm_mem_reg *mem,
1112 			      uint32_t *new_flags)
1113 {
1114 	int i;
1115 
1116 	if (mem->mm_node && placement->lpfn != 0 &&
1117 	    (mem->start < placement->fpfn ||
1118 	     mem->start + mem->num_pages > placement->lpfn))
1119 		return false;
1120 
1121 	for (i = 0; i < placement->num_placement; i++) {
1122 		*new_flags = placement->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 	for (i = 0; i < placement->num_busy_placement; i++) {
1129 		*new_flags = placement->busy_placement[i];
1130 		if ((*new_flags & mem->placement & TTM_PL_MASK_CACHING) &&
1131 		    (*new_flags & mem->placement & TTM_PL_MASK_MEM))
1132 			return true;
1133 	}
1134 
1135 	return false;
1136 }
1137 
1138 int ttm_bo_validate(struct ttm_buffer_object *bo,
1139 			struct ttm_placement *placement,
1140 			bool interruptible,
1141 			bool no_wait_gpu)
1142 {
1143 	int ret;
1144 	uint32_t new_flags;
1145 
1146 	BUG_ON(!ttm_bo_is_reserved(bo));
1147 	/* Check that range is valid */
1148 	if (placement->lpfn || placement->fpfn)
1149 		if (placement->fpfn > placement->lpfn ||
1150 			(placement->lpfn - placement->fpfn) < bo->num_pages)
1151 			return -EINVAL;
1152 	/*
1153 	 * Check whether we need to move buffer.
1154 	 */
1155 	if (!ttm_bo_mem_compat(placement, &bo->mem, &new_flags)) {
1156 		ret = ttm_bo_move_buffer(bo, placement, interruptible,
1157 					 no_wait_gpu);
1158 		if (ret)
1159 			return ret;
1160 	} else {
1161 		/*
1162 		 * Use the access and other non-mapping-related flag bits from
1163 		 * the compatible memory placement flags to the active flags
1164 		 */
1165 		ttm_flag_masked(&bo->mem.placement, new_flags,
1166 				~TTM_PL_MASK_MEMTYPE);
1167 	}
1168 	/*
1169 	 * We might need to add a TTM.
1170 	 */
1171 	if (bo->mem.mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
1172 		ret = ttm_bo_add_ttm(bo, true);
1173 		if (ret)
1174 			return ret;
1175 	}
1176 	return 0;
1177 }
1178 EXPORT_SYMBOL(ttm_bo_validate);
1179 
1180 int ttm_bo_check_placement(struct ttm_buffer_object *bo,
1181 				struct ttm_placement *placement)
1182 {
1183 	BUG_ON((placement->fpfn || placement->lpfn) &&
1184 	       (bo->mem.num_pages > (placement->lpfn - placement->fpfn)));
1185 
1186 	return 0;
1187 }
1188 
1189 int ttm_bo_init(struct ttm_bo_device *bdev,
1190 		struct ttm_buffer_object *bo,
1191 		unsigned long size,
1192 		enum ttm_bo_type type,
1193 		struct ttm_placement *placement,
1194 		uint32_t page_alignment,
1195 		bool interruptible,
1196 		struct uvm_object *persistent_swap_storage,
1197 		size_t acc_size,
1198 		struct sg_table *sg,
1199 		void (*destroy) (struct ttm_buffer_object *))
1200 {
1201 	int ret = 0;
1202 	unsigned long num_pages;
1203 	struct ttm_mem_global *mem_glob = bdev->glob->mem_glob;
1204 
1205 	ret = ttm_mem_global_alloc(mem_glob, acc_size, false, false);
1206 	if (ret) {
1207 		pr_err("Out of kernel memory\n");
1208 		if (destroy)
1209 			(*destroy)(bo);
1210 		else
1211 			kfree(bo);
1212 		return -ENOMEM;
1213 	}
1214 
1215 	num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1216 	if (num_pages == 0) {
1217 		pr_err("Illegal buffer object size\n");
1218 		if (destroy)
1219 			(*destroy)(bo);
1220 		else
1221 			kfree(bo);
1222 		ttm_mem_global_free(mem_glob, acc_size);
1223 		return -EINVAL;
1224 	}
1225 	bo->destroy = destroy;
1226 
1227 	uvm_objinit(&bo->uobj, NULL, 0);
1228 	kref_init(&bo->kref);
1229 	kref_init(&bo->list_kref);
1230 	atomic_set(&bo->cpu_writers, 0);
1231 	atomic_set(&bo->reserved, 1);
1232 	init_waitqueue_head(&bo->event_queue);
1233 	INIT_LIST_HEAD(&bo->lru);
1234 	INIT_LIST_HEAD(&bo->ddestroy);
1235 	INIT_LIST_HEAD(&bo->swap);
1236 	INIT_LIST_HEAD(&bo->io_reserve_lru);
1237 	bo->bdev = bdev;
1238 	bo->glob = bdev->glob;
1239 	bo->type = type;
1240 	bo->num_pages = num_pages;
1241 	bo->mem.size = num_pages << PAGE_SHIFT;
1242 	bo->mem.mem_type = TTM_PL_SYSTEM;
1243 	bo->mem.num_pages = bo->num_pages;
1244 	bo->mem.mm_node = NULL;
1245 	bo->mem.page_alignment = page_alignment;
1246 	bo->mem.bus.io_reserved_vm = false;
1247 	bo->mem.bus.io_reserved_count = 0;
1248 	bo->priv_flags = 0;
1249 	bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
1250 	bo->seq_valid = false;
1251 	bo->persistent_swap_storage = persistent_swap_storage;
1252 	bo->acc_size = acc_size;
1253 	bo->sg = sg;
1254 	atomic_inc(&bo->glob->bo_count);
1255 
1256 	ret = ttm_bo_check_placement(bo, placement);
1257 	if (unlikely(ret != 0))
1258 		goto out_err;
1259 
1260 	/*
1261 	 * For ttm_bo_type_device buffers, allocate
1262 	 * address space from the device.
1263 	 */
1264 	if (bo->type == ttm_bo_type_device ||
1265 	    bo->type == ttm_bo_type_sg) {
1266 		ret = ttm_bo_setup_vm(bo);
1267 		if (ret)
1268 			goto out_err;
1269 	}
1270 
1271 	ret = ttm_bo_validate(bo, placement, interruptible, false);
1272 	if (ret)
1273 		goto out_err;
1274 
1275 	ttm_bo_unreserve(bo);
1276 	return 0;
1277 
1278 out_err:
1279 	ttm_bo_unreserve(bo);
1280 	ttm_bo_unref(&bo);
1281 
1282 	return ret;
1283 }
1284 EXPORT_SYMBOL(ttm_bo_init);
1285 
1286 size_t ttm_bo_acc_size(struct ttm_bo_device *bdev,
1287 		       unsigned long bo_size,
1288 		       unsigned struct_size)
1289 {
1290 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1291 	size_t size = 0;
1292 
1293 	size += ttm_round_pot(struct_size);
1294 	size += PAGE_ALIGN(npages * sizeof(void *));
1295 	size += ttm_round_pot(sizeof(struct ttm_tt));
1296 	return size;
1297 }
1298 EXPORT_SYMBOL(ttm_bo_acc_size);
1299 
1300 size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev,
1301 			   unsigned long bo_size,
1302 			   unsigned struct_size)
1303 {
1304 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1305 	size_t size = 0;
1306 
1307 	size += ttm_round_pot(struct_size);
1308 	size += PAGE_ALIGN(npages * sizeof(void *));
1309 	size += PAGE_ALIGN(npages * sizeof(bus_addr_t));
1310 	size += ttm_round_pot(sizeof(struct ttm_dma_tt));
1311 	return size;
1312 }
1313 EXPORT_SYMBOL(ttm_bo_dma_acc_size);
1314 
1315 int ttm_bo_create(struct ttm_bo_device *bdev,
1316 			unsigned long size,
1317 			enum ttm_bo_type type,
1318 			struct ttm_placement *placement,
1319 			uint32_t page_alignment,
1320 			bool interruptible,
1321 			struct uvm_object *persistent_swap_storage,
1322 			struct ttm_buffer_object **p_bo)
1323 {
1324 	struct ttm_buffer_object *bo;
1325 	size_t acc_size;
1326 	int ret;
1327 
1328 	bo = kzalloc(sizeof(*bo), GFP_KERNEL);
1329 	if (unlikely(bo == NULL))
1330 		return -ENOMEM;
1331 
1332 	acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object));
1333 	ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
1334 			  interruptible, persistent_swap_storage, acc_size,
1335 			  NULL, NULL);
1336 	if (likely(ret == 0))
1337 		*p_bo = bo;
1338 
1339 	return ret;
1340 }
1341 EXPORT_SYMBOL(ttm_bo_create);
1342 
1343 static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev,
1344 					unsigned mem_type, bool allow_errors)
1345 {
1346 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1347 	struct ttm_bo_global *glob = bdev->glob;
1348 	int ret;
1349 
1350 	/*
1351 	 * Can't use standard list traversal since we're unlocking.
1352 	 */
1353 
1354 	spin_lock(&glob->lru_lock);
1355 	while (!list_empty(&man->lru)) {
1356 		spin_unlock(&glob->lru_lock);
1357 		ret = ttm_mem_evict_first(bdev, mem_type, false, false);
1358 		if (ret) {
1359 			if (allow_errors) {
1360 				return ret;
1361 			} else {
1362 				pr_err("Cleanup eviction failed\n");
1363 			}
1364 		}
1365 		spin_lock(&glob->lru_lock);
1366 	}
1367 	spin_unlock(&glob->lru_lock);
1368 	return 0;
1369 }
1370 
1371 int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1372 {
1373 	struct ttm_mem_type_manager *man;
1374 	int ret = -EINVAL;
1375 
1376 	if (mem_type >= TTM_NUM_MEM_TYPES) {
1377 		pr_err("Illegal memory type %d\n", mem_type);
1378 		return ret;
1379 	}
1380 	man = &bdev->man[mem_type];
1381 
1382 	if (!man->has_type) {
1383 		pr_err("Trying to take down uninitialized memory manager type %u\n",
1384 		       mem_type);
1385 		return ret;
1386 	}
1387 
1388 	man->use_type = false;
1389 	man->has_type = false;
1390 
1391 	ret = 0;
1392 	if (mem_type > 0) {
1393 		ttm_bo_force_list_clean(bdev, mem_type, false);
1394 
1395 		ret = (*man->func->takedown)(man);
1396 	}
1397 
1398 	return ret;
1399 }
1400 EXPORT_SYMBOL(ttm_bo_clean_mm);
1401 
1402 int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1403 {
1404 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1405 
1406 	if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
1407 		pr_err("Illegal memory manager memory type %u\n", mem_type);
1408 		return -EINVAL;
1409 	}
1410 
1411 	if (!man->has_type) {
1412 		pr_err("Memory type %u has not been initialized\n", mem_type);
1413 		return 0;
1414 	}
1415 
1416 	return ttm_bo_force_list_clean(bdev, mem_type, true);
1417 }
1418 EXPORT_SYMBOL(ttm_bo_evict_mm);
1419 
1420 int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type,
1421 			unsigned long p_size)
1422 {
1423 	int ret = -EINVAL;
1424 	struct ttm_mem_type_manager *man;
1425 
1426 	BUG_ON(type >= TTM_NUM_MEM_TYPES);
1427 	man = &bdev->man[type];
1428 	BUG_ON(man->has_type);
1429 	man->io_reserve_fastpath = true;
1430 	man->use_io_reserve_lru = false;
1431 	rw_init(&man->io_reserve_mutex, "ttm_iores");
1432 	INIT_LIST_HEAD(&man->io_reserve_lru);
1433 
1434 	ret = bdev->driver->init_mem_type(bdev, type, man);
1435 	if (ret)
1436 		return ret;
1437 	man->bdev = bdev;
1438 
1439 	ret = 0;
1440 	if (type != TTM_PL_SYSTEM) {
1441 		ret = (*man->func->init)(man, p_size);
1442 		if (ret)
1443 			return ret;
1444 	}
1445 	man->has_type = true;
1446 	man->use_type = true;
1447 	man->size = p_size;
1448 
1449 	INIT_LIST_HEAD(&man->lru);
1450 
1451 	return 0;
1452 }
1453 EXPORT_SYMBOL(ttm_bo_init_mm);
1454 
1455 static void ttm_bo_global_kobj_release(struct kobject *kobj)
1456 {
1457 	struct ttm_bo_global *glob =
1458 		container_of(kobj, struct ttm_bo_global, kobj);
1459 
1460 	ttm_mem_unregister_shrink(glob->mem_glob, &glob->shrink);
1461 	km_free(glob->dummy_read_page, PAGE_SIZE, &kv_any, &kp_dma_zero);
1462 	kfree(glob);
1463 }
1464 
1465 void ttm_bo_global_release(struct drm_global_reference *ref)
1466 {
1467 	struct ttm_bo_global *glob = ref->object;
1468 
1469 	kobject_del(&glob->kobj);
1470 	kobject_put(&glob->kobj);
1471 }
1472 EXPORT_SYMBOL(ttm_bo_global_release);
1473 
1474 int ttm_bo_global_init(struct drm_global_reference *ref)
1475 {
1476 	struct ttm_bo_global_ref *bo_ref =
1477 		container_of(ref, struct ttm_bo_global_ref, ref);
1478 	struct ttm_bo_global *glob = ref->object;
1479 	int ret;
1480 
1481 	rw_init(&glob->device_list_mutex, "ttm_devlist");
1482 	mtx_init(&glob->lru_lock, IPL_NONE);
1483 	glob->mem_glob = bo_ref->mem_glob;
1484 	glob->dummy_read_page = km_alloc(PAGE_SIZE, &kv_any, &kp_dma_zero,
1485 	    &kd_waitok);
1486 
1487 	if (unlikely(glob->dummy_read_page == NULL)) {
1488 		ret = -ENOMEM;
1489 		goto out_no_drp;
1490 	}
1491 
1492 	INIT_LIST_HEAD(&glob->swap_lru);
1493 	INIT_LIST_HEAD(&glob->device_list);
1494 
1495 	ttm_mem_init_shrink(&glob->shrink, ttm_bo_swapout);
1496 	ret = ttm_mem_register_shrink(glob->mem_glob, &glob->shrink);
1497 	if (unlikely(ret != 0)) {
1498 		pr_err("Could not register buffer object swapout\n");
1499 		goto out_no_shrink;
1500 	}
1501 
1502 	atomic_set(&glob->bo_count, 0);
1503 
1504 	ret = kobject_init_and_add(
1505 		&glob->kobj, &ttm_bo_glob_kobj_type, ttm_get_kobj(), "buffer_objects");
1506 	if (unlikely(ret != 0))
1507 		kobject_put(&glob->kobj);
1508 	return ret;
1509 out_no_shrink:
1510 	km_free(glob->dummy_read_page, PAGE_SIZE, &kv_any, &kp_dma_zero);
1511 out_no_drp:
1512 	kfree(glob);
1513 	return ret;
1514 }
1515 EXPORT_SYMBOL(ttm_bo_global_init);
1516 
1517 
1518 int ttm_bo_device_release(struct ttm_bo_device *bdev)
1519 {
1520 	int ret = 0;
1521 	unsigned i = TTM_NUM_MEM_TYPES;
1522 	struct ttm_mem_type_manager *man;
1523 	struct ttm_bo_global *glob = bdev->glob;
1524 
1525 	while (i--) {
1526 		man = &bdev->man[i];
1527 		if (man->has_type) {
1528 			man->use_type = false;
1529 			if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) {
1530 				ret = -EBUSY;
1531 				pr_err("DRM memory manager type %d is not clean\n",
1532 				       i);
1533 			}
1534 			man->has_type = false;
1535 		}
1536 	}
1537 
1538 	mutex_lock(&glob->device_list_mutex);
1539 	list_del(&bdev->device_list);
1540 	mutex_unlock(&glob->device_list_mutex);
1541 
1542 	cancel_delayed_work_sync(&bdev->wq);
1543 
1544 	while (ttm_bo_delayed_delete(bdev, true))
1545 		;
1546 
1547 	spin_lock(&glob->lru_lock);
1548 	if (list_empty(&bdev->ddestroy))
1549 		TTM_DEBUG("Delayed destroy list was clean\n");
1550 
1551 	if (list_empty(&bdev->man[0].lru))
1552 		TTM_DEBUG("Swap list was clean\n");
1553 	spin_unlock(&glob->lru_lock);
1554 
1555 	BUG_ON(!drm_mm_clean(&bdev->addr_space_mm));
1556 	write_lock(&bdev->vm_lock);
1557 	drm_mm_takedown(&bdev->addr_space_mm);
1558 	write_unlock(&bdev->vm_lock);
1559 
1560 	return ret;
1561 }
1562 EXPORT_SYMBOL(ttm_bo_device_release);
1563 
1564 int ttm_bo_device_init(struct ttm_bo_device *bdev,
1565 		       struct ttm_bo_global *glob,
1566 		       struct ttm_bo_driver *driver,
1567 		       uint64_t file_page_offset,
1568 		       bool need_dma32)
1569 {
1570 	int ret = -EINVAL;
1571 
1572 	rw_init(&bdev->vm_lock, "ttmvm");
1573 	bdev->driver = driver;
1574 
1575 	memset(bdev->man, 0, sizeof(bdev->man));
1576 
1577 	/*
1578 	 * Initialize the system memory buffer type.
1579 	 * Other types need to be driver / IOCTL initialized.
1580 	 */
1581 	ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0);
1582 	if (unlikely(ret != 0))
1583 		goto out_no_sys;
1584 
1585 	RB_INIT(&bdev->addr_space_rb);
1586 	drm_mm_init(&bdev->addr_space_mm, file_page_offset, 0x10000000);
1587 
1588 	INIT_DELAYED_WORK(&bdev->wq, ttm_bo_delayed_workqueue);
1589 	INIT_LIST_HEAD(&bdev->ddestroy);
1590 	bdev->dev_mapping = NULL;
1591 	bdev->glob = glob;
1592 	bdev->need_dma32 = need_dma32;
1593 	bdev->val_seq = 0;
1594 	mtx_init(&bdev->fence_lock, IPL_NONE);
1595 	mutex_lock(&glob->device_list_mutex);
1596 	list_add_tail(&bdev->device_list, &glob->device_list);
1597 	mutex_unlock(&glob->device_list_mutex);
1598 
1599 	return 0;
1600 out_no_sys:
1601 	return ret;
1602 }
1603 EXPORT_SYMBOL(ttm_bo_device_init);
1604 
1605 /*
1606  * buffer object vm functions.
1607  */
1608 
1609 bool ttm_mem_reg_is_pci(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
1610 {
1611 	struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
1612 
1613 	if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
1614 		if (mem->mem_type == TTM_PL_SYSTEM)
1615 			return false;
1616 
1617 		if (man->flags & TTM_MEMTYPE_FLAG_CMA)
1618 			return false;
1619 
1620 		if (mem->placement & TTM_PL_FLAG_CACHED)
1621 			return false;
1622 	}
1623 	return true;
1624 }
1625 
1626 void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
1627 {
1628 	struct ttm_tt *ttm = bo->ttm;
1629 	struct vm_page *page;
1630 	bus_addr_t addr;
1631 	paddr_t paddr;
1632 	int i;
1633 
1634 	if (bo->mem.bus.is_iomem) {
1635 		for (i = 0; i < bo->mem.num_pages; ++i) {
1636 			addr = bo->mem.bus.base + bo->mem.bus.offset;
1637 			paddr = bus_space_mmap(bo->bdev->memt, addr,
1638 					       i << PAGE_SHIFT, 0, 0);
1639 			page = PHYS_TO_VM_PAGE(paddr);
1640 			if (unlikely(page == NULL))
1641 				continue;
1642 			pmap_page_protect(page, PROT_NONE);
1643 		}
1644 	} else if (ttm) {
1645 		for (i = 0; i < ttm->num_pages; ++i) {
1646 			page = ttm->pages[i];
1647 			if (unlikely(page == NULL))
1648 				continue;
1649 			pmap_page_protect(page, PROT_NONE);
1650 		}
1651 	}
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 
1666 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1667 
1668 static void ttm_bo_vm_insert_rb(struct ttm_buffer_object *bo)
1669 {
1670 	struct ttm_bo_device *bdev = bo->bdev;
1671 
1672 	/* The caller acquired bdev->vm_lock. */
1673 	RB_INSERT(ttm_bo_device_buffer_objects, &bdev->addr_space_rb, bo);
1674 }
1675 
1676 /**
1677  * ttm_bo_setup_vm:
1678  *
1679  * @bo: the buffer to allocate address space for
1680  *
1681  * Allocate address space in the drm device so that applications
1682  * can mmap the buffer and access the contents. This only
1683  * applies to ttm_bo_type_device objects as others are not
1684  * placed in the drm device address space.
1685  */
1686 
1687 static int ttm_bo_setup_vm(struct ttm_buffer_object *bo)
1688 {
1689 	struct ttm_bo_device *bdev = bo->bdev;
1690 	int ret;
1691 
1692 retry_pre_get:
1693 	ret = drm_mm_pre_get(&bdev->addr_space_mm);
1694 	if (unlikely(ret != 0))
1695 		return ret;
1696 
1697 	write_lock(&bdev->vm_lock);
1698 	bo->vm_node = drm_mm_search_free(&bdev->addr_space_mm,
1699 					 bo->mem.num_pages, 0, 0);
1700 
1701 	if (unlikely(bo->vm_node == NULL)) {
1702 		ret = -ENOMEM;
1703 		goto out_unlock;
1704 	}
1705 
1706 	bo->vm_node = drm_mm_get_block_atomic(bo->vm_node,
1707 					      bo->mem.num_pages, 0);
1708 
1709 	if (unlikely(bo->vm_node == NULL)) {
1710 		write_unlock(&bdev->vm_lock);
1711 		goto retry_pre_get;
1712 	}
1713 
1714 	ttm_bo_vm_insert_rb(bo);
1715 	write_unlock(&bdev->vm_lock);
1716 	bo->addr_space_offset = ((uint64_t) bo->vm_node->start) << PAGE_SHIFT;
1717 
1718 	return 0;
1719 out_unlock:
1720 	write_unlock(&bdev->vm_lock);
1721 	return ret;
1722 }
1723 
1724 int ttm_bo_wait(struct ttm_buffer_object *bo,
1725 		bool lazy, bool interruptible, bool no_wait)
1726 {
1727 	struct ttm_bo_driver *driver = bo->bdev->driver;
1728 	struct ttm_bo_device *bdev = bo->bdev;
1729 	void *sync_obj;
1730 	int ret = 0;
1731 
1732 	if (likely(bo->sync_obj == NULL))
1733 		return 0;
1734 
1735 	while (bo->sync_obj) {
1736 
1737 		if (driver->sync_obj_signaled(bo->sync_obj)) {
1738 			void *tmp_obj = bo->sync_obj;
1739 			bo->sync_obj = NULL;
1740 			clear_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags);
1741 			spin_unlock(&bdev->fence_lock);
1742 			driver->sync_obj_unref(&tmp_obj);
1743 			spin_lock(&bdev->fence_lock);
1744 			continue;
1745 		}
1746 
1747 		if (no_wait)
1748 			return -EBUSY;
1749 
1750 		sync_obj = driver->sync_obj_ref(bo->sync_obj);
1751 		spin_unlock(&bdev->fence_lock);
1752 		ret = driver->sync_obj_wait(sync_obj,
1753 					    lazy, interruptible);
1754 		if (unlikely(ret != 0)) {
1755 			driver->sync_obj_unref(&sync_obj);
1756 			spin_lock(&bdev->fence_lock);
1757 			return ret;
1758 		}
1759 		spin_lock(&bdev->fence_lock);
1760 		if (likely(bo->sync_obj == sync_obj)) {
1761 			void *tmp_obj = bo->sync_obj;
1762 			bo->sync_obj = NULL;
1763 			clear_bit(TTM_BO_PRIV_FLAG_MOVING,
1764 				  &bo->priv_flags);
1765 			spin_unlock(&bdev->fence_lock);
1766 			driver->sync_obj_unref(&sync_obj);
1767 			driver->sync_obj_unref(&tmp_obj);
1768 			spin_lock(&bdev->fence_lock);
1769 		} else {
1770 			spin_unlock(&bdev->fence_lock);
1771 			driver->sync_obj_unref(&sync_obj);
1772 			spin_lock(&bdev->fence_lock);
1773 		}
1774 	}
1775 	return 0;
1776 }
1777 EXPORT_SYMBOL(ttm_bo_wait);
1778 
1779 int ttm_bo_synccpu_write_grab(struct ttm_buffer_object *bo, bool no_wait)
1780 {
1781 	struct ttm_bo_device *bdev = bo->bdev;
1782 	int ret = 0;
1783 
1784 	/*
1785 	 * Using ttm_bo_reserve makes sure the lru lists are updated.
1786 	 */
1787 
1788 	ret = ttm_bo_reserve(bo, true, no_wait, false, 0);
1789 	if (unlikely(ret != 0))
1790 		return ret;
1791 	spin_lock(&bdev->fence_lock);
1792 	ret = ttm_bo_wait(bo, false, true, no_wait);
1793 	spin_unlock(&bdev->fence_lock);
1794 	if (likely(ret == 0))
1795 		atomic_inc(&bo->cpu_writers);
1796 	ttm_bo_unreserve(bo);
1797 	return ret;
1798 }
1799 EXPORT_SYMBOL(ttm_bo_synccpu_write_grab);
1800 
1801 void ttm_bo_synccpu_write_release(struct ttm_buffer_object *bo)
1802 {
1803 	atomic_dec(&bo->cpu_writers);
1804 }
1805 EXPORT_SYMBOL(ttm_bo_synccpu_write_release);
1806 
1807 /**
1808  * A buffer object shrink method that tries to swap out the first
1809  * buffer object on the bo_global::swap_lru list.
1810  */
1811 
1812 static int ttm_bo_swapout(struct ttm_mem_shrink *shrink)
1813 {
1814 	struct ttm_bo_global *glob =
1815 	    container_of(shrink, struct ttm_bo_global, shrink);
1816 	struct ttm_buffer_object *bo;
1817 	int ret = -EBUSY;
1818 	int put_count;
1819 	uint32_t swap_placement = (TTM_PL_FLAG_CACHED | TTM_PL_FLAG_SYSTEM);
1820 
1821 	spin_lock(&glob->lru_lock);
1822 	list_for_each_entry(bo, &glob->swap_lru, swap) {
1823 		ret = ttm_bo_reserve_locked(bo, false, true, false, 0);
1824 		if (!ret)
1825 			break;
1826 	}
1827 
1828 	if (ret) {
1829 		spin_unlock(&glob->lru_lock);
1830 		return ret;
1831 	}
1832 
1833 	kref_get(&bo->list_kref);
1834 
1835 	if (!list_empty(&bo->ddestroy)) {
1836 		ret = ttm_bo_cleanup_refs_and_unlock(bo, false, false);
1837 		kref_put(&bo->list_kref, ttm_bo_release_list);
1838 		return ret;
1839 	}
1840 
1841 	put_count = ttm_bo_del_from_lru(bo);
1842 	spin_unlock(&glob->lru_lock);
1843 
1844 	ttm_bo_list_ref_sub(bo, put_count, true);
1845 
1846 	/**
1847 	 * Wait for GPU, then move to system cached.
1848 	 */
1849 
1850 	spin_lock(&bo->bdev->fence_lock);
1851 	ret = ttm_bo_wait(bo, false, false, false);
1852 	spin_unlock(&bo->bdev->fence_lock);
1853 
1854 	if (unlikely(ret != 0))
1855 		goto out;
1856 
1857 	if ((bo->mem.placement & swap_placement) != swap_placement) {
1858 		struct ttm_mem_reg evict_mem;
1859 
1860 		evict_mem = bo->mem;
1861 		evict_mem.mm_node = NULL;
1862 		evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
1863 		evict_mem.mem_type = TTM_PL_SYSTEM;
1864 
1865 		ret = ttm_bo_handle_move_mem(bo, &evict_mem, true,
1866 					     false, false);
1867 		if (unlikely(ret != 0))
1868 			goto out;
1869 	}
1870 
1871 	ttm_bo_unmap_virtual(bo);
1872 
1873 	/**
1874 	 * Swap out. Buffer will be swapped in again as soon as
1875 	 * anyone tries to access a ttm page.
1876 	 */
1877 
1878 	if (bo->bdev->driver->swap_notify)
1879 		bo->bdev->driver->swap_notify(bo);
1880 
1881 	ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
1882 out:
1883 
1884 	/**
1885 	 *
1886 	 * Unreserve without putting on LRU to avoid swapping out an
1887 	 * already swapped buffer.
1888 	 */
1889 
1890 	atomic_set(&bo->reserved, 0);
1891 	wake_up_all(&bo->event_queue);
1892 	kref_put(&bo->list_kref, ttm_bo_release_list);
1893 	return ret;
1894 }
1895 
1896 void ttm_bo_swapout_all(struct ttm_bo_device *bdev)
1897 {
1898 	while (ttm_bo_swapout(&bdev->glob->shrink) == 0)
1899 		;
1900 }
1901 EXPORT_SYMBOL(ttm_bo_swapout_all);
1902