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