xref: /titanic_41/usr/src/lib/libumem/common/umem.c (revision c8343062f6e25afd9c2a31b65df357030e69fa55)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * based on usr/src/uts/common/os/kmem.c r1.64 from 2001/12/18
31  *
32  * The slab allocator, as described in the following two papers:
33  *
34  *	Jeff Bonwick,
35  *	The Slab Allocator: An Object-Caching Kernel Memory Allocator.
36  *	Proceedings of the Summer 1994 Usenix Conference.
37  *	Available as /shared/sac/PSARC/1994/028/materials/kmem.pdf.
38  *
39  *	Jeff Bonwick and Jonathan Adams,
40  *	Magazines and vmem: Extending the Slab Allocator to Many CPUs and
41  *	Arbitrary Resources.
42  *	Proceedings of the 2001 Usenix Conference.
43  *	Available as /shared/sac/PSARC/2000/550/materials/vmem.pdf.
44  *
45  * 1. Overview
46  * -----------
47  * umem is very close to kmem in implementation.  There are four major
48  * areas of divergence:
49  *
50  *	* Initialization
51  *
52  *	* CPU handling
53  *
54  *	* umem_update()
55  *
56  *	* KM_SLEEP v.s. UMEM_NOFAIL
57  *
58  *	* lock ordering
59  *
60  * 2. Initialization
61  * -----------------
62  * kmem is initialized early on in boot, and knows that no one will call
63  * into it before it is ready.  umem does not have these luxuries. Instead,
64  * initialization is divided into two phases:
65  *
66  *	* library initialization, and
67  *
68  *	* first use
69  *
70  * umem's full initialization happens at the time of the first allocation
71  * request (via malloc() and friends, umem_alloc(), or umem_zalloc()),
72  * or the first call to umem_cache_create().
73  *
74  * umem_free(), and umem_cache_alloc() do not require special handling,
75  * since the only way to get valid arguments for them is to successfully
76  * call a function from the first group.
77  *
78  * 2.1. Library Initialization: umem_startup()
79  * -------------------------------------------
80  * umem_startup() is libumem.so's .init section.  It calls pthread_atfork()
81  * to install the handlers necessary for umem's Fork1-Safety.  Because of
82  * race condition issues, all other pre-umem_init() initialization is done
83  * statically (i.e. by the dynamic linker).
84  *
85  * For standalone use, umem_startup() returns everything to its initial
86  * state.
87  *
88  * 2.2. First use: umem_init()
89  * ------------------------------
90  * The first time any memory allocation function is used, we have to
91  * create the backing caches and vmem arenas which are needed for it.
92  * umem_init() is the central point for that task.  When it completes,
93  * umem_ready is either UMEM_READY (all set) or UMEM_READY_INIT_FAILED (unable
94  * to initialize, probably due to lack of memory).
95  *
96  * There are four different paths from which umem_init() is called:
97  *
98  *	* from umem_alloc() or umem_zalloc(), with 0 < size < UMEM_MAXBUF,
99  *
100  *	* from umem_alloc() or umem_zalloc(), with size > UMEM_MAXBUF,
101  *
102  *	* from umem_cache_create(), and
103  *
104  *	* from memalign(), with align > UMEM_ALIGN.
105  *
106  * The last three just check if umem is initialized, and call umem_init()
107  * if it is not.  For performance reasons, the first case is more complicated.
108  *
109  * 2.2.1. umem_alloc()/umem_zalloc(), with 0 < size < UMEM_MAXBUF
110  * -----------------------------------------------------------------
111  * In this case, umem_cache_alloc(&umem_null_cache, ...) is called.
112  * There is special case code in which causes any allocation on
113  * &umem_null_cache to fail by returning (NULL), regardless of the
114  * flags argument.
115  *
116  * So umem_cache_alloc() returns NULL, and umem_alloc()/umem_zalloc() call
117  * umem_alloc_retry().  umem_alloc_retry() sees that the allocation
118  * was agains &umem_null_cache, and calls umem_init().
119  *
120  * If initialization is successful, umem_alloc_retry() returns 1, which
121  * causes umem_alloc()/umem_zalloc() to start over, which causes it to load
122  * the (now valid) cache pointer from umem_alloc_table.
123  *
124  * 2.2.2. Dealing with race conditions
125  * -----------------------------------
126  * There are a couple race conditions resulting from the initialization
127  * code that we have to guard against:
128  *
129  *	* In umem_cache_create(), there is a special UMC_INTERNAL cflag
130  *	that is passed for caches created during initialization.  It
131  *	is illegal for a user to try to create a UMC_INTERNAL cache.
132  *	This allows initialization to proceed, but any other
133  *	umem_cache_create()s will block by calling umem_init().
134  *
135  *	* Since umem_null_cache has a 1-element cache_cpu, it's cache_cpu_mask
136  *	is always zero.  umem_cache_alloc uses cp->cache_cpu_mask to
137  *	mask the cpu number.  This prevents a race between grabbing a
138  *	cache pointer out of umem_alloc_table and growing the cpu array.
139  *
140  *
141  * 3. CPU handling
142  * ---------------
143  * kmem uses the CPU's sequence number to determine which "cpu cache" to
144  * use for an allocation.  Currently, there is no way to get the sequence
145  * number in userspace.
146  *
147  * umem keeps track of cpu information in umem_cpus, an array of umem_max_ncpus
148  * umem_cpu_t structures.  CURCPU() is a a "hint" function, which we then mask
149  * with either umem_cpu_mask or cp->cache_cpu_mask to find the actual "cpu" id.
150  * The mechanics of this is all in the CPU(mask) macro.
151  *
152  * Currently, umem uses _lwp_self() as its hint.
153  *
154  *
155  * 4. The update thread
156  * --------------------
157  * kmem uses a task queue, kmem_taskq, to do periodic maintenance on
158  * every kmem cache.  vmem has a periodic timeout for hash table resizing.
159  * The kmem_taskq also provides a separate context for kmem_cache_reap()'s
160  * to be done in, avoiding issues of the context of kmem_reap() callers.
161  *
162  * Instead, umem has the concept of "updates", which are asynchronous requests
163  * for work attached to single caches.  All caches with pending work are
164  * on a doubly linked list rooted at the umem_null_cache.  All update state
165  * is protected by the umem_update_lock mutex, and the umem_update_cv is used
166  * for notification between threads.
167  *
168  * 4.1. Cache states with regards to updates
169  * -----------------------------------------
170  * A given cache is in one of three states:
171  *
172  * Inactive		cache_uflags is zero, cache_u{next,prev} are NULL
173  *
174  * Work Requested	cache_uflags is non-zero (but UMU_ACTIVE is not set),
175  *			cache_u{next,prev} link the cache onto the global
176  *			update list
177  *
178  * Active		cache_uflags has UMU_ACTIVE set, cache_u{next,prev}
179  *			are NULL, and either umem_update_thr or
180  *			umem_st_update_thr are actively doing work on the
181  *			cache.
182  *
183  * An update can be added to any cache in any state -- if the cache is
184  * Inactive, it transitions to being Work Requested.  If the cache is
185  * Active, the worker will notice the new update and act on it before
186  * transitioning the cache to the Inactive state.
187  *
188  * If a cache is in the Active state, UMU_NOTIFY can be set, which asks
189  * the worker to broadcast the umem_update_cv when it has finished.
190  *
191  * 4.2. Update interface
192  * ---------------------
193  * umem_add_update() adds an update to a particular cache.
194  * umem_updateall() adds an update to all caches.
195  * umem_remove_updates() returns a cache to the Inactive state.
196  *
197  * umem_process_updates() process all caches in the Work Requested state.
198  *
199  * 4.3. Reaping
200  * ------------
201  * When umem_reap() is called (at the time of heap growth), it schedule
202  * UMU_REAP updates on every cache.  It then checks to see if the update
203  * thread exists (umem_update_thr != 0).  If it is, it broadcasts
204  * the umem_update_cv to wake the update thread up, and returns.
205  *
206  * If the update thread does not exist (umem_update_thr == 0), and the
207  * program currently has multiple threads, umem_reap() attempts to create
208  * a new update thread.
209  *
210  * If the process is not multithreaded, or the creation fails, umem_reap()
211  * calls umem_st_update() to do an inline update.
212  *
213  * 4.4. The update thread
214  * ----------------------
215  * The update thread spends most of its time in cond_timedwait() on the
216  * umem_update_cv.  It wakes up under two conditions:
217  *
218  *	* The timedwait times out, in which case it needs to run a global
219  *	update, or
220  *
221  *	* someone cond_broadcast(3THR)s the umem_update_cv, in which case
222  *	it needs to check if there are any caches in the Work Requested
223  *	state.
224  *
225  * When it is time for another global update, umem calls umem_cache_update()
226  * on every cache, then calls vmem_update(), which tunes the vmem structures.
227  * umem_cache_update() can request further work using umem_add_update().
228  *
229  * After any work from the global update completes, the update timer is
230  * reset to umem_reap_interval seconds in the future.  This makes the
231  * updates self-throttling.
232  *
233  * Reaps are similarly self-throttling.  After a UMU_REAP update has
234  * been scheduled on all caches, umem_reap() sets a flag and wakes up the
235  * update thread.  The update thread notices the flag, and resets the
236  * reap state.
237  *
238  * 4.5. Inline updates
239  * -------------------
240  * If the update thread is not running, umem_st_update() is used instead.  It
241  * immediately does a global update (as above), then calls
242  * umem_process_updates() to process both the reaps that umem_reap() added and
243  * any work generated by the global update.  Afterwards, it resets the reap
244  * state.
245  *
246  * While the umem_st_update() is running, umem_st_update_thr holds the thread
247  * id of the thread performing the update.
248  *
249  * 4.6. Updates and fork1()
250  * ------------------------
251  * umem has fork1() pre- and post-handlers which lock up (and release) every
252  * mutex in every cache.  They also lock up the umem_update_lock.  Since
253  * fork1() only copies over a single lwp, other threads (including the update
254  * thread) could have been actively using a cache in the parent.  This
255  * can lead to inconsistencies in the child process.
256  *
257  * Because we locked all of the mutexes, the only possible inconsistancies are:
258  *
259  *	* a umem_cache_alloc() could leak its buffer.
260  *
261  *	* a caller of umem_depot_alloc() could leak a magazine, and all the
262  *	buffers contained in it.
263  *
264  *	* a cache could be in the Active update state.  In the child, there
265  *	would be no thread actually working on it.
266  *
267  *	* a umem_hash_rescale() could leak the new hash table.
268  *
269  *	* a umem_magazine_resize() could be in progress.
270  *
271  *	* a umem_reap() could be in progress.
272  *
273  * The memory leaks we can't do anything about.  umem_release_child() resets
274  * the update state, moves any caches in the Active state to the Work Requested
275  * state.  This might cause some updates to be re-run, but UMU_REAP and
276  * UMU_HASH_RESCALE are effectively idempotent, and the worst that can
277  * happen from umem_magazine_resize() is resizing the magazine twice in close
278  * succession.
279  *
280  * Much of the cleanup in umem_release_child() is skipped if
281  * umem_st_update_thr == thr_self().  This is so that applications which call
282  * fork1() from a cache callback does not break.  Needless to say, any such
283  * application is tremendously broken.
284  *
285  *
286  * 5. KM_SLEEP v.s. UMEM_NOFAIL
287  * ----------------------------
288  * Allocations against kmem and vmem have two basic modes:  SLEEP and
289  * NOSLEEP.  A sleeping allocation is will go to sleep (waiting for
290  * more memory) instead of failing (returning NULL).
291  *
292  * SLEEP allocations presume an extremely multithreaded model, with
293  * a lot of allocation and deallocation activity.  umem cannot presume
294  * that its clients have any particular type of behavior.  Instead,
295  * it provides two types of allocations:
296  *
297  *	* UMEM_DEFAULT, equivalent to KM_NOSLEEP (i.e. return NULL on
298  *	failure)
299  *
300  *	* UMEM_NOFAIL, which, on failure, calls an optional callback
301  *	(registered with umem_nofail_callback()).
302  *
303  * The callback is invoked with no locks held, and can do an arbitrary
304  * amount of work.  It then has a choice between:
305  *
306  *	* Returning UMEM_CALLBACK_RETRY, which will cause the allocation
307  *	to be restarted.
308  *
309  *	* Returning UMEM_CALLBACK_EXIT(status), which will cause exit(2)
310  *	to be invoked with status.  If multiple threads attempt to do
311  *	this simultaneously, only one will call exit(2).
312  *
313  *	* Doing some kind of non-local exit (thr_exit(3thr), longjmp(3C),
314  *	etc.)
315  *
316  * The default callback returns UMEM_CALLBACK_EXIT(255).
317  *
318  * To have these callbacks without risk of state corruption (in the case of
319  * a non-local exit), we have to ensure that the callbacks get invoked
320  * close to the original allocation, with no inconsistent state or held
321  * locks.  The following steps are taken:
322  *
323  *	* All invocations of vmem are VM_NOSLEEP.
324  *
325  *	* All constructor callbacks (which can themselves to allocations)
326  *	are passed UMEM_DEFAULT as their required allocation argument.  This
327  *	way, the constructor will fail, allowing the highest-level allocation
328  *	invoke the nofail callback.
329  *
330  *	If a constructor callback _does_ do a UMEM_NOFAIL allocation, and
331  *	the nofail callback does a non-local exit, we will leak the
332  *	partially-constructed buffer.
333  *
334  *
335  * 6. Lock Ordering
336  * ----------------
337  * umem has a few more locks than kmem does, mostly in the update path.  The
338  * overall lock ordering (earlier locks must be acquired first) is:
339  *
340  *	umem_init_lock
341  *
342  *	vmem_list_lock
343  *	vmem_nosleep_lock.vmpl_mutex
344  *	vmem_t's:
345  *		vm_lock
346  *	sbrk_faillock
347  *
348  *	umem_cache_lock
349  *	umem_update_lock
350  *	umem_flags_lock
351  *	umem_cache_t's:
352  *		cache_cpu[*].cc_lock
353  *		cache_depot_lock
354  *		cache_lock
355  *	umem_log_header_t's:
356  *		lh_cpu[*].clh_lock
357  *		lh_lock
358  */
359 
360 #include "mtlib.h"
361 #include <umem_impl.h>
362 #include <sys/vmem_impl_user.h>
363 #include "umem_base.h"
364 #include "vmem_base.h"
365 
366 #include <sys/processor.h>
367 #include <sys/sysmacros.h>
368 
369 #include <alloca.h>
370 #include <errno.h>
371 #include <limits.h>
372 #include <stdio.h>
373 #include <stdlib.h>
374 #include <string.h>
375 #include <strings.h>
376 #include <signal.h>
377 #include <unistd.h>
378 #include <atomic.h>
379 
380 #include "misc.h"
381 
382 #define	UMEM_VMFLAGS(umflag)	(VM_NOSLEEP)
383 
384 size_t pagesize;
385 
386 /*
387  * The default set of caches to back umem_alloc().
388  * These sizes should be reevaluated periodically.
389  *
390  * We want allocations that are multiples of the coherency granularity
391  * (64 bytes) to be satisfied from a cache which is a multiple of 64
392  * bytes, so that it will be 64-byte aligned.  For all multiples of 64,
393  * the next kmem_cache_size greater than or equal to it must be a
394  * multiple of 64.
395  */
396 static const int umem_alloc_sizes[] = {
397 #ifdef _LP64
398 	1 * 8,
399 	1 * 16,
400 	2 * 16,
401 	3 * 16,
402 #else
403 	1 * 8,
404 	2 * 8,
405 	3 * 8,
406 	4 * 8,		5 * 8,		6 * 8,		7 * 8,
407 #endif
408 	4 * 16,		5 * 16,		6 * 16,		7 * 16,
409 	4 * 32,		5 * 32,		6 * 32,		7 * 32,
410 	4 * 64,		5 * 64,		6 * 64,		7 * 64,
411 	4 * 128,	5 * 128,	6 * 128,	7 * 128,
412 	P2ALIGN(8192 / 7, 64),
413 	P2ALIGN(8192 / 6, 64),
414 	P2ALIGN(8192 / 5, 64),
415 	P2ALIGN(8192 / 4, 64),
416 	P2ALIGN(8192 / 3, 64),
417 	P2ALIGN(8192 / 2, 64),
418 	P2ALIGN(8192 / 1, 64),
419 	4096 * 3,
420 	8192 * 2,
421 };
422 #define	NUM_ALLOC_SIZES (sizeof (umem_alloc_sizes) / sizeof (*umem_alloc_sizes))
423 
424 #define	UMEM_MAXBUF	16384
425 
426 static umem_magtype_t umem_magtype[] = {
427 	{ 1,	8,	3200,	65536	},
428 	{ 3,	16,	256,	32768	},
429 	{ 7,	32,	64,	16384	},
430 	{ 15,	64,	0,	8192	},
431 	{ 31,	64,	0,	4096	},
432 	{ 47,	64,	0,	2048	},
433 	{ 63,	64,	0,	1024	},
434 	{ 95,	64,	0,	512	},
435 	{ 143,	64,	0,	0	},
436 };
437 
438 /*
439  * umem tunables
440  */
441 uint32_t umem_max_ncpus;	/* # of CPU caches. */
442 
443 uint32_t umem_stack_depth = 15; /* # stack frames in a bufctl_audit */
444 uint32_t umem_reap_interval = 10; /* max reaping rate (seconds) */
445 uint_t umem_depot_contention = 2; /* max failed trylocks per real interval */
446 uint_t umem_abort = 1;		/* whether to abort on error */
447 uint_t umem_output = 0;		/* whether to write to standard error */
448 uint_t umem_logging = 0;	/* umem_log_enter() override */
449 uint32_t umem_mtbf = 0;		/* mean time between failures [default: off] */
450 size_t umem_transaction_log_size; /* size of transaction log */
451 size_t umem_content_log_size;	/* size of content log */
452 size_t umem_failure_log_size;	/* failure log [4 pages per CPU] */
453 size_t umem_slab_log_size;	/* slab create log [4 pages per CPU] */
454 size_t umem_content_maxsave = 256; /* UMF_CONTENTS max bytes to log */
455 size_t umem_lite_minsize = 0;	/* minimum buffer size for UMF_LITE */
456 size_t umem_lite_maxalign = 1024; /* maximum buffer alignment for UMF_LITE */
457 size_t umem_maxverify;		/* maximum bytes to inspect in debug routines */
458 size_t umem_minfirewall;	/* hardware-enforced redzone threshold */
459 
460 uint_t umem_flags = 0;
461 
462 mutex_t			umem_init_lock;		/* locks initialization */
463 cond_t			umem_init_cv;		/* initialization CV */
464 thread_t		umem_init_thr;		/* thread initializing */
465 int			umem_init_env_ready;	/* environ pre-initted */
466 int			umem_ready = UMEM_READY_STARTUP;
467 
468 static umem_nofail_callback_t *nofail_callback;
469 static mutex_t		umem_nofail_exit_lock;
470 static thread_t		umem_nofail_exit_thr;
471 
472 static umem_cache_t	*umem_slab_cache;
473 static umem_cache_t	*umem_bufctl_cache;
474 static umem_cache_t	*umem_bufctl_audit_cache;
475 
476 mutex_t			umem_flags_lock;
477 
478 static vmem_t		*heap_arena;
479 static vmem_alloc_t	*heap_alloc;
480 static vmem_free_t	*heap_free;
481 
482 static vmem_t		*umem_internal_arena;
483 static vmem_t		*umem_cache_arena;
484 static vmem_t		*umem_hash_arena;
485 static vmem_t		*umem_log_arena;
486 static vmem_t		*umem_oversize_arena;
487 static vmem_t		*umem_va_arena;
488 static vmem_t		*umem_default_arena;
489 static vmem_t		*umem_firewall_va_arena;
490 static vmem_t		*umem_firewall_arena;
491 
492 vmem_t			*umem_memalign_arena;
493 
494 umem_log_header_t *umem_transaction_log;
495 umem_log_header_t *umem_content_log;
496 umem_log_header_t *umem_failure_log;
497 umem_log_header_t *umem_slab_log;
498 
499 extern thread_t _thr_self(void);
500 #define	CPUHINT()		(_thr_self())
501 #define	CPUHINT_MAX()		INT_MAX
502 
503 #define	CPU(mask)		(umem_cpus + (CPUHINT() & (mask)))
504 static umem_cpu_t umem_startup_cpu = {	/* initial, single, cpu */
505 	UMEM_CACHE_SIZE(0),
506 	0
507 };
508 
509 static uint32_t umem_cpu_mask = 0;			/* global cpu mask */
510 static umem_cpu_t *umem_cpus = &umem_startup_cpu;	/* cpu list */
511 
512 volatile uint32_t umem_reaping;
513 
514 thread_t		umem_update_thr;
515 struct timeval		umem_update_next;	/* timeofday of next update */
516 volatile thread_t	umem_st_update_thr;	/* only used when single-thd */
517 
518 #define	IN_UPDATE()	(thr_self() == umem_update_thr || \
519 			    thr_self() == umem_st_update_thr)
520 #define	IN_REAP()	IN_UPDATE()
521 
522 mutex_t			umem_update_lock;	/* cache_u{next,prev,flags} */
523 cond_t			umem_update_cv;
524 
525 volatile hrtime_t umem_reap_next;	/* min hrtime of next reap */
526 
527 mutex_t			umem_cache_lock;	/* inter-cache linkage only */
528 
529 #ifdef UMEM_STANDALONE
530 umem_cache_t		umem_null_cache;
531 static const umem_cache_t umem_null_cache_template = {
532 #else
533 umem_cache_t		umem_null_cache = {
534 #endif
535 	0, 0, 0, 0, 0,
536 	0, 0,
537 	0, 0,
538 	0, 0,
539 	"invalid_cache",
540 	0, 0,
541 	NULL, NULL, NULL, NULL,
542 	NULL,
543 	0, 0, 0, 0,
544 	&umem_null_cache, &umem_null_cache,
545 	&umem_null_cache, &umem_null_cache,
546 	0,
547 	DEFAULTMUTEX,				/* start of slab layer */
548 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
549 	&umem_null_cache.cache_nullslab,
550 	{
551 		&umem_null_cache,
552 		NULL,
553 		&umem_null_cache.cache_nullslab,
554 		&umem_null_cache.cache_nullslab,
555 		NULL,
556 		-1,
557 		0
558 	},
559 	NULL,
560 	NULL,
561 	DEFAULTMUTEX,				/* start of depot layer */
562 	NULL, {
563 		NULL, 0, 0, 0, 0
564 	}, {
565 		NULL, 0, 0, 0, 0
566 	}, {
567 		{
568 			DEFAULTMUTEX,		/* start of CPU cache */
569 			0, 0, NULL, NULL, -1, -1, 0
570 		}
571 	}
572 };
573 
574 #define	ALLOC_TABLE_4 \
575 	&umem_null_cache, &umem_null_cache, &umem_null_cache, &umem_null_cache
576 
577 #define	ALLOC_TABLE_64 \
578 	ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, \
579 	ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, \
580 	ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, \
581 	ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4
582 
583 #define	ALLOC_TABLE_1024 \
584 	ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, \
585 	ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, \
586 	ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, \
587 	ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64
588 
589 static umem_cache_t *umem_alloc_table[UMEM_MAXBUF >> UMEM_ALIGN_SHIFT] = {
590 	ALLOC_TABLE_1024,
591 	ALLOC_TABLE_1024
592 };
593 
594 
595 /* Used to constrain audit-log stack traces */
596 caddr_t			umem_min_stack;
597 caddr_t			umem_max_stack;
598 
599 
600 /*
601  * we use the _ versions, since we don't want to be cancelled.
602  * Actually, this is automatically taken care of by including "mtlib.h".
603  */
604 extern int _cond_wait(cond_t *cv, mutex_t *mutex);
605 
606 #define	UMERR_MODIFIED	0	/* buffer modified while on freelist */
607 #define	UMERR_REDZONE	1	/* redzone violation (write past end of buf) */
608 #define	UMERR_DUPFREE	2	/* freed a buffer twice */
609 #define	UMERR_BADADDR	3	/* freed a bad (unallocated) address */
610 #define	UMERR_BADBUFTAG	4	/* buftag corrupted */
611 #define	UMERR_BADBUFCTL	5	/* bufctl corrupted */
612 #define	UMERR_BADCACHE	6	/* freed a buffer to the wrong cache */
613 #define	UMERR_BADSIZE	7	/* alloc size != free size */
614 #define	UMERR_BADBASE	8	/* buffer base address wrong */
615 
616 struct {
617 	hrtime_t	ump_timestamp;	/* timestamp of error */
618 	int		ump_error;	/* type of umem error (UMERR_*) */
619 	void		*ump_buffer;	/* buffer that induced abort */
620 	void		*ump_realbuf;	/* real start address for buffer */
621 	umem_cache_t	*ump_cache;	/* buffer's cache according to client */
622 	umem_cache_t	*ump_realcache;	/* actual cache containing buffer */
623 	umem_slab_t	*ump_slab;	/* slab accoring to umem_findslab() */
624 	umem_bufctl_t	*ump_bufctl;	/* bufctl */
625 } umem_abort_info;
626 
627 static void
628 copy_pattern(uint64_t pattern, void *buf_arg, size_t size)
629 {
630 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
631 	uint64_t *buf = buf_arg;
632 
633 	while (buf < bufend)
634 		*buf++ = pattern;
635 }
636 
637 static void *
638 verify_pattern(uint64_t pattern, void *buf_arg, size_t size)
639 {
640 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
641 	uint64_t *buf;
642 
643 	for (buf = buf_arg; buf < bufend; buf++)
644 		if (*buf != pattern)
645 			return (buf);
646 	return (NULL);
647 }
648 
649 static void *
650 verify_and_copy_pattern(uint64_t old, uint64_t new, void *buf_arg, size_t size)
651 {
652 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
653 	uint64_t *buf;
654 
655 	for (buf = buf_arg; buf < bufend; buf++) {
656 		if (*buf != old) {
657 			copy_pattern(old, buf_arg,
658 			    (char *)buf - (char *)buf_arg);
659 			return (buf);
660 		}
661 		*buf = new;
662 	}
663 
664 	return (NULL);
665 }
666 
667 void
668 umem_cache_applyall(void (*func)(umem_cache_t *))
669 {
670 	umem_cache_t *cp;
671 
672 	(void) mutex_lock(&umem_cache_lock);
673 	for (cp = umem_null_cache.cache_next; cp != &umem_null_cache;
674 	    cp = cp->cache_next)
675 		func(cp);
676 	(void) mutex_unlock(&umem_cache_lock);
677 }
678 
679 static void
680 umem_add_update_unlocked(umem_cache_t *cp, int flags)
681 {
682 	umem_cache_t *cnext, *cprev;
683 
684 	flags &= ~UMU_ACTIVE;
685 
686 	if (!flags)
687 		return;
688 
689 	if (cp->cache_uflags & UMU_ACTIVE) {
690 		cp->cache_uflags |= flags;
691 	} else {
692 		if (cp->cache_unext != NULL) {
693 			ASSERT(cp->cache_uflags != 0);
694 			cp->cache_uflags |= flags;
695 		} else {
696 			ASSERT(cp->cache_uflags == 0);
697 			cp->cache_uflags = flags;
698 			cp->cache_unext = cnext = &umem_null_cache;
699 			cp->cache_uprev = cprev = umem_null_cache.cache_uprev;
700 			cnext->cache_uprev = cp;
701 			cprev->cache_unext = cp;
702 		}
703 	}
704 }
705 
706 static void
707 umem_add_update(umem_cache_t *cp, int flags)
708 {
709 	(void) mutex_lock(&umem_update_lock);
710 
711 	umem_add_update_unlocked(cp, flags);
712 
713 	if (!IN_UPDATE())
714 		(void) cond_broadcast(&umem_update_cv);
715 
716 	(void) mutex_unlock(&umem_update_lock);
717 }
718 
719 /*
720  * Remove a cache from the update list, waiting for any in-progress work to
721  * complete first.
722  */
723 static void
724 umem_remove_updates(umem_cache_t *cp)
725 {
726 	(void) mutex_lock(&umem_update_lock);
727 
728 	/*
729 	 * Get it out of the active state
730 	 */
731 	while (cp->cache_uflags & UMU_ACTIVE) {
732 		ASSERT(cp->cache_unext == NULL);
733 
734 		cp->cache_uflags |= UMU_NOTIFY;
735 
736 		/*
737 		 * Make sure the update state is sane, before we wait
738 		 */
739 		ASSERT(umem_update_thr != 0 || umem_st_update_thr != 0);
740 		ASSERT(umem_update_thr != thr_self() &&
741 		    umem_st_update_thr != thr_self());
742 
743 		(void) _cond_wait(&umem_update_cv, &umem_update_lock);
744 	}
745 	/*
746 	 * Get it out of the Work Requested state
747 	 */
748 	if (cp->cache_unext != NULL) {
749 		cp->cache_uprev->cache_unext = cp->cache_unext;
750 		cp->cache_unext->cache_uprev = cp->cache_uprev;
751 		cp->cache_uprev = cp->cache_unext = NULL;
752 		cp->cache_uflags = 0;
753 	}
754 	/*
755 	 * Make sure it is in the Inactive state
756 	 */
757 	ASSERT(cp->cache_unext == NULL && cp->cache_uflags == 0);
758 	(void) mutex_unlock(&umem_update_lock);
759 }
760 
761 static void
762 umem_updateall(int flags)
763 {
764 	umem_cache_t *cp;
765 
766 	/*
767 	 * NOTE:  To prevent deadlock, umem_cache_lock is always acquired first.
768 	 *
769 	 * (umem_add_update is called from things run via umem_cache_applyall)
770 	 */
771 	(void) mutex_lock(&umem_cache_lock);
772 	(void) mutex_lock(&umem_update_lock);
773 
774 	for (cp = umem_null_cache.cache_next; cp != &umem_null_cache;
775 	    cp = cp->cache_next)
776 		umem_add_update_unlocked(cp, flags);
777 
778 	if (!IN_UPDATE())
779 		(void) cond_broadcast(&umem_update_cv);
780 
781 	(void) mutex_unlock(&umem_update_lock);
782 	(void) mutex_unlock(&umem_cache_lock);
783 }
784 
785 /*
786  * Debugging support.  Given a buffer address, find its slab.
787  */
788 static umem_slab_t *
789 umem_findslab(umem_cache_t *cp, void *buf)
790 {
791 	umem_slab_t *sp;
792 
793 	(void) mutex_lock(&cp->cache_lock);
794 	for (sp = cp->cache_nullslab.slab_next;
795 	    sp != &cp->cache_nullslab; sp = sp->slab_next) {
796 		if (UMEM_SLAB_MEMBER(sp, buf)) {
797 			(void) mutex_unlock(&cp->cache_lock);
798 			return (sp);
799 		}
800 	}
801 	(void) mutex_unlock(&cp->cache_lock);
802 
803 	return (NULL);
804 }
805 
806 static void
807 umem_error(int error, umem_cache_t *cparg, void *bufarg)
808 {
809 	umem_buftag_t *btp = NULL;
810 	umem_bufctl_t *bcp = NULL;
811 	umem_cache_t *cp = cparg;
812 	umem_slab_t *sp;
813 	uint64_t *off;
814 	void *buf = bufarg;
815 
816 	int old_logging = umem_logging;
817 
818 	umem_logging = 0;	/* stop logging when a bad thing happens */
819 
820 	umem_abort_info.ump_timestamp = gethrtime();
821 
822 	sp = umem_findslab(cp, buf);
823 	if (sp == NULL) {
824 		for (cp = umem_null_cache.cache_prev; cp != &umem_null_cache;
825 		    cp = cp->cache_prev) {
826 			if ((sp = umem_findslab(cp, buf)) != NULL)
827 				break;
828 		}
829 	}
830 
831 	if (sp == NULL) {
832 		cp = NULL;
833 		error = UMERR_BADADDR;
834 	} else {
835 		if (cp != cparg)
836 			error = UMERR_BADCACHE;
837 		else
838 			buf = (char *)bufarg - ((uintptr_t)bufarg -
839 			    (uintptr_t)sp->slab_base) % cp->cache_chunksize;
840 		if (buf != bufarg)
841 			error = UMERR_BADBASE;
842 		if (cp->cache_flags & UMF_BUFTAG)
843 			btp = UMEM_BUFTAG(cp, buf);
844 		if (cp->cache_flags & UMF_HASH) {
845 			(void) mutex_lock(&cp->cache_lock);
846 			for (bcp = *UMEM_HASH(cp, buf); bcp; bcp = bcp->bc_next)
847 				if (bcp->bc_addr == buf)
848 					break;
849 			(void) mutex_unlock(&cp->cache_lock);
850 			if (bcp == NULL && btp != NULL)
851 				bcp = btp->bt_bufctl;
852 			if (umem_findslab(cp->cache_bufctl_cache, bcp) ==
853 			    NULL || P2PHASE((uintptr_t)bcp, UMEM_ALIGN) ||
854 			    bcp->bc_addr != buf) {
855 				error = UMERR_BADBUFCTL;
856 				bcp = NULL;
857 			}
858 		}
859 	}
860 
861 	umem_abort_info.ump_error = error;
862 	umem_abort_info.ump_buffer = bufarg;
863 	umem_abort_info.ump_realbuf = buf;
864 	umem_abort_info.ump_cache = cparg;
865 	umem_abort_info.ump_realcache = cp;
866 	umem_abort_info.ump_slab = sp;
867 	umem_abort_info.ump_bufctl = bcp;
868 
869 	umem_printf("umem allocator: ");
870 
871 	switch (error) {
872 
873 	case UMERR_MODIFIED:
874 		umem_printf("buffer modified after being freed\n");
875 		off = verify_pattern(UMEM_FREE_PATTERN, buf, cp->cache_verify);
876 		if (off == NULL)	/* shouldn't happen */
877 			off = buf;
878 		umem_printf("modification occurred at offset 0x%lx "
879 		    "(0x%llx replaced by 0x%llx)\n",
880 		    (uintptr_t)off - (uintptr_t)buf,
881 		    (longlong_t)UMEM_FREE_PATTERN, (longlong_t)*off);
882 		break;
883 
884 	case UMERR_REDZONE:
885 		umem_printf("redzone violation: write past end of buffer\n");
886 		break;
887 
888 	case UMERR_BADADDR:
889 		umem_printf("invalid free: buffer not in cache\n");
890 		break;
891 
892 	case UMERR_DUPFREE:
893 		umem_printf("duplicate free: buffer freed twice\n");
894 		break;
895 
896 	case UMERR_BADBUFTAG:
897 		umem_printf("boundary tag corrupted\n");
898 		umem_printf("bcp ^ bxstat = %lx, should be %lx\n",
899 		    (intptr_t)btp->bt_bufctl ^ btp->bt_bxstat,
900 		    UMEM_BUFTAG_FREE);
901 		break;
902 
903 	case UMERR_BADBUFCTL:
904 		umem_printf("bufctl corrupted\n");
905 		break;
906 
907 	case UMERR_BADCACHE:
908 		umem_printf("buffer freed to wrong cache\n");
909 		umem_printf("buffer was allocated from %s,\n", cp->cache_name);
910 		umem_printf("caller attempting free to %s.\n",
911 		    cparg->cache_name);
912 		break;
913 
914 	case UMERR_BADSIZE:
915 		umem_printf("bad free: free size (%u) != alloc size (%u)\n",
916 		    UMEM_SIZE_DECODE(((uint32_t *)btp)[0]),
917 		    UMEM_SIZE_DECODE(((uint32_t *)btp)[1]));
918 		break;
919 
920 	case UMERR_BADBASE:
921 		umem_printf("bad free: free address (%p) != alloc address "
922 		    "(%p)\n", bufarg, buf);
923 		break;
924 	}
925 
926 	umem_printf("buffer=%p  bufctl=%p  cache: %s\n",
927 	    bufarg, (void *)bcp, cparg->cache_name);
928 
929 	if (bcp != NULL && (cp->cache_flags & UMF_AUDIT) &&
930 	    error != UMERR_BADBUFCTL) {
931 		int d;
932 		timespec_t ts;
933 		hrtime_t diff;
934 		umem_bufctl_audit_t *bcap = (umem_bufctl_audit_t *)bcp;
935 
936 		diff = umem_abort_info.ump_timestamp - bcap->bc_timestamp;
937 		ts.tv_sec = diff / NANOSEC;
938 		ts.tv_nsec = diff % NANOSEC;
939 
940 		umem_printf("previous transaction on buffer %p:\n", buf);
941 		umem_printf("thread=%p  time=T-%ld.%09ld  slab=%p  cache: %s\n",
942 		    (void *)(intptr_t)bcap->bc_thread, ts.tv_sec, ts.tv_nsec,
943 		    (void *)sp, cp->cache_name);
944 		for (d = 0; d < MIN(bcap->bc_depth, umem_stack_depth); d++) {
945 			(void) print_sym((void *)bcap->bc_stack[d]);
946 			umem_printf("\n");
947 		}
948 	}
949 
950 	umem_err_recoverable("umem: heap corruption detected");
951 
952 	umem_logging = old_logging;	/* resume logging */
953 }
954 
955 void
956 umem_nofail_callback(umem_nofail_callback_t *cb)
957 {
958 	nofail_callback = cb;
959 }
960 
961 static int
962 umem_alloc_retry(umem_cache_t *cp, int umflag)
963 {
964 	if (cp == &umem_null_cache) {
965 		if (umem_init())
966 			return (1);				/* retry */
967 		/*
968 		 * Initialization failed.  Do normal failure processing.
969 		 */
970 	}
971 	if (umflag & UMEM_NOFAIL) {
972 		int def_result = UMEM_CALLBACK_EXIT(255);
973 		int result = def_result;
974 		umem_nofail_callback_t *callback = nofail_callback;
975 
976 		if (callback != NULL)
977 			result = callback();
978 
979 		if (result == UMEM_CALLBACK_RETRY)
980 			return (1);
981 
982 		if ((result & ~0xFF) != UMEM_CALLBACK_EXIT(0)) {
983 			log_message("nofail callback returned %x\n", result);
984 			result = def_result;
985 		}
986 
987 		/*
988 		 * only one thread will call exit
989 		 */
990 		if (umem_nofail_exit_thr == thr_self())
991 			umem_panic("recursive UMEM_CALLBACK_EXIT()\n");
992 
993 		(void) mutex_lock(&umem_nofail_exit_lock);
994 		umem_nofail_exit_thr = thr_self();
995 		exit(result & 0xFF);
996 		/*NOTREACHED*/
997 	}
998 	return (0);
999 }
1000 
1001 static umem_log_header_t *
1002 umem_log_init(size_t logsize)
1003 {
1004 	umem_log_header_t *lhp;
1005 	int nchunks = 4 * umem_max_ncpus;
1006 	size_t lhsize = offsetof(umem_log_header_t, lh_cpu[umem_max_ncpus]);
1007 	int i;
1008 
1009 	if (logsize == 0)
1010 		return (NULL);
1011 
1012 	/*
1013 	 * Make sure that lhp->lh_cpu[] is nicely aligned
1014 	 * to prevent false sharing of cache lines.
1015 	 */
1016 	lhsize = P2ROUNDUP(lhsize, UMEM_ALIGN);
1017 	lhp = vmem_xalloc(umem_log_arena, lhsize, 64, P2NPHASE(lhsize, 64), 0,
1018 	    NULL, NULL, VM_NOSLEEP);
1019 	if (lhp == NULL)
1020 		goto fail;
1021 
1022 	bzero(lhp, lhsize);
1023 
1024 	(void) mutex_init(&lhp->lh_lock, USYNC_THREAD, NULL);
1025 	lhp->lh_nchunks = nchunks;
1026 	lhp->lh_chunksize = P2ROUNDUP(logsize / nchunks, PAGESIZE);
1027 	if (lhp->lh_chunksize == 0)
1028 		lhp->lh_chunksize = PAGESIZE;
1029 
1030 	lhp->lh_base = vmem_alloc(umem_log_arena,
1031 	    lhp->lh_chunksize * nchunks, VM_NOSLEEP);
1032 	if (lhp->lh_base == NULL)
1033 		goto fail;
1034 
1035 	lhp->lh_free = vmem_alloc(umem_log_arena,
1036 	    nchunks * sizeof (int), VM_NOSLEEP);
1037 	if (lhp->lh_free == NULL)
1038 		goto fail;
1039 
1040 	bzero(lhp->lh_base, lhp->lh_chunksize * nchunks);
1041 
1042 	for (i = 0; i < umem_max_ncpus; i++) {
1043 		umem_cpu_log_header_t *clhp = &lhp->lh_cpu[i];
1044 		(void) mutex_init(&clhp->clh_lock, USYNC_THREAD, NULL);
1045 		clhp->clh_chunk = i;
1046 	}
1047 
1048 	for (i = umem_max_ncpus; i < nchunks; i++)
1049 		lhp->lh_free[i] = i;
1050 
1051 	lhp->lh_head = umem_max_ncpus;
1052 	lhp->lh_tail = 0;
1053 
1054 	return (lhp);
1055 
1056 fail:
1057 	if (lhp != NULL) {
1058 		if (lhp->lh_base != NULL)
1059 			vmem_free(umem_log_arena, lhp->lh_base,
1060 			    lhp->lh_chunksize * nchunks);
1061 
1062 		vmem_xfree(umem_log_arena, lhp, lhsize);
1063 	}
1064 	return (NULL);
1065 }
1066 
1067 static void *
1068 umem_log_enter(umem_log_header_t *lhp, void *data, size_t size)
1069 {
1070 	void *logspace;
1071 	umem_cpu_log_header_t *clhp =
1072 	    &lhp->lh_cpu[CPU(umem_cpu_mask)->cpu_number];
1073 
1074 	if (lhp == NULL || umem_logging == 0)
1075 		return (NULL);
1076 
1077 	(void) mutex_lock(&clhp->clh_lock);
1078 	clhp->clh_hits++;
1079 	if (size > clhp->clh_avail) {
1080 		(void) mutex_lock(&lhp->lh_lock);
1081 		lhp->lh_hits++;
1082 		lhp->lh_free[lhp->lh_tail] = clhp->clh_chunk;
1083 		lhp->lh_tail = (lhp->lh_tail + 1) % lhp->lh_nchunks;
1084 		clhp->clh_chunk = lhp->lh_free[lhp->lh_head];
1085 		lhp->lh_head = (lhp->lh_head + 1) % lhp->lh_nchunks;
1086 		clhp->clh_current = lhp->lh_base +
1087 		    clhp->clh_chunk * lhp->lh_chunksize;
1088 		clhp->clh_avail = lhp->lh_chunksize;
1089 		if (size > lhp->lh_chunksize)
1090 			size = lhp->lh_chunksize;
1091 		(void) mutex_unlock(&lhp->lh_lock);
1092 	}
1093 	logspace = clhp->clh_current;
1094 	clhp->clh_current += size;
1095 	clhp->clh_avail -= size;
1096 	bcopy(data, logspace, size);
1097 	(void) mutex_unlock(&clhp->clh_lock);
1098 	return (logspace);
1099 }
1100 
1101 #define	UMEM_AUDIT(lp, cp, bcp)						\
1102 {									\
1103 	umem_bufctl_audit_t *_bcp = (umem_bufctl_audit_t *)(bcp);	\
1104 	_bcp->bc_timestamp = gethrtime();				\
1105 	_bcp->bc_thread = thr_self();					\
1106 	_bcp->bc_depth = getpcstack(_bcp->bc_stack, umem_stack_depth,	\
1107 	    (cp != NULL) && (cp->cache_flags & UMF_CHECKSIGNAL));	\
1108 	_bcp->bc_lastlog = umem_log_enter((lp), _bcp,			\
1109 	    UMEM_BUFCTL_AUDIT_SIZE);					\
1110 }
1111 
1112 static void
1113 umem_log_event(umem_log_header_t *lp, umem_cache_t *cp,
1114 	umem_slab_t *sp, void *addr)
1115 {
1116 	umem_bufctl_audit_t *bcp;
1117 	UMEM_LOCAL_BUFCTL_AUDIT(&bcp);
1118 
1119 	bzero(bcp, UMEM_BUFCTL_AUDIT_SIZE);
1120 	bcp->bc_addr = addr;
1121 	bcp->bc_slab = sp;
1122 	bcp->bc_cache = cp;
1123 	UMEM_AUDIT(lp, cp, bcp);
1124 }
1125 
1126 /*
1127  * Create a new slab for cache cp.
1128  */
1129 static umem_slab_t *
1130 umem_slab_create(umem_cache_t *cp, int umflag)
1131 {
1132 	size_t slabsize = cp->cache_slabsize;
1133 	size_t chunksize = cp->cache_chunksize;
1134 	int cache_flags = cp->cache_flags;
1135 	size_t color, chunks;
1136 	char *buf, *slab;
1137 	umem_slab_t *sp;
1138 	umem_bufctl_t *bcp;
1139 	vmem_t *vmp = cp->cache_arena;
1140 
1141 	color = cp->cache_color + cp->cache_align;
1142 	if (color > cp->cache_maxcolor)
1143 		color = cp->cache_mincolor;
1144 	cp->cache_color = color;
1145 
1146 	slab = vmem_alloc(vmp, slabsize, UMEM_VMFLAGS(umflag));
1147 
1148 	if (slab == NULL)
1149 		goto vmem_alloc_failure;
1150 
1151 	ASSERT(P2PHASE((uintptr_t)slab, vmp->vm_quantum) == 0);
1152 
1153 	if (!(cp->cache_cflags & UMC_NOTOUCH) &&
1154 	    (cp->cache_flags & UMF_DEADBEEF))
1155 		copy_pattern(UMEM_UNINITIALIZED_PATTERN, slab, slabsize);
1156 
1157 	if (cache_flags & UMF_HASH) {
1158 		if ((sp = _umem_cache_alloc(umem_slab_cache, umflag)) == NULL)
1159 			goto slab_alloc_failure;
1160 		chunks = (slabsize - color) / chunksize;
1161 	} else {
1162 		sp = UMEM_SLAB(cp, slab);
1163 		chunks = (slabsize - sizeof (umem_slab_t) - color) / chunksize;
1164 	}
1165 
1166 	sp->slab_cache	= cp;
1167 	sp->slab_head	= NULL;
1168 	sp->slab_refcnt	= 0;
1169 	sp->slab_base	= buf = slab + color;
1170 	sp->slab_chunks	= chunks;
1171 
1172 	ASSERT(chunks > 0);
1173 	while (chunks-- != 0) {
1174 		if (cache_flags & UMF_HASH) {
1175 			bcp = _umem_cache_alloc(cp->cache_bufctl_cache, umflag);
1176 			if (bcp == NULL)
1177 				goto bufctl_alloc_failure;
1178 			if (cache_flags & UMF_AUDIT) {
1179 				umem_bufctl_audit_t *bcap =
1180 				    (umem_bufctl_audit_t *)bcp;
1181 				bzero(bcap, UMEM_BUFCTL_AUDIT_SIZE);
1182 				bcap->bc_cache = cp;
1183 			}
1184 			bcp->bc_addr = buf;
1185 			bcp->bc_slab = sp;
1186 		} else {
1187 			bcp = UMEM_BUFCTL(cp, buf);
1188 		}
1189 		if (cache_flags & UMF_BUFTAG) {
1190 			umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1191 			btp->bt_redzone = UMEM_REDZONE_PATTERN;
1192 			btp->bt_bufctl = bcp;
1193 			btp->bt_bxstat = (intptr_t)bcp ^ UMEM_BUFTAG_FREE;
1194 			if (cache_flags & UMF_DEADBEEF) {
1195 				copy_pattern(UMEM_FREE_PATTERN, buf,
1196 				    cp->cache_verify);
1197 			}
1198 		}
1199 		bcp->bc_next = sp->slab_head;
1200 		sp->slab_head = bcp;
1201 		buf += chunksize;
1202 	}
1203 
1204 	umem_log_event(umem_slab_log, cp, sp, slab);
1205 
1206 	return (sp);
1207 
1208 bufctl_alloc_failure:
1209 
1210 	while ((bcp = sp->slab_head) != NULL) {
1211 		sp->slab_head = bcp->bc_next;
1212 		_umem_cache_free(cp->cache_bufctl_cache, bcp);
1213 	}
1214 	_umem_cache_free(umem_slab_cache, sp);
1215 
1216 slab_alloc_failure:
1217 
1218 	vmem_free(vmp, slab, slabsize);
1219 
1220 vmem_alloc_failure:
1221 
1222 	umem_log_event(umem_failure_log, cp, NULL, NULL);
1223 	atomic_add_64(&cp->cache_alloc_fail, 1);
1224 
1225 	return (NULL);
1226 }
1227 
1228 /*
1229  * Destroy a slab.
1230  */
1231 static void
1232 umem_slab_destroy(umem_cache_t *cp, umem_slab_t *sp)
1233 {
1234 	vmem_t *vmp = cp->cache_arena;
1235 	void *slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, vmp->vm_quantum);
1236 
1237 	if (cp->cache_flags & UMF_HASH) {
1238 		umem_bufctl_t *bcp;
1239 		while ((bcp = sp->slab_head) != NULL) {
1240 			sp->slab_head = bcp->bc_next;
1241 			_umem_cache_free(cp->cache_bufctl_cache, bcp);
1242 		}
1243 		_umem_cache_free(umem_slab_cache, sp);
1244 	}
1245 	vmem_free(vmp, slab, cp->cache_slabsize);
1246 }
1247 
1248 /*
1249  * Allocate a raw (unconstructed) buffer from cp's slab layer.
1250  */
1251 static void *
1252 umem_slab_alloc(umem_cache_t *cp, int umflag)
1253 {
1254 	umem_bufctl_t *bcp, **hash_bucket;
1255 	umem_slab_t *sp;
1256 	void *buf;
1257 
1258 	(void) mutex_lock(&cp->cache_lock);
1259 	cp->cache_slab_alloc++;
1260 	sp = cp->cache_freelist;
1261 	ASSERT(sp->slab_cache == cp);
1262 	if (sp->slab_head == NULL) {
1263 		/*
1264 		 * The freelist is empty.  Create a new slab.
1265 		 */
1266 		(void) mutex_unlock(&cp->cache_lock);
1267 		if (cp == &umem_null_cache)
1268 			return (NULL);
1269 		if ((sp = umem_slab_create(cp, umflag)) == NULL)
1270 			return (NULL);
1271 		(void) mutex_lock(&cp->cache_lock);
1272 		cp->cache_slab_create++;
1273 		if ((cp->cache_buftotal += sp->slab_chunks) > cp->cache_bufmax)
1274 			cp->cache_bufmax = cp->cache_buftotal;
1275 		sp->slab_next = cp->cache_freelist;
1276 		sp->slab_prev = cp->cache_freelist->slab_prev;
1277 		sp->slab_next->slab_prev = sp;
1278 		sp->slab_prev->slab_next = sp;
1279 		cp->cache_freelist = sp;
1280 	}
1281 
1282 	sp->slab_refcnt++;
1283 	ASSERT(sp->slab_refcnt <= sp->slab_chunks);
1284 
1285 	/*
1286 	 * If we're taking the last buffer in the slab,
1287 	 * remove the slab from the cache's freelist.
1288 	 */
1289 	bcp = sp->slab_head;
1290 	if ((sp->slab_head = bcp->bc_next) == NULL) {
1291 		cp->cache_freelist = sp->slab_next;
1292 		ASSERT(sp->slab_refcnt == sp->slab_chunks);
1293 	}
1294 
1295 	if (cp->cache_flags & UMF_HASH) {
1296 		/*
1297 		 * Add buffer to allocated-address hash table.
1298 		 */
1299 		buf = bcp->bc_addr;
1300 		hash_bucket = UMEM_HASH(cp, buf);
1301 		bcp->bc_next = *hash_bucket;
1302 		*hash_bucket = bcp;
1303 		if ((cp->cache_flags & (UMF_AUDIT | UMF_BUFTAG)) == UMF_AUDIT) {
1304 			UMEM_AUDIT(umem_transaction_log, cp, bcp);
1305 		}
1306 	} else {
1307 		buf = UMEM_BUF(cp, bcp);
1308 	}
1309 
1310 	ASSERT(UMEM_SLAB_MEMBER(sp, buf));
1311 
1312 	(void) mutex_unlock(&cp->cache_lock);
1313 
1314 	return (buf);
1315 }
1316 
1317 /*
1318  * Free a raw (unconstructed) buffer to cp's slab layer.
1319  */
1320 static void
1321 umem_slab_free(umem_cache_t *cp, void *buf)
1322 {
1323 	umem_slab_t *sp;
1324 	umem_bufctl_t *bcp, **prev_bcpp;
1325 
1326 	ASSERT(buf != NULL);
1327 
1328 	(void) mutex_lock(&cp->cache_lock);
1329 	cp->cache_slab_free++;
1330 
1331 	if (cp->cache_flags & UMF_HASH) {
1332 		/*
1333 		 * Look up buffer in allocated-address hash table.
1334 		 */
1335 		prev_bcpp = UMEM_HASH(cp, buf);
1336 		while ((bcp = *prev_bcpp) != NULL) {
1337 			if (bcp->bc_addr == buf) {
1338 				*prev_bcpp = bcp->bc_next;
1339 				sp = bcp->bc_slab;
1340 				break;
1341 			}
1342 			cp->cache_lookup_depth++;
1343 			prev_bcpp = &bcp->bc_next;
1344 		}
1345 	} else {
1346 		bcp = UMEM_BUFCTL(cp, buf);
1347 		sp = UMEM_SLAB(cp, buf);
1348 	}
1349 
1350 	if (bcp == NULL || sp->slab_cache != cp || !UMEM_SLAB_MEMBER(sp, buf)) {
1351 		(void) mutex_unlock(&cp->cache_lock);
1352 		umem_error(UMERR_BADADDR, cp, buf);
1353 		return;
1354 	}
1355 
1356 	if ((cp->cache_flags & (UMF_AUDIT | UMF_BUFTAG)) == UMF_AUDIT) {
1357 		if (cp->cache_flags & UMF_CONTENTS)
1358 			((umem_bufctl_audit_t *)bcp)->bc_contents =
1359 			    umem_log_enter(umem_content_log, buf,
1360 			    cp->cache_contents);
1361 		UMEM_AUDIT(umem_transaction_log, cp, bcp);
1362 	}
1363 
1364 	/*
1365 	 * If this slab isn't currently on the freelist, put it there.
1366 	 */
1367 	if (sp->slab_head == NULL) {
1368 		ASSERT(sp->slab_refcnt == sp->slab_chunks);
1369 		ASSERT(cp->cache_freelist != sp);
1370 		sp->slab_next->slab_prev = sp->slab_prev;
1371 		sp->slab_prev->slab_next = sp->slab_next;
1372 		sp->slab_next = cp->cache_freelist;
1373 		sp->slab_prev = cp->cache_freelist->slab_prev;
1374 		sp->slab_next->slab_prev = sp;
1375 		sp->slab_prev->slab_next = sp;
1376 		cp->cache_freelist = sp;
1377 	}
1378 
1379 	bcp->bc_next = sp->slab_head;
1380 	sp->slab_head = bcp;
1381 
1382 	ASSERT(sp->slab_refcnt >= 1);
1383 	if (--sp->slab_refcnt == 0) {
1384 		/*
1385 		 * There are no outstanding allocations from this slab,
1386 		 * so we can reclaim the memory.
1387 		 */
1388 		sp->slab_next->slab_prev = sp->slab_prev;
1389 		sp->slab_prev->slab_next = sp->slab_next;
1390 		if (sp == cp->cache_freelist)
1391 			cp->cache_freelist = sp->slab_next;
1392 		cp->cache_slab_destroy++;
1393 		cp->cache_buftotal -= sp->slab_chunks;
1394 		(void) mutex_unlock(&cp->cache_lock);
1395 		umem_slab_destroy(cp, sp);
1396 		return;
1397 	}
1398 	(void) mutex_unlock(&cp->cache_lock);
1399 }
1400 
1401 static int
1402 umem_cache_alloc_debug(umem_cache_t *cp, void *buf, int umflag)
1403 {
1404 	umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1405 	umem_bufctl_audit_t *bcp = (umem_bufctl_audit_t *)btp->bt_bufctl;
1406 	uint32_t mtbf;
1407 	int flags_nfatal;
1408 
1409 	if (btp->bt_bxstat != ((intptr_t)bcp ^ UMEM_BUFTAG_FREE)) {
1410 		umem_error(UMERR_BADBUFTAG, cp, buf);
1411 		return (-1);
1412 	}
1413 
1414 	btp->bt_bxstat = (intptr_t)bcp ^ UMEM_BUFTAG_ALLOC;
1415 
1416 	if ((cp->cache_flags & UMF_HASH) && bcp->bc_addr != buf) {
1417 		umem_error(UMERR_BADBUFCTL, cp, buf);
1418 		return (-1);
1419 	}
1420 
1421 	btp->bt_redzone = UMEM_REDZONE_PATTERN;
1422 
1423 	if (cp->cache_flags & UMF_DEADBEEF) {
1424 		if (verify_and_copy_pattern(UMEM_FREE_PATTERN,
1425 		    UMEM_UNINITIALIZED_PATTERN, buf, cp->cache_verify)) {
1426 			umem_error(UMERR_MODIFIED, cp, buf);
1427 			return (-1);
1428 		}
1429 	}
1430 
1431 	if ((mtbf = umem_mtbf | cp->cache_mtbf) != 0 &&
1432 	    gethrtime() % mtbf == 0 &&
1433 	    (umflag & (UMEM_FATAL_FLAGS)) == 0) {
1434 		umem_log_event(umem_failure_log, cp, NULL, NULL);
1435 	} else {
1436 		mtbf = 0;
1437 	}
1438 
1439 	/*
1440 	 * We do not pass fatal flags on to the constructor.  This prevents
1441 	 * leaking buffers in the event of a subordinate constructor failing.
1442 	 */
1443 	flags_nfatal = UMEM_DEFAULT;
1444 	if (mtbf || (cp->cache_constructor != NULL &&
1445 	    cp->cache_constructor(buf, cp->cache_private, flags_nfatal) != 0)) {
1446 		atomic_add_64(&cp->cache_alloc_fail, 1);
1447 		btp->bt_bxstat = (intptr_t)bcp ^ UMEM_BUFTAG_FREE;
1448 		copy_pattern(UMEM_FREE_PATTERN, buf, cp->cache_verify);
1449 		umem_slab_free(cp, buf);
1450 		return (-1);
1451 	}
1452 
1453 	if (cp->cache_flags & UMF_AUDIT) {
1454 		UMEM_AUDIT(umem_transaction_log, cp, bcp);
1455 	}
1456 
1457 	return (0);
1458 }
1459 
1460 static int
1461 umem_cache_free_debug(umem_cache_t *cp, void *buf)
1462 {
1463 	umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1464 	umem_bufctl_audit_t *bcp = (umem_bufctl_audit_t *)btp->bt_bufctl;
1465 	umem_slab_t *sp;
1466 
1467 	if (btp->bt_bxstat != ((intptr_t)bcp ^ UMEM_BUFTAG_ALLOC)) {
1468 		if (btp->bt_bxstat == ((intptr_t)bcp ^ UMEM_BUFTAG_FREE)) {
1469 			umem_error(UMERR_DUPFREE, cp, buf);
1470 			return (-1);
1471 		}
1472 		sp = umem_findslab(cp, buf);
1473 		if (sp == NULL || sp->slab_cache != cp)
1474 			umem_error(UMERR_BADADDR, cp, buf);
1475 		else
1476 			umem_error(UMERR_REDZONE, cp, buf);
1477 		return (-1);
1478 	}
1479 
1480 	btp->bt_bxstat = (intptr_t)bcp ^ UMEM_BUFTAG_FREE;
1481 
1482 	if ((cp->cache_flags & UMF_HASH) && bcp->bc_addr != buf) {
1483 		umem_error(UMERR_BADBUFCTL, cp, buf);
1484 		return (-1);
1485 	}
1486 
1487 	if (btp->bt_redzone != UMEM_REDZONE_PATTERN) {
1488 		umem_error(UMERR_REDZONE, cp, buf);
1489 		return (-1);
1490 	}
1491 
1492 	if (cp->cache_flags & UMF_AUDIT) {
1493 		if (cp->cache_flags & UMF_CONTENTS)
1494 			bcp->bc_contents = umem_log_enter(umem_content_log,
1495 			    buf, cp->cache_contents);
1496 		UMEM_AUDIT(umem_transaction_log, cp, bcp);
1497 	}
1498 
1499 	if (cp->cache_destructor != NULL)
1500 		cp->cache_destructor(buf, cp->cache_private);
1501 
1502 	if (cp->cache_flags & UMF_DEADBEEF)
1503 		copy_pattern(UMEM_FREE_PATTERN, buf, cp->cache_verify);
1504 
1505 	return (0);
1506 }
1507 
1508 /*
1509  * Free each object in magazine mp to cp's slab layer, and free mp itself.
1510  */
1511 static void
1512 umem_magazine_destroy(umem_cache_t *cp, umem_magazine_t *mp, int nrounds)
1513 {
1514 	int round;
1515 
1516 	ASSERT(cp->cache_next == NULL || IN_UPDATE());
1517 
1518 	for (round = 0; round < nrounds; round++) {
1519 		void *buf = mp->mag_round[round];
1520 
1521 		if ((cp->cache_flags & UMF_DEADBEEF) &&
1522 		    verify_pattern(UMEM_FREE_PATTERN, buf,
1523 		    cp->cache_verify) != NULL) {
1524 			umem_error(UMERR_MODIFIED, cp, buf);
1525 			continue;
1526 		}
1527 
1528 		if (!(cp->cache_flags & UMF_BUFTAG) &&
1529 		    cp->cache_destructor != NULL)
1530 			cp->cache_destructor(buf, cp->cache_private);
1531 
1532 		umem_slab_free(cp, buf);
1533 	}
1534 	ASSERT(UMEM_MAGAZINE_VALID(cp, mp));
1535 	_umem_cache_free(cp->cache_magtype->mt_cache, mp);
1536 }
1537 
1538 /*
1539  * Allocate a magazine from the depot.
1540  */
1541 static umem_magazine_t *
1542 umem_depot_alloc(umem_cache_t *cp, umem_maglist_t *mlp)
1543 {
1544 	umem_magazine_t *mp;
1545 
1546 	/*
1547 	 * If we can't get the depot lock without contention,
1548 	 * update our contention count.  We use the depot
1549 	 * contention rate to determine whether we need to
1550 	 * increase the magazine size for better scalability.
1551 	 */
1552 	if (mutex_trylock(&cp->cache_depot_lock) != 0) {
1553 		(void) mutex_lock(&cp->cache_depot_lock);
1554 		cp->cache_depot_contention++;
1555 	}
1556 
1557 	if ((mp = mlp->ml_list) != NULL) {
1558 		ASSERT(UMEM_MAGAZINE_VALID(cp, mp));
1559 		mlp->ml_list = mp->mag_next;
1560 		if (--mlp->ml_total < mlp->ml_min)
1561 			mlp->ml_min = mlp->ml_total;
1562 		mlp->ml_alloc++;
1563 	}
1564 
1565 	(void) mutex_unlock(&cp->cache_depot_lock);
1566 
1567 	return (mp);
1568 }
1569 
1570 /*
1571  * Free a magazine to the depot.
1572  */
1573 static void
1574 umem_depot_free(umem_cache_t *cp, umem_maglist_t *mlp, umem_magazine_t *mp)
1575 {
1576 	(void) mutex_lock(&cp->cache_depot_lock);
1577 	ASSERT(UMEM_MAGAZINE_VALID(cp, mp));
1578 	mp->mag_next = mlp->ml_list;
1579 	mlp->ml_list = mp;
1580 	mlp->ml_total++;
1581 	(void) mutex_unlock(&cp->cache_depot_lock);
1582 }
1583 
1584 /*
1585  * Update the working set statistics for cp's depot.
1586  */
1587 static void
1588 umem_depot_ws_update(umem_cache_t *cp)
1589 {
1590 	(void) mutex_lock(&cp->cache_depot_lock);
1591 	cp->cache_full.ml_reaplimit = cp->cache_full.ml_min;
1592 	cp->cache_full.ml_min = cp->cache_full.ml_total;
1593 	cp->cache_empty.ml_reaplimit = cp->cache_empty.ml_min;
1594 	cp->cache_empty.ml_min = cp->cache_empty.ml_total;
1595 	(void) mutex_unlock(&cp->cache_depot_lock);
1596 }
1597 
1598 /*
1599  * Reap all magazines that have fallen out of the depot's working set.
1600  */
1601 static void
1602 umem_depot_ws_reap(umem_cache_t *cp)
1603 {
1604 	long reap;
1605 	umem_magazine_t *mp;
1606 
1607 	ASSERT(cp->cache_next == NULL || IN_REAP());
1608 
1609 	reap = MIN(cp->cache_full.ml_reaplimit, cp->cache_full.ml_min);
1610 	while (reap-- && (mp = umem_depot_alloc(cp, &cp->cache_full)) != NULL)
1611 		umem_magazine_destroy(cp, mp, cp->cache_magtype->mt_magsize);
1612 
1613 	reap = MIN(cp->cache_empty.ml_reaplimit, cp->cache_empty.ml_min);
1614 	while (reap-- && (mp = umem_depot_alloc(cp, &cp->cache_empty)) != NULL)
1615 		umem_magazine_destroy(cp, mp, 0);
1616 }
1617 
1618 static void
1619 umem_cpu_reload(umem_cpu_cache_t *ccp, umem_magazine_t *mp, int rounds)
1620 {
1621 	ASSERT((ccp->cc_loaded == NULL && ccp->cc_rounds == -1) ||
1622 	    (ccp->cc_loaded && ccp->cc_rounds + rounds == ccp->cc_magsize));
1623 	ASSERT(ccp->cc_magsize > 0);
1624 
1625 	ccp->cc_ploaded = ccp->cc_loaded;
1626 	ccp->cc_prounds = ccp->cc_rounds;
1627 	ccp->cc_loaded = mp;
1628 	ccp->cc_rounds = rounds;
1629 }
1630 
1631 /*
1632  * Allocate a constructed object from cache cp.
1633  */
1634 #pragma weak umem_cache_alloc = _umem_cache_alloc
1635 void *
1636 _umem_cache_alloc(umem_cache_t *cp, int umflag)
1637 {
1638 	umem_cpu_cache_t *ccp;
1639 	umem_magazine_t *fmp;
1640 	void *buf;
1641 	int flags_nfatal;
1642 
1643 retry:
1644 	ccp = UMEM_CPU_CACHE(cp, CPU(cp->cache_cpu_mask));
1645 	(void) mutex_lock(&ccp->cc_lock);
1646 	for (;;) {
1647 		/*
1648 		 * If there's an object available in the current CPU's
1649 		 * loaded magazine, just take it and return.
1650 		 */
1651 		if (ccp->cc_rounds > 0) {
1652 			buf = ccp->cc_loaded->mag_round[--ccp->cc_rounds];
1653 			ccp->cc_alloc++;
1654 			(void) mutex_unlock(&ccp->cc_lock);
1655 			if ((ccp->cc_flags & UMF_BUFTAG) &&
1656 			    umem_cache_alloc_debug(cp, buf, umflag) == -1) {
1657 				if (umem_alloc_retry(cp, umflag)) {
1658 					goto retry;
1659 				}
1660 
1661 				return (NULL);
1662 			}
1663 			return (buf);
1664 		}
1665 
1666 		/*
1667 		 * The loaded magazine is empty.  If the previously loaded
1668 		 * magazine was full, exchange them and try again.
1669 		 */
1670 		if (ccp->cc_prounds > 0) {
1671 			umem_cpu_reload(ccp, ccp->cc_ploaded, ccp->cc_prounds);
1672 			continue;
1673 		}
1674 
1675 		/*
1676 		 * If the magazine layer is disabled, break out now.
1677 		 */
1678 		if (ccp->cc_magsize == 0)
1679 			break;
1680 
1681 		/*
1682 		 * Try to get a full magazine from the depot.
1683 		 */
1684 		fmp = umem_depot_alloc(cp, &cp->cache_full);
1685 		if (fmp != NULL) {
1686 			if (ccp->cc_ploaded != NULL)
1687 				umem_depot_free(cp, &cp->cache_empty,
1688 				    ccp->cc_ploaded);
1689 			umem_cpu_reload(ccp, fmp, ccp->cc_magsize);
1690 			continue;
1691 		}
1692 
1693 		/*
1694 		 * There are no full magazines in the depot,
1695 		 * so fall through to the slab layer.
1696 		 */
1697 		break;
1698 	}
1699 	(void) mutex_unlock(&ccp->cc_lock);
1700 
1701 	/*
1702 	 * We couldn't allocate a constructed object from the magazine layer,
1703 	 * so get a raw buffer from the slab layer and apply its constructor.
1704 	 */
1705 	buf = umem_slab_alloc(cp, umflag);
1706 
1707 	if (buf == NULL) {
1708 		if (cp == &umem_null_cache)
1709 			return (NULL);
1710 		if (umem_alloc_retry(cp, umflag)) {
1711 			goto retry;
1712 		}
1713 
1714 		return (NULL);
1715 	}
1716 
1717 	if (cp->cache_flags & UMF_BUFTAG) {
1718 		/*
1719 		 * Let umem_cache_alloc_debug() apply the constructor for us.
1720 		 */
1721 		if (umem_cache_alloc_debug(cp, buf, umflag) == -1) {
1722 			if (umem_alloc_retry(cp, umflag)) {
1723 				goto retry;
1724 			}
1725 			return (NULL);
1726 		}
1727 		return (buf);
1728 	}
1729 
1730 	/*
1731 	 * We do not pass fatal flags on to the constructor.  This prevents
1732 	 * leaking buffers in the event of a subordinate constructor failing.
1733 	 */
1734 	flags_nfatal = UMEM_DEFAULT;
1735 	if (cp->cache_constructor != NULL &&
1736 	    cp->cache_constructor(buf, cp->cache_private, flags_nfatal) != 0) {
1737 		atomic_add_64(&cp->cache_alloc_fail, 1);
1738 		umem_slab_free(cp, buf);
1739 
1740 		if (umem_alloc_retry(cp, umflag)) {
1741 			goto retry;
1742 		}
1743 		return (NULL);
1744 	}
1745 
1746 	return (buf);
1747 }
1748 
1749 /*
1750  * Free a constructed object to cache cp.
1751  */
1752 #pragma weak umem_cache_free = _umem_cache_free
1753 void
1754 _umem_cache_free(umem_cache_t *cp, void *buf)
1755 {
1756 	umem_cpu_cache_t *ccp = UMEM_CPU_CACHE(cp, CPU(cp->cache_cpu_mask));
1757 	umem_magazine_t *emp;
1758 	umem_magtype_t *mtp;
1759 
1760 	if (ccp->cc_flags & UMF_BUFTAG)
1761 		if (umem_cache_free_debug(cp, buf) == -1)
1762 			return;
1763 
1764 	(void) mutex_lock(&ccp->cc_lock);
1765 	for (;;) {
1766 		/*
1767 		 * If there's a slot available in the current CPU's
1768 		 * loaded magazine, just put the object there and return.
1769 		 */
1770 		if ((uint_t)ccp->cc_rounds < ccp->cc_magsize) {
1771 			ccp->cc_loaded->mag_round[ccp->cc_rounds++] = buf;
1772 			ccp->cc_free++;
1773 			(void) mutex_unlock(&ccp->cc_lock);
1774 			return;
1775 		}
1776 
1777 		/*
1778 		 * The loaded magazine is full.  If the previously loaded
1779 		 * magazine was empty, exchange them and try again.
1780 		 */
1781 		if (ccp->cc_prounds == 0) {
1782 			umem_cpu_reload(ccp, ccp->cc_ploaded, ccp->cc_prounds);
1783 			continue;
1784 		}
1785 
1786 		/*
1787 		 * If the magazine layer is disabled, break out now.
1788 		 */
1789 		if (ccp->cc_magsize == 0)
1790 			break;
1791 
1792 		/*
1793 		 * Try to get an empty magazine from the depot.
1794 		 */
1795 		emp = umem_depot_alloc(cp, &cp->cache_empty);
1796 		if (emp != NULL) {
1797 			if (ccp->cc_ploaded != NULL)
1798 				umem_depot_free(cp, &cp->cache_full,
1799 				    ccp->cc_ploaded);
1800 			umem_cpu_reload(ccp, emp, 0);
1801 			continue;
1802 		}
1803 
1804 		/*
1805 		 * There are no empty magazines in the depot,
1806 		 * so try to allocate a new one.  We must drop all locks
1807 		 * across umem_cache_alloc() because lower layers may
1808 		 * attempt to allocate from this cache.
1809 		 */
1810 		mtp = cp->cache_magtype;
1811 		(void) mutex_unlock(&ccp->cc_lock);
1812 		emp = _umem_cache_alloc(mtp->mt_cache, UMEM_DEFAULT);
1813 		(void) mutex_lock(&ccp->cc_lock);
1814 
1815 		if (emp != NULL) {
1816 			/*
1817 			 * We successfully allocated an empty magazine.
1818 			 * However, we had to drop ccp->cc_lock to do it,
1819 			 * so the cache's magazine size may have changed.
1820 			 * If so, free the magazine and try again.
1821 			 */
1822 			if (ccp->cc_magsize != mtp->mt_magsize) {
1823 				(void) mutex_unlock(&ccp->cc_lock);
1824 				_umem_cache_free(mtp->mt_cache, emp);
1825 				(void) mutex_lock(&ccp->cc_lock);
1826 				continue;
1827 			}
1828 
1829 			/*
1830 			 * We got a magazine of the right size.  Add it to
1831 			 * the depot and try the whole dance again.
1832 			 */
1833 			umem_depot_free(cp, &cp->cache_empty, emp);
1834 			continue;
1835 		}
1836 
1837 		/*
1838 		 * We couldn't allocate an empty magazine,
1839 		 * so fall through to the slab layer.
1840 		 */
1841 		break;
1842 	}
1843 	(void) mutex_unlock(&ccp->cc_lock);
1844 
1845 	/*
1846 	 * We couldn't free our constructed object to the magazine layer,
1847 	 * so apply its destructor and free it to the slab layer.
1848 	 * Note that if UMF_BUFTAG is in effect, umem_cache_free_debug()
1849 	 * will have already applied the destructor.
1850 	 */
1851 	if (!(cp->cache_flags & UMF_BUFTAG) && cp->cache_destructor != NULL)
1852 		cp->cache_destructor(buf, cp->cache_private);
1853 
1854 	umem_slab_free(cp, buf);
1855 }
1856 
1857 #pragma weak umem_zalloc = _umem_zalloc
1858 void *
1859 _umem_zalloc(size_t size, int umflag)
1860 {
1861 	size_t index = (size - 1) >> UMEM_ALIGN_SHIFT;
1862 	void *buf;
1863 
1864 retry:
1865 	if (index < UMEM_MAXBUF >> UMEM_ALIGN_SHIFT) {
1866 		umem_cache_t *cp = umem_alloc_table[index];
1867 		buf = _umem_cache_alloc(cp, umflag);
1868 		if (buf != NULL) {
1869 			if (cp->cache_flags & UMF_BUFTAG) {
1870 				umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1871 				((uint8_t *)buf)[size] = UMEM_REDZONE_BYTE;
1872 				((uint32_t *)btp)[1] = UMEM_SIZE_ENCODE(size);
1873 			}
1874 			bzero(buf, size);
1875 		} else if (umem_alloc_retry(cp, umflag))
1876 			goto retry;
1877 	} else {
1878 		buf = _umem_alloc(size, umflag);	/* handles failure */
1879 		if (buf != NULL)
1880 			bzero(buf, size);
1881 	}
1882 	return (buf);
1883 }
1884 
1885 #pragma weak umem_alloc = _umem_alloc
1886 void *
1887 _umem_alloc(size_t size, int umflag)
1888 {
1889 	size_t index = (size - 1) >> UMEM_ALIGN_SHIFT;
1890 	void *buf;
1891 umem_alloc_retry:
1892 	if (index < UMEM_MAXBUF >> UMEM_ALIGN_SHIFT) {
1893 		umem_cache_t *cp = umem_alloc_table[index];
1894 		buf = _umem_cache_alloc(cp, umflag);
1895 		if ((cp->cache_flags & UMF_BUFTAG) && buf != NULL) {
1896 			umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1897 			((uint8_t *)buf)[size] = UMEM_REDZONE_BYTE;
1898 			((uint32_t *)btp)[1] = UMEM_SIZE_ENCODE(size);
1899 		}
1900 		if (buf == NULL && umem_alloc_retry(cp, umflag))
1901 			goto umem_alloc_retry;
1902 		return (buf);
1903 	}
1904 	if (size == 0)
1905 		return (NULL);
1906 	if (umem_oversize_arena == NULL) {
1907 		if (umem_init())
1908 			ASSERT(umem_oversize_arena != NULL);
1909 		else
1910 			return (NULL);
1911 	}
1912 	buf = vmem_alloc(umem_oversize_arena, size, UMEM_VMFLAGS(umflag));
1913 	if (buf == NULL) {
1914 		umem_log_event(umem_failure_log, NULL, NULL, (void *)size);
1915 		if (umem_alloc_retry(NULL, umflag))
1916 			goto umem_alloc_retry;
1917 	}
1918 	return (buf);
1919 }
1920 
1921 #pragma weak umem_alloc_align = _umem_alloc_align
1922 void *
1923 _umem_alloc_align(size_t size, size_t align, int umflag)
1924 {
1925 	void *buf;
1926 
1927 	if (size == 0)
1928 		return (NULL);
1929 	if ((align & (align - 1)) != 0)
1930 		return (NULL);
1931 	if (align < UMEM_ALIGN)
1932 		align = UMEM_ALIGN;
1933 
1934 umem_alloc_align_retry:
1935 	if (umem_memalign_arena == NULL) {
1936 		if (umem_init())
1937 			ASSERT(umem_oversize_arena != NULL);
1938 		else
1939 			return (NULL);
1940 	}
1941 	buf = vmem_xalloc(umem_memalign_arena, size, align, 0, 0, NULL, NULL,
1942 	    UMEM_VMFLAGS(umflag));
1943 	if (buf == NULL) {
1944 		umem_log_event(umem_failure_log, NULL, NULL, (void *)size);
1945 		if (umem_alloc_retry(NULL, umflag))
1946 			goto umem_alloc_align_retry;
1947 	}
1948 	return (buf);
1949 }
1950 
1951 #pragma weak umem_free = _umem_free
1952 void
1953 _umem_free(void *buf, size_t size)
1954 {
1955 	size_t index = (size - 1) >> UMEM_ALIGN_SHIFT;
1956 
1957 	if (index < UMEM_MAXBUF >> UMEM_ALIGN_SHIFT) {
1958 		umem_cache_t *cp = umem_alloc_table[index];
1959 		if (cp->cache_flags & UMF_BUFTAG) {
1960 			umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1961 			uint32_t *ip = (uint32_t *)btp;
1962 			if (ip[1] != UMEM_SIZE_ENCODE(size)) {
1963 				if (*(uint64_t *)buf == UMEM_FREE_PATTERN) {
1964 					umem_error(UMERR_DUPFREE, cp, buf);
1965 					return;
1966 				}
1967 				if (UMEM_SIZE_VALID(ip[1])) {
1968 					ip[0] = UMEM_SIZE_ENCODE(size);
1969 					umem_error(UMERR_BADSIZE, cp, buf);
1970 				} else {
1971 					umem_error(UMERR_REDZONE, cp, buf);
1972 				}
1973 				return;
1974 			}
1975 			if (((uint8_t *)buf)[size] != UMEM_REDZONE_BYTE) {
1976 				umem_error(UMERR_REDZONE, cp, buf);
1977 				return;
1978 			}
1979 			btp->bt_redzone = UMEM_REDZONE_PATTERN;
1980 		}
1981 		_umem_cache_free(cp, buf);
1982 	} else {
1983 		if (buf == NULL && size == 0)
1984 			return;
1985 		vmem_free(umem_oversize_arena, buf, size);
1986 	}
1987 }
1988 
1989 #pragma weak umem_free_align = _umem_free_align
1990 void
1991 _umem_free_align(void *buf, size_t size)
1992 {
1993 	if (buf == NULL && size == 0)
1994 		return;
1995 	vmem_xfree(umem_memalign_arena, buf, size);
1996 }
1997 
1998 static void *
1999 umem_firewall_va_alloc(vmem_t *vmp, size_t size, int vmflag)
2000 {
2001 	size_t realsize = size + vmp->vm_quantum;
2002 
2003 	/*
2004 	 * Annoying edge case: if 'size' is just shy of ULONG_MAX, adding
2005 	 * vm_quantum will cause integer wraparound.  Check for this, and
2006 	 * blow off the firewall page in this case.  Note that such a
2007 	 * giant allocation (the entire address space) can never be
2008 	 * satisfied, so it will either fail immediately (VM_NOSLEEP)
2009 	 * or sleep forever (VM_SLEEP).  Thus, there is no need for a
2010 	 * corresponding check in umem_firewall_va_free().
2011 	 */
2012 	if (realsize < size)
2013 		realsize = size;
2014 
2015 	return (vmem_alloc(vmp, realsize, vmflag | VM_NEXTFIT));
2016 }
2017 
2018 static void
2019 umem_firewall_va_free(vmem_t *vmp, void *addr, size_t size)
2020 {
2021 	vmem_free(vmp, addr, size + vmp->vm_quantum);
2022 }
2023 
2024 /*
2025  * Reclaim all unused memory from a cache.
2026  */
2027 static void
2028 umem_cache_reap(umem_cache_t *cp)
2029 {
2030 	/*
2031 	 * Ask the cache's owner to free some memory if possible.
2032 	 * The idea is to handle things like the inode cache, which
2033 	 * typically sits on a bunch of memory that it doesn't truly
2034 	 * *need*.  Reclaim policy is entirely up to the owner; this
2035 	 * callback is just an advisory plea for help.
2036 	 */
2037 	if (cp->cache_reclaim != NULL)
2038 		cp->cache_reclaim(cp->cache_private);
2039 
2040 	umem_depot_ws_reap(cp);
2041 }
2042 
2043 /*
2044  * Purge all magazines from a cache and set its magazine limit to zero.
2045  * All calls are serialized by being done by the update thread, except for
2046  * the final call from umem_cache_destroy().
2047  */
2048 static void
2049 umem_cache_magazine_purge(umem_cache_t *cp)
2050 {
2051 	umem_cpu_cache_t *ccp;
2052 	umem_magazine_t *mp, *pmp;
2053 	int rounds, prounds, cpu_seqid;
2054 
2055 	ASSERT(cp->cache_next == NULL || IN_UPDATE());
2056 
2057 	for (cpu_seqid = 0; cpu_seqid < umem_max_ncpus; cpu_seqid++) {
2058 		ccp = &cp->cache_cpu[cpu_seqid];
2059 
2060 		(void) mutex_lock(&ccp->cc_lock);
2061 		mp = ccp->cc_loaded;
2062 		pmp = ccp->cc_ploaded;
2063 		rounds = ccp->cc_rounds;
2064 		prounds = ccp->cc_prounds;
2065 		ccp->cc_loaded = NULL;
2066 		ccp->cc_ploaded = NULL;
2067 		ccp->cc_rounds = -1;
2068 		ccp->cc_prounds = -1;
2069 		ccp->cc_magsize = 0;
2070 		(void) mutex_unlock(&ccp->cc_lock);
2071 
2072 		if (mp)
2073 			umem_magazine_destroy(cp, mp, rounds);
2074 		if (pmp)
2075 			umem_magazine_destroy(cp, pmp, prounds);
2076 	}
2077 
2078 	/*
2079 	 * Updating the working set statistics twice in a row has the
2080 	 * effect of setting the working set size to zero, so everything
2081 	 * is eligible for reaping.
2082 	 */
2083 	umem_depot_ws_update(cp);
2084 	umem_depot_ws_update(cp);
2085 
2086 	umem_depot_ws_reap(cp);
2087 }
2088 
2089 /*
2090  * Enable per-cpu magazines on a cache.
2091  */
2092 static void
2093 umem_cache_magazine_enable(umem_cache_t *cp)
2094 {
2095 	int cpu_seqid;
2096 
2097 	if (cp->cache_flags & UMF_NOMAGAZINE)
2098 		return;
2099 
2100 	for (cpu_seqid = 0; cpu_seqid < umem_max_ncpus; cpu_seqid++) {
2101 		umem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
2102 		(void) mutex_lock(&ccp->cc_lock);
2103 		ccp->cc_magsize = cp->cache_magtype->mt_magsize;
2104 		(void) mutex_unlock(&ccp->cc_lock);
2105 	}
2106 
2107 }
2108 
2109 /*
2110  * Recompute a cache's magazine size.  The trade-off is that larger magazines
2111  * provide a higher transfer rate with the depot, while smaller magazines
2112  * reduce memory consumption.  Magazine resizing is an expensive operation;
2113  * it should not be done frequently.
2114  *
2115  * Changes to the magazine size are serialized by only having one thread
2116  * doing updates. (the update thread)
2117  *
2118  * Note: at present this only grows the magazine size.  It might be useful
2119  * to allow shrinkage too.
2120  */
2121 static void
2122 umem_cache_magazine_resize(umem_cache_t *cp)
2123 {
2124 	umem_magtype_t *mtp = cp->cache_magtype;
2125 
2126 	ASSERT(IN_UPDATE());
2127 
2128 	if (cp->cache_chunksize < mtp->mt_maxbuf) {
2129 		umem_cache_magazine_purge(cp);
2130 		(void) mutex_lock(&cp->cache_depot_lock);
2131 		cp->cache_magtype = ++mtp;
2132 		cp->cache_depot_contention_prev =
2133 		    cp->cache_depot_contention + INT_MAX;
2134 		(void) mutex_unlock(&cp->cache_depot_lock);
2135 		umem_cache_magazine_enable(cp);
2136 	}
2137 }
2138 
2139 /*
2140  * Rescale a cache's hash table, so that the table size is roughly the
2141  * cache size.  We want the average lookup time to be extremely small.
2142  */
2143 static void
2144 umem_hash_rescale(umem_cache_t *cp)
2145 {
2146 	umem_bufctl_t **old_table, **new_table, *bcp;
2147 	size_t old_size, new_size, h;
2148 
2149 	ASSERT(IN_UPDATE());
2150 
2151 	new_size = MAX(UMEM_HASH_INITIAL,
2152 	    1 << (highbit(3 * cp->cache_buftotal + 4) - 2));
2153 	old_size = cp->cache_hash_mask + 1;
2154 
2155 	if ((old_size >> 1) <= new_size && new_size <= (old_size << 1))
2156 		return;
2157 
2158 	new_table = vmem_alloc(umem_hash_arena, new_size * sizeof (void *),
2159 	    VM_NOSLEEP);
2160 	if (new_table == NULL)
2161 		return;
2162 	bzero(new_table, new_size * sizeof (void *));
2163 
2164 	(void) mutex_lock(&cp->cache_lock);
2165 
2166 	old_size = cp->cache_hash_mask + 1;
2167 	old_table = cp->cache_hash_table;
2168 
2169 	cp->cache_hash_mask = new_size - 1;
2170 	cp->cache_hash_table = new_table;
2171 	cp->cache_rescale++;
2172 
2173 	for (h = 0; h < old_size; h++) {
2174 		bcp = old_table[h];
2175 		while (bcp != NULL) {
2176 			void *addr = bcp->bc_addr;
2177 			umem_bufctl_t *next_bcp = bcp->bc_next;
2178 			umem_bufctl_t **hash_bucket = UMEM_HASH(cp, addr);
2179 			bcp->bc_next = *hash_bucket;
2180 			*hash_bucket = bcp;
2181 			bcp = next_bcp;
2182 		}
2183 	}
2184 
2185 	(void) mutex_unlock(&cp->cache_lock);
2186 
2187 	vmem_free(umem_hash_arena, old_table, old_size * sizeof (void *));
2188 }
2189 
2190 /*
2191  * Perform periodic maintenance on a cache: hash rescaling,
2192  * depot working-set update, and magazine resizing.
2193  */
2194 void
2195 umem_cache_update(umem_cache_t *cp)
2196 {
2197 	int update_flags = 0;
2198 
2199 	ASSERT(MUTEX_HELD(&umem_cache_lock));
2200 
2201 	/*
2202 	 * If the cache has become much larger or smaller than its hash table,
2203 	 * fire off a request to rescale the hash table.
2204 	 */
2205 	(void) mutex_lock(&cp->cache_lock);
2206 
2207 	if ((cp->cache_flags & UMF_HASH) &&
2208 	    (cp->cache_buftotal > (cp->cache_hash_mask << 1) ||
2209 	    (cp->cache_buftotal < (cp->cache_hash_mask >> 1) &&
2210 	    cp->cache_hash_mask > UMEM_HASH_INITIAL)))
2211 		update_flags |= UMU_HASH_RESCALE;
2212 
2213 	(void) mutex_unlock(&cp->cache_lock);
2214 
2215 	/*
2216 	 * Update the depot working set statistics.
2217 	 */
2218 	umem_depot_ws_update(cp);
2219 
2220 	/*
2221 	 * If there's a lot of contention in the depot,
2222 	 * increase the magazine size.
2223 	 */
2224 	(void) mutex_lock(&cp->cache_depot_lock);
2225 
2226 	if (cp->cache_chunksize < cp->cache_magtype->mt_maxbuf &&
2227 	    (int)(cp->cache_depot_contention -
2228 	    cp->cache_depot_contention_prev) > umem_depot_contention)
2229 		update_flags |= UMU_MAGAZINE_RESIZE;
2230 
2231 	cp->cache_depot_contention_prev = cp->cache_depot_contention;
2232 
2233 	(void) mutex_unlock(&cp->cache_depot_lock);
2234 
2235 	if (update_flags)
2236 		umem_add_update(cp, update_flags);
2237 }
2238 
2239 /*
2240  * Runs all pending updates.
2241  *
2242  * The update lock must be held on entrance, and will be held on exit.
2243  */
2244 void
2245 umem_process_updates(void)
2246 {
2247 	ASSERT(MUTEX_HELD(&umem_update_lock));
2248 
2249 	while (umem_null_cache.cache_unext != &umem_null_cache) {
2250 		int notify = 0;
2251 		umem_cache_t *cp = umem_null_cache.cache_unext;
2252 
2253 		cp->cache_uprev->cache_unext = cp->cache_unext;
2254 		cp->cache_unext->cache_uprev = cp->cache_uprev;
2255 		cp->cache_uprev = cp->cache_unext = NULL;
2256 
2257 		ASSERT(!(cp->cache_uflags & UMU_ACTIVE));
2258 
2259 		while (cp->cache_uflags) {
2260 			int uflags = (cp->cache_uflags |= UMU_ACTIVE);
2261 			(void) mutex_unlock(&umem_update_lock);
2262 
2263 			/*
2264 			 * The order here is important.  Each step can speed up
2265 			 * later steps.
2266 			 */
2267 
2268 			if (uflags & UMU_HASH_RESCALE)
2269 				umem_hash_rescale(cp);
2270 
2271 			if (uflags & UMU_MAGAZINE_RESIZE)
2272 				umem_cache_magazine_resize(cp);
2273 
2274 			if (uflags & UMU_REAP)
2275 				umem_cache_reap(cp);
2276 
2277 			(void) mutex_lock(&umem_update_lock);
2278 
2279 			/*
2280 			 * check if anyone has requested notification
2281 			 */
2282 			if (cp->cache_uflags & UMU_NOTIFY) {
2283 				uflags |= UMU_NOTIFY;
2284 				notify = 1;
2285 			}
2286 			cp->cache_uflags &= ~uflags;
2287 		}
2288 		if (notify)
2289 			(void) cond_broadcast(&umem_update_cv);
2290 	}
2291 }
2292 
2293 #ifndef UMEM_STANDALONE
2294 static void
2295 umem_st_update(void)
2296 {
2297 	ASSERT(MUTEX_HELD(&umem_update_lock));
2298 	ASSERT(umem_update_thr == 0 && umem_st_update_thr == 0);
2299 
2300 	umem_st_update_thr = thr_self();
2301 
2302 	(void) mutex_unlock(&umem_update_lock);
2303 
2304 	vmem_update(NULL);
2305 	umem_cache_applyall(umem_cache_update);
2306 
2307 	(void) mutex_lock(&umem_update_lock);
2308 
2309 	umem_process_updates();	/* does all of the requested work */
2310 
2311 	umem_reap_next = gethrtime() +
2312 	    (hrtime_t)umem_reap_interval * NANOSEC;
2313 
2314 	umem_reaping = UMEM_REAP_DONE;
2315 
2316 	umem_st_update_thr = 0;
2317 }
2318 #endif
2319 
2320 /*
2321  * Reclaim all unused memory from all caches.  Called from vmem when memory
2322  * gets tight.  Must be called with no locks held.
2323  *
2324  * This just requests a reap on all caches, and notifies the update thread.
2325  */
2326 void
2327 umem_reap(void)
2328 {
2329 #ifndef UMEM_STANDALONE
2330 	extern int __nthreads(void);
2331 #endif
2332 
2333 	if (umem_ready != UMEM_READY || umem_reaping != UMEM_REAP_DONE ||
2334 	    gethrtime() < umem_reap_next)
2335 		return;
2336 
2337 	(void) mutex_lock(&umem_update_lock);
2338 
2339 	if (umem_reaping != UMEM_REAP_DONE || gethrtime() < umem_reap_next) {
2340 		(void) mutex_unlock(&umem_update_lock);
2341 		return;
2342 	}
2343 	umem_reaping = UMEM_REAP_ADDING;	/* lock out other reaps */
2344 
2345 	(void) mutex_unlock(&umem_update_lock);
2346 
2347 	umem_updateall(UMU_REAP);
2348 
2349 	(void) mutex_lock(&umem_update_lock);
2350 
2351 	umem_reaping = UMEM_REAP_ACTIVE;
2352 
2353 	/* Standalone is single-threaded */
2354 #ifndef UMEM_STANDALONE
2355 	if (umem_update_thr == 0) {
2356 		/*
2357 		 * The update thread does not exist.  If the process is
2358 		 * multi-threaded, create it.  If not, or the creation fails,
2359 		 * do the update processing inline.
2360 		 */
2361 		ASSERT(umem_st_update_thr == 0);
2362 
2363 		if (__nthreads() <= 1 || umem_create_update_thread() == 0)
2364 			umem_st_update();
2365 	}
2366 
2367 	(void) cond_broadcast(&umem_update_cv);	/* wake up the update thread */
2368 #endif
2369 
2370 	(void) mutex_unlock(&umem_update_lock);
2371 }
2372 
2373 umem_cache_t *
2374 umem_cache_create(
2375 	char *name,		/* descriptive name for this cache */
2376 	size_t bufsize,		/* size of the objects it manages */
2377 	size_t align,		/* required object alignment */
2378 	umem_constructor_t *constructor, /* object constructor */
2379 	umem_destructor_t *destructor, /* object destructor */
2380 	umem_reclaim_t *reclaim, /* memory reclaim callback */
2381 	void *private,		/* pass-thru arg for constr/destr/reclaim */
2382 	vmem_t *vmp,		/* vmem source for slab allocation */
2383 	int cflags)		/* cache creation flags */
2384 {
2385 	int cpu_seqid;
2386 	size_t chunksize;
2387 	umem_cache_t *cp, *cnext, *cprev;
2388 	umem_magtype_t *mtp;
2389 	size_t csize;
2390 	size_t phase;
2391 
2392 	/*
2393 	 * The init thread is allowed to create internal and quantum caches.
2394 	 *
2395 	 * Other threads must wait until until initialization is complete.
2396 	 */
2397 	if (umem_init_thr == thr_self())
2398 		ASSERT((cflags & (UMC_INTERNAL | UMC_QCACHE)) != 0);
2399 	else {
2400 		ASSERT(!(cflags & UMC_INTERNAL));
2401 		if (umem_ready != UMEM_READY && umem_init() == 0) {
2402 			errno = EAGAIN;
2403 			return (NULL);
2404 		}
2405 	}
2406 
2407 	csize = UMEM_CACHE_SIZE(umem_max_ncpus);
2408 	phase = P2NPHASE(csize, UMEM_CPU_CACHE_SIZE);
2409 
2410 	if (vmp == NULL)
2411 		vmp = umem_default_arena;
2412 
2413 	ASSERT(P2PHASE(phase, UMEM_ALIGN) == 0);
2414 
2415 	/*
2416 	 * Check that the arguments are reasonable
2417 	 */
2418 	if ((align & (align - 1)) != 0 || align > vmp->vm_quantum ||
2419 	    ((cflags & UMC_NOHASH) && (cflags & UMC_NOTOUCH)) ||
2420 	    name == NULL || bufsize == 0) {
2421 		errno = EINVAL;
2422 		return (NULL);
2423 	}
2424 
2425 	/*
2426 	 * If align == 0, we set it to the minimum required alignment.
2427 	 *
2428 	 * If align < UMEM_ALIGN, we round it up to UMEM_ALIGN, unless
2429 	 * UMC_NOTOUCH was passed.
2430 	 */
2431 	if (align == 0) {
2432 		if (P2ROUNDUP(bufsize, UMEM_ALIGN) >= UMEM_SECOND_ALIGN)
2433 			align = UMEM_SECOND_ALIGN;
2434 		else
2435 			align = UMEM_ALIGN;
2436 	} else if (align < UMEM_ALIGN && (cflags & UMC_NOTOUCH) == 0)
2437 		align = UMEM_ALIGN;
2438 
2439 
2440 	/*
2441 	 * Get a umem_cache structure.  We arrange that cp->cache_cpu[]
2442 	 * is aligned on a UMEM_CPU_CACHE_SIZE boundary to prevent
2443 	 * false sharing of per-CPU data.
2444 	 */
2445 	cp = vmem_xalloc(umem_cache_arena, csize, UMEM_CPU_CACHE_SIZE, phase,
2446 	    0, NULL, NULL, VM_NOSLEEP);
2447 
2448 	if (cp == NULL) {
2449 		errno = EAGAIN;
2450 		return (NULL);
2451 	}
2452 
2453 	bzero(cp, csize);
2454 
2455 	(void) mutex_lock(&umem_flags_lock);
2456 	if (umem_flags & UMF_RANDOMIZE)
2457 		umem_flags = (((umem_flags | ~UMF_RANDOM) + 1) & UMF_RANDOM) |
2458 		    UMF_RANDOMIZE;
2459 	cp->cache_flags = umem_flags | (cflags & UMF_DEBUG);
2460 	(void) mutex_unlock(&umem_flags_lock);
2461 
2462 	/*
2463 	 * Make sure all the various flags are reasonable.
2464 	 */
2465 	if (cp->cache_flags & UMF_LITE) {
2466 		if (bufsize >= umem_lite_minsize &&
2467 		    align <= umem_lite_maxalign &&
2468 		    P2PHASE(bufsize, umem_lite_maxalign) != 0) {
2469 			cp->cache_flags |= UMF_BUFTAG;
2470 			cp->cache_flags &= ~(UMF_AUDIT | UMF_FIREWALL);
2471 		} else {
2472 			cp->cache_flags &= ~UMF_DEBUG;
2473 		}
2474 	}
2475 
2476 	if ((cflags & UMC_QCACHE) && (cp->cache_flags & UMF_AUDIT))
2477 		cp->cache_flags |= UMF_NOMAGAZINE;
2478 
2479 	if (cflags & UMC_NODEBUG)
2480 		cp->cache_flags &= ~UMF_DEBUG;
2481 
2482 	if (cflags & UMC_NOTOUCH)
2483 		cp->cache_flags &= ~UMF_TOUCH;
2484 
2485 	if (cflags & UMC_NOHASH)
2486 		cp->cache_flags &= ~(UMF_AUDIT | UMF_FIREWALL);
2487 
2488 	if (cflags & UMC_NOMAGAZINE)
2489 		cp->cache_flags |= UMF_NOMAGAZINE;
2490 
2491 	if ((cp->cache_flags & UMF_AUDIT) && !(cflags & UMC_NOTOUCH))
2492 		cp->cache_flags |= UMF_REDZONE;
2493 
2494 	if ((cp->cache_flags & UMF_BUFTAG) && bufsize >= umem_minfirewall &&
2495 	    !(cp->cache_flags & UMF_LITE) && !(cflags & UMC_NOHASH))
2496 		cp->cache_flags |= UMF_FIREWALL;
2497 
2498 	if (vmp != umem_default_arena || umem_firewall_arena == NULL)
2499 		cp->cache_flags &= ~UMF_FIREWALL;
2500 
2501 	if (cp->cache_flags & UMF_FIREWALL) {
2502 		cp->cache_flags &= ~UMF_BUFTAG;
2503 		cp->cache_flags |= UMF_NOMAGAZINE;
2504 		ASSERT(vmp == umem_default_arena);
2505 		vmp = umem_firewall_arena;
2506 	}
2507 
2508 	/*
2509 	 * Set cache properties.
2510 	 */
2511 	(void) strncpy(cp->cache_name, name, sizeof (cp->cache_name) - 1);
2512 	cp->cache_bufsize = bufsize;
2513 	cp->cache_align = align;
2514 	cp->cache_constructor = constructor;
2515 	cp->cache_destructor = destructor;
2516 	cp->cache_reclaim = reclaim;
2517 	cp->cache_private = private;
2518 	cp->cache_arena = vmp;
2519 	cp->cache_cflags = cflags;
2520 	cp->cache_cpu_mask = umem_cpu_mask;
2521 
2522 	/*
2523 	 * Determine the chunk size.
2524 	 */
2525 	chunksize = bufsize;
2526 
2527 	if (align >= UMEM_ALIGN) {
2528 		chunksize = P2ROUNDUP(chunksize, UMEM_ALIGN);
2529 		cp->cache_bufctl = chunksize - UMEM_ALIGN;
2530 	}
2531 
2532 	if (cp->cache_flags & UMF_BUFTAG) {
2533 		cp->cache_bufctl = chunksize;
2534 		cp->cache_buftag = chunksize;
2535 		chunksize += sizeof (umem_buftag_t);
2536 	}
2537 
2538 	if (cp->cache_flags & UMF_DEADBEEF) {
2539 		cp->cache_verify = MIN(cp->cache_buftag, umem_maxverify);
2540 		if (cp->cache_flags & UMF_LITE)
2541 			cp->cache_verify = MIN(cp->cache_verify, UMEM_ALIGN);
2542 	}
2543 
2544 	cp->cache_contents = MIN(cp->cache_bufctl, umem_content_maxsave);
2545 
2546 	cp->cache_chunksize = chunksize = P2ROUNDUP(chunksize, align);
2547 
2548 	if (chunksize < bufsize) {
2549 		errno = ENOMEM;
2550 		goto fail;
2551 	}
2552 
2553 	/*
2554 	 * Now that we know the chunk size, determine the optimal slab size.
2555 	 */
2556 	if (vmp == umem_firewall_arena) {
2557 		cp->cache_slabsize = P2ROUNDUP(chunksize, vmp->vm_quantum);
2558 		cp->cache_mincolor = cp->cache_slabsize - chunksize;
2559 		cp->cache_maxcolor = cp->cache_mincolor;
2560 		cp->cache_flags |= UMF_HASH;
2561 		ASSERT(!(cp->cache_flags & UMF_BUFTAG));
2562 	} else if ((cflags & UMC_NOHASH) || (!(cflags & UMC_NOTOUCH) &&
2563 	    !(cp->cache_flags & UMF_AUDIT) &&
2564 	    chunksize < vmp->vm_quantum / UMEM_VOID_FRACTION)) {
2565 		cp->cache_slabsize = vmp->vm_quantum;
2566 		cp->cache_mincolor = 0;
2567 		cp->cache_maxcolor =
2568 		    (cp->cache_slabsize - sizeof (umem_slab_t)) % chunksize;
2569 
2570 		if (chunksize + sizeof (umem_slab_t) > cp->cache_slabsize) {
2571 			errno = EINVAL;
2572 			goto fail;
2573 		}
2574 		ASSERT(!(cp->cache_flags & UMF_AUDIT));
2575 	} else {
2576 		size_t chunks, bestfit, waste, slabsize;
2577 		size_t minwaste = LONG_MAX;
2578 
2579 		for (chunks = 1; chunks <= UMEM_VOID_FRACTION; chunks++) {
2580 			slabsize = P2ROUNDUP(chunksize * chunks,
2581 			    vmp->vm_quantum);
2582 			/*
2583 			 * check for overflow
2584 			 */
2585 			if ((slabsize / chunks) < chunksize) {
2586 				errno = ENOMEM;
2587 				goto fail;
2588 			}
2589 			chunks = slabsize / chunksize;
2590 			waste = (slabsize % chunksize) / chunks;
2591 			if (waste < minwaste) {
2592 				minwaste = waste;
2593 				bestfit = slabsize;
2594 			}
2595 		}
2596 		if (cflags & UMC_QCACHE)
2597 			bestfit = MAX(1 << highbit(3 * vmp->vm_qcache_max), 64);
2598 		cp->cache_slabsize = bestfit;
2599 		cp->cache_mincolor = 0;
2600 		cp->cache_maxcolor = bestfit % chunksize;
2601 		cp->cache_flags |= UMF_HASH;
2602 	}
2603 
2604 	if (cp->cache_flags & UMF_HASH) {
2605 		ASSERT(!(cflags & UMC_NOHASH));
2606 		cp->cache_bufctl_cache = (cp->cache_flags & UMF_AUDIT) ?
2607 		    umem_bufctl_audit_cache : umem_bufctl_cache;
2608 	}
2609 
2610 	if (cp->cache_maxcolor >= vmp->vm_quantum)
2611 		cp->cache_maxcolor = vmp->vm_quantum - 1;
2612 
2613 	cp->cache_color = cp->cache_mincolor;
2614 
2615 	/*
2616 	 * Initialize the rest of the slab layer.
2617 	 */
2618 	(void) mutex_init(&cp->cache_lock, USYNC_THREAD, NULL);
2619 
2620 	cp->cache_freelist = &cp->cache_nullslab;
2621 	cp->cache_nullslab.slab_cache = cp;
2622 	cp->cache_nullslab.slab_refcnt = -1;
2623 	cp->cache_nullslab.slab_next = &cp->cache_nullslab;
2624 	cp->cache_nullslab.slab_prev = &cp->cache_nullslab;
2625 
2626 	if (cp->cache_flags & UMF_HASH) {
2627 		cp->cache_hash_table = vmem_alloc(umem_hash_arena,
2628 		    UMEM_HASH_INITIAL * sizeof (void *), VM_NOSLEEP);
2629 		if (cp->cache_hash_table == NULL) {
2630 			errno = EAGAIN;
2631 			goto fail_lock;
2632 		}
2633 		bzero(cp->cache_hash_table,
2634 		    UMEM_HASH_INITIAL * sizeof (void *));
2635 		cp->cache_hash_mask = UMEM_HASH_INITIAL - 1;
2636 		cp->cache_hash_shift = highbit((ulong_t)chunksize) - 1;
2637 	}
2638 
2639 	/*
2640 	 * Initialize the depot.
2641 	 */
2642 	(void) mutex_init(&cp->cache_depot_lock, USYNC_THREAD, NULL);
2643 
2644 	for (mtp = umem_magtype; chunksize <= mtp->mt_minbuf; mtp++)
2645 		continue;
2646 
2647 	cp->cache_magtype = mtp;
2648 
2649 	/*
2650 	 * Initialize the CPU layer.
2651 	 */
2652 	for (cpu_seqid = 0; cpu_seqid < umem_max_ncpus; cpu_seqid++) {
2653 		umem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
2654 		(void) mutex_init(&ccp->cc_lock, USYNC_THREAD, NULL);
2655 		ccp->cc_flags = cp->cache_flags;
2656 		ccp->cc_rounds = -1;
2657 		ccp->cc_prounds = -1;
2658 	}
2659 
2660 	/*
2661 	 * Add the cache to the global list.  This makes it visible
2662 	 * to umem_update(), so the cache must be ready for business.
2663 	 */
2664 	(void) mutex_lock(&umem_cache_lock);
2665 	cp->cache_next = cnext = &umem_null_cache;
2666 	cp->cache_prev = cprev = umem_null_cache.cache_prev;
2667 	cnext->cache_prev = cp;
2668 	cprev->cache_next = cp;
2669 	(void) mutex_unlock(&umem_cache_lock);
2670 
2671 	if (umem_ready == UMEM_READY)
2672 		umem_cache_magazine_enable(cp);
2673 
2674 	return (cp);
2675 
2676 fail_lock:
2677 	(void) mutex_destroy(&cp->cache_lock);
2678 fail:
2679 	vmem_xfree(umem_cache_arena, cp, csize);
2680 	return (NULL);
2681 }
2682 
2683 void
2684 umem_cache_destroy(umem_cache_t *cp)
2685 {
2686 	int cpu_seqid;
2687 
2688 	/*
2689 	 * Remove the cache from the global cache list so that no new updates
2690 	 * will be scheduled on its behalf, wait for any pending tasks to
2691 	 * complete, purge the cache, and then destroy it.
2692 	 */
2693 	(void) mutex_lock(&umem_cache_lock);
2694 	cp->cache_prev->cache_next = cp->cache_next;
2695 	cp->cache_next->cache_prev = cp->cache_prev;
2696 	cp->cache_prev = cp->cache_next = NULL;
2697 	(void) mutex_unlock(&umem_cache_lock);
2698 
2699 	umem_remove_updates(cp);
2700 
2701 	umem_cache_magazine_purge(cp);
2702 
2703 	(void) mutex_lock(&cp->cache_lock);
2704 	if (cp->cache_buftotal != 0)
2705 		log_message("umem_cache_destroy: '%s' (%p) not empty\n",
2706 		    cp->cache_name, (void *)cp);
2707 	cp->cache_reclaim = NULL;
2708 	/*
2709 	 * The cache is now dead.  There should be no further activity.
2710 	 * We enforce this by setting land mines in the constructor and
2711 	 * destructor routines that induce a segmentation fault if invoked.
2712 	 */
2713 	cp->cache_constructor = (umem_constructor_t *)1;
2714 	cp->cache_destructor = (umem_destructor_t *)2;
2715 	(void) mutex_unlock(&cp->cache_lock);
2716 
2717 	if (cp->cache_hash_table != NULL)
2718 		vmem_free(umem_hash_arena, cp->cache_hash_table,
2719 		    (cp->cache_hash_mask + 1) * sizeof (void *));
2720 
2721 	for (cpu_seqid = 0; cpu_seqid < umem_max_ncpus; cpu_seqid++)
2722 		(void) mutex_destroy(&cp->cache_cpu[cpu_seqid].cc_lock);
2723 
2724 	(void) mutex_destroy(&cp->cache_depot_lock);
2725 	(void) mutex_destroy(&cp->cache_lock);
2726 
2727 	vmem_free(umem_cache_arena, cp, UMEM_CACHE_SIZE(umem_max_ncpus));
2728 }
2729 
2730 static int
2731 umem_cache_init(void)
2732 {
2733 	int i;
2734 	size_t size, max_size;
2735 	umem_cache_t *cp;
2736 	umem_magtype_t *mtp;
2737 	char name[UMEM_CACHE_NAMELEN + 1];
2738 	umem_cache_t *umem_alloc_caches[NUM_ALLOC_SIZES];
2739 
2740 	for (i = 0; i < sizeof (umem_magtype) / sizeof (*mtp); i++) {
2741 		mtp = &umem_magtype[i];
2742 		(void) snprintf(name, sizeof (name), "umem_magazine_%d",
2743 		    mtp->mt_magsize);
2744 		mtp->mt_cache = umem_cache_create(name,
2745 		    (mtp->mt_magsize + 1) * sizeof (void *),
2746 		    mtp->mt_align, NULL, NULL, NULL, NULL,
2747 		    umem_internal_arena, UMC_NOHASH | UMC_INTERNAL);
2748 		if (mtp->mt_cache == NULL)
2749 			return (0);
2750 	}
2751 
2752 	umem_slab_cache = umem_cache_create("umem_slab_cache",
2753 	    sizeof (umem_slab_t), 0, NULL, NULL, NULL, NULL,
2754 	    umem_internal_arena, UMC_NOHASH | UMC_INTERNAL);
2755 
2756 	if (umem_slab_cache == NULL)
2757 		return (0);
2758 
2759 	umem_bufctl_cache = umem_cache_create("umem_bufctl_cache",
2760 	    sizeof (umem_bufctl_t), 0, NULL, NULL, NULL, NULL,
2761 	    umem_internal_arena, UMC_NOHASH | UMC_INTERNAL);
2762 
2763 	if (umem_bufctl_cache == NULL)
2764 		return (0);
2765 
2766 	/*
2767 	 * The size of the umem_bufctl_audit structure depends upon
2768 	 * umem_stack_depth.   See umem_impl.h for details on the size
2769 	 * restrictions.
2770 	 */
2771 
2772 	size = UMEM_BUFCTL_AUDIT_SIZE_DEPTH(umem_stack_depth);
2773 	max_size = UMEM_BUFCTL_AUDIT_MAX_SIZE;
2774 
2775 	if (size > max_size) {			/* too large -- truncate */
2776 		int max_frames = UMEM_MAX_STACK_DEPTH;
2777 
2778 		ASSERT(UMEM_BUFCTL_AUDIT_SIZE_DEPTH(max_frames) <= max_size);
2779 
2780 		umem_stack_depth = max_frames;
2781 		size = UMEM_BUFCTL_AUDIT_SIZE_DEPTH(umem_stack_depth);
2782 	}
2783 
2784 	umem_bufctl_audit_cache = umem_cache_create("umem_bufctl_audit_cache",
2785 	    size, 0, NULL, NULL, NULL, NULL, umem_internal_arena,
2786 	    UMC_NOHASH | UMC_INTERNAL);
2787 
2788 	if (umem_bufctl_audit_cache == NULL)
2789 		return (0);
2790 
2791 	if (vmem_backend & VMEM_BACKEND_MMAP)
2792 		umem_va_arena = vmem_create("umem_va",
2793 		    NULL, 0, pagesize,
2794 		    vmem_alloc, vmem_free, heap_arena,
2795 		    8 * pagesize, VM_NOSLEEP);
2796 	else
2797 		umem_va_arena = heap_arena;
2798 
2799 	if (umem_va_arena == NULL)
2800 		return (0);
2801 
2802 	umem_default_arena = vmem_create("umem_default",
2803 	    NULL, 0, pagesize,
2804 	    heap_alloc, heap_free, umem_va_arena,
2805 	    0, VM_NOSLEEP);
2806 
2807 	if (umem_default_arena == NULL)
2808 		return (0);
2809 
2810 	/*
2811 	 * make sure the umem_alloc table initializer is correct
2812 	 */
2813 	i = sizeof (umem_alloc_table) / sizeof (*umem_alloc_table);
2814 	ASSERT(umem_alloc_table[i - 1] == &umem_null_cache);
2815 
2816 	/*
2817 	 * Create the default caches to back umem_alloc()
2818 	 */
2819 	for (i = 0; i < NUM_ALLOC_SIZES; i++) {
2820 		size_t cache_size = umem_alloc_sizes[i];
2821 		size_t align = 0;
2822 		/*
2823 		 * If they allocate a multiple of the coherency granularity,
2824 		 * they get a coherency-granularity-aligned address.
2825 		 */
2826 		if (IS_P2ALIGNED(cache_size, 64))
2827 			align = 64;
2828 		if (IS_P2ALIGNED(cache_size, pagesize))
2829 			align = pagesize;
2830 		(void) snprintf(name, sizeof (name), "umem_alloc_%lu",
2831 		    (long)cache_size);
2832 
2833 		cp = umem_cache_create(name, cache_size, align,
2834 		    NULL, NULL, NULL, NULL, NULL, UMC_INTERNAL);
2835 		if (cp == NULL)
2836 			return (0);
2837 
2838 		umem_alloc_caches[i] = cp;
2839 	}
2840 
2841 	/*
2842 	 * Initialization cannot fail at this point.  Make the caches
2843 	 * visible to umem_alloc() and friends.
2844 	 */
2845 	size = UMEM_ALIGN;
2846 	for (i = 0; i < NUM_ALLOC_SIZES; i++) {
2847 		size_t cache_size = umem_alloc_sizes[i];
2848 
2849 		cp = umem_alloc_caches[i];
2850 
2851 		while (size <= cache_size) {
2852 			umem_alloc_table[(size - 1) >> UMEM_ALIGN_SHIFT] = cp;
2853 			size += UMEM_ALIGN;
2854 		}
2855 	}
2856 	return (1);
2857 }
2858 
2859 /*
2860  * umem_startup() is called early on, and must be called explicitly if we're
2861  * the standalone version.
2862  */
2863 #ifdef UMEM_STANDALONE
2864 void
2865 #else
2866 #pragma init(umem_startup)
2867 static void
2868 #endif
2869 umem_startup(caddr_t start, size_t len, size_t pagesize, caddr_t minstack,
2870     caddr_t maxstack)
2871 {
2872 #ifdef UMEM_STANDALONE
2873 	int idx;
2874 	/* Standalone doesn't fork */
2875 #else
2876 	umem_forkhandler_init(); /* register the fork handler */
2877 #endif
2878 
2879 #ifdef __lint
2880 	/* make lint happy */
2881 	minstack = maxstack;
2882 #endif
2883 
2884 #ifdef UMEM_STANDALONE
2885 	umem_ready = UMEM_READY_STARTUP;
2886 	umem_init_env_ready = 0;
2887 
2888 	umem_min_stack = minstack;
2889 	umem_max_stack = maxstack;
2890 
2891 	nofail_callback = NULL;
2892 	umem_slab_cache = NULL;
2893 	umem_bufctl_cache = NULL;
2894 	umem_bufctl_audit_cache = NULL;
2895 	heap_arena = NULL;
2896 	heap_alloc = NULL;
2897 	heap_free = NULL;
2898 	umem_internal_arena = NULL;
2899 	umem_cache_arena = NULL;
2900 	umem_hash_arena = NULL;
2901 	umem_log_arena = NULL;
2902 	umem_oversize_arena = NULL;
2903 	umem_va_arena = NULL;
2904 	umem_default_arena = NULL;
2905 	umem_firewall_va_arena = NULL;
2906 	umem_firewall_arena = NULL;
2907 	umem_memalign_arena = NULL;
2908 	umem_transaction_log = NULL;
2909 	umem_content_log = NULL;
2910 	umem_failure_log = NULL;
2911 	umem_slab_log = NULL;
2912 	umem_cpu_mask = 0;
2913 
2914 	umem_cpus = &umem_startup_cpu;
2915 	umem_startup_cpu.cpu_cache_offset = UMEM_CACHE_SIZE(0);
2916 	umem_startup_cpu.cpu_number = 0;
2917 
2918 	bcopy(&umem_null_cache_template, &umem_null_cache,
2919 	    sizeof (umem_cache_t));
2920 
2921 	for (idx = 0; idx < (UMEM_MAXBUF >> UMEM_ALIGN_SHIFT); idx++)
2922 		umem_alloc_table[idx] = &umem_null_cache;
2923 #endif
2924 
2925 	/*
2926 	 * Perform initialization specific to the way we've been compiled
2927 	 * (library or standalone)
2928 	 */
2929 	umem_type_init(start, len, pagesize);
2930 
2931 	vmem_startup();
2932 }
2933 
2934 int
2935 umem_init(void)
2936 {
2937 	size_t maxverify, minfirewall;
2938 	size_t size;
2939 	int idx;
2940 	umem_cpu_t *new_cpus;
2941 
2942 	vmem_t *memalign_arena, *oversize_arena;
2943 
2944 	if (thr_self() != umem_init_thr) {
2945 		/*
2946 		 * The usual case -- non-recursive invocation of umem_init().
2947 		 */
2948 		(void) mutex_lock(&umem_init_lock);
2949 		if (umem_ready != UMEM_READY_STARTUP) {
2950 			/*
2951 			 * someone else beat us to initializing umem.  Wait
2952 			 * for them to complete, then return.
2953 			 */
2954 			while (umem_ready == UMEM_READY_INITING)
2955 				(void) _cond_wait(&umem_init_cv,
2956 				    &umem_init_lock);
2957 			ASSERT(umem_ready == UMEM_READY ||
2958 			    umem_ready == UMEM_READY_INIT_FAILED);
2959 			(void) mutex_unlock(&umem_init_lock);
2960 			return (umem_ready == UMEM_READY);
2961 		}
2962 
2963 		ASSERT(umem_ready == UMEM_READY_STARTUP);
2964 		ASSERT(umem_init_env_ready == 0);
2965 
2966 		umem_ready = UMEM_READY_INITING;
2967 		umem_init_thr = thr_self();
2968 
2969 		(void) mutex_unlock(&umem_init_lock);
2970 		umem_setup_envvars(0);		/* can recurse -- see below */
2971 		if (umem_init_env_ready) {
2972 			/*
2973 			 * initialization was completed already
2974 			 */
2975 			ASSERT(umem_ready == UMEM_READY ||
2976 			    umem_ready == UMEM_READY_INIT_FAILED);
2977 			ASSERT(umem_init_thr == 0);
2978 			return (umem_ready == UMEM_READY);
2979 		}
2980 	} else if (!umem_init_env_ready) {
2981 		/*
2982 		 * The umem_setup_envvars() call (above) makes calls into
2983 		 * the dynamic linker and directly into user-supplied code.
2984 		 * Since we cannot know what that code will do, we could be
2985 		 * recursively invoked (by, say, a malloc() call in the code
2986 		 * itself, or in a (C++) _init section it causes to be fired).
2987 		 *
2988 		 * This code is where we end up if such recursion occurs.  We
2989 		 * first clean up any partial results in the envvar code, then
2990 		 * proceed to finish initialization processing in the recursive
2991 		 * call.  The original call will notice this, and return
2992 		 * immediately.
2993 		 */
2994 		umem_setup_envvars(1);		/* clean up any partial state */
2995 	} else {
2996 		umem_panic(
2997 		    "recursive allocation while initializing umem\n");
2998 	}
2999 	umem_init_env_ready = 1;
3000 
3001 	/*
3002 	 * From this point until we finish, recursion into umem_init() will
3003 	 * cause a umem_panic().
3004 	 */
3005 	maxverify = minfirewall = ULONG_MAX;
3006 
3007 	/* LINTED constant condition */
3008 	if (sizeof (umem_cpu_cache_t) != UMEM_CPU_CACHE_SIZE) {
3009 		umem_panic("sizeof (umem_cpu_cache_t) = %d, should be %d\n",
3010 		    sizeof (umem_cpu_cache_t), UMEM_CPU_CACHE_SIZE);
3011 	}
3012 
3013 	umem_max_ncpus = umem_get_max_ncpus();
3014 
3015 	/*
3016 	 * load tunables from environment
3017 	 */
3018 	umem_process_envvars();
3019 
3020 	if (issetugid())
3021 		umem_mtbf = 0;
3022 
3023 	/*
3024 	 * set up vmem
3025 	 */
3026 	if (!(umem_flags & UMF_AUDIT))
3027 		vmem_no_debug();
3028 
3029 	heap_arena = vmem_heap_arena(&heap_alloc, &heap_free);
3030 
3031 	pagesize = heap_arena->vm_quantum;
3032 
3033 	umem_internal_arena = vmem_create("umem_internal", NULL, 0, pagesize,
3034 	    heap_alloc, heap_free, heap_arena, 0, VM_NOSLEEP);
3035 
3036 	umem_default_arena = umem_internal_arena;
3037 
3038 	if (umem_internal_arena == NULL)
3039 		goto fail;
3040 
3041 	umem_cache_arena = vmem_create("umem_cache", NULL, 0, UMEM_ALIGN,
3042 	    vmem_alloc, vmem_free, umem_internal_arena, 0, VM_NOSLEEP);
3043 
3044 	umem_hash_arena = vmem_create("umem_hash", NULL, 0, UMEM_ALIGN,
3045 	    vmem_alloc, vmem_free, umem_internal_arena, 0, VM_NOSLEEP);
3046 
3047 	umem_log_arena = vmem_create("umem_log", NULL, 0, UMEM_ALIGN,
3048 	    heap_alloc, heap_free, heap_arena, 0, VM_NOSLEEP);
3049 
3050 	umem_firewall_va_arena = vmem_create("umem_firewall_va",
3051 	    NULL, 0, pagesize,
3052 	    umem_firewall_va_alloc, umem_firewall_va_free, heap_arena,
3053 	    0, VM_NOSLEEP);
3054 
3055 	if (umem_cache_arena == NULL || umem_hash_arena == NULL ||
3056 	    umem_log_arena == NULL || umem_firewall_va_arena == NULL)
3057 		goto fail;
3058 
3059 	umem_firewall_arena = vmem_create("umem_firewall", NULL, 0, pagesize,
3060 	    heap_alloc, heap_free, umem_firewall_va_arena, 0,
3061 	    VM_NOSLEEP);
3062 
3063 	if (umem_firewall_arena == NULL)
3064 		goto fail;
3065 
3066 	oversize_arena = vmem_create("umem_oversize", NULL, 0, pagesize,
3067 	    heap_alloc, heap_free, minfirewall < ULONG_MAX ?
3068 	    umem_firewall_va_arena : heap_arena, 0, VM_NOSLEEP);
3069 
3070 	memalign_arena = vmem_create("umem_memalign", NULL, 0, UMEM_ALIGN,
3071 	    heap_alloc, heap_free, minfirewall < ULONG_MAX ?
3072 	    umem_firewall_va_arena : heap_arena, 0, VM_NOSLEEP);
3073 
3074 	if (oversize_arena == NULL || memalign_arena == NULL)
3075 		goto fail;
3076 
3077 	if (umem_max_ncpus > CPUHINT_MAX())
3078 		umem_max_ncpus = CPUHINT_MAX();
3079 
3080 	while ((umem_max_ncpus & (umem_max_ncpus - 1)) != 0)
3081 		umem_max_ncpus++;
3082 
3083 	if (umem_max_ncpus == 0)
3084 		umem_max_ncpus = 1;
3085 
3086 	size = umem_max_ncpus * sizeof (umem_cpu_t);
3087 	new_cpus = vmem_alloc(umem_internal_arena, size, VM_NOSLEEP);
3088 	if (new_cpus == NULL)
3089 		goto fail;
3090 
3091 	bzero(new_cpus, size);
3092 	for (idx = 0; idx < umem_max_ncpus; idx++) {
3093 		new_cpus[idx].cpu_number = idx;
3094 		new_cpus[idx].cpu_cache_offset = UMEM_CACHE_SIZE(idx);
3095 	}
3096 	umem_cpus = new_cpus;
3097 	umem_cpu_mask = (umem_max_ncpus - 1);
3098 
3099 	if (umem_maxverify == 0)
3100 		umem_maxverify = maxverify;
3101 
3102 	if (umem_minfirewall == 0)
3103 		umem_minfirewall = minfirewall;
3104 
3105 	/*
3106 	 * Set up updating and reaping
3107 	 */
3108 	umem_reap_next = gethrtime() + NANOSEC;
3109 
3110 #ifndef UMEM_STANDALONE
3111 	(void) gettimeofday(&umem_update_next, NULL);
3112 #endif
3113 
3114 	/*
3115 	 * Set up logging -- failure here is okay, since it will just disable
3116 	 * the logs
3117 	 */
3118 	if (umem_logging) {
3119 		umem_transaction_log = umem_log_init(umem_transaction_log_size);
3120 		umem_content_log = umem_log_init(umem_content_log_size);
3121 		umem_failure_log = umem_log_init(umem_failure_log_size);
3122 		umem_slab_log = umem_log_init(umem_slab_log_size);
3123 	}
3124 
3125 	/*
3126 	 * Set up caches -- if successful, initialization cannot fail, since
3127 	 * allocations from other threads can now succeed.
3128 	 */
3129 	if (umem_cache_init() == 0) {
3130 		log_message("unable to create initial caches\n");
3131 		goto fail;
3132 	}
3133 	umem_oversize_arena = oversize_arena;
3134 	umem_memalign_arena = memalign_arena;
3135 
3136 	umem_cache_applyall(umem_cache_magazine_enable);
3137 
3138 	/*
3139 	 * initialization done, ready to go
3140 	 */
3141 	(void) mutex_lock(&umem_init_lock);
3142 	umem_ready = UMEM_READY;
3143 	umem_init_thr = 0;
3144 	(void) cond_broadcast(&umem_init_cv);
3145 	(void) mutex_unlock(&umem_init_lock);
3146 	return (1);
3147 
3148 fail:
3149 	log_message("umem initialization failed\n");
3150 
3151 	(void) mutex_lock(&umem_init_lock);
3152 	umem_ready = UMEM_READY_INIT_FAILED;
3153 	umem_init_thr = 0;
3154 	(void) cond_broadcast(&umem_init_cv);
3155 	(void) mutex_unlock(&umem_init_lock);
3156 	return (0);
3157 }
3158