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