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