xref: /dragonfly/sys/dev/drm/ttm/ttm_bo.c (revision ef944814)
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 /*
365  * Must interlock with event_queue to avoid race against
366  * wait_event_common() which can cause wait_event_common()
367  * to become stuck.
368  */
369 static void
370 ttm_bo_unreserve_core(struct ttm_buffer_object *bo)
371 {
372 	lockmgr(&bo->event_queue.lock, LK_EXCLUSIVE);
373 	atomic_set(&bo->reserved, 0);
374 	lockmgr(&bo->event_queue.lock, LK_RELEASE);
375 	wake_up_all(&bo->event_queue);
376 }
377 
378 void ttm_bo_unreserve_ticket_locked(struct ttm_buffer_object *bo, struct ww_acquire_ctx *ticket)
379 {
380 	ttm_bo_add_to_lru(bo);
381 	ttm_bo_unreserve_core(bo);
382 }
383 
384 void ttm_bo_unreserve(struct ttm_buffer_object *bo)
385 {
386 	struct ttm_bo_global *glob = bo->glob;
387 
388 	lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
389 	ttm_bo_unreserve_ticket_locked(bo, NULL);
390 	lockmgr(&glob->lru_lock, LK_RELEASE);
391 }
392 EXPORT_SYMBOL(ttm_bo_unreserve);
393 
394 void ttm_bo_unreserve_ticket(struct ttm_buffer_object *bo, struct ww_acquire_ctx *ticket)
395 {
396 	struct ttm_bo_global *glob = bo->glob;
397 
398 	lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
399 	ttm_bo_unreserve_ticket_locked(bo, ticket);
400 	lockmgr(&glob->lru_lock, LK_RELEASE);
401 }
402 EXPORT_SYMBOL(ttm_bo_unreserve_ticket);
403 
404 /*
405  * Call bo->mutex locked.
406  */
407 static int ttm_bo_add_ttm(struct ttm_buffer_object *bo, bool zero_alloc)
408 {
409 	struct ttm_bo_device *bdev = bo->bdev;
410 	struct ttm_bo_global *glob = bo->glob;
411 	int ret = 0;
412 	uint32_t page_flags = 0;
413 
414 	TTM_ASSERT_LOCKED(&bo->mutex);
415 	bo->ttm = NULL;
416 
417 	if (bdev->need_dma32)
418 		page_flags |= TTM_PAGE_FLAG_DMA32;
419 
420 	switch (bo->type) {
421 	case ttm_bo_type_device:
422 		if (zero_alloc)
423 			page_flags |= TTM_PAGE_FLAG_ZERO_ALLOC;
424 	case ttm_bo_type_kernel:
425 		bo->ttm = bdev->driver->ttm_tt_create(bdev, bo->num_pages << PAGE_SHIFT,
426 						      page_flags, glob->dummy_read_page);
427 		if (unlikely(bo->ttm == NULL))
428 			ret = -ENOMEM;
429 		break;
430 	case ttm_bo_type_sg:
431 		bo->ttm = bdev->driver->ttm_tt_create(bdev, bo->num_pages << PAGE_SHIFT,
432 						      page_flags | TTM_PAGE_FLAG_SG,
433 						      glob->dummy_read_page);
434 		if (unlikely(bo->ttm == NULL)) {
435 			ret = -ENOMEM;
436 			break;
437 		}
438 		bo->ttm->sg = bo->sg;
439 		break;
440 	default:
441 		pr_err("Illegal buffer object type\n");
442 		ret = -EINVAL;
443 		break;
444 	}
445 
446 	return ret;
447 }
448 
449 static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo,
450 				  struct ttm_mem_reg *mem,
451 				  bool evict, bool interruptible,
452 				  bool no_wait_gpu)
453 {
454 	struct ttm_bo_device *bdev = bo->bdev;
455 	bool old_is_pci = ttm_mem_reg_is_pci(bdev, &bo->mem);
456 	bool new_is_pci = ttm_mem_reg_is_pci(bdev, mem);
457 	struct ttm_mem_type_manager *old_man = &bdev->man[bo->mem.mem_type];
458 	struct ttm_mem_type_manager *new_man = &bdev->man[mem->mem_type];
459 	int ret = 0;
460 
461 	if (old_is_pci || new_is_pci ||
462 	    ((mem->placement & bo->mem.placement & TTM_PL_MASK_CACHING) == 0)) {
463 		ret = ttm_mem_io_lock(old_man, true);
464 		if (unlikely(ret != 0))
465 			goto out_err;
466 		ttm_bo_unmap_virtual_locked(bo);
467 		ttm_mem_io_unlock(old_man);
468 	}
469 
470 	/*
471 	 * Create and bind a ttm if required.
472 	 */
473 
474 	if (!(new_man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
475 		if (bo->ttm == NULL) {
476 			bool zero = !(old_man->flags & TTM_MEMTYPE_FLAG_FIXED);
477 			ret = ttm_bo_add_ttm(bo, zero);
478 			if (ret)
479 				goto out_err;
480 		}
481 
482 		ret = ttm_tt_set_placement_caching(bo->ttm, mem->placement);
483 		if (ret)
484 			goto out_err;
485 
486 		if (mem->mem_type != TTM_PL_SYSTEM) {
487 			ret = ttm_tt_bind(bo->ttm, mem);
488 			if (ret)
489 				goto out_err;
490 		}
491 
492 		if (bo->mem.mem_type == TTM_PL_SYSTEM) {
493 			if (bdev->driver->move_notify)
494 				bdev->driver->move_notify(bo, mem);
495 			bo->mem = *mem;
496 			mem->mm_node = NULL;
497 			goto moved;
498 		}
499 	}
500 
501 	if (bdev->driver->move_notify)
502 		bdev->driver->move_notify(bo, mem);
503 
504 	if (!(old_man->flags & TTM_MEMTYPE_FLAG_FIXED) &&
505 	    !(new_man->flags & TTM_MEMTYPE_FLAG_FIXED))
506 		ret = ttm_bo_move_ttm(bo, evict, no_wait_gpu, mem);
507 	else if (bdev->driver->move)
508 		ret = bdev->driver->move(bo, evict, interruptible,
509 					 no_wait_gpu, mem);
510 	else
511 		ret = ttm_bo_move_memcpy(bo, evict, no_wait_gpu, mem);
512 
513 	if (ret) {
514 		if (bdev->driver->move_notify) {
515 			struct ttm_mem_reg tmp_mem = *mem;
516 			*mem = bo->mem;
517 			bo->mem = tmp_mem;
518 			bdev->driver->move_notify(bo, mem);
519 			bo->mem = *mem;
520 			*mem = tmp_mem;
521 		}
522 
523 		goto out_err;
524 	}
525 
526 moved:
527 	if (bo->evicted) {
528 		ret = bdev->driver->invalidate_caches(bdev, bo->mem.placement);
529 		if (ret)
530 			pr_err("Can not flush read caches\n");
531 		bo->evicted = false;
532 	}
533 
534 	if (bo->mem.mm_node) {
535 		bo->offset = (bo->mem.start << PAGE_SHIFT) +
536 		    bdev->man[bo->mem.mem_type].gpu_offset;
537 		bo->cur_placement = bo->mem.placement;
538 	} else
539 		bo->offset = 0;
540 
541 	return 0;
542 
543 out_err:
544 	new_man = &bdev->man[bo->mem.mem_type];
545 	if ((new_man->flags & TTM_MEMTYPE_FLAG_FIXED) && bo->ttm) {
546 		ttm_tt_unbind(bo->ttm);
547 		ttm_tt_destroy(bo->ttm);
548 		bo->ttm = NULL;
549 	}
550 
551 	return ret;
552 }
553 
554 /**
555  * Call bo::reserved.
556  * Will release GPU memory type usage on destruction.
557  * This is the place to put in driver specific hooks to release
558  * driver private resources.
559  * Will release the bo::reserved lock.
560  */
561 
562 static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo)
563 {
564 	if (bo->bdev->driver->move_notify)
565 		bo->bdev->driver->move_notify(bo, NULL);
566 
567 	if (bo->ttm) {
568 		ttm_tt_unbind(bo->ttm);
569 		ttm_tt_destroy(bo->ttm);
570 		bo->ttm = NULL;
571 	}
572 	ttm_bo_mem_put(bo, &bo->mem);
573 	ttm_bo_unreserve_core(bo);
574 
575 	/*
576 	 * Since the final reference to this bo may not be dropped by
577 	 * the current task we have to put a memory barrier here to make
578 	 * sure the changes done in this function are always visible.
579 	 *
580 	 * This function only needs protection against the final kref_put.
581 	 */
582 	cpu_mfence();
583 }
584 
585 static void ttm_bo_cleanup_refs_or_queue(struct ttm_buffer_object *bo)
586 {
587 	struct ttm_bo_device *bdev = bo->bdev;
588 	struct ttm_bo_global *glob = bo->glob;
589 	struct ttm_bo_driver *driver = bdev->driver;
590 	void *sync_obj = NULL;
591 	int put_count;
592 	int ret;
593 
594 	lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
595 	ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
596 
597 	lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
598 	(void) ttm_bo_wait(bo, false, false, true);
599 	if (!ret && !bo->sync_obj) {
600 		lockmgr(&bdev->fence_lock, LK_RELEASE);
601 		put_count = ttm_bo_del_from_lru(bo);
602 
603 		lockmgr(&glob->lru_lock, LK_RELEASE);
604 		ttm_bo_cleanup_memtype_use(bo);
605 
606 		ttm_bo_list_ref_sub(bo, put_count, true);
607 
608 		return;
609 	}
610 	if (bo->sync_obj)
611 		sync_obj = driver->sync_obj_ref(bo->sync_obj);
612 	lockmgr(&bdev->fence_lock, LK_RELEASE);
613 
614 	if (!ret) {
615 
616 		/*
617 		 * Make NO_EVICT bos immediately available to
618 		 * shrinkers, now that they are queued for
619 		 * destruction.
620 		 */
621 		if (bo->mem.placement & TTM_PL_FLAG_NO_EVICT) {
622 			bo->mem.placement &= ~TTM_PL_FLAG_NO_EVICT;
623 			ttm_bo_add_to_lru(bo);
624 		}
625 
626 		ttm_bo_unreserve_core(bo);
627 	}
628 
629 	kref_get(&bo->list_kref);
630 	list_add_tail(&bo->ddestroy, &bdev->ddestroy);
631 	lockmgr(&glob->lru_lock, LK_RELEASE);
632 
633 	if (sync_obj) {
634 		driver->sync_obj_flush(sync_obj);
635 		driver->sync_obj_unref(&sync_obj);
636 	}
637 	schedule_delayed_work(&bdev->wq,
638 			      ((hz / 100) < 1) ? 1 : hz / 100);
639 }
640 
641 /**
642  * function ttm_bo_cleanup_refs_and_unlock
643  * If bo idle, remove from delayed- and lru lists, and unref.
644  * If not idle, do nothing.
645  *
646  * Must be called with lru_lock and reservation held, this function
647  * will drop both before returning.
648  *
649  * @interruptible         Any sleeps should occur interruptibly.
650  * @no_wait_gpu           Never wait for gpu. Return -EBUSY instead.
651  */
652 
653 static int ttm_bo_cleanup_refs_and_unlock(struct ttm_buffer_object *bo,
654 					  bool interruptible,
655 					  bool no_wait_gpu)
656 {
657 	struct ttm_bo_device *bdev = bo->bdev;
658 	struct ttm_bo_driver *driver = bdev->driver;
659 	struct ttm_bo_global *glob = bo->glob;
660 	int put_count;
661 	int ret;
662 
663 	lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
664 	ret = ttm_bo_wait(bo, false, false, true);
665 
666 	if (ret && !no_wait_gpu) {
667 		void *sync_obj;
668 
669 		/*
670 		 * Take a reference to the fence and unreserve,
671 		 * at this point the buffer should be dead, so
672 		 * no new sync objects can be attached.
673 		 */
674 		sync_obj = driver->sync_obj_ref(bo->sync_obj);
675 		lockmgr(&bdev->fence_lock, LK_RELEASE);
676 
677 		ttm_bo_unreserve_core(bo);
678 		lockmgr(&glob->lru_lock, LK_RELEASE);
679 
680 		ret = driver->sync_obj_wait(sync_obj, false, interruptible);
681 		driver->sync_obj_unref(&sync_obj);
682 		if (ret)
683 			return ret;
684 
685 		/*
686 		 * remove sync_obj with ttm_bo_wait, the wait should be
687 		 * finished, and no new wait object should have been added.
688 		 */
689 		lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
690 		ret = ttm_bo_wait(bo, false, false, true);
691 		WARN_ON(ret);
692 		lockmgr(&bdev->fence_lock, LK_RELEASE);
693 		if (ret)
694 			return ret;
695 
696 		lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
697 		ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
698 
699 		/*
700 		 * We raced, and lost, someone else holds the reservation now,
701 		 * and is probably busy in ttm_bo_cleanup_memtype_use.
702 		 *
703 		 * Even if it's not the case, because we finished waiting any
704 		 * delayed destruction would succeed, so just return success
705 		 * here.
706 		 */
707 		if (ret) {
708 			lockmgr(&glob->lru_lock, LK_RELEASE);
709 			return 0;
710 		}
711 	} else
712 		lockmgr(&bdev->fence_lock, LK_RELEASE);
713 
714 	if (ret || unlikely(list_empty(&bo->ddestroy))) {
715 		ttm_bo_unreserve_core(bo);
716 		lockmgr(&glob->lru_lock, LK_RELEASE);
717 		return ret;
718 	}
719 
720 	put_count = ttm_bo_del_from_lru(bo);
721 	list_del_init(&bo->ddestroy);
722 	++put_count;
723 
724 	lockmgr(&glob->lru_lock, LK_RELEASE);
725 	ttm_bo_cleanup_memtype_use(bo);
726 
727 	ttm_bo_list_ref_sub(bo, put_count, true);
728 
729 	return 0;
730 }
731 
732 /**
733  * Traverse the delayed list, and call ttm_bo_cleanup_refs on all
734  * encountered buffers.
735  */
736 
737 static int ttm_bo_delayed_delete(struct ttm_bo_device *bdev, bool remove_all)
738 {
739 	struct ttm_bo_global *glob = bdev->glob;
740 	struct ttm_buffer_object *entry = NULL;
741 	int ret = 0;
742 
743 	lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
744 	if (list_empty(&bdev->ddestroy))
745 		goto out_unlock;
746 
747 	entry = list_first_entry(&bdev->ddestroy,
748 		struct ttm_buffer_object, ddestroy);
749 	kref_get(&entry->list_kref);
750 
751 	for (;;) {
752 		struct ttm_buffer_object *nentry = NULL;
753 
754 		if (entry->ddestroy.next != &bdev->ddestroy) {
755 			nentry = list_first_entry(&entry->ddestroy,
756 				struct ttm_buffer_object, ddestroy);
757 			kref_get(&nentry->list_kref);
758 		}
759 
760 		ret = ttm_bo_reserve_nolru(entry, false, true, false, 0);
761 		if (remove_all && ret) {
762 			lockmgr(&glob->lru_lock, LK_RELEASE);
763 			ret = ttm_bo_reserve_nolru(entry, false, false,
764 						   false, 0);
765 			lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
766 		}
767 
768 		if (!ret)
769 			ret = ttm_bo_cleanup_refs_and_unlock(entry, false,
770 							     !remove_all);
771 		else
772 			lockmgr(&glob->lru_lock, LK_RELEASE);
773 
774 		kref_put(&entry->list_kref, ttm_bo_release_list);
775 		entry = nentry;
776 
777 		if (ret || !entry)
778 			goto out;
779 
780 		lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
781 		if (list_empty(&entry->ddestroy))
782 			break;
783 	}
784 
785 out_unlock:
786 	lockmgr(&glob->lru_lock, LK_RELEASE);
787 out:
788 	if (entry)
789 		kref_put(&entry->list_kref, ttm_bo_release_list);
790 	return ret;
791 }
792 
793 static void ttm_bo_delayed_workqueue(struct work_struct *work)
794 {
795 	struct ttm_bo_device *bdev =
796 	    container_of(work, struct ttm_bo_device, wq.work);
797 
798 	if (ttm_bo_delayed_delete(bdev, false)) {
799 		schedule_delayed_work(&bdev->wq,
800 				      ((hz / 100) < 1) ? 1 : hz / 100);
801 	}
802 }
803 
804 /*
805  * NOTE: bdev->vm_lock already held on call, this function release it.
806  */
807 static void ttm_bo_release(struct kref *kref)
808 {
809 	struct ttm_buffer_object *bo =
810 	    container_of(kref, struct ttm_buffer_object, kref);
811 	struct ttm_bo_device *bdev = bo->bdev;
812 	struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
813 	int release_active;
814 
815 	if (atomic_read(&bo->kref.refcount) > 0) {
816 		lockmgr(&bdev->vm_lock, LK_RELEASE);
817 		return;
818 	}
819 	if (likely(bo->vm_node != NULL)) {
820 		RB_REMOVE(ttm_bo_device_buffer_objects,
821 				&bdev->addr_space_rb, bo);
822 		drm_mm_put_block(bo->vm_node);
823 		bo->vm_node = NULL;
824 	}
825 
826 	/*
827 	 * Should we clean up our implied list_kref?  Because ttm_bo_release()
828 	 * can be called reentrantly due to races (this may not be true any
829 	 * more with the lock management changes in the deref), it is possible
830 	 * to get here twice, but there's only one list_kref ref to drop and
831 	 * in the other path 'bo' can be kfree()d by another thread the
832 	 * instant we release our lock.
833 	 */
834 	release_active = test_bit(TTM_BO_PRIV_FLAG_ACTIVE, &bo->priv_flags);
835 	if (release_active) {
836 		clear_bit(TTM_BO_PRIV_FLAG_ACTIVE, &bo->priv_flags);
837 		lockmgr(&bdev->vm_lock, LK_RELEASE);
838 		ttm_mem_io_lock(man, false);
839 		ttm_mem_io_free_vm(bo);
840 		ttm_mem_io_unlock(man);
841 		ttm_bo_cleanup_refs_or_queue(bo);
842 		kref_put(&bo->list_kref, ttm_bo_release_list);
843 	} else {
844 		lockmgr(&bdev->vm_lock, LK_RELEASE);
845 	}
846 }
847 
848 void ttm_bo_unref(struct ttm_buffer_object **p_bo)
849 {
850 	struct ttm_buffer_object *bo = *p_bo;
851 	struct ttm_bo_device *bdev = bo->bdev;
852 
853 	*p_bo = NULL;
854 	lockmgr(&bdev->vm_lock, LK_EXCLUSIVE);
855 	if (kref_put(&bo->kref, ttm_bo_release) == 0)
856 		lockmgr(&bdev->vm_lock, LK_RELEASE);
857 }
858 EXPORT_SYMBOL(ttm_bo_unref);
859 
860 int ttm_bo_lock_delayed_workqueue(struct ttm_bo_device *bdev)
861 {
862 	return cancel_delayed_work_sync(&bdev->wq);
863 }
864 EXPORT_SYMBOL(ttm_bo_lock_delayed_workqueue);
865 
866 void ttm_bo_unlock_delayed_workqueue(struct ttm_bo_device *bdev, int resched)
867 {
868 	if (resched)
869 		schedule_delayed_work(&bdev->wq,
870 				      ((hz / 100) < 1) ? 1 : hz / 100);
871 }
872 EXPORT_SYMBOL(ttm_bo_unlock_delayed_workqueue);
873 
874 static int ttm_bo_evict(struct ttm_buffer_object *bo, bool interruptible,
875 			bool no_wait_gpu)
876 {
877 	struct ttm_bo_device *bdev = bo->bdev;
878 	struct ttm_mem_reg evict_mem;
879 	struct ttm_placement placement;
880 	int ret = 0;
881 
882 	lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
883 	ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
884 	lockmgr(&bdev->fence_lock, LK_RELEASE);
885 
886 	if (unlikely(ret != 0)) {
887 		if (ret != -ERESTARTSYS) {
888 			pr_err("Failed to expire sync object before buffer eviction\n");
889 		}
890 		goto out;
891 	}
892 
893 	BUG_ON(!ttm_bo_is_reserved(bo));
894 
895 	evict_mem = bo->mem;
896 	evict_mem.mm_node = NULL;
897 	evict_mem.bus.io_reserved_vm = false;
898 	evict_mem.bus.io_reserved_count = 0;
899 
900 	placement.num_placement = 0;
901 	placement.num_busy_placement = 0;
902 	bdev->driver->evict_flags(bo, &placement);
903 	ret = ttm_bo_mem_space(bo, &placement, &evict_mem, interruptible,
904 				no_wait_gpu);
905 	if (ret) {
906 		if (ret != -ERESTARTSYS) {
907 			pr_err("Failed to find memory space for buffer 0x%p eviction\n",
908 			       bo);
909 			ttm_bo_mem_space_debug(bo, &placement);
910 		}
911 		goto out;
912 	}
913 
914 	ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, interruptible,
915 				     no_wait_gpu);
916 	if (ret) {
917 		if (ret != -ERESTARTSYS)
918 			pr_err("Buffer eviction failed\n");
919 		ttm_bo_mem_put(bo, &evict_mem);
920 		goto out;
921 	}
922 	bo->evicted = true;
923 out:
924 	return ret;
925 }
926 
927 static int ttm_mem_evict_first(struct ttm_bo_device *bdev,
928 				uint32_t mem_type,
929 				bool interruptible,
930 				bool no_wait_gpu)
931 {
932 	struct ttm_bo_global *glob = bdev->glob;
933 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
934 	struct ttm_buffer_object *bo;
935 	int ret = -EBUSY, put_count;
936 
937 	lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
938 	list_for_each_entry(bo, &man->lru, lru) {
939 		ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
940 		if (!ret)
941 			break;
942 	}
943 
944 	if (ret) {
945 		lockmgr(&glob->lru_lock, LK_RELEASE);
946 		return ret;
947 	}
948 
949 	kref_get(&bo->list_kref);
950 
951 	if (!list_empty(&bo->ddestroy)) {
952 		ret = ttm_bo_cleanup_refs_and_unlock(bo, interruptible,
953 						     no_wait_gpu);
954 		kref_put(&bo->list_kref, ttm_bo_release_list);
955 		return ret;
956 	}
957 
958 	put_count = ttm_bo_del_from_lru(bo);
959 	lockmgr(&glob->lru_lock, LK_RELEASE);
960 
961 	BUG_ON(ret != 0);
962 
963 	ttm_bo_list_ref_sub(bo, put_count, true);
964 
965 	ret = ttm_bo_evict(bo, interruptible, no_wait_gpu);
966 	ttm_bo_unreserve(bo);
967 
968 	kref_put(&bo->list_kref, ttm_bo_release_list);
969 	return ret;
970 }
971 
972 void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem)
973 {
974 	struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type];
975 
976 	if (mem->mm_node)
977 		(*man->func->put_node)(man, mem);
978 }
979 EXPORT_SYMBOL(ttm_bo_mem_put);
980 
981 /**
982  * Repeatedly evict memory from the LRU for @mem_type until we create enough
983  * space, or we've evicted everything and there isn't enough space.
984  */
985 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
986 					uint32_t mem_type,
987 					const struct ttm_place *place,
988 					struct ttm_mem_reg *mem,
989 					bool interruptible,
990 					bool no_wait_gpu)
991 {
992 	struct ttm_bo_device *bdev = bo->bdev;
993 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
994 	int ret;
995 
996 	do {
997 		ret = (*man->func->get_node)(man, bo, place, mem);
998 		if (unlikely(ret != 0))
999 			return ret;
1000 		if (mem->mm_node)
1001 			break;
1002 		ret = ttm_mem_evict_first(bdev, mem_type,
1003 					  interruptible, no_wait_gpu);
1004 		if (unlikely(ret != 0))
1005 			return ret;
1006 	} while (1);
1007 	if (mem->mm_node == NULL)
1008 		return -ENOMEM;
1009 	mem->mem_type = mem_type;
1010 	return 0;
1011 }
1012 
1013 static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man,
1014 				      uint32_t cur_placement,
1015 				      uint32_t proposed_placement)
1016 {
1017 	uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
1018 	uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
1019 
1020 	/**
1021 	 * Keep current caching if possible.
1022 	 */
1023 
1024 	if ((cur_placement & caching) != 0)
1025 		result |= (cur_placement & caching);
1026 	else if ((man->default_caching & caching) != 0)
1027 		result |= man->default_caching;
1028 	else if ((TTM_PL_FLAG_CACHED & caching) != 0)
1029 		result |= TTM_PL_FLAG_CACHED;
1030 	else if ((TTM_PL_FLAG_WC & caching) != 0)
1031 		result |= TTM_PL_FLAG_WC;
1032 	else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
1033 		result |= TTM_PL_FLAG_UNCACHED;
1034 
1035 	return result;
1036 }
1037 
1038 static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man,
1039 				 uint32_t mem_type,
1040 				 const struct ttm_place *place,
1041 				 uint32_t *masked_placement)
1042 {
1043 	uint32_t cur_flags = ttm_bo_type_flags(mem_type);
1044 
1045 	if ((cur_flags & place->flags & TTM_PL_MASK_MEM) == 0)
1046 		return false;
1047 
1048 	if ((place->flags & man->available_caching) == 0)
1049 		return false;
1050 
1051 	cur_flags |= (place->flags & man->available_caching);
1052 
1053 	*masked_placement = cur_flags;
1054 	return true;
1055 }
1056 
1057 /**
1058  * Creates space for memory region @mem according to its type.
1059  *
1060  * This function first searches for free space in compatible memory types in
1061  * the priority order defined by the driver.  If free space isn't found, then
1062  * ttm_bo_mem_force_space is attempted in priority order to evict and find
1063  * space.
1064  */
1065 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1066 			struct ttm_placement *placement,
1067 			struct ttm_mem_reg *mem,
1068 			bool interruptible,
1069 			bool no_wait_gpu)
1070 {
1071 	struct ttm_bo_device *bdev = bo->bdev;
1072 	struct ttm_mem_type_manager *man;
1073 	uint32_t mem_type = TTM_PL_SYSTEM;
1074 	uint32_t cur_flags = 0;
1075 	bool type_found = false;
1076 	bool type_ok = false;
1077 	bool has_erestartsys = false;
1078 	int i, ret;
1079 
1080 	mem->mm_node = NULL;
1081 	for (i = 0; i < placement->num_placement; ++i) {
1082 		const struct ttm_place *place = &placement->placement[i];
1083 
1084 		ret = ttm_mem_type_from_place(place, &mem_type);
1085 		if (ret)
1086 			return ret;
1087 		man = &bdev->man[mem_type];
1088 
1089 		type_ok = ttm_bo_mt_compatible(man, mem_type, place,
1090 						&cur_flags);
1091 
1092 		if (!type_ok)
1093 			continue;
1094 
1095 		cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
1096 						  cur_flags);
1097 		/*
1098 		 * Use the access and other non-mapping-related flag bits from
1099 		 * the memory placement flags to the current flags
1100 		 */
1101 		ttm_flag_masked(&cur_flags, place->flags,
1102 				~TTM_PL_MASK_MEMTYPE);
1103 
1104 		if (mem_type == TTM_PL_SYSTEM)
1105 			break;
1106 
1107 		if (man->has_type && man->use_type) {
1108 			type_found = true;
1109 			ret = (*man->func->get_node)(man, bo, place, mem);
1110 			if (unlikely(ret))
1111 				return ret;
1112 		}
1113 		if (mem->mm_node)
1114 			break;
1115 	}
1116 
1117 	if ((type_ok && (mem_type == TTM_PL_SYSTEM)) || mem->mm_node) {
1118 		mem->mem_type = mem_type;
1119 		mem->placement = cur_flags;
1120 		return 0;
1121 	}
1122 
1123 	if (!type_found)
1124 		return -EINVAL;
1125 
1126 	for (i = 0; i < placement->num_busy_placement; ++i) {
1127 		const struct ttm_place *place = &placement->busy_placement[i];
1128 
1129 		ret = ttm_mem_type_from_place(place, &mem_type);
1130 		if (ret)
1131 			return ret;
1132 		man = &bdev->man[mem_type];
1133 		if (!man->has_type)
1134 			continue;
1135 		if (!ttm_bo_mt_compatible(man, mem_type, place, &cur_flags))
1136 			continue;
1137 
1138 		cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
1139 						  cur_flags);
1140 		/*
1141 		 * Use the access and other non-mapping-related flag bits from
1142 		 * the memory placement flags to the current flags
1143 		 */
1144 		ttm_flag_masked(&cur_flags, place->flags,
1145 				~TTM_PL_MASK_MEMTYPE);
1146 
1147 		if (mem_type == TTM_PL_SYSTEM) {
1148 			mem->mem_type = mem_type;
1149 			mem->placement = cur_flags;
1150 			mem->mm_node = NULL;
1151 			return 0;
1152 		}
1153 
1154 		ret = ttm_bo_mem_force_space(bo, mem_type, place, mem,
1155 						interruptible, no_wait_gpu);
1156 		if (ret == 0 && mem->mm_node) {
1157 			mem->placement = cur_flags;
1158 			return 0;
1159 		}
1160 		if (ret == -ERESTARTSYS)
1161 			has_erestartsys = true;
1162 	}
1163 	ret = (has_erestartsys) ? -ERESTARTSYS : -ENOMEM;
1164 	return ret;
1165 }
1166 EXPORT_SYMBOL(ttm_bo_mem_space);
1167 
1168 static int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
1169 			struct ttm_placement *placement,
1170 			bool interruptible,
1171 			bool no_wait_gpu)
1172 {
1173 	int ret = 0;
1174 	struct ttm_mem_reg mem;
1175 	struct ttm_bo_device *bdev = bo->bdev;
1176 
1177 	BUG_ON(!ttm_bo_is_reserved(bo));
1178 
1179 	/*
1180 	 * FIXME: It's possible to pipeline buffer moves.
1181 	 * Have the driver move function wait for idle when necessary,
1182 	 * instead of doing it here.
1183 	 */
1184 	lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1185 	ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
1186 	lockmgr(&bdev->fence_lock, LK_RELEASE);
1187 	if (ret)
1188 		return ret;
1189 	mem.num_pages = bo->num_pages;
1190 	mem.size = mem.num_pages << PAGE_SHIFT;
1191 	mem.page_alignment = bo->mem.page_alignment;
1192 	mem.bus.io_reserved_vm = false;
1193 	mem.bus.io_reserved_count = 0;
1194 	/*
1195 	 * Determine where to move the buffer.
1196 	 */
1197 	ret = ttm_bo_mem_space(bo, placement, &mem,
1198 			       interruptible, no_wait_gpu);
1199 	if (ret)
1200 		goto out_unlock;
1201 	ret = ttm_bo_handle_move_mem(bo, &mem, false,
1202 				     interruptible, no_wait_gpu);
1203 out_unlock:
1204 	if (ret && mem.mm_node)
1205 		ttm_bo_mem_put(bo, &mem);
1206 	return ret;
1207 }
1208 
1209 static bool ttm_bo_mem_compat(struct ttm_placement *placement,
1210 			      struct ttm_mem_reg *mem,
1211 			      uint32_t *new_flags)
1212 {
1213 	int i;
1214 
1215 	for (i = 0; i < placement->num_placement; i++) {
1216 		const struct ttm_place *heap = &placement->placement[i];
1217 		if (mem->mm_node &&
1218 		    (mem->start < heap->fpfn ||
1219 		     (heap->lpfn != 0 && (mem->start + mem->num_pages) > heap->lpfn)))
1220 			continue;
1221 
1222 		*new_flags = heap->flags;
1223 		if ((*new_flags & mem->placement & TTM_PL_MASK_CACHING) &&
1224 		    (*new_flags & mem->placement & TTM_PL_MASK_MEM))
1225 			return true;
1226 	}
1227 
1228 	for (i = 0; i < placement->num_busy_placement; i++) {
1229 		const struct ttm_place *heap = &placement->busy_placement[i];
1230 		if (mem->mm_node &&
1231 		    (mem->start < heap->fpfn ||
1232 		     (heap->lpfn != 0 && (mem->start + mem->num_pages) > heap->lpfn)))
1233 			continue;
1234 
1235 		*new_flags = heap->flags;
1236 		if ((*new_flags & mem->placement & TTM_PL_MASK_CACHING) &&
1237 		    (*new_flags & mem->placement & TTM_PL_MASK_MEM))
1238 			return true;
1239 	}
1240 
1241 	return false;
1242 }
1243 
1244 int ttm_bo_validate(struct ttm_buffer_object *bo,
1245 			struct ttm_placement *placement,
1246 			bool interruptible,
1247 			bool no_wait_gpu)
1248 {
1249 	int ret;
1250 	uint32_t new_flags;
1251 
1252 	BUG_ON(!ttm_bo_is_reserved(bo));
1253 	/*
1254 	 * Check whether we need to move buffer.
1255 	 */
1256 	if (!ttm_bo_mem_compat(placement, &bo->mem, &new_flags)) {
1257 		ret = ttm_bo_move_buffer(bo, placement, interruptible,
1258 					 no_wait_gpu);
1259 		if (ret)
1260 			return ret;
1261 	} else {
1262 		/*
1263 		 * Use the access and other non-mapping-related flag bits from
1264 		 * the compatible memory placement flags to the active flags
1265 		 */
1266 		ttm_flag_masked(&bo->mem.placement, new_flags,
1267 				~TTM_PL_MASK_MEMTYPE);
1268 	}
1269 	/*
1270 	 * We might need to add a TTM.
1271 	 */
1272 	if (bo->mem.mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
1273 		ret = ttm_bo_add_ttm(bo, true);
1274 		if (ret)
1275 			return ret;
1276 	}
1277 	return 0;
1278 }
1279 EXPORT_SYMBOL(ttm_bo_validate);
1280 
1281 int ttm_bo_init(struct ttm_bo_device *bdev,
1282 		struct ttm_buffer_object *bo,
1283 		unsigned long size,
1284 		enum ttm_bo_type type,
1285 		struct ttm_placement *placement,
1286 		uint32_t page_alignment,
1287 		bool interruptible,
1288 		struct vm_object *persistent_swap_storage,
1289 		size_t acc_size,
1290 		struct sg_table *sg,
1291 		void (*destroy) (struct ttm_buffer_object *))
1292 {
1293 	int ret = 0;
1294 	unsigned long num_pages;
1295 	struct ttm_mem_global *mem_glob = bdev->glob->mem_glob;
1296 
1297 	ret = ttm_mem_global_alloc(mem_glob, acc_size, false, false);
1298 	if (ret) {
1299 		pr_err("Out of kernel memory\n");
1300 		if (destroy)
1301 			(*destroy)(bo);
1302 		else
1303 			kfree(bo);
1304 		return -ENOMEM;
1305 	}
1306 
1307 	num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1308 	if (num_pages == 0) {
1309 		pr_err("Illegal buffer object size\n");
1310 		if (destroy)
1311 			(*destroy)(bo);
1312 		else
1313 			kfree(bo);
1314 		ttm_mem_global_free(mem_glob, acc_size);
1315 		return -EINVAL;
1316 	}
1317 	bo->destroy = destroy;
1318 
1319 	kref_init(&bo->kref);
1320 	kref_init(&bo->list_kref);
1321 	atomic_set(&bo->cpu_writers, 0);
1322 	atomic_set(&bo->reserved, 1);
1323 	init_waitqueue_head(&bo->event_queue);
1324 	INIT_LIST_HEAD(&bo->lru);
1325 	INIT_LIST_HEAD(&bo->ddestroy);
1326 	INIT_LIST_HEAD(&bo->swap);
1327 	INIT_LIST_HEAD(&bo->io_reserve_lru);
1328 	bo->bdev = bdev;
1329 	bo->glob = bdev->glob;
1330 	bo->type = type;
1331 	bo->num_pages = num_pages;
1332 	bo->mem.size = num_pages << PAGE_SHIFT;
1333 	bo->mem.mem_type = TTM_PL_SYSTEM;
1334 	bo->mem.num_pages = bo->num_pages;
1335 	bo->mem.mm_node = NULL;
1336 	bo->mem.page_alignment = page_alignment;
1337 	bo->mem.bus.io_reserved_vm = false;
1338 	bo->mem.bus.io_reserved_count = 0;
1339 	bo->priv_flags = 0;
1340 	bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
1341 	bo->seq_valid = false;
1342 	bo->persistent_swap_storage = persistent_swap_storage;
1343 	bo->acc_size = acc_size;
1344 	bo->sg = sg;
1345 	atomic_inc(&bo->glob->bo_count);
1346 
1347 	/*
1348 	 * Mirror ref from kref_init() for list_kref.
1349 	 */
1350 	set_bit(TTM_BO_PRIV_FLAG_ACTIVE, &bo->priv_flags);
1351 
1352 	/*
1353 	 * For ttm_bo_type_device buffers, allocate
1354 	 * address space from the device.
1355 	 */
1356 	if (bo->type == ttm_bo_type_device ||
1357 	    bo->type == ttm_bo_type_sg) {
1358 		ret = ttm_bo_setup_vm(bo);
1359 		if (ret)
1360 			goto out_err;
1361 	}
1362 
1363 	ret = ttm_bo_validate(bo, placement, interruptible, false);
1364 	if (ret)
1365 		goto out_err;
1366 
1367 	ttm_bo_unreserve(bo);
1368 	return 0;
1369 
1370 out_err:
1371 	ttm_bo_unreserve(bo);
1372 	ttm_bo_unref(&bo);
1373 
1374 	return ret;
1375 }
1376 EXPORT_SYMBOL(ttm_bo_init);
1377 
1378 size_t ttm_bo_acc_size(struct ttm_bo_device *bdev,
1379 		       unsigned long bo_size,
1380 		       unsigned struct_size)
1381 {
1382 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1383 	size_t size = 0;
1384 
1385 	size += ttm_round_pot(struct_size);
1386 	size += PAGE_ALIGN(npages * sizeof(void *));
1387 	size += ttm_round_pot(sizeof(struct ttm_tt));
1388 	return size;
1389 }
1390 EXPORT_SYMBOL(ttm_bo_acc_size);
1391 
1392 size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev,
1393 			   unsigned long bo_size,
1394 			   unsigned struct_size)
1395 {
1396 	unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1397 	size_t size = 0;
1398 
1399 	size += ttm_round_pot(struct_size);
1400 	size += PAGE_ALIGN(npages * sizeof(void *));
1401 	size += PAGE_ALIGN(npages * sizeof(dma_addr_t));
1402 	size += ttm_round_pot(sizeof(struct ttm_dma_tt));
1403 	return size;
1404 }
1405 EXPORT_SYMBOL(ttm_bo_dma_acc_size);
1406 
1407 int ttm_bo_create(struct ttm_bo_device *bdev,
1408 			unsigned long size,
1409 			enum ttm_bo_type type,
1410 			struct ttm_placement *placement,
1411 			uint32_t page_alignment,
1412 			bool interruptible,
1413 			struct vm_object *persistent_swap_storage,
1414 			struct ttm_buffer_object **p_bo)
1415 {
1416 	struct ttm_buffer_object *bo;
1417 	size_t acc_size;
1418 	int ret;
1419 
1420 	*p_bo = NULL;
1421 	bo = kzalloc(sizeof(*bo), GFP_KERNEL);
1422 	if (unlikely(bo == NULL))
1423 		return -ENOMEM;
1424 
1425 	acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object));
1426 	ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
1427 			  interruptible, persistent_swap_storage, acc_size,
1428 			  NULL, NULL);
1429 	if (likely(ret == 0))
1430 		*p_bo = bo;
1431 
1432 	return ret;
1433 }
1434 EXPORT_SYMBOL(ttm_bo_create);
1435 
1436 static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev,
1437 					unsigned mem_type, bool allow_errors)
1438 {
1439 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1440 	struct ttm_bo_global *glob = bdev->glob;
1441 	int ret;
1442 
1443 	/*
1444 	 * Can't use standard list traversal since we're unlocking.
1445 	 */
1446 
1447 	lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
1448 	while (!list_empty(&man->lru)) {
1449 		lockmgr(&glob->lru_lock, LK_RELEASE);
1450 		ret = ttm_mem_evict_first(bdev, mem_type, false, false);
1451 		if (ret) {
1452 			if (allow_errors) {
1453 				return ret;
1454 			} else {
1455 				pr_err("Cleanup eviction failed\n");
1456 			}
1457 		}
1458 		lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
1459 	}
1460 	lockmgr(&glob->lru_lock, LK_RELEASE);
1461 	return 0;
1462 }
1463 
1464 int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1465 {
1466 	struct ttm_mem_type_manager *man;
1467 	int ret = -EINVAL;
1468 
1469 	if (mem_type >= TTM_NUM_MEM_TYPES) {
1470 		pr_err("Illegal memory type %d\n", mem_type);
1471 		return ret;
1472 	}
1473 	man = &bdev->man[mem_type];
1474 
1475 	if (!man->has_type) {
1476 		pr_err("Trying to take down uninitialized memory manager type %u\n",
1477 		       mem_type);
1478 		return ret;
1479 	}
1480 
1481 	man->use_type = false;
1482 	man->has_type = false;
1483 
1484 	ret = 0;
1485 	if (mem_type > 0) {
1486 		ttm_bo_force_list_clean(bdev, mem_type, false);
1487 
1488 		ret = (*man->func->takedown)(man);
1489 	}
1490 
1491 	return ret;
1492 }
1493 EXPORT_SYMBOL(ttm_bo_clean_mm);
1494 
1495 int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1496 {
1497 	struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1498 
1499 	if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
1500 		pr_err("Illegal memory manager memory type %u\n", mem_type);
1501 		return -EINVAL;
1502 	}
1503 
1504 	if (!man->has_type) {
1505 		pr_err("Memory type %u has not been initialized\n", mem_type);
1506 		return 0;
1507 	}
1508 
1509 	return ttm_bo_force_list_clean(bdev, mem_type, true);
1510 }
1511 EXPORT_SYMBOL(ttm_bo_evict_mm);
1512 
1513 int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type,
1514 			unsigned long p_size)
1515 {
1516 	int ret = -EINVAL;
1517 	struct ttm_mem_type_manager *man;
1518 
1519 	BUG_ON(type >= TTM_NUM_MEM_TYPES);
1520 	man = &bdev->man[type];
1521 	BUG_ON(man->has_type);
1522 	man->io_reserve_fastpath = true;
1523 	man->use_io_reserve_lru = false;
1524 	lockinit(&man->io_reserve_mutex, "ttmman", 0, LK_CANRECURSE);
1525 	INIT_LIST_HEAD(&man->io_reserve_lru);
1526 
1527 	ret = bdev->driver->init_mem_type(bdev, type, man);
1528 	if (ret)
1529 		return ret;
1530 	man->bdev = bdev;
1531 
1532 	ret = 0;
1533 	if (type != TTM_PL_SYSTEM) {
1534 		ret = (*man->func->init)(man, p_size);
1535 		if (ret)
1536 			return ret;
1537 	}
1538 	man->has_type = true;
1539 	man->use_type = true;
1540 	man->size = p_size;
1541 
1542 	INIT_LIST_HEAD(&man->lru);
1543 
1544 	return 0;
1545 }
1546 EXPORT_SYMBOL(ttm_bo_init_mm);
1547 
1548 static void ttm_bo_global_kobj_release(struct kobject *kobj)
1549 {
1550 	struct ttm_bo_global *glob =
1551 		container_of(kobj, struct ttm_bo_global, kobj);
1552 
1553 	ttm_mem_unregister_shrink(glob->mem_glob, &glob->shrink);
1554 	__free_page(glob->dummy_read_page);
1555 	kfree(glob);
1556 }
1557 
1558 void ttm_bo_global_release(struct drm_global_reference *ref)
1559 {
1560 	struct ttm_bo_global *glob = ref->object;
1561 
1562 	kobject_del(&glob->kobj);
1563 	kobject_put(&glob->kobj);
1564 }
1565 EXPORT_SYMBOL(ttm_bo_global_release);
1566 
1567 int ttm_bo_global_init(struct drm_global_reference *ref)
1568 {
1569 	struct ttm_bo_global_ref *bo_ref =
1570 		container_of(ref, struct ttm_bo_global_ref, ref);
1571 	struct ttm_bo_global *glob = ref->object;
1572 	int ret;
1573 
1574 	lockinit(&glob->device_list_mutex, "ttmdlm", 0, LK_CANRECURSE);
1575 	lockinit(&glob->lru_lock, "ttmlru", 0, LK_CANRECURSE);
1576 	glob->mem_glob = bo_ref->mem_glob;
1577 	glob->dummy_read_page = alloc_page(__GFP_ZERO | GFP_DMA32);
1578 
1579 	if (unlikely(glob->dummy_read_page == NULL)) {
1580 		ret = -ENOMEM;
1581 		goto out_no_drp;
1582 	}
1583 
1584 	INIT_LIST_HEAD(&glob->swap_lru);
1585 	INIT_LIST_HEAD(&glob->device_list);
1586 
1587 	ttm_mem_init_shrink(&glob->shrink, ttm_bo_swapout);
1588 	ret = ttm_mem_register_shrink(glob->mem_glob, &glob->shrink);
1589 	if (unlikely(ret != 0)) {
1590 		pr_err("Could not register buffer object swapout\n");
1591 		goto out_no_shrink;
1592 	}
1593 
1594 	atomic_set(&glob->bo_count, 0);
1595 
1596 	ret = kobject_init_and_add(
1597 		&glob->kobj, &ttm_bo_glob_kobj_type, ttm_get_kobj(), "buffer_objects");
1598 	if (unlikely(ret != 0))
1599 		kobject_put(&glob->kobj);
1600 	return ret;
1601 out_no_shrink:
1602 	__free_page(glob->dummy_read_page);
1603 out_no_drp:
1604 	kfree(glob);
1605 	return ret;
1606 }
1607 EXPORT_SYMBOL(ttm_bo_global_init);
1608 
1609 
1610 int ttm_bo_device_release(struct ttm_bo_device *bdev)
1611 {
1612 	int ret = 0;
1613 	unsigned i = TTM_NUM_MEM_TYPES;
1614 	struct ttm_mem_type_manager *man;
1615 	struct ttm_bo_global *glob = bdev->glob;
1616 
1617 	while (i--) {
1618 		man = &bdev->man[i];
1619 		if (man->has_type) {
1620 			man->use_type = false;
1621 			if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) {
1622 				ret = -EBUSY;
1623 				pr_err("DRM memory manager type %d is not clean\n",
1624 				       i);
1625 			}
1626 			man->has_type = false;
1627 		}
1628 	}
1629 
1630 	mutex_lock(&glob->device_list_mutex);
1631 	list_del(&bdev->device_list);
1632 	mutex_unlock(&glob->device_list_mutex);
1633 
1634 	cancel_delayed_work_sync(&bdev->wq);
1635 
1636 	while (ttm_bo_delayed_delete(bdev, true))
1637 		;
1638 
1639 	lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
1640 	if (list_empty(&bdev->ddestroy))
1641 		TTM_DEBUG("Delayed destroy list was clean\n");
1642 
1643 	if (list_empty(&bdev->man[0].lru))
1644 		TTM_DEBUG("Swap list was clean\n");
1645 	lockmgr(&glob->lru_lock, LK_RELEASE);
1646 
1647 	BUG_ON(!drm_mm_clean(&bdev->addr_space_mm));
1648 	lockmgr(&bdev->vm_lock, LK_EXCLUSIVE);
1649 	drm_mm_takedown(&bdev->addr_space_mm);
1650 	lockmgr(&bdev->vm_lock, LK_RELEASE);
1651 
1652 	return ret;
1653 }
1654 EXPORT_SYMBOL(ttm_bo_device_release);
1655 
1656 int ttm_bo_device_init(struct ttm_bo_device *bdev,
1657 		       struct ttm_bo_global *glob,
1658 		       struct ttm_bo_driver *driver,
1659 		       uint64_t file_page_offset,
1660 		       bool need_dma32)
1661 {
1662 	int ret = -EINVAL;
1663 
1664 	lockinit(&bdev->vm_lock, "ttmvml", 0, LK_CANRECURSE);
1665 	bdev->driver = driver;
1666 
1667 	memset(bdev->man, 0, sizeof(bdev->man));
1668 
1669 	/*
1670 	 * Initialize the system memory buffer type.
1671 	 * Other types need to be driver / IOCTL initialized.
1672 	 */
1673 	ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0);
1674 	if (unlikely(ret != 0))
1675 		goto out_no_sys;
1676 
1677 	RB_INIT(&bdev->addr_space_rb);
1678 	drm_mm_init(&bdev->addr_space_mm, file_page_offset, 0x10000000);
1679 
1680 	INIT_DELAYED_WORK(&bdev->wq, ttm_bo_delayed_workqueue);
1681 	INIT_LIST_HEAD(&bdev->ddestroy);
1682 	bdev->dev_mapping = NULL;
1683 	bdev->glob = glob;
1684 	bdev->need_dma32 = need_dma32;
1685 	bdev->val_seq = 0;
1686 	lockinit(&bdev->fence_lock, "ttmfence", 0, LK_CANRECURSE);
1687 	mutex_lock(&glob->device_list_mutex);
1688 	list_add_tail(&bdev->device_list, &glob->device_list);
1689 	mutex_unlock(&glob->device_list_mutex);
1690 
1691 	return 0;
1692 out_no_sys:
1693 	return ret;
1694 }
1695 EXPORT_SYMBOL(ttm_bo_device_init);
1696 
1697 /*
1698  * buffer object vm functions.
1699  */
1700 
1701 bool ttm_mem_reg_is_pci(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
1702 {
1703 	struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
1704 
1705 	if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
1706 		if (mem->mem_type == TTM_PL_SYSTEM)
1707 			return false;
1708 
1709 		if (man->flags & TTM_MEMTYPE_FLAG_CMA)
1710 			return false;
1711 
1712 		if (mem->placement & TTM_PL_FLAG_CACHED)
1713 			return false;
1714 	}
1715 	return true;
1716 }
1717 
1718 void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
1719 {
1720 
1721 	ttm_bo_release_mmap(bo);
1722 	ttm_mem_io_free_vm(bo);
1723 }
1724 
1725 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1726 {
1727 	struct ttm_bo_device *bdev = bo->bdev;
1728 	struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
1729 
1730 	ttm_mem_io_lock(man, false);
1731 	ttm_bo_unmap_virtual_locked(bo);
1732 	ttm_mem_io_unlock(man);
1733 }
1734 
1735 
1736 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1737 
1738 static void ttm_bo_vm_insert_rb(struct ttm_buffer_object *bo)
1739 {
1740 	struct ttm_bo_device *bdev = bo->bdev;
1741 
1742 	/* The caller acquired bdev->vm_lock. */
1743 	RB_INSERT(ttm_bo_device_buffer_objects, &bdev->addr_space_rb, bo);
1744 }
1745 
1746 /**
1747  * ttm_bo_setup_vm:
1748  *
1749  * @bo: the buffer to allocate address space for
1750  *
1751  * Allocate address space in the drm device so that applications
1752  * can mmap the buffer and access the contents. This only
1753  * applies to ttm_bo_type_device objects as others are not
1754  * placed in the drm device address space.
1755  */
1756 
1757 static int ttm_bo_setup_vm(struct ttm_buffer_object *bo)
1758 {
1759 	struct ttm_bo_device *bdev = bo->bdev;
1760 	int ret;
1761 
1762 retry_pre_get:
1763 	ret = drm_mm_pre_get(&bdev->addr_space_mm);
1764 	if (unlikely(ret != 0))
1765 		return ret;
1766 
1767 	lockmgr(&bdev->vm_lock, LK_EXCLUSIVE);
1768 	bo->vm_node = drm_mm_search_free(&bdev->addr_space_mm,
1769 					 bo->mem.num_pages, 0, 0);
1770 
1771 	if (unlikely(bo->vm_node == NULL)) {
1772 		ret = -ENOMEM;
1773 		goto out_unlock;
1774 	}
1775 
1776 	bo->vm_node = drm_mm_get_block_atomic(bo->vm_node,
1777 					      bo->mem.num_pages, 0);
1778 
1779 	if (unlikely(bo->vm_node == NULL)) {
1780 		lockmgr(&bdev->vm_lock, LK_RELEASE);
1781 		goto retry_pre_get;
1782 	}
1783 
1784 	ttm_bo_vm_insert_rb(bo);
1785 	lockmgr(&bdev->vm_lock, LK_RELEASE);
1786 	bo->addr_space_offset = ((uint64_t) bo->vm_node->start) << PAGE_SHIFT;
1787 
1788 	return 0;
1789 out_unlock:
1790 	lockmgr(&bdev->vm_lock, LK_RELEASE);
1791 	return ret;
1792 }
1793 
1794 int ttm_bo_wait(struct ttm_buffer_object *bo,
1795 		bool lazy, bool interruptible, bool no_wait)
1796 {
1797 	struct ttm_bo_driver *driver = bo->bdev->driver;
1798 	struct ttm_bo_device *bdev = bo->bdev;
1799 	void *sync_obj;
1800 	int ret = 0;
1801 
1802 	if (likely(bo->sync_obj == NULL))
1803 		return 0;
1804 
1805 	while (bo->sync_obj) {
1806 
1807 		if (driver->sync_obj_signaled(bo->sync_obj)) {
1808 			void *tmp_obj = bo->sync_obj;
1809 			bo->sync_obj = NULL;
1810 			clear_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags);
1811 			lockmgr(&bdev->fence_lock, LK_RELEASE);
1812 			driver->sync_obj_unref(&tmp_obj);
1813 			lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1814 			continue;
1815 		}
1816 
1817 		if (no_wait)
1818 			return -EBUSY;
1819 
1820 		sync_obj = driver->sync_obj_ref(bo->sync_obj);
1821 		lockmgr(&bdev->fence_lock, LK_RELEASE);
1822 		ret = driver->sync_obj_wait(sync_obj,
1823 					    lazy, interruptible);
1824 		if (unlikely(ret != 0)) {
1825 			driver->sync_obj_unref(&sync_obj);
1826 			lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1827 			return ret;
1828 		}
1829 		lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1830 		if (likely(bo->sync_obj == sync_obj)) {
1831 			void *tmp_obj = bo->sync_obj;
1832 			bo->sync_obj = NULL;
1833 			clear_bit(TTM_BO_PRIV_FLAG_MOVING,
1834 				  &bo->priv_flags);
1835 			lockmgr(&bdev->fence_lock, LK_RELEASE);
1836 			driver->sync_obj_unref(&sync_obj);
1837 			driver->sync_obj_unref(&tmp_obj);
1838 			lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1839 		} else {
1840 			lockmgr(&bdev->fence_lock, LK_RELEASE);
1841 			driver->sync_obj_unref(&sync_obj);
1842 			lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1843 		}
1844 	}
1845 	return 0;
1846 }
1847 EXPORT_SYMBOL(ttm_bo_wait);
1848 
1849 int ttm_bo_synccpu_write_grab(struct ttm_buffer_object *bo, bool no_wait)
1850 {
1851 	struct ttm_bo_device *bdev = bo->bdev;
1852 	int ret = 0;
1853 
1854 	/*
1855 	 * Using ttm_bo_reserve makes sure the lru lists are updated.
1856 	 */
1857 
1858 	ret = ttm_bo_reserve(bo, true, no_wait, false, 0);
1859 	if (unlikely(ret != 0))
1860 		return ret;
1861 	lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1862 	ret = ttm_bo_wait(bo, false, true, no_wait);
1863 	lockmgr(&bdev->fence_lock, LK_RELEASE);
1864 	if (likely(ret == 0))
1865 		atomic_inc(&bo->cpu_writers);
1866 	ttm_bo_unreserve(bo);
1867 	return ret;
1868 }
1869 EXPORT_SYMBOL(ttm_bo_synccpu_write_grab);
1870 
1871 void ttm_bo_synccpu_write_release(struct ttm_buffer_object *bo)
1872 {
1873 	atomic_dec(&bo->cpu_writers);
1874 }
1875 EXPORT_SYMBOL(ttm_bo_synccpu_write_release);
1876 
1877 /**
1878  * A buffer object shrink method that tries to swap out the first
1879  * buffer object on the bo_global::swap_lru list.
1880  */
1881 
1882 static int ttm_bo_swapout(struct ttm_mem_shrink *shrink)
1883 {
1884 	struct ttm_bo_global *glob =
1885 	    container_of(shrink, struct ttm_bo_global, shrink);
1886 	struct ttm_buffer_object *bo;
1887 	int ret = -EBUSY;
1888 	int put_count;
1889 	uint32_t swap_placement = (TTM_PL_FLAG_CACHED | TTM_PL_FLAG_SYSTEM);
1890 
1891 	lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
1892 	list_for_each_entry(bo, &glob->swap_lru, swap) {
1893 		ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
1894 		if (!ret)
1895 			break;
1896 	}
1897 
1898 	if (ret) {
1899 		lockmgr(&glob->lru_lock, LK_RELEASE);
1900 		return ret;
1901 	}
1902 
1903 	kref_get(&bo->list_kref);
1904 
1905 	if (!list_empty(&bo->ddestroy)) {
1906 		ret = ttm_bo_cleanup_refs_and_unlock(bo, false, false);
1907 		kref_put(&bo->list_kref, ttm_bo_release_list);
1908 		return ret;
1909 	}
1910 
1911 	put_count = ttm_bo_del_from_lru(bo);
1912 	lockmgr(&glob->lru_lock, LK_RELEASE);
1913 
1914 	ttm_bo_list_ref_sub(bo, put_count, true);
1915 
1916 	/**
1917 	 * Wait for GPU, then move to system cached.
1918 	 */
1919 
1920 	lockmgr(&bo->bdev->fence_lock, LK_EXCLUSIVE);
1921 	ret = ttm_bo_wait(bo, false, false, false);
1922 	lockmgr(&bo->bdev->fence_lock, LK_RELEASE);
1923 
1924 	if (unlikely(ret != 0))
1925 		goto out;
1926 
1927 	if ((bo->mem.placement & swap_placement) != swap_placement) {
1928 		struct ttm_mem_reg evict_mem;
1929 
1930 		evict_mem = bo->mem;
1931 		evict_mem.mm_node = NULL;
1932 		evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
1933 		evict_mem.mem_type = TTM_PL_SYSTEM;
1934 
1935 		ret = ttm_bo_handle_move_mem(bo, &evict_mem, true,
1936 					     false, false);
1937 		if (unlikely(ret != 0))
1938 			goto out;
1939 	}
1940 
1941 	ttm_bo_unmap_virtual(bo);
1942 
1943 	/**
1944 	 * Swap out. Buffer will be swapped in again as soon as
1945 	 * anyone tries to access a ttm page.
1946 	 */
1947 
1948 	if (bo->bdev->driver->swap_notify)
1949 		bo->bdev->driver->swap_notify(bo);
1950 
1951 	ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
1952 out:
1953 
1954 	/**
1955 	 *
1956 	 * Unreserve without putting on LRU to avoid swapping out an
1957 	 * already swapped buffer.
1958 	 */
1959 
1960 	ttm_bo_unreserve_core(bo);
1961 	kref_put(&bo->list_kref, ttm_bo_release_list);
1962 	return ret;
1963 }
1964 
1965 void ttm_bo_swapout_all(struct ttm_bo_device *bdev)
1966 {
1967 	while (ttm_bo_swapout(&bdev->glob->shrink) == 0)
1968 		;
1969 }
1970 EXPORT_SYMBOL(ttm_bo_swapout_all);
1971