xref: /titanic_52/usr/src/uts/common/os/vmem.c (revision 0bb073995ac5a95bd35f2dd790df1ea3d8c2d507)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * Big Theory Statement for the virtual memory allocator.
30  *
31  * For a more complete description of the main ideas, see:
32  *
33  *	Jeff Bonwick and Jonathan Adams,
34  *
35  *	Magazines and vmem: Extending the Slab Allocator to Many CPUs and
36  *	Arbitrary Resources.
37  *
38  *	Proceedings of the 2001 Usenix Conference.
39  *	Available as http://www.usenix.org/event/usenix01/bonwick.html
40  *
41  *
42  * 1. General Concepts
43  * -------------------
44  *
45  * 1.1 Overview
46  * ------------
47  * We divide the kernel address space into a number of logically distinct
48  * pieces, or *arenas*: text, data, heap, stack, and so on.  Within these
49  * arenas we often subdivide further; for example, we use heap addresses
50  * not only for the kernel heap (kmem_alloc() space), but also for DVMA,
51  * bp_mapin(), /dev/kmem, and even some device mappings like the TOD chip.
52  * The kernel address space, therefore, is most accurately described as
53  * a tree of arenas in which each node of the tree *imports* some subset
54  * of its parent.  The virtual memory allocator manages these arenas and
55  * supports their natural hierarchical structure.
56  *
57  * 1.2 Arenas
58  * ----------
59  * An arena is nothing more than a set of integers.  These integers most
60  * commonly represent virtual addresses, but in fact they can represent
61  * anything at all.  For example, we could use an arena containing the
62  * integers minpid through maxpid to allocate process IDs.  vmem_create()
63  * and vmem_destroy() create and destroy vmem arenas.  In order to
64  * differentiate between arenas used for adresses and arenas used for
65  * identifiers, the VMC_IDENTIFIER flag is passed to vmem_create().  This
66  * prevents identifier exhaustion from being diagnosed as general memory
67  * failure.
68  *
69  * 1.3 Spans
70  * ---------
71  * We represent the integers in an arena as a collection of *spans*, or
72  * contiguous ranges of integers.  For example, the kernel heap consists
73  * of just one span: [kernelheap, ekernelheap).  Spans can be added to an
74  * arena in two ways: explicitly, by vmem_add(), or implicitly, by
75  * importing, as described in Section 1.5 below.
76  *
77  * 1.4 Segments
78  * ------------
79  * Spans are subdivided into *segments*, each of which is either allocated
80  * or free.  A segment, like a span, is a contiguous range of integers.
81  * Each allocated segment [addr, addr + size) represents exactly one
82  * vmem_alloc(size) that returned addr.  Free segments represent the space
83  * between allocated segments.  If two free segments are adjacent, we
84  * coalesce them into one larger segment; that is, if segments [a, b) and
85  * [b, c) are both free, we merge them into a single segment [a, c).
86  * The segments within a span are linked together in increasing-address order
87  * so we can easily determine whether coalescing is possible.
88  *
89  * Segments never cross span boundaries.  When all segments within
90  * an imported span become free, we return the span to its source.
91  *
92  * 1.5 Imported Memory
93  * -------------------
94  * As mentioned in the overview, some arenas are logical subsets of
95  * other arenas.  For example, kmem_va_arena (a virtual address cache
96  * that satisfies most kmem_slab_create() requests) is just a subset
97  * of heap_arena (the kernel heap) that provides caching for the most
98  * common slab sizes.  When kmem_va_arena runs out of virtual memory,
99  * it *imports* more from the heap; we say that heap_arena is the
100  * *vmem source* for kmem_va_arena.  vmem_create() allows you to
101  * specify any existing vmem arena as the source for your new arena.
102  * Topologically, since every arena is a child of at most one source,
103  * the set of all arenas forms a collection of trees.
104  *
105  * 1.6 Constrained Allocations
106  * ---------------------------
107  * Some vmem clients are quite picky about the kind of address they want.
108  * For example, the DVMA code may need an address that is at a particular
109  * phase with respect to some alignment (to get good cache coloring), or
110  * that lies within certain limits (the addressable range of a device),
111  * or that doesn't cross some boundary (a DMA counter restriction) --
112  * or all of the above.  vmem_xalloc() allows the client to specify any
113  * or all of these constraints.
114  *
115  * 1.7 The Vmem Quantum
116  * --------------------
117  * Every arena has a notion of 'quantum', specified at vmem_create() time,
118  * that defines the arena's minimum unit of currency.  Most commonly the
119  * quantum is either 1 or PAGESIZE, but any power of 2 is legal.
120  * All vmem allocations are guaranteed to be quantum-aligned.
121  *
122  * 1.8 Quantum Caching
123  * -------------------
124  * A vmem arena may be so hot (frequently used) that the scalability of vmem
125  * allocation is a significant concern.  We address this by allowing the most
126  * common allocation sizes to be serviced by the kernel memory allocator,
127  * which provides low-latency per-cpu caching.  The qcache_max argument to
128  * vmem_create() specifies the largest allocation size to cache.
129  *
130  * 1.9 Relationship to Kernel Memory Allocator
131  * -------------------------------------------
132  * Every kmem cache has a vmem arena as its slab supplier.  The kernel memory
133  * allocator uses vmem_alloc() and vmem_free() to create and destroy slabs.
134  *
135  *
136  * 2. Implementation
137  * -----------------
138  *
139  * 2.1 Segment lists and markers
140  * -----------------------------
141  * The segment structure (vmem_seg_t) contains two doubly-linked lists.
142  *
143  * The arena list (vs_anext/vs_aprev) links all segments in the arena.
144  * In addition to the allocated and free segments, the arena contains
145  * special marker segments at span boundaries.  Span markers simplify
146  * coalescing and importing logic by making it easy to tell both when
147  * we're at a span boundary (so we don't coalesce across it), and when
148  * a span is completely free (its neighbors will both be span markers).
149  *
150  * Imported spans will have vs_import set.
151  *
152  * The next-of-kin list (vs_knext/vs_kprev) links segments of the same type:
153  * (1) for allocated segments, vs_knext is the hash chain linkage;
154  * (2) for free segments, vs_knext is the freelist linkage;
155  * (3) for span marker segments, vs_knext is the next span marker.
156  *
157  * 2.2 Allocation hashing
158  * ----------------------
159  * We maintain a hash table of all allocated segments, hashed by address.
160  * This allows vmem_free() to discover the target segment in constant time.
161  * vmem_update() periodically resizes hash tables to keep hash chains short.
162  *
163  * 2.3 Freelist management
164  * -----------------------
165  * We maintain power-of-2 freelists for free segments, i.e. free segments
166  * of size >= 2^n reside in vmp->vm_freelist[n].  To ensure constant-time
167  * allocation, vmem_xalloc() looks not in the first freelist that *might*
168  * satisfy the allocation, but in the first freelist that *definitely*
169  * satisfies the allocation (unless VM_BESTFIT is specified, or all larger
170  * freelists are empty).  For example, a 1000-byte allocation will be
171  * satisfied not from the 512..1023-byte freelist, whose members *might*
172  * contains a 1000-byte segment, but from a 1024-byte or larger freelist,
173  * the first member of which will *definitely* satisfy the allocation.
174  * This ensures that vmem_xalloc() works in constant time.
175  *
176  * We maintain a bit map to determine quickly which freelists are non-empty.
177  * vmp->vm_freemap & (1 << n) is non-zero iff vmp->vm_freelist[n] is non-empty.
178  *
179  * The different freelists are linked together into one large freelist,
180  * with the freelist heads serving as markers.  Freelist markers simplify
181  * the maintenance of vm_freemap by making it easy to tell when we're taking
182  * the last member of a freelist (both of its neighbors will be markers).
183  *
184  * 2.4 Vmem Locking
185  * ----------------
186  * For simplicity, all arena state is protected by a per-arena lock.
187  * For very hot arenas, use quantum caching for scalability.
188  *
189  * 2.5 Vmem Population
190  * -------------------
191  * Any internal vmem routine that might need to allocate new segment
192  * structures must prepare in advance by calling vmem_populate(), which
193  * will preallocate enough vmem_seg_t's to get is through the entire
194  * operation without dropping the arena lock.
195  *
196  * 2.6 Auditing
197  * ------------
198  * If KMF_AUDIT is set in kmem_flags, we audit vmem allocations as well.
199  * Since virtual addresses cannot be scribbled on, there is no equivalent
200  * in vmem to redzone checking, deadbeef, or other kmem debugging features.
201  * Moreover, we do not audit frees because segment coalescing destroys the
202  * association between an address and its segment structure.  Auditing is
203  * thus intended primarily to keep track of who's consuming the arena.
204  * Debugging support could certainly be extended in the future if it proves
205  * necessary, but we do so much live checking via the allocation hash table
206  * that even non-DEBUG systems get quite a bit of sanity checking already.
207  */
208 
209 #include <sys/vmem_impl.h>
210 #include <sys/kmem.h>
211 #include <sys/kstat.h>
212 #include <sys/param.h>
213 #include <sys/systm.h>
214 #include <sys/atomic.h>
215 #include <sys/bitmap.h>
216 #include <sys/sysmacros.h>
217 #include <sys/cmn_err.h>
218 #include <sys/debug.h>
219 #include <sys/panic.h>
220 
221 #define	VMEM_INITIAL		10	/* early vmem arenas */
222 #define	VMEM_SEG_INITIAL	200	/* early segments */
223 
224 /*
225  * Adding a new span to an arena requires two segment structures: one to
226  * represent the span, and one to represent the free segment it contains.
227  */
228 #define	VMEM_SEGS_PER_SPAN_CREATE	2
229 
230 /*
231  * Allocating a piece of an existing segment requires 0-2 segment structures
232  * depending on how much of the segment we're allocating.
233  *
234  * To allocate the entire segment, no new segment structures are needed; we
235  * simply move the existing segment structure from the freelist to the
236  * allocation hash table.
237  *
238  * To allocate a piece from the left or right end of the segment, we must
239  * split the segment into two pieces (allocated part and remainder), so we
240  * need one new segment structure to represent the remainder.
241  *
242  * To allocate from the middle of a segment, we need two new segment strucures
243  * to represent the remainders on either side of the allocated part.
244  */
245 #define	VMEM_SEGS_PER_EXACT_ALLOC	0
246 #define	VMEM_SEGS_PER_LEFT_ALLOC	1
247 #define	VMEM_SEGS_PER_RIGHT_ALLOC	1
248 #define	VMEM_SEGS_PER_MIDDLE_ALLOC	2
249 
250 /*
251  * vmem_populate() preallocates segment structures for vmem to do its work.
252  * It must preallocate enough for the worst case, which is when we must import
253  * a new span and then allocate from the middle of it.
254  */
255 #define	VMEM_SEGS_PER_ALLOC_MAX		\
256 	(VMEM_SEGS_PER_SPAN_CREATE + VMEM_SEGS_PER_MIDDLE_ALLOC)
257 
258 /*
259  * The segment structures themselves are allocated from vmem_seg_arena, so
260  * we have a recursion problem when vmem_seg_arena needs to populate itself.
261  * We address this by working out the maximum number of segment structures
262  * this act will require, and multiplying by the maximum number of threads
263  * that we'll allow to do it simultaneously.
264  *
265  * The worst-case segment consumption to populate vmem_seg_arena is as
266  * follows (depicted as a stack trace to indicate why events are occurring):
267  *
268  * (In order to lower the fragmentation in the heap_arena, we specify a
269  * minimum import size for the vmem_metadata_arena which is the same size
270  * as the kmem_va quantum cache allocations.  This causes the worst-case
271  * allocation from the vmem_metadata_arena to be 3 segments.)
272  *
273  * vmem_alloc(vmem_seg_arena)		-> 2 segs (span create + exact alloc)
274  *  segkmem_alloc(vmem_metadata_arena)
275  *   vmem_alloc(vmem_metadata_arena)	-> 3 segs (span create + left alloc)
276  *    vmem_alloc(heap_arena)		-> 1 seg (left alloc)
277  *   page_create()
278  *   hat_memload()
279  *    kmem_cache_alloc()
280  *     kmem_slab_create()
281  *	vmem_alloc(hat_memload_arena)	-> 2 segs (span create + exact alloc)
282  *	 segkmem_alloc(heap_arena)
283  *	  vmem_alloc(heap_arena)	-> 1 seg (left alloc)
284  *	  page_create()
285  *	  hat_memload()		-> (hat layer won't recurse further)
286  *
287  * The worst-case consumption for each arena is 3 segment structures.
288  * Of course, a 3-seg reserve could easily be blown by multiple threads.
289  * Therefore, we serialize all allocations from vmem_seg_arena (which is OK
290  * because they're rare).  We cannot allow a non-blocking allocation to get
291  * tied up behind a blocking allocation, however, so we use separate locks
292  * for VM_SLEEP and VM_NOSLEEP allocations.  Similarly, VM_PUSHPAGE allocations
293  * must not block behind ordinary VM_SLEEPs.  In addition, if the system is
294  * panicking then we must keep enough resources for panic_thread to do its
295  * work.  Thus we have at most four threads trying to allocate from
296  * vmem_seg_arena, and each thread consumes at most three segment structures,
297  * so we must maintain a 12-seg reserve.
298  */
299 #define	VMEM_POPULATE_RESERVE	12
300 
301 /*
302  * vmem_populate() ensures that each arena has VMEM_MINFREE seg structures
303  * so that it can satisfy the worst-case allocation *and* participate in
304  * worst-case allocation from vmem_seg_arena.
305  */
306 #define	VMEM_MINFREE	(VMEM_POPULATE_RESERVE + VMEM_SEGS_PER_ALLOC_MAX)
307 
308 static vmem_t vmem0[VMEM_INITIAL];
309 static vmem_t *vmem_populator[VMEM_INITIAL];
310 static uint32_t vmem_id;
311 static uint32_t vmem_populators;
312 static vmem_seg_t vmem_seg0[VMEM_SEG_INITIAL];
313 static vmem_seg_t *vmem_segfree;
314 static kmutex_t vmem_list_lock;
315 static kmutex_t vmem_segfree_lock;
316 static kmutex_t vmem_sleep_lock;
317 static kmutex_t vmem_nosleep_lock;
318 static kmutex_t vmem_pushpage_lock;
319 static kmutex_t vmem_panic_lock;
320 static vmem_t *vmem_list;
321 static vmem_t *vmem_metadata_arena;
322 static vmem_t *vmem_seg_arena;
323 static vmem_t *vmem_hash_arena;
324 static vmem_t *vmem_vmem_arena;
325 static long vmem_update_interval = 15;	/* vmem_update() every 15 seconds */
326 uint32_t vmem_mtbf;		/* mean time between failures [default: off] */
327 size_t vmem_seg_size = sizeof (vmem_seg_t);
328 
329 static vmem_kstat_t vmem_kstat_template = {
330 	{ "mem_inuse",		KSTAT_DATA_UINT64 },
331 	{ "mem_import",		KSTAT_DATA_UINT64 },
332 	{ "mem_total",		KSTAT_DATA_UINT64 },
333 	{ "vmem_source",	KSTAT_DATA_UINT32 },
334 	{ "alloc",		KSTAT_DATA_UINT64 },
335 	{ "free",		KSTAT_DATA_UINT64 },
336 	{ "wait",		KSTAT_DATA_UINT64 },
337 	{ "fail",		KSTAT_DATA_UINT64 },
338 	{ "lookup",		KSTAT_DATA_UINT64 },
339 	{ "search",		KSTAT_DATA_UINT64 },
340 	{ "populate_wait",	KSTAT_DATA_UINT64 },
341 	{ "populate_fail",	KSTAT_DATA_UINT64 },
342 	{ "contains",		KSTAT_DATA_UINT64 },
343 	{ "contains_search",	KSTAT_DATA_UINT64 },
344 };
345 
346 /*
347  * Insert/delete from arena list (type 'a') or next-of-kin list (type 'k').
348  */
349 #define	VMEM_INSERT(vprev, vsp, type)					\
350 {									\
351 	vmem_seg_t *vnext = (vprev)->vs_##type##next;			\
352 	(vsp)->vs_##type##next = (vnext);				\
353 	(vsp)->vs_##type##prev = (vprev);				\
354 	(vprev)->vs_##type##next = (vsp);				\
355 	(vnext)->vs_##type##prev = (vsp);				\
356 }
357 
358 #define	VMEM_DELETE(vsp, type)						\
359 {									\
360 	vmem_seg_t *vprev = (vsp)->vs_##type##prev;			\
361 	vmem_seg_t *vnext = (vsp)->vs_##type##next;			\
362 	(vprev)->vs_##type##next = (vnext);				\
363 	(vnext)->vs_##type##prev = (vprev);				\
364 }
365 
366 /*
367  * Get a vmem_seg_t from the global segfree list.
368  */
369 static vmem_seg_t *
370 vmem_getseg_global(void)
371 {
372 	vmem_seg_t *vsp;
373 
374 	mutex_enter(&vmem_segfree_lock);
375 	if ((vsp = vmem_segfree) != NULL)
376 		vmem_segfree = vsp->vs_knext;
377 	mutex_exit(&vmem_segfree_lock);
378 
379 	return (vsp);
380 }
381 
382 /*
383  * Put a vmem_seg_t on the global segfree list.
384  */
385 static void
386 vmem_putseg_global(vmem_seg_t *vsp)
387 {
388 	mutex_enter(&vmem_segfree_lock);
389 	vsp->vs_knext = vmem_segfree;
390 	vmem_segfree = vsp;
391 	mutex_exit(&vmem_segfree_lock);
392 }
393 
394 /*
395  * Get a vmem_seg_t from vmp's segfree list.
396  */
397 static vmem_seg_t *
398 vmem_getseg(vmem_t *vmp)
399 {
400 	vmem_seg_t *vsp;
401 
402 	ASSERT(vmp->vm_nsegfree > 0);
403 
404 	vsp = vmp->vm_segfree;
405 	vmp->vm_segfree = vsp->vs_knext;
406 	vmp->vm_nsegfree--;
407 
408 	return (vsp);
409 }
410 
411 /*
412  * Put a vmem_seg_t on vmp's segfree list.
413  */
414 static void
415 vmem_putseg(vmem_t *vmp, vmem_seg_t *vsp)
416 {
417 	vsp->vs_knext = vmp->vm_segfree;
418 	vmp->vm_segfree = vsp;
419 	vmp->vm_nsegfree++;
420 }
421 
422 /*
423  * Add vsp to the appropriate freelist.
424  */
425 static void
426 vmem_freelist_insert(vmem_t *vmp, vmem_seg_t *vsp)
427 {
428 	vmem_seg_t *vprev;
429 
430 	ASSERT(*VMEM_HASH(vmp, vsp->vs_start) != vsp);
431 
432 	vprev = (vmem_seg_t *)&vmp->vm_freelist[highbit(VS_SIZE(vsp)) - 1];
433 	vsp->vs_type = VMEM_FREE;
434 	vmp->vm_freemap |= VS_SIZE(vprev);
435 	VMEM_INSERT(vprev, vsp, k);
436 
437 	cv_broadcast(&vmp->vm_cv);
438 }
439 
440 /*
441  * Take vsp from the freelist.
442  */
443 static void
444 vmem_freelist_delete(vmem_t *vmp, vmem_seg_t *vsp)
445 {
446 	ASSERT(*VMEM_HASH(vmp, vsp->vs_start) != vsp);
447 	ASSERT(vsp->vs_type == VMEM_FREE);
448 
449 	if (vsp->vs_knext->vs_start == 0 && vsp->vs_kprev->vs_start == 0) {
450 		/*
451 		 * The segments on both sides of 'vsp' are freelist heads,
452 		 * so taking vsp leaves the freelist at vsp->vs_kprev empty.
453 		 */
454 		ASSERT(vmp->vm_freemap & VS_SIZE(vsp->vs_kprev));
455 		vmp->vm_freemap ^= VS_SIZE(vsp->vs_kprev);
456 	}
457 	VMEM_DELETE(vsp, k);
458 }
459 
460 /*
461  * Add vsp to the allocated-segment hash table and update kstats.
462  */
463 static void
464 vmem_hash_insert(vmem_t *vmp, vmem_seg_t *vsp)
465 {
466 	vmem_seg_t **bucket;
467 
468 	vsp->vs_type = VMEM_ALLOC;
469 	bucket = VMEM_HASH(vmp, vsp->vs_start);
470 	vsp->vs_knext = *bucket;
471 	*bucket = vsp;
472 
473 	if (vmem_seg_size == sizeof (vmem_seg_t)) {
474 		vsp->vs_depth = (uint8_t)getpcstack(vsp->vs_stack,
475 		    VMEM_STACK_DEPTH);
476 		vsp->vs_thread = curthread;
477 		vsp->vs_timestamp = gethrtime();
478 	} else {
479 		vsp->vs_depth = 0;
480 	}
481 
482 	vmp->vm_kstat.vk_alloc.value.ui64++;
483 	vmp->vm_kstat.vk_mem_inuse.value.ui64 += VS_SIZE(vsp);
484 }
485 
486 /*
487  * Remove vsp from the allocated-segment hash table and update kstats.
488  */
489 static vmem_seg_t *
490 vmem_hash_delete(vmem_t *vmp, uintptr_t addr, size_t size)
491 {
492 	vmem_seg_t *vsp, **prev_vspp;
493 
494 	prev_vspp = VMEM_HASH(vmp, addr);
495 	while ((vsp = *prev_vspp) != NULL) {
496 		if (vsp->vs_start == addr) {
497 			*prev_vspp = vsp->vs_knext;
498 			break;
499 		}
500 		vmp->vm_kstat.vk_lookup.value.ui64++;
501 		prev_vspp = &vsp->vs_knext;
502 	}
503 
504 	if (vsp == NULL)
505 		panic("vmem_hash_delete(%p, %lx, %lu): bad free",
506 		    (void *)vmp, addr, size);
507 	if (VS_SIZE(vsp) != size)
508 		panic("vmem_hash_delete(%p, %lx, %lu): wrong size (expect %lu)",
509 		    (void *)vmp, addr, size, VS_SIZE(vsp));
510 
511 	vmp->vm_kstat.vk_free.value.ui64++;
512 	vmp->vm_kstat.vk_mem_inuse.value.ui64 -= size;
513 
514 	return (vsp);
515 }
516 
517 /*
518  * Create a segment spanning the range [start, end) and add it to the arena.
519  */
520 static vmem_seg_t *
521 vmem_seg_create(vmem_t *vmp, vmem_seg_t *vprev, uintptr_t start, uintptr_t end)
522 {
523 	vmem_seg_t *newseg = vmem_getseg(vmp);
524 
525 	newseg->vs_start = start;
526 	newseg->vs_end = end;
527 	newseg->vs_type = 0;
528 	newseg->vs_import = 0;
529 
530 	VMEM_INSERT(vprev, newseg, a);
531 
532 	return (newseg);
533 }
534 
535 /*
536  * Remove segment vsp from the arena.
537  */
538 static void
539 vmem_seg_destroy(vmem_t *vmp, vmem_seg_t *vsp)
540 {
541 	ASSERT(vsp->vs_type != VMEM_ROTOR);
542 	VMEM_DELETE(vsp, a);
543 
544 	vmem_putseg(vmp, vsp);
545 }
546 
547 /*
548  * Add the span [vaddr, vaddr + size) to vmp and update kstats.
549  */
550 static vmem_seg_t *
551 vmem_span_create(vmem_t *vmp, void *vaddr, size_t size, uint8_t import)
552 {
553 	vmem_seg_t *newseg, *span;
554 	uintptr_t start = (uintptr_t)vaddr;
555 	uintptr_t end = start + size;
556 
557 	ASSERT(MUTEX_HELD(&vmp->vm_lock));
558 
559 	if ((start | end) & (vmp->vm_quantum - 1))
560 		panic("vmem_span_create(%p, %p, %lu): misaligned",
561 		    (void *)vmp, vaddr, size);
562 
563 	span = vmem_seg_create(vmp, vmp->vm_seg0.vs_aprev, start, end);
564 	span->vs_type = VMEM_SPAN;
565 	span->vs_import = import;
566 	VMEM_INSERT(vmp->vm_seg0.vs_kprev, span, k);
567 
568 	newseg = vmem_seg_create(vmp, span, start, end);
569 	vmem_freelist_insert(vmp, newseg);
570 
571 	if (import)
572 		vmp->vm_kstat.vk_mem_import.value.ui64 += size;
573 	vmp->vm_kstat.vk_mem_total.value.ui64 += size;
574 
575 	return (newseg);
576 }
577 
578 /*
579  * Remove span vsp from vmp and update kstats.
580  */
581 static void
582 vmem_span_destroy(vmem_t *vmp, vmem_seg_t *vsp)
583 {
584 	vmem_seg_t *span = vsp->vs_aprev;
585 	size_t size = VS_SIZE(vsp);
586 
587 	ASSERT(MUTEX_HELD(&vmp->vm_lock));
588 	ASSERT(span->vs_type == VMEM_SPAN);
589 
590 	if (span->vs_import)
591 		vmp->vm_kstat.vk_mem_import.value.ui64 -= size;
592 	vmp->vm_kstat.vk_mem_total.value.ui64 -= size;
593 
594 	VMEM_DELETE(span, k);
595 
596 	vmem_seg_destroy(vmp, vsp);
597 	vmem_seg_destroy(vmp, span);
598 }
599 
600 /*
601  * Allocate the subrange [addr, addr + size) from segment vsp.
602  * If there are leftovers on either side, place them on the freelist.
603  * Returns a pointer to the segment representing [addr, addr + size).
604  */
605 static vmem_seg_t *
606 vmem_seg_alloc(vmem_t *vmp, vmem_seg_t *vsp, uintptr_t addr, size_t size)
607 {
608 	uintptr_t vs_start = vsp->vs_start;
609 	uintptr_t vs_end = vsp->vs_end;
610 	size_t vs_size = vs_end - vs_start;
611 	size_t realsize = P2ROUNDUP(size, vmp->vm_quantum);
612 	uintptr_t addr_end = addr + realsize;
613 
614 	ASSERT(P2PHASE(vs_start, vmp->vm_quantum) == 0);
615 	ASSERT(P2PHASE(addr, vmp->vm_quantum) == 0);
616 	ASSERT(vsp->vs_type == VMEM_FREE);
617 	ASSERT(addr >= vs_start && addr_end - 1 <= vs_end - 1);
618 	ASSERT(addr - 1 <= addr_end - 1);
619 
620 	/*
621 	 * If we're allocating from the start of the segment, and the
622 	 * remainder will be on the same freelist, we can save quite
623 	 * a bit of work.
624 	 */
625 	if (P2SAMEHIGHBIT(vs_size, vs_size - realsize) && addr == vs_start) {
626 		ASSERT(highbit(vs_size) == highbit(vs_size - realsize));
627 		vsp->vs_start = addr_end;
628 		vsp = vmem_seg_create(vmp, vsp->vs_aprev, addr, addr + size);
629 		vmem_hash_insert(vmp, vsp);
630 		return (vsp);
631 	}
632 
633 	vmem_freelist_delete(vmp, vsp);
634 
635 	if (vs_end != addr_end)
636 		vmem_freelist_insert(vmp,
637 		    vmem_seg_create(vmp, vsp, addr_end, vs_end));
638 
639 	if (vs_start != addr)
640 		vmem_freelist_insert(vmp,
641 		    vmem_seg_create(vmp, vsp->vs_aprev, vs_start, addr));
642 
643 	vsp->vs_start = addr;
644 	vsp->vs_end = addr + size;
645 
646 	vmem_hash_insert(vmp, vsp);
647 	return (vsp);
648 }
649 
650 /*
651  * Returns 1 if we are populating, 0 otherwise.
652  * Call it if we want to prevent recursion from HAT.
653  */
654 int
655 vmem_is_populator()
656 {
657 	return (mutex_owner(&vmem_sleep_lock) == curthread ||
658 	    mutex_owner(&vmem_nosleep_lock) == curthread ||
659 	    mutex_owner(&vmem_pushpage_lock) == curthread ||
660 	    mutex_owner(&vmem_panic_lock) == curthread);
661 }
662 
663 /*
664  * Populate vmp's segfree list with VMEM_MINFREE vmem_seg_t structures.
665  */
666 static int
667 vmem_populate(vmem_t *vmp, int vmflag)
668 {
669 	char *p;
670 	vmem_seg_t *vsp;
671 	ssize_t nseg;
672 	size_t size;
673 	kmutex_t *lp;
674 	int i;
675 
676 	while (vmp->vm_nsegfree < VMEM_MINFREE &&
677 	    (vsp = vmem_getseg_global()) != NULL)
678 		vmem_putseg(vmp, vsp);
679 
680 	if (vmp->vm_nsegfree >= VMEM_MINFREE)
681 		return (1);
682 
683 	/*
684 	 * If we're already populating, tap the reserve.
685 	 */
686 	if (vmem_is_populator()) {
687 		ASSERT(vmp->vm_cflags & VMC_POPULATOR);
688 		return (1);
689 	}
690 
691 	mutex_exit(&vmp->vm_lock);
692 
693 	if (panic_thread == curthread)
694 		lp = &vmem_panic_lock;
695 	else if (vmflag & VM_NOSLEEP)
696 		lp = &vmem_nosleep_lock;
697 	else if (vmflag & VM_PUSHPAGE)
698 		lp = &vmem_pushpage_lock;
699 	else
700 		lp = &vmem_sleep_lock;
701 
702 	mutex_enter(lp);
703 
704 	nseg = VMEM_MINFREE + vmem_populators * VMEM_POPULATE_RESERVE;
705 	size = P2ROUNDUP(nseg * vmem_seg_size, vmem_seg_arena->vm_quantum);
706 	nseg = size / vmem_seg_size;
707 
708 	/*
709 	 * The following vmem_alloc() may need to populate vmem_seg_arena
710 	 * and all the things it imports from.  When doing so, it will tap
711 	 * each arena's reserve to prevent recursion (see the block comment
712 	 * above the definition of VMEM_POPULATE_RESERVE).
713 	 */
714 	p = vmem_alloc(vmem_seg_arena, size, vmflag & VM_KMFLAGS);
715 	if (p == NULL) {
716 		mutex_exit(lp);
717 		mutex_enter(&vmp->vm_lock);
718 		vmp->vm_kstat.vk_populate_fail.value.ui64++;
719 		return (0);
720 	}
721 
722 	/*
723 	 * Restock the arenas that may have been depleted during population.
724 	 */
725 	for (i = 0; i < vmem_populators; i++) {
726 		mutex_enter(&vmem_populator[i]->vm_lock);
727 		while (vmem_populator[i]->vm_nsegfree < VMEM_POPULATE_RESERVE)
728 			vmem_putseg(vmem_populator[i],
729 			    (vmem_seg_t *)(p + --nseg * vmem_seg_size));
730 		mutex_exit(&vmem_populator[i]->vm_lock);
731 	}
732 
733 	mutex_exit(lp);
734 	mutex_enter(&vmp->vm_lock);
735 
736 	/*
737 	 * Now take our own segments.
738 	 */
739 	ASSERT(nseg >= VMEM_MINFREE);
740 	while (vmp->vm_nsegfree < VMEM_MINFREE)
741 		vmem_putseg(vmp, (vmem_seg_t *)(p + --nseg * vmem_seg_size));
742 
743 	/*
744 	 * Give the remainder to charity.
745 	 */
746 	while (nseg > 0)
747 		vmem_putseg_global((vmem_seg_t *)(p + --nseg * vmem_seg_size));
748 
749 	return (1);
750 }
751 
752 /*
753  * Advance a walker from its previous position to 'afterme'.
754  * Note: may drop and reacquire vmp->vm_lock.
755  */
756 static void
757 vmem_advance(vmem_t *vmp, vmem_seg_t *walker, vmem_seg_t *afterme)
758 {
759 	vmem_seg_t *vprev = walker->vs_aprev;
760 	vmem_seg_t *vnext = walker->vs_anext;
761 	vmem_seg_t *vsp = NULL;
762 
763 	VMEM_DELETE(walker, a);
764 
765 	if (afterme != NULL)
766 		VMEM_INSERT(afterme, walker, a);
767 
768 	/*
769 	 * The walker segment's presence may have prevented its neighbors
770 	 * from coalescing.  If so, coalesce them now.
771 	 */
772 	if (vprev->vs_type == VMEM_FREE) {
773 		if (vnext->vs_type == VMEM_FREE) {
774 			ASSERT(vprev->vs_end == vnext->vs_start);
775 			vmem_freelist_delete(vmp, vnext);
776 			vmem_freelist_delete(vmp, vprev);
777 			vprev->vs_end = vnext->vs_end;
778 			vmem_freelist_insert(vmp, vprev);
779 			vmem_seg_destroy(vmp, vnext);
780 		}
781 		vsp = vprev;
782 	} else if (vnext->vs_type == VMEM_FREE) {
783 		vsp = vnext;
784 	}
785 
786 	/*
787 	 * vsp could represent a complete imported span,
788 	 * in which case we must return it to the source.
789 	 */
790 	if (vsp != NULL && vsp->vs_aprev->vs_import &&
791 	    vmp->vm_source_free != NULL &&
792 	    vsp->vs_aprev->vs_type == VMEM_SPAN &&
793 	    vsp->vs_anext->vs_type == VMEM_SPAN) {
794 		void *vaddr = (void *)vsp->vs_start;
795 		size_t size = VS_SIZE(vsp);
796 		ASSERT(size == VS_SIZE(vsp->vs_aprev));
797 		vmem_freelist_delete(vmp, vsp);
798 		vmem_span_destroy(vmp, vsp);
799 		mutex_exit(&vmp->vm_lock);
800 		vmp->vm_source_free(vmp->vm_source, vaddr, size);
801 		mutex_enter(&vmp->vm_lock);
802 	}
803 }
804 
805 /*
806  * VM_NEXTFIT allocations deliberately cycle through all virtual addresses
807  * in an arena, so that we avoid reusing addresses for as long as possible.
808  * This helps to catch used-after-freed bugs.  It's also the perfect policy
809  * for allocating things like process IDs, where we want to cycle through
810  * all values in order.
811  */
812 static void *
813 vmem_nextfit_alloc(vmem_t *vmp, size_t size, int vmflag)
814 {
815 	vmem_seg_t *vsp, *rotor;
816 	uintptr_t addr;
817 	size_t realsize = P2ROUNDUP(size, vmp->vm_quantum);
818 	size_t vs_size;
819 
820 	mutex_enter(&vmp->vm_lock);
821 
822 	if (vmp->vm_nsegfree < VMEM_MINFREE && !vmem_populate(vmp, vmflag)) {
823 		mutex_exit(&vmp->vm_lock);
824 		return (NULL);
825 	}
826 
827 	/*
828 	 * The common case is that the segment right after the rotor is free,
829 	 * and large enough that extracting 'size' bytes won't change which
830 	 * freelist it's on.  In this case we can avoid a *lot* of work.
831 	 * Instead of the normal vmem_seg_alloc(), we just advance the start
832 	 * address of the victim segment.  Instead of moving the rotor, we
833 	 * create the new segment structure *behind the rotor*, which has
834 	 * the same effect.  And finally, we know we don't have to coalesce
835 	 * the rotor's neighbors because the new segment lies between them.
836 	 */
837 	rotor = &vmp->vm_rotor;
838 	vsp = rotor->vs_anext;
839 	if (vsp->vs_type == VMEM_FREE && (vs_size = VS_SIZE(vsp)) > realsize &&
840 	    P2SAMEHIGHBIT(vs_size, vs_size - realsize)) {
841 		ASSERT(highbit(vs_size) == highbit(vs_size - realsize));
842 		addr = vsp->vs_start;
843 		vsp->vs_start = addr + realsize;
844 		vmem_hash_insert(vmp,
845 		    vmem_seg_create(vmp, rotor->vs_aprev, addr, addr + size));
846 		mutex_exit(&vmp->vm_lock);
847 		return ((void *)addr);
848 	}
849 
850 	/*
851 	 * Starting at the rotor, look for a segment large enough to
852 	 * satisfy the allocation.
853 	 */
854 	for (;;) {
855 		vmp->vm_kstat.vk_search.value.ui64++;
856 		if (vsp->vs_type == VMEM_FREE && VS_SIZE(vsp) >= size)
857 			break;
858 		vsp = vsp->vs_anext;
859 		if (vsp == rotor) {
860 			/*
861 			 * We've come full circle.  One possibility is that the
862 			 * there's actually enough space, but the rotor itself
863 			 * is preventing the allocation from succeeding because
864 			 * it's sitting between two free segments.  Therefore,
865 			 * we advance the rotor and see if that liberates a
866 			 * suitable segment.
867 			 */
868 			vmem_advance(vmp, rotor, rotor->vs_anext);
869 			vsp = rotor->vs_aprev;
870 			if (vsp->vs_type == VMEM_FREE && VS_SIZE(vsp) >= size)
871 				break;
872 			/*
873 			 * If there's a lower arena we can import from, or it's
874 			 * a VM_NOSLEEP allocation, let vmem_xalloc() handle it.
875 			 * Otherwise, wait until another thread frees something.
876 			 */
877 			if (vmp->vm_source_alloc != NULL ||
878 			    (vmflag & VM_NOSLEEP)) {
879 				mutex_exit(&vmp->vm_lock);
880 				return (vmem_xalloc(vmp, size, vmp->vm_quantum,
881 				    0, 0, NULL, NULL, vmflag & VM_KMFLAGS));
882 			}
883 			vmp->vm_kstat.vk_wait.value.ui64++;
884 			cv_wait(&vmp->vm_cv, &vmp->vm_lock);
885 			vsp = rotor->vs_anext;
886 		}
887 	}
888 
889 	/*
890 	 * We found a segment.  Extract enough space to satisfy the allocation.
891 	 */
892 	addr = vsp->vs_start;
893 	vsp = vmem_seg_alloc(vmp, vsp, addr, size);
894 	ASSERT(vsp->vs_type == VMEM_ALLOC &&
895 	    vsp->vs_start == addr && vsp->vs_end == addr + size);
896 
897 	/*
898 	 * Advance the rotor to right after the newly-allocated segment.
899 	 * That's where the next VM_NEXTFIT allocation will begin searching.
900 	 */
901 	vmem_advance(vmp, rotor, vsp);
902 	mutex_exit(&vmp->vm_lock);
903 	return ((void *)addr);
904 }
905 
906 /*
907  * Checks if vmp is guaranteed to have a size-byte buffer somewhere on its
908  * freelist.  If size is not a power-of-2, it can return a false-negative.
909  *
910  * Used to decide if a newly imported span is superfluous after re-acquiring
911  * the arena lock.
912  */
913 static int
914 vmem_canalloc(vmem_t *vmp, size_t size)
915 {
916 	int hb;
917 	int flist = 0;
918 	ASSERT(MUTEX_HELD(&vmp->vm_lock));
919 
920 	if ((size & (size - 1)) == 0)
921 		flist = lowbit(P2ALIGN(vmp->vm_freemap, size));
922 	else if ((hb = highbit(size)) < VMEM_FREELISTS)
923 		flist = lowbit(P2ALIGN(vmp->vm_freemap, 1UL << hb));
924 
925 	return (flist);
926 }
927 
928 /*
929  * Allocate size bytes at offset phase from an align boundary such that the
930  * resulting segment [addr, addr + size) is a subset of [minaddr, maxaddr)
931  * that does not straddle a nocross-aligned boundary.
932  */
933 void *
934 vmem_xalloc(vmem_t *vmp, size_t size, size_t align_arg, size_t phase,
935 	size_t nocross, void *minaddr, void *maxaddr, int vmflag)
936 {
937 	vmem_seg_t *vsp;
938 	vmem_seg_t *vbest = NULL;
939 	uintptr_t addr, taddr, start, end;
940 	uintptr_t align = (align_arg != 0) ? align_arg : vmp->vm_quantum;
941 	void *vaddr, *xvaddr = NULL;
942 	size_t xsize;
943 	int hb, flist, resv;
944 	uint32_t mtbf;
945 
946 	if ((align | phase | nocross) & (vmp->vm_quantum - 1))
947 		panic("vmem_xalloc(%p, %lu, %lu, %lu, %lu, %p, %p, %x): "
948 		    "parameters not vm_quantum aligned",
949 		    (void *)vmp, size, align_arg, phase, nocross,
950 		    minaddr, maxaddr, vmflag);
951 
952 	if (nocross != 0 &&
953 	    (align > nocross || P2ROUNDUP(phase + size, align) > nocross))
954 		panic("vmem_xalloc(%p, %lu, %lu, %lu, %lu, %p, %p, %x): "
955 		    "overconstrained allocation",
956 		    (void *)vmp, size, align_arg, phase, nocross,
957 		    minaddr, maxaddr, vmflag);
958 
959 	if (phase >= align || (align & (align - 1)) != 0 ||
960 	    (nocross & (nocross - 1)) != 0)
961 		panic("vmem_xalloc(%p, %lu, %lu, %lu, %lu, %p, %p, %x): "
962 		    "parameters inconsistent or invalid",
963 		    (void *)vmp, size, align_arg, phase, nocross,
964 		    minaddr, maxaddr, vmflag);
965 
966 	if ((mtbf = vmem_mtbf | vmp->vm_mtbf) != 0 && gethrtime() % mtbf == 0 &&
967 	    (vmflag & (VM_NOSLEEP | VM_PANIC)) == VM_NOSLEEP)
968 		return (NULL);
969 
970 	mutex_enter(&vmp->vm_lock);
971 	for (;;) {
972 		if (vmp->vm_nsegfree < VMEM_MINFREE &&
973 		    !vmem_populate(vmp, vmflag))
974 			break;
975 do_alloc:
976 		/*
977 		 * highbit() returns the highest bit + 1, which is exactly
978 		 * what we want: we want to search the first freelist whose
979 		 * members are *definitely* large enough to satisfy our
980 		 * allocation.  However, there are certain cases in which we
981 		 * want to look at the next-smallest freelist (which *might*
982 		 * be able to satisfy the allocation):
983 		 *
984 		 * (1)	The size is exactly a power of 2, in which case
985 		 *	the smaller freelist is always big enough;
986 		 *
987 		 * (2)	All other freelists are empty;
988 		 *
989 		 * (3)	We're in the highest possible freelist, which is
990 		 *	always empty (e.g. the 4GB freelist on 32-bit systems);
991 		 *
992 		 * (4)	We're doing a best-fit or first-fit allocation.
993 		 */
994 		if ((size & (size - 1)) == 0) {
995 			flist = lowbit(P2ALIGN(vmp->vm_freemap, size));
996 		} else {
997 			hb = highbit(size);
998 			if ((vmp->vm_freemap >> hb) == 0 ||
999 			    hb == VMEM_FREELISTS ||
1000 			    (vmflag & (VM_BESTFIT | VM_FIRSTFIT)))
1001 				hb--;
1002 			flist = lowbit(P2ALIGN(vmp->vm_freemap, 1UL << hb));
1003 		}
1004 
1005 		for (vbest = NULL, vsp = (flist == 0) ? NULL :
1006 		    vmp->vm_freelist[flist - 1].vs_knext;
1007 		    vsp != NULL; vsp = vsp->vs_knext) {
1008 			vmp->vm_kstat.vk_search.value.ui64++;
1009 			if (vsp->vs_start == 0) {
1010 				/*
1011 				 * We're moving up to a larger freelist,
1012 				 * so if we've already found a candidate,
1013 				 * the fit can't possibly get any better.
1014 				 */
1015 				if (vbest != NULL)
1016 					break;
1017 				/*
1018 				 * Find the next non-empty freelist.
1019 				 */
1020 				flist = lowbit(P2ALIGN(vmp->vm_freemap,
1021 				    VS_SIZE(vsp)));
1022 				if (flist-- == 0)
1023 					break;
1024 				vsp = (vmem_seg_t *)&vmp->vm_freelist[flist];
1025 				ASSERT(vsp->vs_knext->vs_type == VMEM_FREE);
1026 				continue;
1027 			}
1028 			if (vsp->vs_end - 1 < (uintptr_t)minaddr)
1029 				continue;
1030 			if (vsp->vs_start > (uintptr_t)maxaddr - 1)
1031 				continue;
1032 			start = MAX(vsp->vs_start, (uintptr_t)minaddr);
1033 			end = MIN(vsp->vs_end - 1, (uintptr_t)maxaddr - 1) + 1;
1034 			taddr = P2PHASEUP(start, align, phase);
1035 			if (P2CROSS(taddr, taddr + size - 1, nocross))
1036 				taddr +=
1037 				    P2ROUNDUP(P2NPHASE(taddr, nocross), align);
1038 			if ((taddr - start) + size > end - start ||
1039 			    (vbest != NULL && VS_SIZE(vsp) >= VS_SIZE(vbest)))
1040 				continue;
1041 			vbest = vsp;
1042 			addr = taddr;
1043 			if (!(vmflag & VM_BESTFIT) || VS_SIZE(vbest) == size)
1044 				break;
1045 		}
1046 		if (vbest != NULL)
1047 			break;
1048 		ASSERT(xvaddr == NULL);
1049 		if (size == 0)
1050 			panic("vmem_xalloc(): size == 0");
1051 		if (vmp->vm_source_alloc != NULL && nocross == 0 &&
1052 		    minaddr == NULL && maxaddr == NULL) {
1053 			size_t aneeded, asize;
1054 			size_t aquantum = MAX(vmp->vm_quantum,
1055 			    vmp->vm_source->vm_quantum);
1056 			size_t aphase = phase;
1057 			if ((align > aquantum) &&
1058 			    !(vmp->vm_cflags & VMC_XALIGN)) {
1059 				aphase = (P2PHASE(phase, aquantum) != 0) ?
1060 				    align - vmp->vm_quantum : align - aquantum;
1061 				ASSERT(aphase >= phase);
1062 			}
1063 			aneeded = MAX(size + aphase, vmp->vm_min_import);
1064 			asize = P2ROUNDUP(aneeded, aquantum);
1065 
1066 			/*
1067 			 * Determine how many segment structures we'll consume.
1068 			 * The calculation must be precise because if we're
1069 			 * here on behalf of vmem_populate(), we are taking
1070 			 * segments from a very limited reserve.
1071 			 */
1072 			if (size == asize && !(vmp->vm_cflags & VMC_XALLOC))
1073 				resv = VMEM_SEGS_PER_SPAN_CREATE +
1074 				    VMEM_SEGS_PER_EXACT_ALLOC;
1075 			else if (phase == 0 &&
1076 			    align <= vmp->vm_source->vm_quantum)
1077 				resv = VMEM_SEGS_PER_SPAN_CREATE +
1078 				    VMEM_SEGS_PER_LEFT_ALLOC;
1079 			else
1080 				resv = VMEM_SEGS_PER_ALLOC_MAX;
1081 
1082 			ASSERT(vmp->vm_nsegfree >= resv);
1083 			vmp->vm_nsegfree -= resv;	/* reserve our segs */
1084 			mutex_exit(&vmp->vm_lock);
1085 			if (vmp->vm_cflags & VMC_XALLOC) {
1086 				size_t oasize = asize;
1087 				vaddr = ((vmem_ximport_t *)
1088 				    vmp->vm_source_alloc)(vmp->vm_source,
1089 				    &asize, align, vmflag & VM_KMFLAGS);
1090 				ASSERT(asize >= oasize);
1091 				ASSERT(P2PHASE(asize,
1092 				    vmp->vm_source->vm_quantum) == 0);
1093 				ASSERT(!(vmp->vm_cflags & VMC_XALIGN) ||
1094 				    IS_P2ALIGNED(vaddr, align));
1095 			} else {
1096 				vaddr = vmp->vm_source_alloc(vmp->vm_source,
1097 				    asize, vmflag & VM_KMFLAGS);
1098 			}
1099 			mutex_enter(&vmp->vm_lock);
1100 			vmp->vm_nsegfree += resv;	/* claim reservation */
1101 			aneeded = size + align - vmp->vm_quantum;
1102 			aneeded = P2ROUNDUP(aneeded, vmp->vm_quantum);
1103 			if (vaddr != NULL) {
1104 				/*
1105 				 * Since we dropped the vmem lock while
1106 				 * calling the import function, other
1107 				 * threads could have imported space
1108 				 * and made our import unnecessary.  In
1109 				 * order to save space, we return
1110 				 * excess imports immediately.
1111 				 */
1112 				if (asize > aneeded &&
1113 				    vmp->vm_source_free != NULL &&
1114 				    vmem_canalloc(vmp, aneeded)) {
1115 					ASSERT(resv >=
1116 					    VMEM_SEGS_PER_MIDDLE_ALLOC);
1117 					xvaddr = vaddr;
1118 					xsize = asize;
1119 					goto do_alloc;
1120 				}
1121 				vbest = vmem_span_create(vmp, vaddr, asize, 1);
1122 				addr = P2PHASEUP(vbest->vs_start, align, phase);
1123 				break;
1124 			} else if (vmem_canalloc(vmp, aneeded)) {
1125 				/*
1126 				 * Our import failed, but another thread
1127 				 * added sufficient free memory to the arena
1128 				 * to satisfy our request.  Go back and
1129 				 * grab it.
1130 				 */
1131 				ASSERT(resv >= VMEM_SEGS_PER_MIDDLE_ALLOC);
1132 				goto do_alloc;
1133 			}
1134 		}
1135 
1136 		/*
1137 		 * If the requestor chooses to fail the allocation attempt
1138 		 * rather than reap wait and retry - get out of the loop.
1139 		 */
1140 		if (vmflag & VM_ABORT)
1141 			break;
1142 		mutex_exit(&vmp->vm_lock);
1143 		if (vmp->vm_cflags & VMC_IDENTIFIER)
1144 			kmem_reap_idspace();
1145 		else
1146 			kmem_reap();
1147 		mutex_enter(&vmp->vm_lock);
1148 		if (vmflag & VM_NOSLEEP)
1149 			break;
1150 		vmp->vm_kstat.vk_wait.value.ui64++;
1151 		cv_wait(&vmp->vm_cv, &vmp->vm_lock);
1152 	}
1153 	if (vbest != NULL) {
1154 		ASSERT(vbest->vs_type == VMEM_FREE);
1155 		ASSERT(vbest->vs_knext != vbest);
1156 		(void) vmem_seg_alloc(vmp, vbest, addr, size);
1157 		mutex_exit(&vmp->vm_lock);
1158 		if (xvaddr)
1159 			vmp->vm_source_free(vmp->vm_source, xvaddr, xsize);
1160 		ASSERT(P2PHASE(addr, align) == phase);
1161 		ASSERT(!P2CROSS(addr, addr + size - 1, nocross));
1162 		ASSERT(addr >= (uintptr_t)minaddr);
1163 		ASSERT(addr + size - 1 <= (uintptr_t)maxaddr - 1);
1164 		return ((void *)addr);
1165 	}
1166 	vmp->vm_kstat.vk_fail.value.ui64++;
1167 	mutex_exit(&vmp->vm_lock);
1168 	if (vmflag & VM_PANIC)
1169 		panic("vmem_xalloc(%p, %lu, %lu, %lu, %lu, %p, %p, %x): "
1170 		    "cannot satisfy mandatory allocation",
1171 		    (void *)vmp, size, align_arg, phase, nocross,
1172 		    minaddr, maxaddr, vmflag);
1173 	ASSERT(xvaddr == NULL);
1174 	return (NULL);
1175 }
1176 
1177 /*
1178  * Free the segment [vaddr, vaddr + size), where vaddr was a constrained
1179  * allocation.  vmem_xalloc() and vmem_xfree() must always be paired because
1180  * both routines bypass the quantum caches.
1181  */
1182 void
1183 vmem_xfree(vmem_t *vmp, void *vaddr, size_t size)
1184 {
1185 	vmem_seg_t *vsp, *vnext, *vprev;
1186 
1187 	mutex_enter(&vmp->vm_lock);
1188 
1189 	vsp = vmem_hash_delete(vmp, (uintptr_t)vaddr, size);
1190 	vsp->vs_end = P2ROUNDUP(vsp->vs_end, vmp->vm_quantum);
1191 
1192 	/*
1193 	 * Attempt to coalesce with the next segment.
1194 	 */
1195 	vnext = vsp->vs_anext;
1196 	if (vnext->vs_type == VMEM_FREE) {
1197 		ASSERT(vsp->vs_end == vnext->vs_start);
1198 		vmem_freelist_delete(vmp, vnext);
1199 		vsp->vs_end = vnext->vs_end;
1200 		vmem_seg_destroy(vmp, vnext);
1201 	}
1202 
1203 	/*
1204 	 * Attempt to coalesce with the previous segment.
1205 	 */
1206 	vprev = vsp->vs_aprev;
1207 	if (vprev->vs_type == VMEM_FREE) {
1208 		ASSERT(vprev->vs_end == vsp->vs_start);
1209 		vmem_freelist_delete(vmp, vprev);
1210 		vprev->vs_end = vsp->vs_end;
1211 		vmem_seg_destroy(vmp, vsp);
1212 		vsp = vprev;
1213 	}
1214 
1215 	/*
1216 	 * If the entire span is free, return it to the source.
1217 	 */
1218 	if (vsp->vs_aprev->vs_import && vmp->vm_source_free != NULL &&
1219 	    vsp->vs_aprev->vs_type == VMEM_SPAN &&
1220 	    vsp->vs_anext->vs_type == VMEM_SPAN) {
1221 		vaddr = (void *)vsp->vs_start;
1222 		size = VS_SIZE(vsp);
1223 		ASSERT(size == VS_SIZE(vsp->vs_aprev));
1224 		vmem_span_destroy(vmp, vsp);
1225 		mutex_exit(&vmp->vm_lock);
1226 		vmp->vm_source_free(vmp->vm_source, vaddr, size);
1227 	} else {
1228 		vmem_freelist_insert(vmp, vsp);
1229 		mutex_exit(&vmp->vm_lock);
1230 	}
1231 }
1232 
1233 /*
1234  * Allocate size bytes from arena vmp.  Returns the allocated address
1235  * on success, NULL on failure.  vmflag specifies VM_SLEEP or VM_NOSLEEP,
1236  * and may also specify best-fit, first-fit, or next-fit allocation policy
1237  * instead of the default instant-fit policy.  VM_SLEEP allocations are
1238  * guaranteed to succeed.
1239  */
1240 void *
1241 vmem_alloc(vmem_t *vmp, size_t size, int vmflag)
1242 {
1243 	vmem_seg_t *vsp;
1244 	uintptr_t addr;
1245 	int hb;
1246 	int flist = 0;
1247 	uint32_t mtbf;
1248 
1249 	if (size - 1 < vmp->vm_qcache_max)
1250 		return (kmem_cache_alloc(vmp->vm_qcache[(size - 1) >>
1251 		    vmp->vm_qshift], vmflag & VM_KMFLAGS));
1252 
1253 	if ((mtbf = vmem_mtbf | vmp->vm_mtbf) != 0 && gethrtime() % mtbf == 0 &&
1254 	    (vmflag & (VM_NOSLEEP | VM_PANIC)) == VM_NOSLEEP)
1255 		return (NULL);
1256 
1257 	if (vmflag & VM_NEXTFIT)
1258 		return (vmem_nextfit_alloc(vmp, size, vmflag));
1259 
1260 	if (vmflag & (VM_BESTFIT | VM_FIRSTFIT))
1261 		return (vmem_xalloc(vmp, size, vmp->vm_quantum, 0, 0,
1262 		    NULL, NULL, vmflag));
1263 
1264 	/*
1265 	 * Unconstrained instant-fit allocation from the segment list.
1266 	 */
1267 	mutex_enter(&vmp->vm_lock);
1268 
1269 	if (vmp->vm_nsegfree >= VMEM_MINFREE || vmem_populate(vmp, vmflag)) {
1270 		if ((size & (size - 1)) == 0)
1271 			flist = lowbit(P2ALIGN(vmp->vm_freemap, size));
1272 		else if ((hb = highbit(size)) < VMEM_FREELISTS)
1273 			flist = lowbit(P2ALIGN(vmp->vm_freemap, 1UL << hb));
1274 	}
1275 
1276 	if (flist-- == 0) {
1277 		mutex_exit(&vmp->vm_lock);
1278 		return (vmem_xalloc(vmp, size, vmp->vm_quantum,
1279 		    0, 0, NULL, NULL, vmflag));
1280 	}
1281 
1282 	ASSERT(size <= (1UL << flist));
1283 	vsp = vmp->vm_freelist[flist].vs_knext;
1284 	addr = vsp->vs_start;
1285 	(void) vmem_seg_alloc(vmp, vsp, addr, size);
1286 	mutex_exit(&vmp->vm_lock);
1287 	return ((void *)addr);
1288 }
1289 
1290 /*
1291  * Free the segment [vaddr, vaddr + size).
1292  */
1293 void
1294 vmem_free(vmem_t *vmp, void *vaddr, size_t size)
1295 {
1296 	if (size - 1 < vmp->vm_qcache_max)
1297 		kmem_cache_free(vmp->vm_qcache[(size - 1) >> vmp->vm_qshift],
1298 		    vaddr);
1299 	else
1300 		vmem_xfree(vmp, vaddr, size);
1301 }
1302 
1303 /*
1304  * Determine whether arena vmp contains the segment [vaddr, vaddr + size).
1305  */
1306 int
1307 vmem_contains(vmem_t *vmp, void *vaddr, size_t size)
1308 {
1309 	uintptr_t start = (uintptr_t)vaddr;
1310 	uintptr_t end = start + size;
1311 	vmem_seg_t *vsp;
1312 	vmem_seg_t *seg0 = &vmp->vm_seg0;
1313 
1314 	mutex_enter(&vmp->vm_lock);
1315 	vmp->vm_kstat.vk_contains.value.ui64++;
1316 	for (vsp = seg0->vs_knext; vsp != seg0; vsp = vsp->vs_knext) {
1317 		vmp->vm_kstat.vk_contains_search.value.ui64++;
1318 		ASSERT(vsp->vs_type == VMEM_SPAN);
1319 		if (start >= vsp->vs_start && end - 1 <= vsp->vs_end - 1)
1320 			break;
1321 	}
1322 	mutex_exit(&vmp->vm_lock);
1323 	return (vsp != seg0);
1324 }
1325 
1326 /*
1327  * Add the span [vaddr, vaddr + size) to arena vmp.
1328  */
1329 void *
1330 vmem_add(vmem_t *vmp, void *vaddr, size_t size, int vmflag)
1331 {
1332 	if (vaddr == NULL || size == 0)
1333 		panic("vmem_add(%p, %p, %lu): bad arguments",
1334 		    (void *)vmp, vaddr, size);
1335 
1336 	ASSERT(!vmem_contains(vmp, vaddr, size));
1337 
1338 	mutex_enter(&vmp->vm_lock);
1339 	if (vmem_populate(vmp, vmflag))
1340 		(void) vmem_span_create(vmp, vaddr, size, 0);
1341 	else
1342 		vaddr = NULL;
1343 	mutex_exit(&vmp->vm_lock);
1344 	return (vaddr);
1345 }
1346 
1347 /*
1348  * Walk the vmp arena, applying func to each segment matching typemask.
1349  * If VMEM_REENTRANT is specified, the arena lock is dropped across each
1350  * call to func(); otherwise, it is held for the duration of vmem_walk()
1351  * to ensure a consistent snapshot.  Note that VMEM_REENTRANT callbacks
1352  * are *not* necessarily consistent, so they may only be used when a hint
1353  * is adequate.
1354  */
1355 void
1356 vmem_walk(vmem_t *vmp, int typemask,
1357 	void (*func)(void *, void *, size_t), void *arg)
1358 {
1359 	vmem_seg_t *vsp;
1360 	vmem_seg_t *seg0 = &vmp->vm_seg0;
1361 	vmem_seg_t walker;
1362 
1363 	if (typemask & VMEM_WALKER)
1364 		return;
1365 
1366 	bzero(&walker, sizeof (walker));
1367 	walker.vs_type = VMEM_WALKER;
1368 
1369 	mutex_enter(&vmp->vm_lock);
1370 	VMEM_INSERT(seg0, &walker, a);
1371 	for (vsp = seg0->vs_anext; vsp != seg0; vsp = vsp->vs_anext) {
1372 		if (vsp->vs_type & typemask) {
1373 			void *start = (void *)vsp->vs_start;
1374 			size_t size = VS_SIZE(vsp);
1375 			if (typemask & VMEM_REENTRANT) {
1376 				vmem_advance(vmp, &walker, vsp);
1377 				mutex_exit(&vmp->vm_lock);
1378 				func(arg, start, size);
1379 				mutex_enter(&vmp->vm_lock);
1380 				vsp = &walker;
1381 			} else {
1382 				func(arg, start, size);
1383 			}
1384 		}
1385 	}
1386 	vmem_advance(vmp, &walker, NULL);
1387 	mutex_exit(&vmp->vm_lock);
1388 }
1389 
1390 /*
1391  * Return the total amount of memory whose type matches typemask.  Thus:
1392  *
1393  *	typemask VMEM_ALLOC yields total memory allocated (in use).
1394  *	typemask VMEM_FREE yields total memory free (available).
1395  *	typemask (VMEM_ALLOC | VMEM_FREE) yields total arena size.
1396  */
1397 size_t
1398 vmem_size(vmem_t *vmp, int typemask)
1399 {
1400 	uint64_t size = 0;
1401 
1402 	if (typemask & VMEM_ALLOC)
1403 		size += vmp->vm_kstat.vk_mem_inuse.value.ui64;
1404 	if (typemask & VMEM_FREE)
1405 		size += vmp->vm_kstat.vk_mem_total.value.ui64 -
1406 		    vmp->vm_kstat.vk_mem_inuse.value.ui64;
1407 	return ((size_t)size);
1408 }
1409 
1410 /*
1411  * Create an arena called name whose initial span is [base, base + size).
1412  * The arena's natural unit of currency is quantum, so vmem_alloc()
1413  * guarantees quantum-aligned results.  The arena may import new spans
1414  * by invoking afunc() on source, and may return those spans by invoking
1415  * ffunc() on source.  To make small allocations fast and scalable,
1416  * the arena offers high-performance caching for each integer multiple
1417  * of quantum up to qcache_max.
1418  */
1419 static vmem_t *
1420 vmem_create_common(const char *name, void *base, size_t size, size_t quantum,
1421 	void *(*afunc)(vmem_t *, size_t, int),
1422 	void (*ffunc)(vmem_t *, void *, size_t),
1423 	vmem_t *source, size_t qcache_max, int vmflag)
1424 {
1425 	int i;
1426 	size_t nqcache;
1427 	vmem_t *vmp, *cur, **vmpp;
1428 	vmem_seg_t *vsp;
1429 	vmem_freelist_t *vfp;
1430 	uint32_t id = atomic_add_32_nv(&vmem_id, 1);
1431 
1432 	if (vmem_vmem_arena != NULL) {
1433 		vmp = vmem_alloc(vmem_vmem_arena, sizeof (vmem_t),
1434 		    vmflag & VM_KMFLAGS);
1435 	} else {
1436 		ASSERT(id <= VMEM_INITIAL);
1437 		vmp = &vmem0[id - 1];
1438 	}
1439 
1440 	/* An identifier arena must inherit from another identifier arena */
1441 	ASSERT(source == NULL || ((source->vm_cflags & VMC_IDENTIFIER) ==
1442 	    (vmflag & VMC_IDENTIFIER)));
1443 
1444 	if (vmp == NULL)
1445 		return (NULL);
1446 	bzero(vmp, sizeof (vmem_t));
1447 
1448 	(void) snprintf(vmp->vm_name, VMEM_NAMELEN, "%s", name);
1449 	mutex_init(&vmp->vm_lock, NULL, MUTEX_DEFAULT, NULL);
1450 	cv_init(&vmp->vm_cv, NULL, CV_DEFAULT, NULL);
1451 	vmp->vm_cflags = vmflag;
1452 	vmflag &= VM_KMFLAGS;
1453 
1454 	vmp->vm_quantum = quantum;
1455 	vmp->vm_qshift = highbit(quantum) - 1;
1456 	nqcache = MIN(qcache_max >> vmp->vm_qshift, VMEM_NQCACHE_MAX);
1457 
1458 	for (i = 0; i <= VMEM_FREELISTS; i++) {
1459 		vfp = &vmp->vm_freelist[i];
1460 		vfp->vs_end = 1UL << i;
1461 		vfp->vs_knext = (vmem_seg_t *)(vfp + 1);
1462 		vfp->vs_kprev = (vmem_seg_t *)(vfp - 1);
1463 	}
1464 
1465 	vmp->vm_freelist[0].vs_kprev = NULL;
1466 	vmp->vm_freelist[VMEM_FREELISTS].vs_knext = NULL;
1467 	vmp->vm_freelist[VMEM_FREELISTS].vs_end = 0;
1468 	vmp->vm_hash_table = vmp->vm_hash0;
1469 	vmp->vm_hash_mask = VMEM_HASH_INITIAL - 1;
1470 	vmp->vm_hash_shift = highbit(vmp->vm_hash_mask);
1471 
1472 	vsp = &vmp->vm_seg0;
1473 	vsp->vs_anext = vsp;
1474 	vsp->vs_aprev = vsp;
1475 	vsp->vs_knext = vsp;
1476 	vsp->vs_kprev = vsp;
1477 	vsp->vs_type = VMEM_SPAN;
1478 
1479 	vsp = &vmp->vm_rotor;
1480 	vsp->vs_type = VMEM_ROTOR;
1481 	VMEM_INSERT(&vmp->vm_seg0, vsp, a);
1482 
1483 	bcopy(&vmem_kstat_template, &vmp->vm_kstat, sizeof (vmem_kstat_t));
1484 
1485 	vmp->vm_id = id;
1486 	if (source != NULL)
1487 		vmp->vm_kstat.vk_source_id.value.ui32 = source->vm_id;
1488 	vmp->vm_source = source;
1489 	vmp->vm_source_alloc = afunc;
1490 	vmp->vm_source_free = ffunc;
1491 
1492 	/*
1493 	 * Some arenas (like vmem_metadata and kmem_metadata) cannot
1494 	 * use quantum caching to lower fragmentation.  Instead, we
1495 	 * increase their imports, giving a similar effect.
1496 	 */
1497 	if (vmp->vm_cflags & VMC_NO_QCACHE) {
1498 		vmp->vm_min_import =
1499 		    VMEM_QCACHE_SLABSIZE(nqcache << vmp->vm_qshift);
1500 		nqcache = 0;
1501 	}
1502 
1503 	if (nqcache != 0) {
1504 		ASSERT(!(vmflag & VM_NOSLEEP));
1505 		vmp->vm_qcache_max = nqcache << vmp->vm_qshift;
1506 		for (i = 0; i < nqcache; i++) {
1507 			char buf[VMEM_NAMELEN + 21];
1508 			(void) sprintf(buf, "%s_%lu", vmp->vm_name,
1509 			    (i + 1) * quantum);
1510 			vmp->vm_qcache[i] = kmem_cache_create(buf,
1511 			    (i + 1) * quantum, quantum, NULL, NULL, NULL,
1512 			    NULL, vmp, KMC_QCACHE | KMC_NOTOUCH);
1513 		}
1514 	}
1515 
1516 	if ((vmp->vm_ksp = kstat_create("vmem", vmp->vm_id, vmp->vm_name,
1517 	    "vmem", KSTAT_TYPE_NAMED, sizeof (vmem_kstat_t) /
1518 	    sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL)) != NULL) {
1519 		vmp->vm_ksp->ks_data = &vmp->vm_kstat;
1520 		kstat_install(vmp->vm_ksp);
1521 	}
1522 
1523 	mutex_enter(&vmem_list_lock);
1524 	vmpp = &vmem_list;
1525 	while ((cur = *vmpp) != NULL)
1526 		vmpp = &cur->vm_next;
1527 	*vmpp = vmp;
1528 	mutex_exit(&vmem_list_lock);
1529 
1530 	if (vmp->vm_cflags & VMC_POPULATOR) {
1531 		ASSERT(vmem_populators < VMEM_INITIAL);
1532 		vmem_populator[atomic_add_32_nv(&vmem_populators, 1) - 1] = vmp;
1533 		mutex_enter(&vmp->vm_lock);
1534 		(void) vmem_populate(vmp, vmflag | VM_PANIC);
1535 		mutex_exit(&vmp->vm_lock);
1536 	}
1537 
1538 	if ((base || size) && vmem_add(vmp, base, size, vmflag) == NULL) {
1539 		vmem_destroy(vmp);
1540 		return (NULL);
1541 	}
1542 
1543 	return (vmp);
1544 }
1545 
1546 vmem_t *
1547 vmem_xcreate(const char *name, void *base, size_t size, size_t quantum,
1548     vmem_ximport_t *afunc, vmem_free_t *ffunc, vmem_t *source,
1549     size_t qcache_max, int vmflag)
1550 {
1551 	ASSERT(!(vmflag & (VMC_POPULATOR | VMC_XALLOC)));
1552 	vmflag &= ~(VMC_POPULATOR | VMC_XALLOC);
1553 
1554 	return (vmem_create_common(name, base, size, quantum,
1555 	    (vmem_alloc_t *)afunc, ffunc, source, qcache_max,
1556 	    vmflag | VMC_XALLOC));
1557 }
1558 
1559 vmem_t *
1560 vmem_create(const char *name, void *base, size_t size, size_t quantum,
1561     vmem_alloc_t *afunc, vmem_free_t *ffunc, vmem_t *source,
1562     size_t qcache_max, int vmflag)
1563 {
1564 	ASSERT(!(vmflag & (VMC_XALLOC | VMC_XALIGN)));
1565 	vmflag &= ~(VMC_XALLOC | VMC_XALIGN);
1566 
1567 	return (vmem_create_common(name, base, size, quantum,
1568 	    afunc, ffunc, source, qcache_max, vmflag));
1569 }
1570 
1571 /*
1572  * Destroy arena vmp.
1573  */
1574 void
1575 vmem_destroy(vmem_t *vmp)
1576 {
1577 	vmem_t *cur, **vmpp;
1578 	vmem_seg_t *seg0 = &vmp->vm_seg0;
1579 	vmem_seg_t *vsp;
1580 	size_t leaked;
1581 	int i;
1582 
1583 	mutex_enter(&vmem_list_lock);
1584 	vmpp = &vmem_list;
1585 	while ((cur = *vmpp) != vmp)
1586 		vmpp = &cur->vm_next;
1587 	*vmpp = vmp->vm_next;
1588 	mutex_exit(&vmem_list_lock);
1589 
1590 	for (i = 0; i < VMEM_NQCACHE_MAX; i++)
1591 		if (vmp->vm_qcache[i])
1592 			kmem_cache_destroy(vmp->vm_qcache[i]);
1593 
1594 	leaked = vmem_size(vmp, VMEM_ALLOC);
1595 	if (leaked != 0)
1596 		cmn_err(CE_WARN, "vmem_destroy('%s'): leaked %lu %s",
1597 		    vmp->vm_name, leaked, (vmp->vm_cflags & VMC_IDENTIFIER) ?
1598 		    "identifiers" : "bytes");
1599 
1600 	if (vmp->vm_hash_table != vmp->vm_hash0)
1601 		vmem_free(vmem_hash_arena, vmp->vm_hash_table,
1602 		    (vmp->vm_hash_mask + 1) * sizeof (void *));
1603 
1604 	/*
1605 	 * Give back the segment structures for anything that's left in the
1606 	 * arena, e.g. the primary spans and their free segments.
1607 	 */
1608 	VMEM_DELETE(&vmp->vm_rotor, a);
1609 	for (vsp = seg0->vs_anext; vsp != seg0; vsp = vsp->vs_anext)
1610 		vmem_putseg_global(vsp);
1611 
1612 	while (vmp->vm_nsegfree > 0)
1613 		vmem_putseg_global(vmem_getseg(vmp));
1614 
1615 	kstat_delete(vmp->vm_ksp);
1616 
1617 	mutex_destroy(&vmp->vm_lock);
1618 	cv_destroy(&vmp->vm_cv);
1619 	vmem_free(vmem_vmem_arena, vmp, sizeof (vmem_t));
1620 }
1621 
1622 /*
1623  * Resize vmp's hash table to keep the average lookup depth near 1.0.
1624  */
1625 static void
1626 vmem_hash_rescale(vmem_t *vmp)
1627 {
1628 	vmem_seg_t **old_table, **new_table, *vsp;
1629 	size_t old_size, new_size, h, nseg;
1630 
1631 	nseg = (size_t)(vmp->vm_kstat.vk_alloc.value.ui64 -
1632 	    vmp->vm_kstat.vk_free.value.ui64);
1633 
1634 	new_size = MAX(VMEM_HASH_INITIAL, 1 << (highbit(3 * nseg + 4) - 2));
1635 	old_size = vmp->vm_hash_mask + 1;
1636 
1637 	if ((old_size >> 1) <= new_size && new_size <= (old_size << 1))
1638 		return;
1639 
1640 	new_table = vmem_alloc(vmem_hash_arena, new_size * sizeof (void *),
1641 	    VM_NOSLEEP);
1642 	if (new_table == NULL)
1643 		return;
1644 	bzero(new_table, new_size * sizeof (void *));
1645 
1646 	mutex_enter(&vmp->vm_lock);
1647 
1648 	old_size = vmp->vm_hash_mask + 1;
1649 	old_table = vmp->vm_hash_table;
1650 
1651 	vmp->vm_hash_mask = new_size - 1;
1652 	vmp->vm_hash_table = new_table;
1653 	vmp->vm_hash_shift = highbit(vmp->vm_hash_mask);
1654 
1655 	for (h = 0; h < old_size; h++) {
1656 		vsp = old_table[h];
1657 		while (vsp != NULL) {
1658 			uintptr_t addr = vsp->vs_start;
1659 			vmem_seg_t *next_vsp = vsp->vs_knext;
1660 			vmem_seg_t **hash_bucket = VMEM_HASH(vmp, addr);
1661 			vsp->vs_knext = *hash_bucket;
1662 			*hash_bucket = vsp;
1663 			vsp = next_vsp;
1664 		}
1665 	}
1666 
1667 	mutex_exit(&vmp->vm_lock);
1668 
1669 	if (old_table != vmp->vm_hash0)
1670 		vmem_free(vmem_hash_arena, old_table,
1671 		    old_size * sizeof (void *));
1672 }
1673 
1674 /*
1675  * Perform periodic maintenance on all vmem arenas.
1676  */
1677 void
1678 vmem_update(void *dummy)
1679 {
1680 	vmem_t *vmp;
1681 
1682 	mutex_enter(&vmem_list_lock);
1683 	for (vmp = vmem_list; vmp != NULL; vmp = vmp->vm_next) {
1684 		/*
1685 		 * If threads are waiting for resources, wake them up
1686 		 * periodically so they can issue another kmem_reap()
1687 		 * to reclaim resources cached by the slab allocator.
1688 		 */
1689 		cv_broadcast(&vmp->vm_cv);
1690 
1691 		/*
1692 		 * Rescale the hash table to keep the hash chains short.
1693 		 */
1694 		vmem_hash_rescale(vmp);
1695 	}
1696 	mutex_exit(&vmem_list_lock);
1697 
1698 	(void) timeout(vmem_update, dummy, vmem_update_interval * hz);
1699 }
1700 
1701 /*
1702  * Prepare vmem for use.
1703  */
1704 vmem_t *
1705 vmem_init(const char *heap_name,
1706 	void *heap_start, size_t heap_size, size_t heap_quantum,
1707 	void *(*heap_alloc)(vmem_t *, size_t, int),
1708 	void (*heap_free)(vmem_t *, void *, size_t))
1709 {
1710 	uint32_t id;
1711 	int nseg = VMEM_SEG_INITIAL;
1712 	vmem_t *heap;
1713 
1714 	while (--nseg >= 0)
1715 		vmem_putseg_global(&vmem_seg0[nseg]);
1716 
1717 	heap = vmem_create(heap_name,
1718 	    heap_start, heap_size, heap_quantum,
1719 	    NULL, NULL, NULL, 0,
1720 	    VM_SLEEP | VMC_POPULATOR);
1721 
1722 	vmem_metadata_arena = vmem_create("vmem_metadata",
1723 	    NULL, 0, heap_quantum,
1724 	    vmem_alloc, vmem_free, heap, 8 * heap_quantum,
1725 	    VM_SLEEP | VMC_POPULATOR | VMC_NO_QCACHE);
1726 
1727 	vmem_seg_arena = vmem_create("vmem_seg",
1728 	    NULL, 0, heap_quantum,
1729 	    heap_alloc, heap_free, vmem_metadata_arena, 0,
1730 	    VM_SLEEP | VMC_POPULATOR);
1731 
1732 	vmem_hash_arena = vmem_create("vmem_hash",
1733 	    NULL, 0, 8,
1734 	    heap_alloc, heap_free, vmem_metadata_arena, 0,
1735 	    VM_SLEEP);
1736 
1737 	vmem_vmem_arena = vmem_create("vmem_vmem",
1738 	    vmem0, sizeof (vmem0), 1,
1739 	    heap_alloc, heap_free, vmem_metadata_arena, 0,
1740 	    VM_SLEEP);
1741 
1742 	for (id = 0; id < vmem_id; id++)
1743 		(void) vmem_xalloc(vmem_vmem_arena, sizeof (vmem_t),
1744 		    1, 0, 0, &vmem0[id], &vmem0[id + 1],
1745 		    VM_NOSLEEP | VM_BESTFIT | VM_PANIC);
1746 
1747 	return (heap);
1748 }
1749