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