xref: /titanic_41/usr/src/uts/common/os/vmem.c (revision ae5b046d8f8cec187d40041c4b74b43f561d5ac7)
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 		    vmp, addr, size);
507 	if (VS_SIZE(vsp) != size)
508 		panic("vmem_hash_delete(%p, %lx, %lu): wrong size (expect %lu)",
509 		    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 		    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", vmp, vaddr, size);
1334 
1335 	ASSERT(!vmem_contains(vmp, vaddr, size));
1336 
1337 	mutex_enter(&vmp->vm_lock);
1338 	if (vmem_populate(vmp, vmflag))
1339 		(void) vmem_span_create(vmp, vaddr, size, 0);
1340 	else
1341 		vaddr = NULL;
1342 	mutex_exit(&vmp->vm_lock);
1343 	return (vaddr);
1344 }
1345 
1346 /*
1347  * Walk the vmp arena, applying func to each segment matching typemask.
1348  * If VMEM_REENTRANT is specified, the arena lock is dropped across each
1349  * call to func(); otherwise, it is held for the duration of vmem_walk()
1350  * to ensure a consistent snapshot.  Note that VMEM_REENTRANT callbacks
1351  * are *not* necessarily consistent, so they may only be used when a hint
1352  * is adequate.
1353  */
1354 void
1355 vmem_walk(vmem_t *vmp, int typemask,
1356 	void (*func)(void *, void *, size_t), void *arg)
1357 {
1358 	vmem_seg_t *vsp;
1359 	vmem_seg_t *seg0 = &vmp->vm_seg0;
1360 	vmem_seg_t walker;
1361 
1362 	if (typemask & VMEM_WALKER)
1363 		return;
1364 
1365 	bzero(&walker, sizeof (walker));
1366 	walker.vs_type = VMEM_WALKER;
1367 
1368 	mutex_enter(&vmp->vm_lock);
1369 	VMEM_INSERT(seg0, &walker, a);
1370 	for (vsp = seg0->vs_anext; vsp != seg0; vsp = vsp->vs_anext) {
1371 		if (vsp->vs_type & typemask) {
1372 			void *start = (void *)vsp->vs_start;
1373 			size_t size = VS_SIZE(vsp);
1374 			if (typemask & VMEM_REENTRANT) {
1375 				vmem_advance(vmp, &walker, vsp);
1376 				mutex_exit(&vmp->vm_lock);
1377 				func(arg, start, size);
1378 				mutex_enter(&vmp->vm_lock);
1379 				vsp = &walker;
1380 			} else {
1381 				func(arg, start, size);
1382 			}
1383 		}
1384 	}
1385 	vmem_advance(vmp, &walker, NULL);
1386 	mutex_exit(&vmp->vm_lock);
1387 }
1388 
1389 /*
1390  * Return the total amount of memory whose type matches typemask.  Thus:
1391  *
1392  *	typemask VMEM_ALLOC yields total memory allocated (in use).
1393  *	typemask VMEM_FREE yields total memory free (available).
1394  *	typemask (VMEM_ALLOC | VMEM_FREE) yields total arena size.
1395  */
1396 size_t
1397 vmem_size(vmem_t *vmp, int typemask)
1398 {
1399 	uint64_t size = 0;
1400 
1401 	if (typemask & VMEM_ALLOC)
1402 		size += vmp->vm_kstat.vk_mem_inuse.value.ui64;
1403 	if (typemask & VMEM_FREE)
1404 		size += vmp->vm_kstat.vk_mem_total.value.ui64 -
1405 		    vmp->vm_kstat.vk_mem_inuse.value.ui64;
1406 	return ((size_t)size);
1407 }
1408 
1409 /*
1410  * Create an arena called name whose initial span is [base, base + size).
1411  * The arena's natural unit of currency is quantum, so vmem_alloc()
1412  * guarantees quantum-aligned results.  The arena may import new spans
1413  * by invoking afunc() on source, and may return those spans by invoking
1414  * ffunc() on source.  To make small allocations fast and scalable,
1415  * the arena offers high-performance caching for each integer multiple
1416  * of quantum up to qcache_max.
1417  */
1418 static vmem_t *
1419 vmem_create_common(const char *name, void *base, size_t size, size_t quantum,
1420 	void *(*afunc)(vmem_t *, size_t, int),
1421 	void (*ffunc)(vmem_t *, void *, size_t),
1422 	vmem_t *source, size_t qcache_max, int vmflag)
1423 {
1424 	int i;
1425 	size_t nqcache;
1426 	vmem_t *vmp, *cur, **vmpp;
1427 	vmem_seg_t *vsp;
1428 	vmem_freelist_t *vfp;
1429 	uint32_t id = atomic_add_32_nv(&vmem_id, 1);
1430 
1431 	if (vmem_vmem_arena != NULL) {
1432 		vmp = vmem_alloc(vmem_vmem_arena, sizeof (vmem_t),
1433 		    vmflag & VM_KMFLAGS);
1434 	} else {
1435 		ASSERT(id <= VMEM_INITIAL);
1436 		vmp = &vmem0[id - 1];
1437 	}
1438 
1439 	/* An identifier arena must inherit from another identifier arena */
1440 	ASSERT(source == NULL || ((source->vm_cflags & VMC_IDENTIFIER) ==
1441 	    (vmflag & VMC_IDENTIFIER)));
1442 
1443 	if (vmp == NULL)
1444 		return (NULL);
1445 	bzero(vmp, sizeof (vmem_t));
1446 
1447 	(void) snprintf(vmp->vm_name, VMEM_NAMELEN, "%s", name);
1448 	mutex_init(&vmp->vm_lock, NULL, MUTEX_DEFAULT, NULL);
1449 	cv_init(&vmp->vm_cv, NULL, CV_DEFAULT, NULL);
1450 	vmp->vm_cflags = vmflag;
1451 	vmflag &= VM_KMFLAGS;
1452 
1453 	vmp->vm_quantum = quantum;
1454 	vmp->vm_qshift = highbit(quantum) - 1;
1455 	nqcache = MIN(qcache_max >> vmp->vm_qshift, VMEM_NQCACHE_MAX);
1456 
1457 	for (i = 0; i <= VMEM_FREELISTS; i++) {
1458 		vfp = &vmp->vm_freelist[i];
1459 		vfp->vs_end = 1UL << i;
1460 		vfp->vs_knext = (vmem_seg_t *)(vfp + 1);
1461 		vfp->vs_kprev = (vmem_seg_t *)(vfp - 1);
1462 	}
1463 
1464 	vmp->vm_freelist[0].vs_kprev = NULL;
1465 	vmp->vm_freelist[VMEM_FREELISTS].vs_knext = NULL;
1466 	vmp->vm_freelist[VMEM_FREELISTS].vs_end = 0;
1467 	vmp->vm_hash_table = vmp->vm_hash0;
1468 	vmp->vm_hash_mask = VMEM_HASH_INITIAL - 1;
1469 	vmp->vm_hash_shift = highbit(vmp->vm_hash_mask);
1470 
1471 	vsp = &vmp->vm_seg0;
1472 	vsp->vs_anext = vsp;
1473 	vsp->vs_aprev = vsp;
1474 	vsp->vs_knext = vsp;
1475 	vsp->vs_kprev = vsp;
1476 	vsp->vs_type = VMEM_SPAN;
1477 
1478 	vsp = &vmp->vm_rotor;
1479 	vsp->vs_type = VMEM_ROTOR;
1480 	VMEM_INSERT(&vmp->vm_seg0, vsp, a);
1481 
1482 	bcopy(&vmem_kstat_template, &vmp->vm_kstat, sizeof (vmem_kstat_t));
1483 
1484 	vmp->vm_id = id;
1485 	if (source != NULL)
1486 		vmp->vm_kstat.vk_source_id.value.ui32 = source->vm_id;
1487 	vmp->vm_source = source;
1488 	vmp->vm_source_alloc = afunc;
1489 	vmp->vm_source_free = ffunc;
1490 
1491 	/*
1492 	 * Some arenas (like vmem_metadata and kmem_metadata) cannot
1493 	 * use quantum caching to lower fragmentation.  Instead, we
1494 	 * increase their imports, giving a similar effect.
1495 	 */
1496 	if (vmp->vm_cflags & VMC_NO_QCACHE) {
1497 		vmp->vm_min_import =
1498 		    VMEM_QCACHE_SLABSIZE(nqcache << vmp->vm_qshift);
1499 		nqcache = 0;
1500 	}
1501 
1502 	if (nqcache != 0) {
1503 		ASSERT(!(vmflag & VM_NOSLEEP));
1504 		vmp->vm_qcache_max = nqcache << vmp->vm_qshift;
1505 		for (i = 0; i < nqcache; i++) {
1506 			char buf[VMEM_NAMELEN + 21];
1507 			(void) sprintf(buf, "%s_%lu", vmp->vm_name,
1508 			    (i + 1) * quantum);
1509 			vmp->vm_qcache[i] = kmem_cache_create(buf,
1510 			    (i + 1) * quantum, quantum, NULL, NULL, NULL,
1511 			    NULL, vmp, KMC_QCACHE | KMC_NOTOUCH);
1512 		}
1513 	}
1514 
1515 	if ((vmp->vm_ksp = kstat_create("vmem", vmp->vm_id, vmp->vm_name,
1516 	    "vmem", KSTAT_TYPE_NAMED, sizeof (vmem_kstat_t) /
1517 	    sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL)) != NULL) {
1518 		vmp->vm_ksp->ks_data = &vmp->vm_kstat;
1519 		kstat_install(vmp->vm_ksp);
1520 	}
1521 
1522 	mutex_enter(&vmem_list_lock);
1523 	vmpp = &vmem_list;
1524 	while ((cur = *vmpp) != NULL)
1525 		vmpp = &cur->vm_next;
1526 	*vmpp = vmp;
1527 	mutex_exit(&vmem_list_lock);
1528 
1529 	if (vmp->vm_cflags & VMC_POPULATOR) {
1530 		ASSERT(vmem_populators < VMEM_INITIAL);
1531 		vmem_populator[atomic_add_32_nv(&vmem_populators, 1) - 1] = vmp;
1532 		mutex_enter(&vmp->vm_lock);
1533 		(void) vmem_populate(vmp, vmflag | VM_PANIC);
1534 		mutex_exit(&vmp->vm_lock);
1535 	}
1536 
1537 	if ((base || size) && vmem_add(vmp, base, size, vmflag) == NULL) {
1538 		vmem_destroy(vmp);
1539 		return (NULL);
1540 	}
1541 
1542 	return (vmp);
1543 }
1544 
1545 vmem_t *
1546 vmem_xcreate(const char *name, void *base, size_t size, size_t quantum,
1547     vmem_ximport_t *afunc, vmem_free_t *ffunc, vmem_t *source,
1548     size_t qcache_max, int vmflag)
1549 {
1550 	ASSERT(!(vmflag & (VMC_POPULATOR | VMC_XALLOC)));
1551 	vmflag &= ~(VMC_POPULATOR | VMC_XALLOC);
1552 
1553 	return (vmem_create_common(name, base, size, quantum,
1554 	    (vmem_alloc_t *)afunc, ffunc, source, qcache_max,
1555 	    vmflag | VMC_XALLOC));
1556 }
1557 
1558 vmem_t *
1559 vmem_create(const char *name, void *base, size_t size, size_t quantum,
1560     vmem_alloc_t *afunc, vmem_free_t *ffunc, vmem_t *source,
1561     size_t qcache_max, int vmflag)
1562 {
1563 	ASSERT(!(vmflag & (VMC_XALLOC | VMC_XALIGN)));
1564 	vmflag &= ~(VMC_XALLOC | VMC_XALIGN);
1565 
1566 	return (vmem_create_common(name, base, size, quantum,
1567 	    afunc, ffunc, source, qcache_max, vmflag));
1568 }
1569 
1570 /*
1571  * Destroy arena vmp.
1572  */
1573 void
1574 vmem_destroy(vmem_t *vmp)
1575 {
1576 	vmem_t *cur, **vmpp;
1577 	vmem_seg_t *seg0 = &vmp->vm_seg0;
1578 	vmem_seg_t *vsp;
1579 	size_t leaked;
1580 	int i;
1581 
1582 	mutex_enter(&vmem_list_lock);
1583 	vmpp = &vmem_list;
1584 	while ((cur = *vmpp) != vmp)
1585 		vmpp = &cur->vm_next;
1586 	*vmpp = vmp->vm_next;
1587 	mutex_exit(&vmem_list_lock);
1588 
1589 	for (i = 0; i < VMEM_NQCACHE_MAX; i++)
1590 		if (vmp->vm_qcache[i])
1591 			kmem_cache_destroy(vmp->vm_qcache[i]);
1592 
1593 	leaked = vmem_size(vmp, VMEM_ALLOC);
1594 	if (leaked != 0)
1595 		cmn_err(CE_WARN, "vmem_destroy('%s'): leaked %lu %s",
1596 		    vmp->vm_name, leaked, (vmp->vm_cflags & VMC_IDENTIFIER) ?
1597 		    "identifiers" : "bytes");
1598 
1599 	if (vmp->vm_hash_table != vmp->vm_hash0)
1600 		vmem_free(vmem_hash_arena, vmp->vm_hash_table,
1601 		    (vmp->vm_hash_mask + 1) * sizeof (void *));
1602 
1603 	/*
1604 	 * Give back the segment structures for anything that's left in the
1605 	 * arena, e.g. the primary spans and their free segments.
1606 	 */
1607 	VMEM_DELETE(&vmp->vm_rotor, a);
1608 	for (vsp = seg0->vs_anext; vsp != seg0; vsp = vsp->vs_anext)
1609 		vmem_putseg_global(vsp);
1610 
1611 	while (vmp->vm_nsegfree > 0)
1612 		vmem_putseg_global(vmem_getseg(vmp));
1613 
1614 	kstat_delete(vmp->vm_ksp);
1615 
1616 	mutex_destroy(&vmp->vm_lock);
1617 	cv_destroy(&vmp->vm_cv);
1618 	vmem_free(vmem_vmem_arena, vmp, sizeof (vmem_t));
1619 }
1620 
1621 /*
1622  * Resize vmp's hash table to keep the average lookup depth near 1.0.
1623  */
1624 static void
1625 vmem_hash_rescale(vmem_t *vmp)
1626 {
1627 	vmem_seg_t **old_table, **new_table, *vsp;
1628 	size_t old_size, new_size, h, nseg;
1629 
1630 	nseg = (size_t)(vmp->vm_kstat.vk_alloc.value.ui64 -
1631 	    vmp->vm_kstat.vk_free.value.ui64);
1632 
1633 	new_size = MAX(VMEM_HASH_INITIAL, 1 << (highbit(3 * nseg + 4) - 2));
1634 	old_size = vmp->vm_hash_mask + 1;
1635 
1636 	if ((old_size >> 1) <= new_size && new_size <= (old_size << 1))
1637 		return;
1638 
1639 	new_table = vmem_alloc(vmem_hash_arena, new_size * sizeof (void *),
1640 	    VM_NOSLEEP);
1641 	if (new_table == NULL)
1642 		return;
1643 	bzero(new_table, new_size * sizeof (void *));
1644 
1645 	mutex_enter(&vmp->vm_lock);
1646 
1647 	old_size = vmp->vm_hash_mask + 1;
1648 	old_table = vmp->vm_hash_table;
1649 
1650 	vmp->vm_hash_mask = new_size - 1;
1651 	vmp->vm_hash_table = new_table;
1652 	vmp->vm_hash_shift = highbit(vmp->vm_hash_mask);
1653 
1654 	for (h = 0; h < old_size; h++) {
1655 		vsp = old_table[h];
1656 		while (vsp != NULL) {
1657 			uintptr_t addr = vsp->vs_start;
1658 			vmem_seg_t *next_vsp = vsp->vs_knext;
1659 			vmem_seg_t **hash_bucket = VMEM_HASH(vmp, addr);
1660 			vsp->vs_knext = *hash_bucket;
1661 			*hash_bucket = vsp;
1662 			vsp = next_vsp;
1663 		}
1664 	}
1665 
1666 	mutex_exit(&vmp->vm_lock);
1667 
1668 	if (old_table != vmp->vm_hash0)
1669 		vmem_free(vmem_hash_arena, old_table,
1670 		    old_size * sizeof (void *));
1671 }
1672 
1673 /*
1674  * Perform periodic maintenance on all vmem arenas.
1675  */
1676 void
1677 vmem_update(void *dummy)
1678 {
1679 	vmem_t *vmp;
1680 
1681 	mutex_enter(&vmem_list_lock);
1682 	for (vmp = vmem_list; vmp != NULL; vmp = vmp->vm_next) {
1683 		/*
1684 		 * If threads are waiting for resources, wake them up
1685 		 * periodically so they can issue another kmem_reap()
1686 		 * to reclaim resources cached by the slab allocator.
1687 		 */
1688 		cv_broadcast(&vmp->vm_cv);
1689 
1690 		/*
1691 		 * Rescale the hash table to keep the hash chains short.
1692 		 */
1693 		vmem_hash_rescale(vmp);
1694 	}
1695 	mutex_exit(&vmem_list_lock);
1696 
1697 	(void) timeout(vmem_update, dummy, vmem_update_interval * hz);
1698 }
1699 
1700 /*
1701  * Prepare vmem for use.
1702  */
1703 vmem_t *
1704 vmem_init(const char *heap_name,
1705 	void *heap_start, size_t heap_size, size_t heap_quantum,
1706 	void *(*heap_alloc)(vmem_t *, size_t, int),
1707 	void (*heap_free)(vmem_t *, void *, size_t))
1708 {
1709 	uint32_t id;
1710 	int nseg = VMEM_SEG_INITIAL;
1711 	vmem_t *heap;
1712 
1713 	while (--nseg >= 0)
1714 		vmem_putseg_global(&vmem_seg0[nseg]);
1715 
1716 	heap = vmem_create(heap_name,
1717 	    heap_start, heap_size, heap_quantum,
1718 	    NULL, NULL, NULL, 0,
1719 	    VM_SLEEP | VMC_POPULATOR);
1720 
1721 	vmem_metadata_arena = vmem_create("vmem_metadata",
1722 	    NULL, 0, heap_quantum,
1723 	    vmem_alloc, vmem_free, heap, 8 * heap_quantum,
1724 	    VM_SLEEP | VMC_POPULATOR | VMC_NO_QCACHE);
1725 
1726 	vmem_seg_arena = vmem_create("vmem_seg",
1727 	    NULL, 0, heap_quantum,
1728 	    heap_alloc, heap_free, vmem_metadata_arena, 0,
1729 	    VM_SLEEP | VMC_POPULATOR);
1730 
1731 	vmem_hash_arena = vmem_create("vmem_hash",
1732 	    NULL, 0, 8,
1733 	    heap_alloc, heap_free, vmem_metadata_arena, 0,
1734 	    VM_SLEEP);
1735 
1736 	vmem_vmem_arena = vmem_create("vmem_vmem",
1737 	    vmem0, sizeof (vmem0), 1,
1738 	    heap_alloc, heap_free, vmem_metadata_arena, 0,
1739 	    VM_SLEEP);
1740 
1741 	for (id = 0; id < vmem_id; id++)
1742 		(void) vmem_xalloc(vmem_vmem_arena, sizeof (vmem_t),
1743 		    1, 0, 0, &vmem0[id], &vmem0[id + 1],
1744 		    VM_NOSLEEP | VM_BESTFIT | VM_PANIC);
1745 
1746 	return (heap);
1747 }
1748