xref: /freebsd/sys/kern/subr_vmem.c (revision 3bdf775801b218aa5a89564839405b122f4b233e)
1 /*-
2  * Copyright (c)2006,2007,2008,2009 YAMAMOTO Takashi,
3  * Copyright (c) 2013 EMC Corp.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * From:
30  *	$NetBSD: vmem_impl.h,v 1.2 2013/01/29 21:26:24 para Exp $
31  *	$NetBSD: subr_vmem.c,v 1.83 2013/03/06 11:20:10 yamt Exp $
32  */
33 
34 /*
35  * reference:
36  * -	Magazines and Vmem: Extending the Slab Allocator
37  *	to Many CPUs and Arbitrary Resources
38  *	http://www.usenix.org/event/usenix01/bonwick.html
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include "opt_ddb.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/queue.h>
50 #include <sys/callout.h>
51 #include <sys/hash.h>
52 #include <sys/lock.h>
53 #include <sys/malloc.h>
54 #include <sys/mutex.h>
55 #include <sys/smp.h>
56 #include <sys/condvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/taskqueue.h>
59 #include <sys/vmem.h>
60 
61 #include "opt_vm.h"
62 
63 #include <vm/uma.h>
64 #include <vm/vm.h>
65 #include <vm/pmap.h>
66 #include <vm/vm_map.h>
67 #include <vm/vm_object.h>
68 #include <vm/vm_kern.h>
69 #include <vm/vm_extern.h>
70 #include <vm/vm_param.h>
71 #include <vm/vm_pageout.h>
72 
73 #define	VMEM_OPTORDER		5
74 #define	VMEM_OPTVALUE		(1 << VMEM_OPTORDER)
75 #define	VMEM_MAXORDER						\
76     (VMEM_OPTVALUE - 1 + sizeof(vmem_size_t) * NBBY - VMEM_OPTORDER)
77 
78 #define	VMEM_HASHSIZE_MIN	16
79 #define	VMEM_HASHSIZE_MAX	131072
80 
81 #define	VMEM_QCACHE_IDX_MAX	16
82 
83 #define	VMEM_FITMASK	(M_BESTFIT | M_FIRSTFIT)
84 
85 #define	VMEM_FLAGS						\
86     (M_NOWAIT | M_WAITOK | M_USE_RESERVE | M_NOVM | M_BESTFIT | M_FIRSTFIT)
87 
88 #define	BT_FLAGS	(M_NOWAIT | M_WAITOK | M_USE_RESERVE | M_NOVM)
89 
90 #define	QC_NAME_MAX	16
91 
92 /*
93  * Data structures private to vmem.
94  */
95 MALLOC_DEFINE(M_VMEM, "vmem", "vmem internal structures");
96 
97 typedef struct vmem_btag bt_t;
98 
99 TAILQ_HEAD(vmem_seglist, vmem_btag);
100 LIST_HEAD(vmem_freelist, vmem_btag);
101 LIST_HEAD(vmem_hashlist, vmem_btag);
102 
103 struct qcache {
104 	uma_zone_t	qc_cache;
105 	vmem_t 		*qc_vmem;
106 	vmem_size_t	qc_size;
107 	char		qc_name[QC_NAME_MAX];
108 };
109 typedef struct qcache qcache_t;
110 #define	QC_POOL_TO_QCACHE(pool)	((qcache_t *)(pool->pr_qcache))
111 
112 #define	VMEM_NAME_MAX	16
113 
114 /* vmem arena */
115 struct vmem {
116 	struct mtx_padalign	vm_lock;
117 	struct cv		vm_cv;
118 	char			vm_name[VMEM_NAME_MAX+1];
119 	LIST_ENTRY(vmem)	vm_alllist;
120 	struct vmem_hashlist	vm_hash0[VMEM_HASHSIZE_MIN];
121 	struct vmem_freelist	vm_freelist[VMEM_MAXORDER];
122 	struct vmem_seglist	vm_seglist;
123 	struct vmem_hashlist	*vm_hashlist;
124 	vmem_size_t		vm_hashsize;
125 
126 	/* Constant after init */
127 	vmem_size_t		vm_qcache_max;
128 	vmem_size_t		vm_quantum_mask;
129 	vmem_size_t		vm_import_quantum;
130 	int			vm_quantum_shift;
131 
132 	/* Written on alloc/free */
133 	LIST_HEAD(, vmem_btag)	vm_freetags;
134 	int			vm_nfreetags;
135 	int			vm_nbusytag;
136 	vmem_size_t		vm_inuse;
137 	vmem_size_t		vm_size;
138 
139 	/* Used on import. */
140 	vmem_import_t		*vm_importfn;
141 	vmem_release_t		*vm_releasefn;
142 	void			*vm_arg;
143 
144 	/* Space exhaustion callback. */
145 	vmem_reclaim_t		*vm_reclaimfn;
146 
147 	/* quantum cache */
148 	qcache_t		vm_qcache[VMEM_QCACHE_IDX_MAX];
149 };
150 
151 /* boundary tag */
152 struct vmem_btag {
153 	TAILQ_ENTRY(vmem_btag) bt_seglist;
154 	union {
155 		LIST_ENTRY(vmem_btag) u_freelist; /* BT_TYPE_FREE */
156 		LIST_ENTRY(vmem_btag) u_hashlist; /* BT_TYPE_BUSY */
157 	} bt_u;
158 #define	bt_hashlist	bt_u.u_hashlist
159 #define	bt_freelist	bt_u.u_freelist
160 	vmem_addr_t	bt_start;
161 	vmem_size_t	bt_size;
162 	int		bt_type;
163 };
164 
165 #define	BT_TYPE_SPAN		1	/* Allocated from importfn */
166 #define	BT_TYPE_SPAN_STATIC	2	/* vmem_add() or create. */
167 #define	BT_TYPE_FREE		3	/* Available space. */
168 #define	BT_TYPE_BUSY		4	/* Used space. */
169 #define	BT_ISSPAN_P(bt)	((bt)->bt_type <= BT_TYPE_SPAN_STATIC)
170 
171 #define	BT_END(bt)	((bt)->bt_start + (bt)->bt_size - 1)
172 
173 #if defined(DIAGNOSTIC)
174 static int enable_vmem_check = 1;
175 SYSCTL_INT(_debug, OID_AUTO, vmem_check, CTLFLAG_RW,
176     &enable_vmem_check, 0, "Enable vmem check");
177 static void vmem_check(vmem_t *);
178 #endif
179 
180 static struct callout	vmem_periodic_ch;
181 static int		vmem_periodic_interval;
182 static struct task	vmem_periodic_wk;
183 
184 static struct mtx_padalign vmem_list_lock;
185 static LIST_HEAD(, vmem) vmem_list = LIST_HEAD_INITIALIZER(vmem_list);
186 
187 /* ---- misc */
188 #define	VMEM_CONDVAR_INIT(vm, wchan)	cv_init(&vm->vm_cv, wchan)
189 #define	VMEM_CONDVAR_DESTROY(vm)	cv_destroy(&vm->vm_cv)
190 #define	VMEM_CONDVAR_WAIT(vm)		cv_wait(&vm->vm_cv, &vm->vm_lock)
191 #define	VMEM_CONDVAR_BROADCAST(vm)	cv_broadcast(&vm->vm_cv)
192 
193 
194 #define	VMEM_LOCK(vm)		mtx_lock(&vm->vm_lock)
195 #define	VMEM_TRYLOCK(vm)	mtx_trylock(&vm->vm_lock)
196 #define	VMEM_UNLOCK(vm)		mtx_unlock(&vm->vm_lock)
197 #define	VMEM_LOCK_INIT(vm, name) mtx_init(&vm->vm_lock, (name), NULL, MTX_DEF)
198 #define	VMEM_LOCK_DESTROY(vm)	mtx_destroy(&vm->vm_lock)
199 #define	VMEM_ASSERT_LOCKED(vm)	mtx_assert(&vm->vm_lock, MA_OWNED);
200 
201 #define	VMEM_ALIGNUP(addr, align)	(-(-(addr) & -(align)))
202 
203 #define	VMEM_CROSS_P(addr1, addr2, boundary) \
204 	((((addr1) ^ (addr2)) & -(boundary)) != 0)
205 
206 #define	ORDER2SIZE(order)	((order) < VMEM_OPTVALUE ? ((order) + 1) : \
207     (vmem_size_t)1 << ((order) - (VMEM_OPTVALUE - VMEM_OPTORDER - 1)))
208 #define	SIZE2ORDER(size)	((size) <= VMEM_OPTVALUE ? ((size) - 1) : \
209     (flsl(size) + (VMEM_OPTVALUE - VMEM_OPTORDER - 2)))
210 
211 /*
212  * Maximum number of boundary tags that may be required to satisfy an
213  * allocation.  Two may be required to import.  Another two may be
214  * required to clip edges.
215  */
216 #define	BT_MAXALLOC	4
217 
218 /*
219  * Max free limits the number of locally cached boundary tags.  We
220  * just want to avoid hitting the zone allocator for every call.
221  */
222 #define BT_MAXFREE	(BT_MAXALLOC * 8)
223 
224 /* Allocator for boundary tags. */
225 static uma_zone_t vmem_bt_zone;
226 
227 /* boot time arena storage. */
228 static struct vmem kernel_arena_storage;
229 static struct vmem kmem_arena_storage;
230 static struct vmem buffer_arena_storage;
231 static struct vmem transient_arena_storage;
232 vmem_t *kernel_arena = &kernel_arena_storage;
233 vmem_t *kmem_arena = &kmem_arena_storage;
234 vmem_t *buffer_arena = &buffer_arena_storage;
235 vmem_t *transient_arena = &transient_arena_storage;
236 
237 #ifdef DEBUG_MEMGUARD
238 static struct vmem memguard_arena_storage;
239 vmem_t *memguard_arena = &memguard_arena_storage;
240 #endif
241 
242 /*
243  * Fill the vmem's boundary tag cache.  We guarantee that boundary tag
244  * allocation will not fail once bt_fill() passes.  To do so we cache
245  * at least the maximum possible tag allocations in the arena.
246  */
247 static int
248 bt_fill(vmem_t *vm, int flags)
249 {
250 	bt_t *bt;
251 
252 	VMEM_ASSERT_LOCKED(vm);
253 
254 	/*
255 	 * Only allow the kmem arena to dip into reserve tags.  It is the
256 	 * vmem where new tags come from.
257 	 */
258 	flags &= BT_FLAGS;
259 	if (vm != kmem_arena)
260 		flags &= ~M_USE_RESERVE;
261 
262 	/*
263 	 * Loop until we meet the reserve.  To minimize the lock shuffle
264 	 * and prevent simultaneous fills we first try a NOWAIT regardless
265 	 * of the caller's flags.  Specify M_NOVM so we don't recurse while
266 	 * holding a vmem lock.
267 	 */
268 	while (vm->vm_nfreetags < BT_MAXALLOC) {
269 		bt = uma_zalloc(vmem_bt_zone,
270 		    (flags & M_USE_RESERVE) | M_NOWAIT | M_NOVM);
271 		if (bt == NULL) {
272 			VMEM_UNLOCK(vm);
273 			bt = uma_zalloc(vmem_bt_zone, flags);
274 			VMEM_LOCK(vm);
275 			if (bt == NULL && (flags & M_NOWAIT) != 0)
276 				break;
277 		}
278 		LIST_INSERT_HEAD(&vm->vm_freetags, bt, bt_freelist);
279 		vm->vm_nfreetags++;
280 	}
281 
282 	if (vm->vm_nfreetags < BT_MAXALLOC)
283 		return ENOMEM;
284 
285 	return 0;
286 }
287 
288 /*
289  * Pop a tag off of the freetag stack.
290  */
291 static bt_t *
292 bt_alloc(vmem_t *vm)
293 {
294 	bt_t *bt;
295 
296 	VMEM_ASSERT_LOCKED(vm);
297 	bt = LIST_FIRST(&vm->vm_freetags);
298 	MPASS(bt != NULL);
299 	LIST_REMOVE(bt, bt_freelist);
300 	vm->vm_nfreetags--;
301 
302 	return bt;
303 }
304 
305 /*
306  * Trim the per-vmem free list.  Returns with the lock released to
307  * avoid allocator recursions.
308  */
309 static void
310 bt_freetrim(vmem_t *vm, int freelimit)
311 {
312 	LIST_HEAD(, vmem_btag) freetags;
313 	bt_t *bt;
314 
315 	LIST_INIT(&freetags);
316 	VMEM_ASSERT_LOCKED(vm);
317 	while (vm->vm_nfreetags > freelimit) {
318 		bt = LIST_FIRST(&vm->vm_freetags);
319 		LIST_REMOVE(bt, bt_freelist);
320 		vm->vm_nfreetags--;
321 		LIST_INSERT_HEAD(&freetags, bt, bt_freelist);
322 	}
323 	VMEM_UNLOCK(vm);
324 	while ((bt = LIST_FIRST(&freetags)) != NULL) {
325 		LIST_REMOVE(bt, bt_freelist);
326 		uma_zfree(vmem_bt_zone, bt);
327 	}
328 }
329 
330 static inline void
331 bt_free(vmem_t *vm, bt_t *bt)
332 {
333 
334 	VMEM_ASSERT_LOCKED(vm);
335 	MPASS(LIST_FIRST(&vm->vm_freetags) != bt);
336 	LIST_INSERT_HEAD(&vm->vm_freetags, bt, bt_freelist);
337 	vm->vm_nfreetags++;
338 }
339 
340 /*
341  * freelist[0] ... [1, 1]
342  * freelist[1] ... [2, 2]
343  *  :
344  * freelist[29] ... [30, 30]
345  * freelist[30] ... [31, 31]
346  * freelist[31] ... [32, 63]
347  * freelist[33] ... [64, 127]
348  *  :
349  * freelist[n] ... [(1 << (n - 26)), (1 << (n - 25)) - 1]
350  *  :
351  */
352 
353 static struct vmem_freelist *
354 bt_freehead_tofree(vmem_t *vm, vmem_size_t size)
355 {
356 	const vmem_size_t qsize = size >> vm->vm_quantum_shift;
357 	const int idx = SIZE2ORDER(qsize);
358 
359 	MPASS(size != 0 && qsize != 0);
360 	MPASS((size & vm->vm_quantum_mask) == 0);
361 	MPASS(idx >= 0);
362 	MPASS(idx < VMEM_MAXORDER);
363 
364 	return &vm->vm_freelist[idx];
365 }
366 
367 /*
368  * bt_freehead_toalloc: return the freelist for the given size and allocation
369  * strategy.
370  *
371  * For M_FIRSTFIT, return the list in which any blocks are large enough
372  * for the requested size.  otherwise, return the list which can have blocks
373  * large enough for the requested size.
374  */
375 static struct vmem_freelist *
376 bt_freehead_toalloc(vmem_t *vm, vmem_size_t size, int strat)
377 {
378 	const vmem_size_t qsize = size >> vm->vm_quantum_shift;
379 	int idx = SIZE2ORDER(qsize);
380 
381 	MPASS(size != 0 && qsize != 0);
382 	MPASS((size & vm->vm_quantum_mask) == 0);
383 
384 	if (strat == M_FIRSTFIT && ORDER2SIZE(idx) != qsize) {
385 		idx++;
386 		/* check too large request? */
387 	}
388 	MPASS(idx >= 0);
389 	MPASS(idx < VMEM_MAXORDER);
390 
391 	return &vm->vm_freelist[idx];
392 }
393 
394 /* ---- boundary tag hash */
395 
396 static struct vmem_hashlist *
397 bt_hashhead(vmem_t *vm, vmem_addr_t addr)
398 {
399 	struct vmem_hashlist *list;
400 	unsigned int hash;
401 
402 	hash = hash32_buf(&addr, sizeof(addr), 0);
403 	list = &vm->vm_hashlist[hash % vm->vm_hashsize];
404 
405 	return list;
406 }
407 
408 static bt_t *
409 bt_lookupbusy(vmem_t *vm, vmem_addr_t addr)
410 {
411 	struct vmem_hashlist *list;
412 	bt_t *bt;
413 
414 	VMEM_ASSERT_LOCKED(vm);
415 	list = bt_hashhead(vm, addr);
416 	LIST_FOREACH(bt, list, bt_hashlist) {
417 		if (bt->bt_start == addr) {
418 			break;
419 		}
420 	}
421 
422 	return bt;
423 }
424 
425 static void
426 bt_rembusy(vmem_t *vm, bt_t *bt)
427 {
428 
429 	VMEM_ASSERT_LOCKED(vm);
430 	MPASS(vm->vm_nbusytag > 0);
431 	vm->vm_inuse -= bt->bt_size;
432 	vm->vm_nbusytag--;
433 	LIST_REMOVE(bt, bt_hashlist);
434 }
435 
436 static void
437 bt_insbusy(vmem_t *vm, bt_t *bt)
438 {
439 	struct vmem_hashlist *list;
440 
441 	VMEM_ASSERT_LOCKED(vm);
442 	MPASS(bt->bt_type == BT_TYPE_BUSY);
443 
444 	list = bt_hashhead(vm, bt->bt_start);
445 	LIST_INSERT_HEAD(list, bt, bt_hashlist);
446 	vm->vm_nbusytag++;
447 	vm->vm_inuse += bt->bt_size;
448 }
449 
450 /* ---- boundary tag list */
451 
452 static void
453 bt_remseg(vmem_t *vm, bt_t *bt)
454 {
455 
456 	TAILQ_REMOVE(&vm->vm_seglist, bt, bt_seglist);
457 	bt_free(vm, bt);
458 }
459 
460 static void
461 bt_insseg(vmem_t *vm, bt_t *bt, bt_t *prev)
462 {
463 
464 	TAILQ_INSERT_AFTER(&vm->vm_seglist, prev, bt, bt_seglist);
465 }
466 
467 static void
468 bt_insseg_tail(vmem_t *vm, bt_t *bt)
469 {
470 
471 	TAILQ_INSERT_TAIL(&vm->vm_seglist, bt, bt_seglist);
472 }
473 
474 static void
475 bt_remfree(vmem_t *vm, bt_t *bt)
476 {
477 
478 	MPASS(bt->bt_type == BT_TYPE_FREE);
479 
480 	LIST_REMOVE(bt, bt_freelist);
481 }
482 
483 static void
484 bt_insfree(vmem_t *vm, bt_t *bt)
485 {
486 	struct vmem_freelist *list;
487 
488 	list = bt_freehead_tofree(vm, bt->bt_size);
489 	LIST_INSERT_HEAD(list, bt, bt_freelist);
490 }
491 
492 /* ---- vmem internal functions */
493 
494 /*
495  * Import from the arena into the quantum cache in UMA.
496  */
497 static int
498 qc_import(void *arg, void **store, int cnt, int flags)
499 {
500 	qcache_t *qc;
501 	vmem_addr_t addr;
502 	int i;
503 
504 	qc = arg;
505 	flags |= M_BESTFIT;
506 	for (i = 0; i < cnt; i++) {
507 		if (vmem_xalloc(qc->qc_vmem, qc->qc_size, 0, 0, 0,
508 		    VMEM_ADDR_MIN, VMEM_ADDR_MAX, flags, &addr) != 0)
509 			break;
510 		store[i] = (void *)addr;
511 		/* Only guarantee one allocation. */
512 		flags &= ~M_WAITOK;
513 		flags |= M_NOWAIT;
514 	}
515 	return i;
516 }
517 
518 /*
519  * Release memory from the UMA cache to the arena.
520  */
521 static void
522 qc_release(void *arg, void **store, int cnt)
523 {
524 	qcache_t *qc;
525 	int i;
526 
527 	qc = arg;
528 	for (i = 0; i < cnt; i++)
529 		vmem_xfree(qc->qc_vmem, (vmem_addr_t)store[i], qc->qc_size);
530 }
531 
532 static void
533 qc_init(vmem_t *vm, vmem_size_t qcache_max)
534 {
535 	qcache_t *qc;
536 	vmem_size_t size;
537 	int qcache_idx_max;
538 	int i;
539 
540 	MPASS((qcache_max & vm->vm_quantum_mask) == 0);
541 	qcache_idx_max = MIN(qcache_max >> vm->vm_quantum_shift,
542 	    VMEM_QCACHE_IDX_MAX);
543 	vm->vm_qcache_max = qcache_idx_max << vm->vm_quantum_shift;
544 	for (i = 0; i < qcache_idx_max; i++) {
545 		qc = &vm->vm_qcache[i];
546 		size = (i + 1) << vm->vm_quantum_shift;
547 		snprintf(qc->qc_name, sizeof(qc->qc_name), "%s-%zu",
548 		    vm->vm_name, size);
549 		qc->qc_vmem = vm;
550 		qc->qc_size = size;
551 		qc->qc_cache = uma_zcache_create(qc->qc_name, size,
552 		    NULL, NULL, NULL, NULL, qc_import, qc_release, qc,
553 		    UMA_ZONE_VM);
554 		MPASS(qc->qc_cache);
555 	}
556 }
557 
558 static void
559 qc_destroy(vmem_t *vm)
560 {
561 	int qcache_idx_max;
562 	int i;
563 
564 	qcache_idx_max = vm->vm_qcache_max >> vm->vm_quantum_shift;
565 	for (i = 0; i < qcache_idx_max; i++)
566 		uma_zdestroy(vm->vm_qcache[i].qc_cache);
567 }
568 
569 static void
570 qc_drain(vmem_t *vm)
571 {
572 	int qcache_idx_max;
573 	int i;
574 
575 	qcache_idx_max = vm->vm_qcache_max >> vm->vm_quantum_shift;
576 	for (i = 0; i < qcache_idx_max; i++)
577 		zone_drain(vm->vm_qcache[i].qc_cache);
578 }
579 
580 #ifndef UMA_MD_SMALL_ALLOC
581 
582 static struct mtx_padalign vmem_bt_lock;
583 
584 /*
585  * vmem_bt_alloc:  Allocate a new page of boundary tags.
586  *
587  * On architectures with uma_small_alloc there is no recursion; no address
588  * space need be allocated to allocate boundary tags.  For the others, we
589  * must handle recursion.  Boundary tags are necessary to allocate new
590  * boundary tags.
591  *
592  * UMA guarantees that enough tags are held in reserve to allocate a new
593  * page of kva.  We dip into this reserve by specifying M_USE_RESERVE only
594  * when allocating the page to hold new boundary tags.  In this way the
595  * reserve is automatically filled by the allocation that uses the reserve.
596  *
597  * We still have to guarantee that the new tags are allocated atomically since
598  * many threads may try concurrently.  The bt_lock provides this guarantee.
599  * We convert WAITOK allocations to NOWAIT and then handle the blocking here
600  * on failure.  It's ok to return NULL for a WAITOK allocation as UMA will
601  * loop again after checking to see if we lost the race to allocate.
602  *
603  * There is a small race between vmem_bt_alloc() returning the page and the
604  * zone lock being acquired to add the page to the zone.  For WAITOK
605  * allocations we just pause briefly.  NOWAIT may experience a transient
606  * failure.  To alleviate this we permit a small number of simultaneous
607  * fills to proceed concurrently so NOWAIT is less likely to fail unless
608  * we are really out of KVA.
609  */
610 static void *
611 vmem_bt_alloc(uma_zone_t zone, int bytes, uint8_t *pflag, int wait)
612 {
613 	vmem_addr_t addr;
614 
615 	*pflag = UMA_SLAB_KMEM;
616 
617 	/*
618 	 * Single thread boundary tag allocation so that the address space
619 	 * and memory are added in one atomic operation.
620 	 */
621 	mtx_lock(&vmem_bt_lock);
622 	if (vmem_xalloc(kmem_arena, bytes, 0, 0, 0, VMEM_ADDR_MIN,
623 	    VMEM_ADDR_MAX, M_NOWAIT | M_NOVM | M_USE_RESERVE | M_BESTFIT,
624 	    &addr) == 0) {
625 		if (kmem_back(kmem_object, addr, bytes,
626 		    M_NOWAIT | M_USE_RESERVE) == 0) {
627 			mtx_unlock(&vmem_bt_lock);
628 			return ((void *)addr);
629 		}
630 		vmem_xfree(kmem_arena, addr, bytes);
631 		mtx_unlock(&vmem_bt_lock);
632 		/*
633 		 * Out of memory, not address space.  This may not even be
634 		 * possible due to M_USE_RESERVE page allocation.
635 		 */
636 		if (wait & M_WAITOK)
637 			VM_WAIT;
638 		return (NULL);
639 	}
640 	mtx_unlock(&vmem_bt_lock);
641 	/*
642 	 * We're either out of address space or lost a fill race.
643 	 */
644 	if (wait & M_WAITOK)
645 		pause("btalloc", 1);
646 
647 	return (NULL);
648 }
649 #endif
650 
651 void
652 vmem_startup(void)
653 {
654 
655 	mtx_init(&vmem_list_lock, "vmem list lock", NULL, MTX_DEF);
656 	vmem_bt_zone = uma_zcreate("vmem btag",
657 	    sizeof(struct vmem_btag), NULL, NULL, NULL, NULL,
658 	    UMA_ALIGN_PTR, UMA_ZONE_VM);
659 #ifndef UMA_MD_SMALL_ALLOC
660 	mtx_init(&vmem_bt_lock, "btag lock", NULL, MTX_DEF);
661 	uma_prealloc(vmem_bt_zone, BT_MAXALLOC);
662 	/*
663 	 * Reserve enough tags to allocate new tags.  We allow multiple
664 	 * CPUs to attempt to allocate new tags concurrently to limit
665 	 * false restarts in UMA.
666 	 */
667 	uma_zone_reserve(vmem_bt_zone, BT_MAXALLOC * (mp_ncpus + 1) / 2);
668 	uma_zone_set_allocf(vmem_bt_zone, vmem_bt_alloc);
669 #endif
670 }
671 
672 /* ---- rehash */
673 
674 static int
675 vmem_rehash(vmem_t *vm, vmem_size_t newhashsize)
676 {
677 	bt_t *bt;
678 	int i;
679 	struct vmem_hashlist *newhashlist;
680 	struct vmem_hashlist *oldhashlist;
681 	vmem_size_t oldhashsize;
682 
683 	MPASS(newhashsize > 0);
684 
685 	newhashlist = malloc(sizeof(struct vmem_hashlist) * newhashsize,
686 	    M_VMEM, M_NOWAIT);
687 	if (newhashlist == NULL)
688 		return ENOMEM;
689 	for (i = 0; i < newhashsize; i++) {
690 		LIST_INIT(&newhashlist[i]);
691 	}
692 
693 	VMEM_LOCK(vm);
694 	oldhashlist = vm->vm_hashlist;
695 	oldhashsize = vm->vm_hashsize;
696 	vm->vm_hashlist = newhashlist;
697 	vm->vm_hashsize = newhashsize;
698 	if (oldhashlist == NULL) {
699 		VMEM_UNLOCK(vm);
700 		return 0;
701 	}
702 	for (i = 0; i < oldhashsize; i++) {
703 		while ((bt = LIST_FIRST(&oldhashlist[i])) != NULL) {
704 			bt_rembusy(vm, bt);
705 			bt_insbusy(vm, bt);
706 		}
707 	}
708 	VMEM_UNLOCK(vm);
709 
710 	if (oldhashlist != vm->vm_hash0) {
711 		free(oldhashlist, M_VMEM);
712 	}
713 
714 	return 0;
715 }
716 
717 static void
718 vmem_periodic_kick(void *dummy)
719 {
720 
721 	taskqueue_enqueue(taskqueue_thread, &vmem_periodic_wk);
722 }
723 
724 static void
725 vmem_periodic(void *unused, int pending)
726 {
727 	vmem_t *vm;
728 	vmem_size_t desired;
729 	vmem_size_t current;
730 
731 	mtx_lock(&vmem_list_lock);
732 	LIST_FOREACH(vm, &vmem_list, vm_alllist) {
733 #ifdef DIAGNOSTIC
734 		/* Convenient time to verify vmem state. */
735 		if (enable_vmem_check == 1) {
736 			VMEM_LOCK(vm);
737 			vmem_check(vm);
738 			VMEM_UNLOCK(vm);
739 		}
740 #endif
741 		desired = 1 << flsl(vm->vm_nbusytag);
742 		desired = MIN(MAX(desired, VMEM_HASHSIZE_MIN),
743 		    VMEM_HASHSIZE_MAX);
744 		current = vm->vm_hashsize;
745 
746 		/* Grow in powers of two.  Shrink less aggressively. */
747 		if (desired >= current * 2 || desired * 4 <= current)
748 			vmem_rehash(vm, desired);
749 	}
750 	mtx_unlock(&vmem_list_lock);
751 
752 	callout_reset(&vmem_periodic_ch, vmem_periodic_interval,
753 	    vmem_periodic_kick, NULL);
754 }
755 
756 static void
757 vmem_start_callout(void *unused)
758 {
759 
760 	TASK_INIT(&vmem_periodic_wk, 0, vmem_periodic, NULL);
761 	vmem_periodic_interval = hz * 10;
762 	callout_init(&vmem_periodic_ch, CALLOUT_MPSAFE);
763 	callout_reset(&vmem_periodic_ch, vmem_periodic_interval,
764 	    vmem_periodic_kick, NULL);
765 }
766 SYSINIT(vfs, SI_SUB_CONFIGURE, SI_ORDER_ANY, vmem_start_callout, NULL);
767 
768 static void
769 vmem_add1(vmem_t *vm, vmem_addr_t addr, vmem_size_t size, int type)
770 {
771 	bt_t *btspan;
772 	bt_t *btfree;
773 
774 	MPASS(type == BT_TYPE_SPAN || type == BT_TYPE_SPAN_STATIC);
775 	MPASS((size & vm->vm_quantum_mask) == 0);
776 
777 	btspan = bt_alloc(vm);
778 	btspan->bt_type = type;
779 	btspan->bt_start = addr;
780 	btspan->bt_size = size;
781 	bt_insseg_tail(vm, btspan);
782 
783 	btfree = bt_alloc(vm);
784 	btfree->bt_type = BT_TYPE_FREE;
785 	btfree->bt_start = addr;
786 	btfree->bt_size = size;
787 	bt_insseg(vm, btfree, btspan);
788 	bt_insfree(vm, btfree);
789 
790 	vm->vm_size += size;
791 }
792 
793 static void
794 vmem_destroy1(vmem_t *vm)
795 {
796 	bt_t *bt;
797 
798 	/*
799 	 * Drain per-cpu quantum caches.
800 	 */
801 	qc_destroy(vm);
802 
803 	/*
804 	 * The vmem should now only contain empty segments.
805 	 */
806 	VMEM_LOCK(vm);
807 	MPASS(vm->vm_nbusytag == 0);
808 
809 	while ((bt = TAILQ_FIRST(&vm->vm_seglist)) != NULL)
810 		bt_remseg(vm, bt);
811 
812 	if (vm->vm_hashlist != NULL && vm->vm_hashlist != vm->vm_hash0)
813 		free(vm->vm_hashlist, M_VMEM);
814 
815 	bt_freetrim(vm, 0);
816 
817 	VMEM_CONDVAR_DESTROY(vm);
818 	VMEM_LOCK_DESTROY(vm);
819 	free(vm, M_VMEM);
820 }
821 
822 static int
823 vmem_import(vmem_t *vm, vmem_size_t size, vmem_size_t align, int flags)
824 {
825 	vmem_addr_t addr;
826 	int error;
827 
828 	if (vm->vm_importfn == NULL)
829 		return EINVAL;
830 
831 	/*
832 	 * To make sure we get a span that meets the alignment we double it
833 	 * and add the size to the tail.  This slightly overestimates.
834 	 */
835 	if (align != vm->vm_quantum_mask + 1)
836 		size = (align * 2) + size;
837 	size = roundup(size, vm->vm_import_quantum);
838 
839 	/*
840 	 * Hide MAXALLOC tags so we're guaranteed to be able to add this
841 	 * span and the tag we want to allocate from it.
842 	 */
843 	MPASS(vm->vm_nfreetags >= BT_MAXALLOC);
844 	vm->vm_nfreetags -= BT_MAXALLOC;
845 	VMEM_UNLOCK(vm);
846 	error = (vm->vm_importfn)(vm->vm_arg, size, flags, &addr);
847 	VMEM_LOCK(vm);
848 	vm->vm_nfreetags += BT_MAXALLOC;
849 	if (error)
850 		return ENOMEM;
851 
852 	vmem_add1(vm, addr, size, BT_TYPE_SPAN);
853 
854 	return 0;
855 }
856 
857 /*
858  * vmem_fit: check if a bt can satisfy the given restrictions.
859  *
860  * it's a caller's responsibility to ensure the region is big enough
861  * before calling us.
862  */
863 static int
864 vmem_fit(const bt_t *bt, vmem_size_t size, vmem_size_t align,
865     vmem_size_t phase, vmem_size_t nocross, vmem_addr_t minaddr,
866     vmem_addr_t maxaddr, vmem_addr_t *addrp)
867 {
868 	vmem_addr_t start;
869 	vmem_addr_t end;
870 
871 	MPASS(size > 0);
872 	MPASS(bt->bt_size >= size); /* caller's responsibility */
873 
874 	/*
875 	 * XXX assumption: vmem_addr_t and vmem_size_t are
876 	 * unsigned integer of the same size.
877 	 */
878 
879 	start = bt->bt_start;
880 	if (start < minaddr) {
881 		start = minaddr;
882 	}
883 	end = BT_END(bt);
884 	if (end > maxaddr)
885 		end = maxaddr;
886 	if (start > end)
887 		return (ENOMEM);
888 
889 	start = VMEM_ALIGNUP(start - phase, align) + phase;
890 	if (start < bt->bt_start)
891 		start += align;
892 	if (VMEM_CROSS_P(start, start + size - 1, nocross)) {
893 		MPASS(align < nocross);
894 		start = VMEM_ALIGNUP(start - phase, nocross) + phase;
895 	}
896 	if (start <= end && end - start >= size - 1) {
897 		MPASS((start & (align - 1)) == phase);
898 		MPASS(!VMEM_CROSS_P(start, start + size - 1, nocross));
899 		MPASS(minaddr <= start);
900 		MPASS(maxaddr == 0 || start + size - 1 <= maxaddr);
901 		MPASS(bt->bt_start <= start);
902 		MPASS(BT_END(bt) - start >= size - 1);
903 		*addrp = start;
904 
905 		return (0);
906 	}
907 	return (ENOMEM);
908 }
909 
910 /*
911  * vmem_clip:  Trim the boundary tag edges to the requested start and size.
912  */
913 static void
914 vmem_clip(vmem_t *vm, bt_t *bt, vmem_addr_t start, vmem_size_t size)
915 {
916 	bt_t *btnew;
917 	bt_t *btprev;
918 
919 	VMEM_ASSERT_LOCKED(vm);
920 	MPASS(bt->bt_type == BT_TYPE_FREE);
921 	MPASS(bt->bt_size >= size);
922 	bt_remfree(vm, bt);
923 	if (bt->bt_start != start) {
924 		btprev = bt_alloc(vm);
925 		btprev->bt_type = BT_TYPE_FREE;
926 		btprev->bt_start = bt->bt_start;
927 		btprev->bt_size = start - bt->bt_start;
928 		bt->bt_start = start;
929 		bt->bt_size -= btprev->bt_size;
930 		bt_insfree(vm, btprev);
931 		bt_insseg(vm, btprev,
932 		    TAILQ_PREV(bt, vmem_seglist, bt_seglist));
933 	}
934 	MPASS(bt->bt_start == start);
935 	if (bt->bt_size != size && bt->bt_size - size > vm->vm_quantum_mask) {
936 		/* split */
937 		btnew = bt_alloc(vm);
938 		btnew->bt_type = BT_TYPE_BUSY;
939 		btnew->bt_start = bt->bt_start;
940 		btnew->bt_size = size;
941 		bt->bt_start = bt->bt_start + size;
942 		bt->bt_size -= size;
943 		bt_insfree(vm, bt);
944 		bt_insseg(vm, btnew,
945 		    TAILQ_PREV(bt, vmem_seglist, bt_seglist));
946 		bt_insbusy(vm, btnew);
947 		bt = btnew;
948 	} else {
949 		bt->bt_type = BT_TYPE_BUSY;
950 		bt_insbusy(vm, bt);
951 	}
952 	MPASS(bt->bt_size >= size);
953 	bt->bt_type = BT_TYPE_BUSY;
954 }
955 
956 /* ---- vmem API */
957 
958 void
959 vmem_set_import(vmem_t *vm, vmem_import_t *importfn,
960      vmem_release_t *releasefn, void *arg, vmem_size_t import_quantum)
961 {
962 
963 	VMEM_LOCK(vm);
964 	vm->vm_importfn = importfn;
965 	vm->vm_releasefn = releasefn;
966 	vm->vm_arg = arg;
967 	vm->vm_import_quantum = import_quantum;
968 	VMEM_UNLOCK(vm);
969 }
970 
971 void
972 vmem_set_reclaim(vmem_t *vm, vmem_reclaim_t *reclaimfn)
973 {
974 
975 	VMEM_LOCK(vm);
976 	vm->vm_reclaimfn = reclaimfn;
977 	VMEM_UNLOCK(vm);
978 }
979 
980 /*
981  * vmem_init: Initializes vmem arena.
982  */
983 vmem_t *
984 vmem_init(vmem_t *vm, const char *name, vmem_addr_t base, vmem_size_t size,
985     vmem_size_t quantum, vmem_size_t qcache_max, int flags)
986 {
987 	int i;
988 
989 	MPASS(quantum > 0);
990 	MPASS((quantum & (quantum - 1)) == 0);
991 
992 	bzero(vm, sizeof(*vm));
993 
994 	VMEM_CONDVAR_INIT(vm, name);
995 	VMEM_LOCK_INIT(vm, name);
996 	vm->vm_nfreetags = 0;
997 	LIST_INIT(&vm->vm_freetags);
998 	strlcpy(vm->vm_name, name, sizeof(vm->vm_name));
999 	vm->vm_quantum_mask = quantum - 1;
1000 	vm->vm_quantum_shift = flsl(quantum) - 1;
1001 	vm->vm_nbusytag = 0;
1002 	vm->vm_size = 0;
1003 	vm->vm_inuse = 0;
1004 	qc_init(vm, qcache_max);
1005 
1006 	TAILQ_INIT(&vm->vm_seglist);
1007 	for (i = 0; i < VMEM_MAXORDER; i++) {
1008 		LIST_INIT(&vm->vm_freelist[i]);
1009 	}
1010 	memset(&vm->vm_hash0, 0, sizeof(vm->vm_hash0));
1011 	vm->vm_hashsize = VMEM_HASHSIZE_MIN;
1012 	vm->vm_hashlist = vm->vm_hash0;
1013 
1014 	if (size != 0) {
1015 		if (vmem_add(vm, base, size, flags) != 0) {
1016 			vmem_destroy1(vm);
1017 			return NULL;
1018 		}
1019 	}
1020 
1021 	mtx_lock(&vmem_list_lock);
1022 	LIST_INSERT_HEAD(&vmem_list, vm, vm_alllist);
1023 	mtx_unlock(&vmem_list_lock);
1024 
1025 	return vm;
1026 }
1027 
1028 /*
1029  * vmem_create: create an arena.
1030  */
1031 vmem_t *
1032 vmem_create(const char *name, vmem_addr_t base, vmem_size_t size,
1033     vmem_size_t quantum, vmem_size_t qcache_max, int flags)
1034 {
1035 
1036 	vmem_t *vm;
1037 
1038 	vm = malloc(sizeof(*vm), M_VMEM, flags & (M_WAITOK|M_NOWAIT));
1039 	if (vm == NULL)
1040 		return (NULL);
1041 	if (vmem_init(vm, name, base, size, quantum, qcache_max,
1042 	    flags) == NULL) {
1043 		free(vm, M_VMEM);
1044 		return (NULL);
1045 	}
1046 	return (vm);
1047 }
1048 
1049 void
1050 vmem_destroy(vmem_t *vm)
1051 {
1052 
1053 	mtx_lock(&vmem_list_lock);
1054 	LIST_REMOVE(vm, vm_alllist);
1055 	mtx_unlock(&vmem_list_lock);
1056 
1057 	vmem_destroy1(vm);
1058 }
1059 
1060 vmem_size_t
1061 vmem_roundup_size(vmem_t *vm, vmem_size_t size)
1062 {
1063 
1064 	return (size + vm->vm_quantum_mask) & ~vm->vm_quantum_mask;
1065 }
1066 
1067 /*
1068  * vmem_alloc: allocate resource from the arena.
1069  */
1070 int
1071 vmem_alloc(vmem_t *vm, vmem_size_t size, int flags, vmem_addr_t *addrp)
1072 {
1073 	const int strat __unused = flags & VMEM_FITMASK;
1074 	qcache_t *qc;
1075 
1076 	flags &= VMEM_FLAGS;
1077 	MPASS(size > 0);
1078 	MPASS(strat == M_BESTFIT || strat == M_FIRSTFIT);
1079 	if ((flags & M_NOWAIT) == 0)
1080 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "vmem_alloc");
1081 
1082 	if (size <= vm->vm_qcache_max) {
1083 		qc = &vm->vm_qcache[(size - 1) >> vm->vm_quantum_shift];
1084 		*addrp = (vmem_addr_t)uma_zalloc(qc->qc_cache, flags);
1085 		if (*addrp == 0)
1086 			return (ENOMEM);
1087 		return (0);
1088 	}
1089 
1090 	return vmem_xalloc(vm, size, 0, 0, 0, VMEM_ADDR_MIN, VMEM_ADDR_MAX,
1091 	    flags, addrp);
1092 }
1093 
1094 int
1095 vmem_xalloc(vmem_t *vm, const vmem_size_t size0, vmem_size_t align,
1096     const vmem_size_t phase, const vmem_size_t nocross,
1097     const vmem_addr_t minaddr, const vmem_addr_t maxaddr, int flags,
1098     vmem_addr_t *addrp)
1099 {
1100 	const vmem_size_t size = vmem_roundup_size(vm, size0);
1101 	struct vmem_freelist *list;
1102 	struct vmem_freelist *first;
1103 	struct vmem_freelist *end;
1104 	vmem_size_t avail;
1105 	bt_t *bt;
1106 	int error;
1107 	int strat;
1108 
1109 	flags &= VMEM_FLAGS;
1110 	strat = flags & VMEM_FITMASK;
1111 	MPASS(size0 > 0);
1112 	MPASS(size > 0);
1113 	MPASS(strat == M_BESTFIT || strat == M_FIRSTFIT);
1114 	MPASS((flags & (M_NOWAIT|M_WAITOK)) != (M_NOWAIT|M_WAITOK));
1115 	if ((flags & M_NOWAIT) == 0)
1116 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "vmem_xalloc");
1117 	MPASS((align & vm->vm_quantum_mask) == 0);
1118 	MPASS((align & (align - 1)) == 0);
1119 	MPASS((phase & vm->vm_quantum_mask) == 0);
1120 	MPASS((nocross & vm->vm_quantum_mask) == 0);
1121 	MPASS((nocross & (nocross - 1)) == 0);
1122 	MPASS((align == 0 && phase == 0) || phase < align);
1123 	MPASS(nocross == 0 || nocross >= size);
1124 	MPASS(minaddr <= maxaddr);
1125 	MPASS(!VMEM_CROSS_P(phase, phase + size - 1, nocross));
1126 
1127 	if (align == 0)
1128 		align = vm->vm_quantum_mask + 1;
1129 
1130 	*addrp = 0;
1131 	end = &vm->vm_freelist[VMEM_MAXORDER];
1132 	/*
1133 	 * choose a free block from which we allocate.
1134 	 */
1135 	first = bt_freehead_toalloc(vm, size, strat);
1136 	VMEM_LOCK(vm);
1137 	for (;;) {
1138 		/*
1139 		 * Make sure we have enough tags to complete the
1140 		 * operation.
1141 		 */
1142 		if (vm->vm_nfreetags < BT_MAXALLOC &&
1143 		    bt_fill(vm, flags) != 0) {
1144 			error = ENOMEM;
1145 			break;
1146 		}
1147 		/*
1148 	 	 * Scan freelists looking for a tag that satisfies the
1149 		 * allocation.  If we're doing BESTFIT we may encounter
1150 		 * sizes below the request.  If we're doing FIRSTFIT we
1151 		 * inspect only the first element from each list.
1152 		 */
1153 		for (list = first; list < end; list++) {
1154 			LIST_FOREACH(bt, list, bt_freelist) {
1155 				if (bt->bt_size >= size) {
1156 					error = vmem_fit(bt, size, align, phase,
1157 					    nocross, minaddr, maxaddr, addrp);
1158 					if (error == 0) {
1159 						vmem_clip(vm, bt, *addrp, size);
1160 						goto out;
1161 					}
1162 				}
1163 				/* FIRST skips to the next list. */
1164 				if (strat == M_FIRSTFIT)
1165 					break;
1166 			}
1167 		}
1168 		/*
1169 		 * Retry if the fast algorithm failed.
1170 		 */
1171 		if (strat == M_FIRSTFIT) {
1172 			strat = M_BESTFIT;
1173 			first = bt_freehead_toalloc(vm, size, strat);
1174 			continue;
1175 		}
1176 		/*
1177 		 * XXX it is possible to fail to meet restrictions with the
1178 		 * imported region.  It is up to the user to specify the
1179 		 * import quantum such that it can satisfy any allocation.
1180 		 */
1181 		if (vmem_import(vm, size, align, flags) == 0)
1182 			continue;
1183 
1184 		/*
1185 		 * Try to free some space from the quantum cache or reclaim
1186 		 * functions if available.
1187 		 */
1188 		if (vm->vm_qcache_max != 0 || vm->vm_reclaimfn != NULL) {
1189 			avail = vm->vm_size - vm->vm_inuse;
1190 			VMEM_UNLOCK(vm);
1191 			if (vm->vm_qcache_max != 0)
1192 				qc_drain(vm);
1193 			if (vm->vm_reclaimfn != NULL)
1194 				vm->vm_reclaimfn(vm, flags);
1195 			VMEM_LOCK(vm);
1196 			/* If we were successful retry even NOWAIT. */
1197 			if (vm->vm_size - vm->vm_inuse > avail)
1198 				continue;
1199 		}
1200 		if ((flags & M_NOWAIT) != 0) {
1201 			error = ENOMEM;
1202 			break;
1203 		}
1204 		VMEM_CONDVAR_WAIT(vm);
1205 	}
1206 out:
1207 	VMEM_UNLOCK(vm);
1208 	if (error != 0 && (flags & M_NOWAIT) == 0)
1209 		panic("failed to allocate waiting allocation\n");
1210 
1211 	return (error);
1212 }
1213 
1214 /*
1215  * vmem_free: free the resource to the arena.
1216  */
1217 void
1218 vmem_free(vmem_t *vm, vmem_addr_t addr, vmem_size_t size)
1219 {
1220 	qcache_t *qc;
1221 	MPASS(size > 0);
1222 
1223 	if (size <= vm->vm_qcache_max) {
1224 		qc = &vm->vm_qcache[(size - 1) >> vm->vm_quantum_shift];
1225 		uma_zfree(qc->qc_cache, (void *)addr);
1226 	} else
1227 		vmem_xfree(vm, addr, size);
1228 }
1229 
1230 void
1231 vmem_xfree(vmem_t *vm, vmem_addr_t addr, vmem_size_t size)
1232 {
1233 	bt_t *bt;
1234 	bt_t *t;
1235 
1236 	MPASS(size > 0);
1237 
1238 	VMEM_LOCK(vm);
1239 	bt = bt_lookupbusy(vm, addr);
1240 	MPASS(bt != NULL);
1241 	MPASS(bt->bt_start == addr);
1242 	MPASS(bt->bt_size == vmem_roundup_size(vm, size) ||
1243 	    bt->bt_size - vmem_roundup_size(vm, size) <= vm->vm_quantum_mask);
1244 	MPASS(bt->bt_type == BT_TYPE_BUSY);
1245 	bt_rembusy(vm, bt);
1246 	bt->bt_type = BT_TYPE_FREE;
1247 
1248 	/* coalesce */
1249 	t = TAILQ_NEXT(bt, bt_seglist);
1250 	if (t != NULL && t->bt_type == BT_TYPE_FREE) {
1251 		MPASS(BT_END(bt) < t->bt_start);	/* YYY */
1252 		bt->bt_size += t->bt_size;
1253 		bt_remfree(vm, t);
1254 		bt_remseg(vm, t);
1255 	}
1256 	t = TAILQ_PREV(bt, vmem_seglist, bt_seglist);
1257 	if (t != NULL && t->bt_type == BT_TYPE_FREE) {
1258 		MPASS(BT_END(t) < bt->bt_start);	/* YYY */
1259 		bt->bt_size += t->bt_size;
1260 		bt->bt_start = t->bt_start;
1261 		bt_remfree(vm, t);
1262 		bt_remseg(vm, t);
1263 	}
1264 
1265 	t = TAILQ_PREV(bt, vmem_seglist, bt_seglist);
1266 	MPASS(t != NULL);
1267 	MPASS(BT_ISSPAN_P(t) || t->bt_type == BT_TYPE_BUSY);
1268 	if (vm->vm_releasefn != NULL && t->bt_type == BT_TYPE_SPAN &&
1269 	    t->bt_size == bt->bt_size) {
1270 		vmem_addr_t spanaddr;
1271 		vmem_size_t spansize;
1272 
1273 		MPASS(t->bt_start == bt->bt_start);
1274 		spanaddr = bt->bt_start;
1275 		spansize = bt->bt_size;
1276 		bt_remseg(vm, bt);
1277 		bt_remseg(vm, t);
1278 		vm->vm_size -= spansize;
1279 		VMEM_CONDVAR_BROADCAST(vm);
1280 		bt_freetrim(vm, BT_MAXFREE);
1281 		(*vm->vm_releasefn)(vm->vm_arg, spanaddr, spansize);
1282 	} else {
1283 		bt_insfree(vm, bt);
1284 		VMEM_CONDVAR_BROADCAST(vm);
1285 		bt_freetrim(vm, BT_MAXFREE);
1286 	}
1287 }
1288 
1289 /*
1290  * vmem_add:
1291  *
1292  */
1293 int
1294 vmem_add(vmem_t *vm, vmem_addr_t addr, vmem_size_t size, int flags)
1295 {
1296 	int error;
1297 
1298 	error = 0;
1299 	flags &= VMEM_FLAGS;
1300 	VMEM_LOCK(vm);
1301 	if (vm->vm_nfreetags >= BT_MAXALLOC || bt_fill(vm, flags) == 0)
1302 		vmem_add1(vm, addr, size, BT_TYPE_SPAN_STATIC);
1303 	else
1304 		error = ENOMEM;
1305 	VMEM_UNLOCK(vm);
1306 
1307 	return (error);
1308 }
1309 
1310 /*
1311  * vmem_size: information about arenas size
1312  */
1313 vmem_size_t
1314 vmem_size(vmem_t *vm, int typemask)
1315 {
1316 
1317 	switch (typemask) {
1318 	case VMEM_ALLOC:
1319 		return vm->vm_inuse;
1320 	case VMEM_FREE:
1321 		return vm->vm_size - vm->vm_inuse;
1322 	case VMEM_FREE|VMEM_ALLOC:
1323 		return vm->vm_size;
1324 	default:
1325 		panic("vmem_size");
1326 	}
1327 }
1328 
1329 /* ---- debug */
1330 
1331 #if defined(DDB) || defined(DIAGNOSTIC)
1332 
1333 static void bt_dump(const bt_t *, int (*)(const char *, ...)
1334     __printflike(1, 2));
1335 
1336 static const char *
1337 bt_type_string(int type)
1338 {
1339 
1340 	switch (type) {
1341 	case BT_TYPE_BUSY:
1342 		return "busy";
1343 	case BT_TYPE_FREE:
1344 		return "free";
1345 	case BT_TYPE_SPAN:
1346 		return "span";
1347 	case BT_TYPE_SPAN_STATIC:
1348 		return "static span";
1349 	default:
1350 		break;
1351 	}
1352 	return "BOGUS";
1353 }
1354 
1355 static void
1356 bt_dump(const bt_t *bt, int (*pr)(const char *, ...))
1357 {
1358 
1359 	(*pr)("\t%p: %jx %jx, %d(%s)\n",
1360 	    bt, (intmax_t)bt->bt_start, (intmax_t)bt->bt_size,
1361 	    bt->bt_type, bt_type_string(bt->bt_type));
1362 }
1363 
1364 static void
1365 vmem_dump(const vmem_t *vm , int (*pr)(const char *, ...) __printflike(1, 2))
1366 {
1367 	const bt_t *bt;
1368 	int i;
1369 
1370 	(*pr)("vmem %p '%s'\n", vm, vm->vm_name);
1371 	TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) {
1372 		bt_dump(bt, pr);
1373 	}
1374 
1375 	for (i = 0; i < VMEM_MAXORDER; i++) {
1376 		const struct vmem_freelist *fl = &vm->vm_freelist[i];
1377 
1378 		if (LIST_EMPTY(fl)) {
1379 			continue;
1380 		}
1381 
1382 		(*pr)("freelist[%d]\n", i);
1383 		LIST_FOREACH(bt, fl, bt_freelist) {
1384 			bt_dump(bt, pr);
1385 		}
1386 	}
1387 }
1388 
1389 #endif /* defined(DDB) || defined(DIAGNOSTIC) */
1390 
1391 #if defined(DDB)
1392 static bt_t *
1393 vmem_whatis_lookup(vmem_t *vm, vmem_addr_t addr)
1394 {
1395 	bt_t *bt;
1396 
1397 	TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) {
1398 		if (BT_ISSPAN_P(bt)) {
1399 			continue;
1400 		}
1401 		if (bt->bt_start <= addr && addr <= BT_END(bt)) {
1402 			return bt;
1403 		}
1404 	}
1405 
1406 	return NULL;
1407 }
1408 
1409 void
1410 vmem_whatis(vmem_addr_t addr, int (*pr)(const char *, ...))
1411 {
1412 	vmem_t *vm;
1413 
1414 	LIST_FOREACH(vm, &vmem_list, vm_alllist) {
1415 		bt_t *bt;
1416 
1417 		bt = vmem_whatis_lookup(vm, addr);
1418 		if (bt == NULL) {
1419 			continue;
1420 		}
1421 		(*pr)("%p is %p+%zu in VMEM '%s' (%s)\n",
1422 		    (void *)addr, (void *)bt->bt_start,
1423 		    (vmem_size_t)(addr - bt->bt_start), vm->vm_name,
1424 		    (bt->bt_type == BT_TYPE_BUSY) ? "allocated" : "free");
1425 	}
1426 }
1427 
1428 void
1429 vmem_printall(const char *modif, int (*pr)(const char *, ...))
1430 {
1431 	const vmem_t *vm;
1432 
1433 	LIST_FOREACH(vm, &vmem_list, vm_alllist) {
1434 		vmem_dump(vm, pr);
1435 	}
1436 }
1437 
1438 void
1439 vmem_print(vmem_addr_t addr, const char *modif, int (*pr)(const char *, ...))
1440 {
1441 	const vmem_t *vm = (const void *)addr;
1442 
1443 	vmem_dump(vm, pr);
1444 }
1445 #endif /* defined(DDB) */
1446 
1447 #define vmem_printf printf
1448 
1449 #if defined(DIAGNOSTIC)
1450 
1451 static bool
1452 vmem_check_sanity(vmem_t *vm)
1453 {
1454 	const bt_t *bt, *bt2;
1455 
1456 	MPASS(vm != NULL);
1457 
1458 	TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) {
1459 		if (bt->bt_start > BT_END(bt)) {
1460 			printf("corrupted tag\n");
1461 			bt_dump(bt, vmem_printf);
1462 			return false;
1463 		}
1464 	}
1465 	TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) {
1466 		TAILQ_FOREACH(bt2, &vm->vm_seglist, bt_seglist) {
1467 			if (bt == bt2) {
1468 				continue;
1469 			}
1470 			if (BT_ISSPAN_P(bt) != BT_ISSPAN_P(bt2)) {
1471 				continue;
1472 			}
1473 			if (bt->bt_start <= BT_END(bt2) &&
1474 			    bt2->bt_start <= BT_END(bt)) {
1475 				printf("overwrapped tags\n");
1476 				bt_dump(bt, vmem_printf);
1477 				bt_dump(bt2, vmem_printf);
1478 				return false;
1479 			}
1480 		}
1481 	}
1482 
1483 	return true;
1484 }
1485 
1486 static void
1487 vmem_check(vmem_t *vm)
1488 {
1489 
1490 	if (!vmem_check_sanity(vm)) {
1491 		panic("insanity vmem %p", vm);
1492 	}
1493 }
1494 
1495 #endif /* defined(DIAGNOSTIC) */
1496