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