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