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
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.
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]
23 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
27 * Portions Copyright 2006 OmniTI, Inc.
30 /* #pragma ident "@(#)umem.c 1.11 05/06/08 SMI" */
41 * There is a nuance in the behaviour of the umem port compared
42 * with umem on Solaris.
44 * On Linux umem will not return memory back to the OS until umem fails
45 * to allocate a chunk. On failure, umem_reap() will be called automatically,
46 * to return memory to the OS. If your code is going to be running
47 * for a long time on Linux and mixes calls to different memory allocators
48 * (e.g.: malloc()) and umem, your code will need to call
49 * umem_reap() periodically.
51 * This doesn't happen on Solaris, because malloc is replaced
52 * with umem calls, meaning that umem_reap() is called automatically.
56 * http://docs.sun.com/app/docs/doc/816-5173/6mbb8advq?a=view
58 * http://access1.sun.com/techarticles/libumem.html
63 * based on usr/src/uts/common/os/kmem.c r1.64 from 2001/12/18
65 * The slab allocator, as described in the following two papers:
68 * The Slab Allocator: An Object-Caching Kernel Memory Allocator.
69 * Proceedings of the Summer 1994 Usenix Conference.
70 * Available as /shared/sac/PSARC/1994/028/materials/kmem.pdf.
72 * Jeff Bonwick and Jonathan Adams,
73 * Magazines and vmem: Extending the Slab Allocator to Many CPUs and
74 * Arbitrary Resources.
75 * Proceedings of the 2001 Usenix Conference.
76 * Available as /shared/sac/PSARC/2000/550/materials/vmem.pdf.
80 * umem is very close to kmem in implementation. There are four major
81 * areas of divergence:
89 * * KM_SLEEP v.s. UMEM_NOFAIL
94 * kmem is initialized early on in boot, and knows that no one will call
95 * into it before it is ready. umem does not have these luxuries. Instead,
96 * initialization is divided into two phases:
98 * * library initialization, and
102 * umem's full initialization happens at the time of the first allocation
103 * request (via malloc() and friends, umem_alloc(), or umem_zalloc()),
104 * or the first call to umem_cache_create().
106 * umem_free(), and umem_cache_alloc() do not require special handling,
107 * since the only way to get valid arguments for them is to successfully
108 * call a function from the first group.
110 * 2.1. Library Initialization: umem_startup()
111 * -------------------------------------------
112 * umem_startup() is libumem.so's .init section. It calls pthread_atfork()
113 * to install the handlers necessary for umem's Fork1-Safety. Because of
114 * race condition issues, all other pre-umem_init() initialization is done
115 * statically (i.e. by the dynamic linker).
117 * For standalone use, umem_startup() returns everything to its initial
120 * 2.2. First use: umem_init()
121 * ------------------------------
122 * The first time any memory allocation function is used, we have to
123 * create the backing caches and vmem arenas which are needed for it.
124 * umem_init() is the central point for that task. When it completes,
125 * umem_ready is either UMEM_READY (all set) or UMEM_READY_INIT_FAILED (unable
126 * to initialize, probably due to lack of memory).
128 * There are four different paths from which umem_init() is called:
130 * * from umem_alloc() or umem_zalloc(), with 0 < size < UMEM_MAXBUF,
132 * * from umem_alloc() or umem_zalloc(), with size > UMEM_MAXBUF,
134 * * from umem_cache_create(), and
136 * * from memalign(), with align > UMEM_ALIGN.
138 * The last three just check if umem is initialized, and call umem_init()
139 * if it is not. For performance reasons, the first case is more complicated.
141 * 2.2.1. umem_alloc()/umem_zalloc(), with 0 < size < UMEM_MAXBUF
142 * -----------------------------------------------------------------
143 * In this case, umem_cache_alloc(&umem_null_cache, ...) is called.
144 * There is special case code in which causes any allocation on
145 * &umem_null_cache to fail by returning (NULL), regardless of the
148 * So umem_cache_alloc() returns NULL, and umem_alloc()/umem_zalloc() call
149 * umem_alloc_retry(). umem_alloc_retry() sees that the allocation
150 * was agains &umem_null_cache, and calls umem_init().
152 * If initialization is successful, umem_alloc_retry() returns 1, which
153 * causes umem_alloc()/umem_zalloc() to start over, which causes it to load
154 * the (now valid) cache pointer from umem_alloc_table.
156 * 2.2.2. Dealing with race conditions
157 * -----------------------------------
158 * There are a couple race conditions resulting from the initialization
159 * code that we have to guard against:
161 * * In umem_cache_create(), there is a special UMC_INTERNAL cflag
162 * that is passed for caches created during initialization. It
163 * is illegal for a user to try to create a UMC_INTERNAL cache.
164 * This allows initialization to proceed, but any other
165 * umem_cache_create()s will block by calling umem_init().
167 * * Since umem_null_cache has a 1-element cache_cpu, it's cache_cpu_mask
168 * is always zero. umem_cache_alloc uses cp->cache_cpu_mask to
169 * mask the cpu number. This prevents a race between grabbing a
170 * cache pointer out of umem_alloc_table and growing the cpu array.
175 * kmem uses the CPU's sequence number to determine which "cpu cache" to
176 * use for an allocation. Currently, there is no way to get the sequence
177 * number in userspace.
179 * umem keeps track of cpu information in umem_cpus, an array of umem_max_ncpus
180 * umem_cpu_t structures. CURCPU() is a a "hint" function, which we then mask
181 * with either umem_cpu_mask or cp->cache_cpu_mask to find the actual "cpu" id.
182 * The mechanics of this is all in the CPU(mask) macro.
184 * Currently, umem uses _lwp_self() as its hint.
187 * 4. The update thread
188 * --------------------
189 * kmem uses a task queue, kmem_taskq, to do periodic maintenance on
190 * every kmem cache. vmem has a periodic timeout for hash table resizing.
191 * The kmem_taskq also provides a separate context for kmem_cache_reap()'s
192 * to be done in, avoiding issues of the context of kmem_reap() callers.
194 * Instead, umem has the concept of "updates", which are asynchronous requests
195 * for work attached to single caches. All caches with pending work are
196 * on a doubly linked list rooted at the umem_null_cache. All update state
197 * is protected by the umem_update_lock mutex, and the umem_update_cv is used
198 * for notification between threads.
200 * 4.1. Cache states with regards to updates
201 * -----------------------------------------
202 * A given cache is in one of three states:
204 * Inactive cache_uflags is zero, cache_u{next,prev} are NULL
206 * Work Requested cache_uflags is non-zero (but UMU_ACTIVE is not set),
207 * cache_u{next,prev} link the cache onto the global
210 * Active cache_uflags has UMU_ACTIVE set, cache_u{next,prev}
211 * are NULL, and either umem_update_thr or
212 * umem_st_update_thr are actively doing work on the
215 * An update can be added to any cache in any state -- if the cache is
216 * Inactive, it transitions to being Work Requested. If the cache is
217 * Active, the worker will notice the new update and act on it before
218 * transitioning the cache to the Inactive state.
220 * If a cache is in the Active state, UMU_NOTIFY can be set, which asks
221 * the worker to broadcast the umem_update_cv when it has finished.
223 * 4.2. Update interface
224 * ---------------------
225 * umem_add_update() adds an update to a particular cache.
226 * umem_updateall() adds an update to all caches.
227 * umem_remove_updates() returns a cache to the Inactive state.
229 * umem_process_updates() process all caches in the Work Requested state.
233 * When umem_reap() is called (at the time of heap growth), it schedule
234 * UMU_REAP updates on every cache. It then checks to see if the update
235 * thread exists (umem_update_thr != 0). If it is, it broadcasts
236 * the umem_update_cv to wake the update thread up, and returns.
238 * If the update thread does not exist (umem_update_thr == 0), and the
239 * program currently has multiple threads, umem_reap() attempts to create
240 * a new update thread.
242 * If the process is not multithreaded, or the creation fails, umem_reap()
243 * calls umem_st_update() to do an inline update.
245 * 4.4. The update thread
246 * ----------------------
247 * The update thread spends most of its time in cond_timedwait() on the
248 * umem_update_cv. It wakes up under two conditions:
250 * * The timedwait times out, in which case it needs to run a global
253 * * someone cond_broadcast(3THR)s the umem_update_cv, in which case
254 * it needs to check if there are any caches in the Work Requested
257 * When it is time for another global update, umem calls umem_cache_update()
258 * on every cache, then calls vmem_update(), which tunes the vmem structures.
259 * umem_cache_update() can request further work using umem_add_update().
261 * After any work from the global update completes, the update timer is
262 * reset to umem_reap_interval seconds in the future. This makes the
263 * updates self-throttling.
265 * Reaps are similarly self-throttling. After a UMU_REAP update has
266 * been scheduled on all caches, umem_reap() sets a flag and wakes up the
267 * update thread. The update thread notices the flag, and resets the
270 * 4.5. Inline updates
271 * -------------------
272 * If the update thread is not running, umem_st_update() is used instead. It
273 * immediately does a global update (as above), then calls
274 * umem_process_updates() to process both the reaps that umem_reap() added and
275 * any work generated by the global update. Afterwards, it resets the reap
278 * While the umem_st_update() is running, umem_st_update_thr holds the thread
279 * id of the thread performing the update.
281 * 4.6. Updates and fork1()
282 * ------------------------
283 * umem has fork1() pre- and post-handlers which lock up (and release) every
284 * mutex in every cache. They also lock up the umem_update_lock. Since
285 * fork1() only copies over a single lwp, other threads (including the update
286 * thread) could have been actively using a cache in the parent. This
287 * can lead to inconsistencies in the child process.
289 * Because we locked all of the mutexes, the only possible inconsistancies are:
291 * * a umem_cache_alloc() could leak its buffer.
293 * * a caller of umem_depot_alloc() could leak a magazine, and all the
294 * buffers contained in it.
296 * * a cache could be in the Active update state. In the child, there
297 * would be no thread actually working on it.
299 * * a umem_hash_rescale() could leak the new hash table.
301 * * a umem_magazine_resize() could be in progress.
303 * * a umem_reap() could be in progress.
305 * The memory leaks we can't do anything about. umem_release_child() resets
306 * the update state, moves any caches in the Active state to the Work Requested
307 * state. This might cause some updates to be re-run, but UMU_REAP and
308 * UMU_HASH_RESCALE are effectively idempotent, and the worst that can
309 * happen from umem_magazine_resize() is resizing the magazine twice in close
312 * Much of the cleanup in umem_release_child() is skipped if
313 * umem_st_update_thr == thr_self(). This is so that applications which call
314 * fork1() from a cache callback does not break. Needless to say, any such
315 * application is tremendously broken.
318 * 5. KM_SLEEP v.s. UMEM_NOFAIL
319 * ----------------------------
320 * Allocations against kmem and vmem have two basic modes: SLEEP and
321 * NOSLEEP. A sleeping allocation is will go to sleep (waiting for
322 * more memory) instead of failing (returning NULL).
324 * SLEEP allocations presume an extremely multithreaded model, with
325 * a lot of allocation and deallocation activity. umem cannot presume
326 * that its clients have any particular type of behavior. Instead,
327 * it provides two types of allocations:
329 * * UMEM_DEFAULT, equivalent to KM_NOSLEEP (i.e. return NULL on
332 * * UMEM_NOFAIL, which, on failure, calls an optional callback
333 * (registered with umem_nofail_callback()).
335 * The callback is invoked with no locks held, and can do an arbitrary
336 * amount of work. It then has a choice between:
338 * * Returning UMEM_CALLBACK_RETRY, which will cause the allocation
341 * * Returning UMEM_CALLBACK_EXIT(status), which will cause exit(2)
342 * to be invoked with status. If multiple threads attempt to do
343 * this simultaneously, only one will call exit(2).
345 * * Doing some kind of non-local exit (thr_exit(3thr), longjmp(3C),
348 * The default callback returns UMEM_CALLBACK_EXIT(255).
350 * To have these callbacks without risk of state corruption (in the case of
351 * a non-local exit), we have to ensure that the callbacks get invoked
352 * close to the original allocation, with no inconsistent state or held
353 * locks. The following steps are taken:
355 * * All invocations of vmem are VM_NOSLEEP.
357 * * All constructor callbacks (which can themselves to allocations)
358 * are passed UMEM_DEFAULT as their required allocation argument. This
359 * way, the constructor will fail, allowing the highest-level allocation
360 * invoke the nofail callback.
362 * If a constructor callback _does_ do a UMEM_NOFAIL allocation, and
363 * the nofail callback does a non-local exit, we will leak the
364 * partially-constructed buffer.
369 /* #include "mtlib.h" */
370 #include <umem_impl.h>
371 #include <sys/vmem_impl_user.h>
372 #include "umem_base.h"
373 #include "vmem_base.h"
375 #if HAVE_SYS_PROCESSOR_H
376 #include <sys/processor.h>
378 #if HAVE_SYS_SYSMACROS_H
379 #include <sys/sysmacros.h>
403 #define UMEM_VMFLAGS(umflag) (VM_NOSLEEP)
408 * The default set of caches to back umem_alloc().
409 * These sizes should be reevaluated periodically.
411 * We want allocations that are multiples of the coherency granularity
412 * (64 bytes) to be satisfied from a cache which is a multiple of 64
413 * bytes, so that it will be 64-byte aligned. For all multiples of 64,
414 * the next kmem_cache_size greater than or equal to it must be a
417 static const int umem_alloc_sizes[] = {
427 4 * 8, 5 * 8, 6 * 8, 7 * 8,
429 4 * 16, 5 * 16, 6 * 16, 7 * 16,
430 4 * 32, 5 * 32, 6 * 32, 7 * 32,
431 4 * 64, 5 * 64, 6 * 64, 7 * 64,
432 4 * 128, 5 * 128, 6 * 128, 7 * 128,
433 P2ALIGN(8192 / 7, 64),
434 P2ALIGN(8192 / 6, 64),
435 P2ALIGN(8192 / 5, 64),
436 P2ALIGN(8192 / 4, 64),
437 P2ALIGN(8192 / 3, 64),
438 P2ALIGN(8192 / 2, 64),
439 P2ALIGN(8192 / 1, 64),
443 #define NUM_ALLOC_SIZES (sizeof (umem_alloc_sizes) / sizeof (*umem_alloc_sizes))
445 #define UMEM_MAXBUF 16384
447 static umem_magtype_t umem_magtype[] = {
448 { 1, 8, 3200, 65536 },
449 { 3, 16, 256, 32768 },
450 { 7, 32, 64, 16384 },
462 uint32_t umem_max_ncpus; /* # of CPU caches. */
464 uint32_t umem_stack_depth = 15; /* # stack frames in a bufctl_audit */
465 uint32_t umem_reap_interval = 10; /* max reaping rate (seconds) */
466 uint_t umem_depot_contention = 2; /* max failed trylocks per real interval */
467 uint_t umem_abort = 1; /* whether to abort on error */
468 uint_t umem_output = 0; /* whether to write to standard error */
469 uint_t umem_logging = 0; /* umem_log_enter() override */
470 uint32_t umem_mtbf = 0; /* mean time between failures [default: off] */
471 size_t umem_transaction_log_size; /* size of transaction log */
472 size_t umem_content_log_size; /* size of content log */
473 size_t umem_failure_log_size; /* failure log [4 pages per CPU] */
474 size_t umem_slab_log_size; /* slab create log [4 pages per CPU] */
475 size_t umem_content_maxsave = 256; /* UMF_CONTENTS max bytes to log */
476 size_t umem_lite_minsize = 0; /* minimum buffer size for UMF_LITE */
477 size_t umem_lite_maxalign = 1024; /* maximum buffer alignment for UMF_LITE */
478 size_t umem_maxverify; /* maximum bytes to inspect in debug routines */
479 size_t umem_minfirewall; /* hardware-enforced redzone threshold */
481 uint_t umem_flags = 0;
483 mutex_t umem_init_lock = DEFAULTMUTEX; /* locks initialization */
484 cond_t umem_init_cv = DEFAULTCV; /* initialization CV */
485 thread_t umem_init_thr; /* thread initializing */
486 int umem_init_env_ready; /* environ pre-initted */
487 int umem_ready = UMEM_READY_STARTUP;
489 static umem_nofail_callback_t *nofail_callback;
490 static mutex_t umem_nofail_exit_lock = DEFAULTMUTEX;
491 static thread_t umem_nofail_exit_thr;
493 static umem_cache_t *umem_slab_cache;
494 static umem_cache_t *umem_bufctl_cache;
495 static umem_cache_t *umem_bufctl_audit_cache;
497 mutex_t umem_flags_lock = DEFAULTMUTEX;
499 static vmem_t *heap_arena;
500 static vmem_alloc_t *heap_alloc;
501 static vmem_free_t *heap_free;
503 static vmem_t *umem_internal_arena;
504 static vmem_t *umem_cache_arena;
505 static vmem_t *umem_hash_arena;
506 static vmem_t *umem_log_arena;
507 static vmem_t *umem_oversize_arena;
508 static vmem_t *umem_va_arena;
509 static vmem_t *umem_default_arena;
510 static vmem_t *umem_firewall_va_arena;
511 static vmem_t *umem_firewall_arena;
513 vmem_t *umem_memalign_arena;
515 umem_log_header_t *umem_transaction_log;
516 umem_log_header_t *umem_content_log;
517 umem_log_header_t *umem_failure_log;
518 umem_log_header_t *umem_slab_log;
520 extern thread_t _thr_self(void);
521 #if defined(__MACH__) || defined(__FreeBSD__)
522 # define CPUHINT() ((int)(_thr_self()))
526 #define CPUHINT() (_thr_self())
529 #define CPUHINT_MAX() INT_MAX
531 #define CPU(mask) (umem_cpus + (CPUHINT() & (mask)))
532 static umem_cpu_t umem_startup_cpu = { /* initial, single, cpu */
537 static uint32_t umem_cpu_mask = 0; /* global cpu mask */
538 static umem_cpu_t *umem_cpus = &umem_startup_cpu; /* cpu list */
540 volatile uint32_t umem_reaping;
542 thread_t umem_update_thr;
543 struct timeval umem_update_next; /* timeofday of next update */
544 volatile thread_t umem_st_update_thr; /* only used when single-thd */
546 #define IN_UPDATE() (thr_self() == umem_update_thr || \
547 thr_self() == umem_st_update_thr)
548 #define IN_REAP() IN_UPDATE()
550 mutex_t umem_update_lock = DEFAULTMUTEX; /* cache_u{next,prev,flags} */
551 cond_t umem_update_cv = DEFAULTCV;
553 volatile hrtime_t umem_reap_next; /* min hrtime of next reap */
555 mutex_t umem_cache_lock = DEFAULTMUTEX; /* inter-cache linkage only */
557 #ifdef UMEM_STANDALONE
558 umem_cache_t umem_null_cache;
559 static const umem_cache_t umem_null_cache_template = {
561 umem_cache_t umem_null_cache = {
569 NULL, NULL, NULL, NULL,
572 &umem_null_cache, &umem_null_cache,
573 &umem_null_cache, &umem_null_cache,
575 DEFAULTMUTEX, /* start of slab layer */
576 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
577 &umem_null_cache.cache_nullslab,
581 &umem_null_cache.cache_nullslab,
582 &umem_null_cache.cache_nullslab,
589 DEFAULTMUTEX, /* start of depot layer */
596 DEFAULTMUTEX, /* start of CPU cache */
597 0, 0, NULL, NULL, -1, -1, 0
602 #define ALLOC_TABLE_4 \
603 &umem_null_cache, &umem_null_cache, &umem_null_cache, &umem_null_cache
605 #define ALLOC_TABLE_64 \
606 ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, \
607 ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, \
608 ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, \
609 ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4, ALLOC_TABLE_4
611 #define ALLOC_TABLE_1024 \
612 ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, \
613 ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, \
614 ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, \
615 ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64, ALLOC_TABLE_64
617 static umem_cache_t *umem_alloc_table[UMEM_MAXBUF >> UMEM_ALIGN_SHIFT] = {
623 /* Used to constrain audit-log stack traces */
624 caddr_t umem_min_stack;
625 caddr_t umem_max_stack;
629 * we use the _ versions, since we don't want to be cancelled.
630 * Actually, this is automatically taken care of by including "mtlib.h".
632 extern int _cond_wait(cond_t *cv, mutex_t *mutex);
634 #define UMERR_MODIFIED 0 /* buffer modified while on freelist */
635 #define UMERR_REDZONE 1 /* redzone violation (write past end of buf) */
636 #define UMERR_DUPFREE 2 /* freed a buffer twice */
637 #define UMERR_BADADDR 3 /* freed a bad (unallocated) address */
638 #define UMERR_BADBUFTAG 4 /* buftag corrupted */
639 #define UMERR_BADBUFCTL 5 /* bufctl corrupted */
640 #define UMERR_BADCACHE 6 /* freed a buffer to the wrong cache */
641 #define UMERR_BADSIZE 7 /* alloc size != free size */
642 #define UMERR_BADBASE 8 /* buffer base address wrong */
645 hrtime_t ump_timestamp; /* timestamp of error */
646 int ump_error; /* type of umem error (UMERR_*) */
647 void *ump_buffer; /* buffer that induced abort */
648 void *ump_realbuf; /* real start address for buffer */
649 umem_cache_t *ump_cache; /* buffer's cache according to client */
650 umem_cache_t *ump_realcache; /* actual cache containing buffer */
651 umem_slab_t *ump_slab; /* slab accoring to umem_findslab() */
652 umem_bufctl_t *ump_bufctl; /* bufctl */
656 copy_pattern(uint64_t pattern, void *buf_arg, size_t size)
658 uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
659 uint64_t *buf = buf_arg;
666 verify_pattern(uint64_t pattern, void *buf_arg, size_t size)
668 uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
671 for (buf = buf_arg; buf < bufend; buf++)
678 verify_and_copy_pattern(uint64_t old, uint64_t new, void *buf_arg, size_t size)
680 uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
683 for (buf = buf_arg; buf < bufend; buf++) {
685 copy_pattern(old, buf_arg,
686 (char *)buf - (char *)buf_arg);
696 umem_cache_applyall(void (*func)(umem_cache_t *))
700 (void) mutex_lock(&umem_cache_lock);
701 for (cp = umem_null_cache.cache_next; cp != &umem_null_cache;
704 (void) mutex_unlock(&umem_cache_lock);
708 umem_add_update_unlocked(umem_cache_t *cp, int flags)
710 umem_cache_t *cnext, *cprev;
712 flags &= ~UMU_ACTIVE;
717 if (cp->cache_uflags & UMU_ACTIVE) {
718 cp->cache_uflags |= flags;
720 if (cp->cache_unext != NULL) {
721 ASSERT(cp->cache_uflags != 0);
722 cp->cache_uflags |= flags;
724 ASSERT(cp->cache_uflags == 0);
725 cp->cache_uflags = flags;
726 cp->cache_unext = cnext = &umem_null_cache;
727 cp->cache_uprev = cprev = umem_null_cache.cache_uprev;
728 cnext->cache_uprev = cp;
729 cprev->cache_unext = cp;
735 umem_add_update(umem_cache_t *cp, int flags)
737 (void) mutex_lock(&umem_update_lock);
739 umem_add_update_unlocked(cp, flags);
742 (void) cond_broadcast(&umem_update_cv);
744 (void) mutex_unlock(&umem_update_lock);
748 * Remove a cache from the update list, waiting for any in-progress work to
752 umem_remove_updates(umem_cache_t *cp)
754 (void) mutex_lock(&umem_update_lock);
757 * Get it out of the active state
759 while (cp->cache_uflags & UMU_ACTIVE) {
760 ASSERT(cp->cache_unext == NULL);
762 cp->cache_uflags |= UMU_NOTIFY;
765 * Make sure the update state is sane, before we wait
767 ASSERT(umem_update_thr != 0 || umem_st_update_thr != 0);
768 ASSERT(umem_update_thr != thr_self() &&
769 umem_st_update_thr != thr_self());
771 (void) _cond_wait(&umem_update_cv, &umem_update_lock);
774 * Get it out of the Work Requested state
776 if (cp->cache_unext != NULL) {
777 cp->cache_uprev->cache_unext = cp->cache_unext;
778 cp->cache_unext->cache_uprev = cp->cache_uprev;
779 cp->cache_uprev = cp->cache_unext = NULL;
780 cp->cache_uflags = 0;
783 * Make sure it is in the Inactive state
785 ASSERT(cp->cache_unext == NULL && cp->cache_uflags == 0);
786 (void) mutex_unlock(&umem_update_lock);
790 umem_updateall(int flags)
795 * NOTE: To prevent deadlock, umem_cache_lock is always acquired first.
797 * (umem_add_update is called from things run via umem_cache_applyall)
799 (void) mutex_lock(&umem_cache_lock);
800 (void) mutex_lock(&umem_update_lock);
802 for (cp = umem_null_cache.cache_next; cp != &umem_null_cache;
804 umem_add_update_unlocked(cp, flags);
807 (void) cond_broadcast(&umem_update_cv);
809 (void) mutex_unlock(&umem_update_lock);
810 (void) mutex_unlock(&umem_cache_lock);
814 * Debugging support. Given a buffer address, find its slab.
817 umem_findslab(umem_cache_t *cp, void *buf)
821 (void) mutex_lock(&cp->cache_lock);
822 for (sp = cp->cache_nullslab.slab_next;
823 sp != &cp->cache_nullslab; sp = sp->slab_next) {
824 if (UMEM_SLAB_MEMBER(sp, buf)) {
825 (void) mutex_unlock(&cp->cache_lock);
829 (void) mutex_unlock(&cp->cache_lock);
835 umem_error(int error, umem_cache_t *cparg, void *bufarg)
837 umem_buftag_t *btp = NULL;
838 umem_bufctl_t *bcp = NULL;
839 umem_cache_t *cp = cparg;
844 int old_logging = umem_logging;
846 umem_logging = 0; /* stop logging when a bad thing happens */
848 umem_abort_info.ump_timestamp = gethrtime();
850 sp = umem_findslab(cp, buf);
852 for (cp = umem_null_cache.cache_prev; cp != &umem_null_cache;
853 cp = cp->cache_prev) {
854 if ((sp = umem_findslab(cp, buf)) != NULL)
861 error = UMERR_BADADDR;
864 error = UMERR_BADCACHE;
866 buf = (char *)bufarg - ((uintptr_t)bufarg -
867 (uintptr_t)sp->slab_base) % cp->cache_chunksize;
869 error = UMERR_BADBASE;
870 if (cp->cache_flags & UMF_BUFTAG)
871 btp = UMEM_BUFTAG(cp, buf);
872 if (cp->cache_flags & UMF_HASH) {
873 (void) mutex_lock(&cp->cache_lock);
874 for (bcp = *UMEM_HASH(cp, buf); bcp; bcp = bcp->bc_next)
875 if (bcp->bc_addr == buf)
877 (void) mutex_unlock(&cp->cache_lock);
878 if (bcp == NULL && btp != NULL)
879 bcp = btp->bt_bufctl;
880 if (umem_findslab(cp->cache_bufctl_cache, bcp) ==
881 NULL || P2PHASE((uintptr_t)bcp, UMEM_ALIGN) ||
882 bcp->bc_addr != buf) {
883 error = UMERR_BADBUFCTL;
889 umem_abort_info.ump_error = error;
890 umem_abort_info.ump_buffer = bufarg;
891 umem_abort_info.ump_realbuf = buf;
892 umem_abort_info.ump_cache = cparg;
893 umem_abort_info.ump_realcache = cp;
894 umem_abort_info.ump_slab = sp;
895 umem_abort_info.ump_bufctl = bcp;
897 umem_printf("umem allocator: ");
902 umem_printf("buffer modified after being freed\n");
903 off = verify_pattern(UMEM_FREE_PATTERN, buf, cp->cache_verify);
904 if (off == NULL) /* shouldn't happen */
906 umem_printf("modification occurred at offset 0x%lx "
907 "(0x%llx replaced by 0x%llx)\n",
908 (uintptr_t)off - (uintptr_t)buf,
909 (longlong_t)UMEM_FREE_PATTERN, (longlong_t)*off);
913 umem_printf("redzone violation: write past end of buffer\n");
917 umem_printf("invalid free: buffer not in cache\n");
921 umem_printf("duplicate free: buffer freed twice\n");
924 case UMERR_BADBUFTAG:
925 umem_printf("boundary tag corrupted\n");
926 umem_printf("bcp ^ bxstat = %lx, should be %lx\n",
927 (intptr_t)btp->bt_bufctl ^ btp->bt_bxstat,
931 case UMERR_BADBUFCTL:
932 umem_printf("bufctl corrupted\n");
936 umem_printf("buffer freed to wrong cache\n");
937 umem_printf("buffer was allocated from %s,\n", cp->cache_name);
938 umem_printf("caller attempting free to %s.\n",
943 umem_printf("bad free: free size (%u) != alloc size (%u)\n",
944 UMEM_SIZE_DECODE(((uint32_t *)btp)[0]),
945 UMEM_SIZE_DECODE(((uint32_t *)btp)[1]));
949 umem_printf("bad free: free address (%p) != alloc address "
950 "(%p)\n", bufarg, buf);
954 umem_printf("buffer=%p bufctl=%p cache: %s\n",
955 bufarg, (void *)bcp, cparg->cache_name);
957 if (bcp != NULL && (cp->cache_flags & UMF_AUDIT) &&
958 error != UMERR_BADBUFCTL) {
962 umem_bufctl_audit_t *bcap = (umem_bufctl_audit_t *)bcp;
964 diff = umem_abort_info.ump_timestamp - bcap->bc_timestamp;
965 ts.tv_sec = diff / NANOSEC;
966 ts.tv_nsec = diff % NANOSEC;
968 umem_printf("previous transaction on buffer %p:\n", buf);
969 umem_printf("thread=%p time=T-%ld.%09ld slab=%p cache: %s\n",
970 (void *)(intptr_t)bcap->bc_thread, ts.tv_sec, ts.tv_nsec,
971 (void *)sp, cp->cache_name);
972 for (d = 0; d < MIN(bcap->bc_depth, umem_stack_depth); d++) {
973 (void) print_sym((void *)bcap->bc_stack[d]);
978 umem_err_recoverable("umem: heap corruption detected");
980 umem_logging = old_logging; /* resume logging */
984 umem_nofail_callback(umem_nofail_callback_t *cb)
986 nofail_callback = cb;
990 umem_alloc_retry(umem_cache_t *cp, int umflag)
992 if (cp == &umem_null_cache) {
994 return (1); /* retry */
996 * Initialization failed. Do normal failure processing.
999 if (umflag & UMEM_NOFAIL) {
1000 int def_result = UMEM_CALLBACK_EXIT(255);
1001 int result = def_result;
1002 umem_nofail_callback_t *callback = nofail_callback;
1004 if (callback != NULL)
1005 result = callback();
1007 if (result == UMEM_CALLBACK_RETRY)
1010 if ((result & ~0xFF) != UMEM_CALLBACK_EXIT(0)) {
1011 log_message("nofail callback returned %x\n", result);
1012 result = def_result;
1016 * only one thread will call exit
1018 if (umem_nofail_exit_thr == thr_self())
1019 umem_panic("recursive UMEM_CALLBACK_EXIT()\n");
1021 (void) mutex_lock(&umem_nofail_exit_lock);
1022 umem_nofail_exit_thr = thr_self();
1023 exit(result & 0xFF);
1029 static umem_log_header_t *
1030 umem_log_init(size_t logsize)
1032 umem_log_header_t *lhp;
1033 int nchunks = 4 * umem_max_ncpus;
1034 size_t lhsize = offsetof(umem_log_header_t, lh_cpu[umem_max_ncpus]);
1041 * Make sure that lhp->lh_cpu[] is nicely aligned
1042 * to prevent false sharing of cache lines.
1044 lhsize = P2ROUNDUP(lhsize, UMEM_ALIGN);
1045 lhp = vmem_xalloc(umem_log_arena, lhsize, 64, P2NPHASE(lhsize, 64), 0,
1046 NULL, NULL, VM_NOSLEEP);
1052 (void) mutex_init(&lhp->lh_lock, USYNC_THREAD, NULL);
1053 lhp->lh_nchunks = nchunks;
1054 lhp->lh_chunksize = P2ROUNDUP(logsize / nchunks, PAGESIZE);
1055 if (lhp->lh_chunksize == 0)
1056 lhp->lh_chunksize = PAGESIZE;
1058 lhp->lh_base = vmem_alloc(umem_log_arena,
1059 lhp->lh_chunksize * nchunks, VM_NOSLEEP);
1060 if (lhp->lh_base == NULL)
1063 lhp->lh_free = vmem_alloc(umem_log_arena,
1064 nchunks * sizeof (int), VM_NOSLEEP);
1065 if (lhp->lh_free == NULL)
1068 bzero(lhp->lh_base, lhp->lh_chunksize * nchunks);
1070 for (i = 0; i < umem_max_ncpus; i++) {
1071 umem_cpu_log_header_t *clhp = &lhp->lh_cpu[i];
1072 (void) mutex_init(&clhp->clh_lock, USYNC_THREAD, NULL);
1073 clhp->clh_chunk = i;
1076 for (i = umem_max_ncpus; i < nchunks; i++)
1077 lhp->lh_free[i] = i;
1079 lhp->lh_head = umem_max_ncpus;
1086 if (lhp->lh_base != NULL)
1087 vmem_free(umem_log_arena, lhp->lh_base,
1088 lhp->lh_chunksize * nchunks);
1090 vmem_xfree(umem_log_arena, lhp, lhsize);
1096 umem_log_enter(umem_log_header_t *lhp, void *data, size_t size)
1099 umem_cpu_log_header_t *clhp =
1100 &(lhp->lh_cpu[CPU(umem_cpu_mask)->cpu_number]);
1102 if (lhp == NULL || umem_logging == 0)
1105 (void) mutex_lock(&clhp->clh_lock);
1107 if (size > clhp->clh_avail) {
1108 (void) mutex_lock(&lhp->lh_lock);
1110 lhp->lh_free[lhp->lh_tail] = clhp->clh_chunk;
1111 lhp->lh_tail = (lhp->lh_tail + 1) % lhp->lh_nchunks;
1112 clhp->clh_chunk = lhp->lh_free[lhp->lh_head];
1113 lhp->lh_head = (lhp->lh_head + 1) % lhp->lh_nchunks;
1114 clhp->clh_current = lhp->lh_base +
1115 clhp->clh_chunk * lhp->lh_chunksize;
1116 clhp->clh_avail = lhp->lh_chunksize;
1117 if (size > lhp->lh_chunksize)
1118 size = lhp->lh_chunksize;
1119 (void) mutex_unlock(&lhp->lh_lock);
1121 logspace = clhp->clh_current;
1122 clhp->clh_current += size;
1123 clhp->clh_avail -= size;
1124 bcopy(data, logspace, size);
1125 (void) mutex_unlock(&clhp->clh_lock);
1129 #define UMEM_AUDIT(lp, cp, bcp) \
1131 umem_bufctl_audit_t *_bcp = (umem_bufctl_audit_t *)(bcp); \
1132 _bcp->bc_timestamp = gethrtime(); \
1133 _bcp->bc_thread = thr_self(); \
1134 _bcp->bc_depth = getpcstack(_bcp->bc_stack, umem_stack_depth, \
1135 (cp != NULL) && (cp->cache_flags & UMF_CHECKSIGNAL)); \
1136 _bcp->bc_lastlog = umem_log_enter((lp), _bcp, \
1137 UMEM_BUFCTL_AUDIT_SIZE); \
1141 umem_log_event(umem_log_header_t *lp, umem_cache_t *cp,
1142 umem_slab_t *sp, void *addr)
1144 umem_bufctl_audit_t *bcp;
1145 UMEM_LOCAL_BUFCTL_AUDIT(&bcp);
1147 bzero(bcp, UMEM_BUFCTL_AUDIT_SIZE);
1148 bcp->bc_addr = addr;
1151 UMEM_AUDIT(lp, cp, bcp);
1155 * Create a new slab for cache cp.
1157 static umem_slab_t *
1158 umem_slab_create(umem_cache_t *cp, int umflag)
1160 size_t slabsize = cp->cache_slabsize;
1161 size_t chunksize = cp->cache_chunksize;
1162 int cache_flags = cp->cache_flags;
1163 size_t color, chunks;
1167 vmem_t *vmp = cp->cache_arena;
1169 color = cp->cache_color + cp->cache_align;
1170 if (color > cp->cache_maxcolor)
1171 color = cp->cache_mincolor;
1172 cp->cache_color = color;
1174 slab = vmem_alloc(vmp, slabsize, UMEM_VMFLAGS(umflag));
1177 goto vmem_alloc_failure;
1179 ASSERT(P2PHASE((uintptr_t)slab, vmp->vm_quantum) == 0);
1181 if (!(cp->cache_cflags & UMC_NOTOUCH) &&
1182 (cp->cache_flags & UMF_DEADBEEF))
1183 copy_pattern(UMEM_UNINITIALIZED_PATTERN, slab, slabsize);
1185 if (cache_flags & UMF_HASH) {
1186 if ((sp = _umem_cache_alloc(umem_slab_cache, umflag)) == NULL)
1187 goto slab_alloc_failure;
1188 chunks = (slabsize - color) / chunksize;
1190 sp = UMEM_SLAB(cp, slab);
1191 chunks = (slabsize - sizeof (umem_slab_t) - color) / chunksize;
1194 sp->slab_cache = cp;
1195 sp->slab_head = NULL;
1196 sp->slab_refcnt = 0;
1197 sp->slab_base = buf = slab + color;
1198 sp->slab_chunks = chunks;
1201 while (chunks-- != 0) {
1202 if (cache_flags & UMF_HASH) {
1203 bcp = _umem_cache_alloc(cp->cache_bufctl_cache, umflag);
1205 goto bufctl_alloc_failure;
1206 if (cache_flags & UMF_AUDIT) {
1207 umem_bufctl_audit_t *bcap =
1208 (umem_bufctl_audit_t *)bcp;
1209 bzero(bcap, UMEM_BUFCTL_AUDIT_SIZE);
1210 bcap->bc_cache = cp;
1215 bcp = UMEM_BUFCTL(cp, buf);
1217 if (cache_flags & UMF_BUFTAG) {
1218 umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1219 btp->bt_redzone = UMEM_REDZONE_PATTERN;
1220 btp->bt_bufctl = bcp;
1221 btp->bt_bxstat = (intptr_t)bcp ^ UMEM_BUFTAG_FREE;
1222 if (cache_flags & UMF_DEADBEEF) {
1223 copy_pattern(UMEM_FREE_PATTERN, buf,
1227 bcp->bc_next = sp->slab_head;
1228 sp->slab_head = bcp;
1232 umem_log_event(umem_slab_log, cp, sp, slab);
1236 bufctl_alloc_failure:
1238 while ((bcp = sp->slab_head) != NULL) {
1239 sp->slab_head = bcp->bc_next;
1240 _umem_cache_free(cp->cache_bufctl_cache, bcp);
1242 _umem_cache_free(umem_slab_cache, sp);
1246 vmem_free(vmp, slab, slabsize);
1250 umem_log_event(umem_failure_log, cp, NULL, NULL);
1251 atomic_add_64(&cp->cache_alloc_fail, 1);
1260 umem_slab_destroy(umem_cache_t *cp, umem_slab_t *sp)
1262 vmem_t *vmp = cp->cache_arena;
1263 void *slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, vmp->vm_quantum);
1265 if (cp->cache_flags & UMF_HASH) {
1267 while ((bcp = sp->slab_head) != NULL) {
1268 sp->slab_head = bcp->bc_next;
1269 _umem_cache_free(cp->cache_bufctl_cache, bcp);
1271 _umem_cache_free(umem_slab_cache, sp);
1273 vmem_free(vmp, slab, cp->cache_slabsize);
1277 * Allocate a raw (unconstructed) buffer from cp's slab layer.
1280 umem_slab_alloc(umem_cache_t *cp, int umflag)
1282 umem_bufctl_t *bcp, **hash_bucket;
1286 (void) mutex_lock(&cp->cache_lock);
1287 cp->cache_slab_alloc++;
1288 sp = cp->cache_freelist;
1289 ASSERT(sp->slab_cache == cp);
1290 if (sp->slab_head == NULL) {
1292 * The freelist is empty. Create a new slab.
1294 (void) mutex_unlock(&cp->cache_lock);
1295 if (cp == &umem_null_cache)
1297 if ((sp = umem_slab_create(cp, umflag)) == NULL)
1299 (void) mutex_lock(&cp->cache_lock);
1300 cp->cache_slab_create++;
1301 if ((cp->cache_buftotal += sp->slab_chunks) > cp->cache_bufmax)
1302 cp->cache_bufmax = cp->cache_buftotal;
1303 sp->slab_next = cp->cache_freelist;
1304 sp->slab_prev = cp->cache_freelist->slab_prev;
1305 sp->slab_next->slab_prev = sp;
1306 sp->slab_prev->slab_next = sp;
1307 cp->cache_freelist = sp;
1311 ASSERT(sp->slab_refcnt <= sp->slab_chunks);
1314 * If we're taking the last buffer in the slab,
1315 * remove the slab from the cache's freelist.
1317 bcp = sp->slab_head;
1318 if ((sp->slab_head = bcp->bc_next) == NULL) {
1319 cp->cache_freelist = sp->slab_next;
1320 ASSERT(sp->slab_refcnt == sp->slab_chunks);
1323 if (cp->cache_flags & UMF_HASH) {
1325 * Add buffer to allocated-address hash table.
1328 hash_bucket = UMEM_HASH(cp, buf);
1329 bcp->bc_next = *hash_bucket;
1331 if ((cp->cache_flags & (UMF_AUDIT | UMF_BUFTAG)) == UMF_AUDIT) {
1332 UMEM_AUDIT(umem_transaction_log, cp, bcp);
1335 buf = UMEM_BUF(cp, bcp);
1338 ASSERT(UMEM_SLAB_MEMBER(sp, buf));
1340 (void) mutex_unlock(&cp->cache_lock);
1346 * Free a raw (unconstructed) buffer to cp's slab layer.
1349 umem_slab_free(umem_cache_t *cp, void *buf)
1352 umem_bufctl_t *bcp, **prev_bcpp;
1354 ASSERT(buf != NULL);
1356 (void) mutex_lock(&cp->cache_lock);
1357 cp->cache_slab_free++;
1359 if (cp->cache_flags & UMF_HASH) {
1361 * Look up buffer in allocated-address hash table.
1363 prev_bcpp = UMEM_HASH(cp, buf);
1364 while ((bcp = *prev_bcpp) != NULL) {
1365 if (bcp->bc_addr == buf) {
1366 *prev_bcpp = bcp->bc_next;
1370 cp->cache_lookup_depth++;
1371 prev_bcpp = &bcp->bc_next;
1374 bcp = UMEM_BUFCTL(cp, buf);
1375 sp = UMEM_SLAB(cp, buf);
1378 if (bcp == NULL || sp->slab_cache != cp || !UMEM_SLAB_MEMBER(sp, buf)) {
1379 (void) mutex_unlock(&cp->cache_lock);
1380 umem_error(UMERR_BADADDR, cp, buf);
1384 if ((cp->cache_flags & (UMF_AUDIT | UMF_BUFTAG)) == UMF_AUDIT) {
1385 if (cp->cache_flags & UMF_CONTENTS)
1386 ((umem_bufctl_audit_t *)bcp)->bc_contents =
1387 umem_log_enter(umem_content_log, buf,
1388 cp->cache_contents);
1389 UMEM_AUDIT(umem_transaction_log, cp, bcp);
1393 * If this slab isn't currently on the freelist, put it there.
1395 if (sp->slab_head == NULL) {
1396 ASSERT(sp->slab_refcnt == sp->slab_chunks);
1397 ASSERT(cp->cache_freelist != sp);
1398 sp->slab_next->slab_prev = sp->slab_prev;
1399 sp->slab_prev->slab_next = sp->slab_next;
1400 sp->slab_next = cp->cache_freelist;
1401 sp->slab_prev = cp->cache_freelist->slab_prev;
1402 sp->slab_next->slab_prev = sp;
1403 sp->slab_prev->slab_next = sp;
1404 cp->cache_freelist = sp;
1407 bcp->bc_next = sp->slab_head;
1408 sp->slab_head = bcp;
1410 ASSERT(sp->slab_refcnt >= 1);
1411 if (--sp->slab_refcnt == 0) {
1413 * There are no outstanding allocations from this slab,
1414 * so we can reclaim the memory.
1416 sp->slab_next->slab_prev = sp->slab_prev;
1417 sp->slab_prev->slab_next = sp->slab_next;
1418 if (sp == cp->cache_freelist)
1419 cp->cache_freelist = sp->slab_next;
1420 cp->cache_slab_destroy++;
1421 cp->cache_buftotal -= sp->slab_chunks;
1422 (void) mutex_unlock(&cp->cache_lock);
1423 umem_slab_destroy(cp, sp);
1426 (void) mutex_unlock(&cp->cache_lock);
1430 umem_cache_alloc_debug(umem_cache_t *cp, void *buf, int umflag)
1432 umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1433 umem_bufctl_audit_t *bcp = (umem_bufctl_audit_t *)btp->bt_bufctl;
1437 if (btp->bt_bxstat != ((intptr_t)bcp ^ UMEM_BUFTAG_FREE)) {
1438 umem_error(UMERR_BADBUFTAG, cp, buf);
1442 btp->bt_bxstat = (intptr_t)bcp ^ UMEM_BUFTAG_ALLOC;
1444 if ((cp->cache_flags & UMF_HASH) && bcp->bc_addr != buf) {
1445 umem_error(UMERR_BADBUFCTL, cp, buf);
1449 btp->bt_redzone = UMEM_REDZONE_PATTERN;
1451 if (cp->cache_flags & UMF_DEADBEEF) {
1452 if (verify_and_copy_pattern(UMEM_FREE_PATTERN,
1453 UMEM_UNINITIALIZED_PATTERN, buf, cp->cache_verify)) {
1454 umem_error(UMERR_MODIFIED, cp, buf);
1459 if ((mtbf = umem_mtbf | cp->cache_mtbf) != 0 &&
1460 gethrtime() % mtbf == 0 &&
1461 (umflag & (UMEM_FATAL_FLAGS)) == 0) {
1462 umem_log_event(umem_failure_log, cp, NULL, NULL);
1468 * We do not pass fatal flags on to the constructor. This prevents
1469 * leaking buffers in the event of a subordinate constructor failing.
1471 flags_nfatal = UMEM_DEFAULT;
1472 if (mtbf || (cp->cache_constructor != NULL &&
1473 cp->cache_constructor(buf, cp->cache_private, flags_nfatal) != 0)) {
1474 atomic_add_64(&cp->cache_alloc_fail, 1);
1475 btp->bt_bxstat = (intptr_t)bcp ^ UMEM_BUFTAG_FREE;
1476 copy_pattern(UMEM_FREE_PATTERN, buf, cp->cache_verify);
1477 umem_slab_free(cp, buf);
1481 if (cp->cache_flags & UMF_AUDIT) {
1482 UMEM_AUDIT(umem_transaction_log, cp, bcp);
1489 umem_cache_free_debug(umem_cache_t *cp, void *buf)
1491 umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1492 umem_bufctl_audit_t *bcp = (umem_bufctl_audit_t *)btp->bt_bufctl;
1495 if (btp->bt_bxstat != ((intptr_t)bcp ^ UMEM_BUFTAG_ALLOC)) {
1496 if (btp->bt_bxstat == ((intptr_t)bcp ^ UMEM_BUFTAG_FREE)) {
1497 umem_error(UMERR_DUPFREE, cp, buf);
1500 sp = umem_findslab(cp, buf);
1501 if (sp == NULL || sp->slab_cache != cp)
1502 umem_error(UMERR_BADADDR, cp, buf);
1504 umem_error(UMERR_REDZONE, cp, buf);
1508 btp->bt_bxstat = (intptr_t)bcp ^ UMEM_BUFTAG_FREE;
1510 if ((cp->cache_flags & UMF_HASH) && bcp->bc_addr != buf) {
1511 umem_error(UMERR_BADBUFCTL, cp, buf);
1515 if (btp->bt_redzone != UMEM_REDZONE_PATTERN) {
1516 umem_error(UMERR_REDZONE, cp, buf);
1520 if (cp->cache_flags & UMF_AUDIT) {
1521 if (cp->cache_flags & UMF_CONTENTS)
1522 bcp->bc_contents = umem_log_enter(umem_content_log,
1523 buf, cp->cache_contents);
1524 UMEM_AUDIT(umem_transaction_log, cp, bcp);
1527 if (cp->cache_destructor != NULL)
1528 cp->cache_destructor(buf, cp->cache_private);
1530 if (cp->cache_flags & UMF_DEADBEEF)
1531 copy_pattern(UMEM_FREE_PATTERN, buf, cp->cache_verify);
1537 * Free each object in magazine mp to cp's slab layer, and free mp itself.
1540 umem_magazine_destroy(umem_cache_t *cp, umem_magazine_t *mp, int nrounds)
1544 ASSERT(cp->cache_next == NULL || IN_UPDATE());
1546 for (round = 0; round < nrounds; round++) {
1547 void *buf = mp->mag_round[round];
1549 if ((cp->cache_flags & UMF_DEADBEEF) &&
1550 verify_pattern(UMEM_FREE_PATTERN, buf,
1551 cp->cache_verify) != NULL) {
1552 umem_error(UMERR_MODIFIED, cp, buf);
1556 if (!(cp->cache_flags & UMF_BUFTAG) &&
1557 cp->cache_destructor != NULL)
1558 cp->cache_destructor(buf, cp->cache_private);
1560 umem_slab_free(cp, buf);
1562 ASSERT(UMEM_MAGAZINE_VALID(cp, mp));
1563 _umem_cache_free(cp->cache_magtype->mt_cache, mp);
1567 * Allocate a magazine from the depot.
1569 static umem_magazine_t *
1570 umem_depot_alloc(umem_cache_t *cp, umem_maglist_t *mlp)
1572 umem_magazine_t *mp;
1575 * If we can't get the depot lock without contention,
1576 * update our contention count. We use the depot
1577 * contention rate to determine whether we need to
1578 * increase the magazine size for better scalability.
1580 if (mutex_trylock(&cp->cache_depot_lock) != 0) {
1581 (void) mutex_lock(&cp->cache_depot_lock);
1582 cp->cache_depot_contention++;
1585 if ((mp = mlp->ml_list) != NULL) {
1586 ASSERT(UMEM_MAGAZINE_VALID(cp, mp));
1587 mlp->ml_list = mp->mag_next;
1588 if (--mlp->ml_total < mlp->ml_min)
1589 mlp->ml_min = mlp->ml_total;
1593 (void) mutex_unlock(&cp->cache_depot_lock);
1599 * Free a magazine to the depot.
1602 umem_depot_free(umem_cache_t *cp, umem_maglist_t *mlp, umem_magazine_t *mp)
1604 (void) mutex_lock(&cp->cache_depot_lock);
1605 ASSERT(UMEM_MAGAZINE_VALID(cp, mp));
1606 mp->mag_next = mlp->ml_list;
1609 (void) mutex_unlock(&cp->cache_depot_lock);
1613 * Update the working set statistics for cp's depot.
1616 umem_depot_ws_update(umem_cache_t *cp)
1618 (void) mutex_lock(&cp->cache_depot_lock);
1619 cp->cache_full.ml_reaplimit = cp->cache_full.ml_min;
1620 cp->cache_full.ml_min = cp->cache_full.ml_total;
1621 cp->cache_empty.ml_reaplimit = cp->cache_empty.ml_min;
1622 cp->cache_empty.ml_min = cp->cache_empty.ml_total;
1623 (void) mutex_unlock(&cp->cache_depot_lock);
1627 * Reap all magazines that have fallen out of the depot's working set.
1630 umem_depot_ws_reap(umem_cache_t *cp)
1633 umem_magazine_t *mp;
1635 ASSERT(cp->cache_next == NULL || IN_REAP());
1637 reap = MIN(cp->cache_full.ml_reaplimit, cp->cache_full.ml_min);
1638 while (reap-- && (mp = umem_depot_alloc(cp, &cp->cache_full)) != NULL)
1639 umem_magazine_destroy(cp, mp, cp->cache_magtype->mt_magsize);
1641 reap = MIN(cp->cache_empty.ml_reaplimit, cp->cache_empty.ml_min);
1642 while (reap-- && (mp = umem_depot_alloc(cp, &cp->cache_empty)) != NULL)
1643 umem_magazine_destroy(cp, mp, 0);
1647 umem_cpu_reload(umem_cpu_cache_t *ccp, umem_magazine_t *mp, int rounds)
1649 ASSERT((ccp->cc_loaded == NULL && ccp->cc_rounds == -1) ||
1650 (ccp->cc_loaded && ccp->cc_rounds + rounds == ccp->cc_magsize));
1651 ASSERT(ccp->cc_magsize > 0);
1653 ccp->cc_ploaded = ccp->cc_loaded;
1654 ccp->cc_prounds = ccp->cc_rounds;
1655 ccp->cc_loaded = mp;
1656 ccp->cc_rounds = rounds;
1660 * Allocate a constructed object from cache cp.
1662 #ifndef NO_WEAK_SYMBOLS
1663 #pragma weak umem_cache_alloc = _umem_cache_alloc
1666 _umem_cache_alloc(umem_cache_t *cp, int umflag)
1668 umem_cpu_cache_t *ccp;
1669 umem_magazine_t *fmp;
1674 ccp = UMEM_CPU_CACHE(cp, CPU(cp->cache_cpu_mask));
1675 (void) mutex_lock(&ccp->cc_lock);
1678 * If there's an object available in the current CPU's
1679 * loaded magazine, just take it and return.
1681 if (ccp->cc_rounds > 0) {
1682 buf = ccp->cc_loaded->mag_round[--ccp->cc_rounds];
1684 (void) mutex_unlock(&ccp->cc_lock);
1685 if ((ccp->cc_flags & UMF_BUFTAG) &&
1686 umem_cache_alloc_debug(cp, buf, umflag) == -1) {
1687 if (umem_alloc_retry(cp, umflag)) {
1697 * The loaded magazine is empty. If the previously loaded
1698 * magazine was full, exchange them and try again.
1700 if (ccp->cc_prounds > 0) {
1701 umem_cpu_reload(ccp, ccp->cc_ploaded, ccp->cc_prounds);
1706 * If the magazine layer is disabled, break out now.
1708 if (ccp->cc_magsize == 0)
1712 * Try to get a full magazine from the depot.
1714 fmp = umem_depot_alloc(cp, &cp->cache_full);
1716 if (ccp->cc_ploaded != NULL)
1717 umem_depot_free(cp, &cp->cache_empty,
1719 umem_cpu_reload(ccp, fmp, ccp->cc_magsize);
1724 * There are no full magazines in the depot,
1725 * so fall through to the slab layer.
1729 (void) mutex_unlock(&ccp->cc_lock);
1732 * We couldn't allocate a constructed object from the magazine layer,
1733 * so get a raw buffer from the slab layer and apply its constructor.
1735 buf = umem_slab_alloc(cp, umflag);
1738 if (cp == &umem_null_cache)
1740 if (umem_alloc_retry(cp, umflag)) {
1747 if (cp->cache_flags & UMF_BUFTAG) {
1749 * Let umem_cache_alloc_debug() apply the constructor for us.
1751 if (umem_cache_alloc_debug(cp, buf, umflag) == -1) {
1752 if (umem_alloc_retry(cp, umflag)) {
1761 * We do not pass fatal flags on to the constructor. This prevents
1762 * leaking buffers in the event of a subordinate constructor failing.
1764 flags_nfatal = UMEM_DEFAULT;
1765 if (cp->cache_constructor != NULL &&
1766 cp->cache_constructor(buf, cp->cache_private, flags_nfatal) != 0) {
1767 atomic_add_64(&cp->cache_alloc_fail, 1);
1768 umem_slab_free(cp, buf);
1770 if (umem_alloc_retry(cp, umflag)) {
1780 * Free a constructed object to cache cp.
1782 #ifndef NO_WEAK_SYMBOLS
1783 #pragma weak umem_cache_free = _umem_cache_free
1786 _umem_cache_free(umem_cache_t *cp, void *buf)
1788 umem_cpu_cache_t *ccp = UMEM_CPU_CACHE(cp, CPU(cp->cache_cpu_mask));
1789 umem_magazine_t *emp;
1790 umem_magtype_t *mtp;
1792 if (ccp->cc_flags & UMF_BUFTAG)
1793 if (umem_cache_free_debug(cp, buf) == -1)
1796 (void) mutex_lock(&ccp->cc_lock);
1799 * If there's a slot available in the current CPU's
1800 * loaded magazine, just put the object there and return.
1802 if ((uint_t)ccp->cc_rounds < ccp->cc_magsize) {
1803 ccp->cc_loaded->mag_round[ccp->cc_rounds++] = buf;
1805 (void) mutex_unlock(&ccp->cc_lock);
1810 * The loaded magazine is full. If the previously loaded
1811 * magazine was empty, exchange them and try again.
1813 if (ccp->cc_prounds == 0) {
1814 umem_cpu_reload(ccp, ccp->cc_ploaded, ccp->cc_prounds);
1819 * If the magazine layer is disabled, break out now.
1821 if (ccp->cc_magsize == 0)
1825 * Try to get an empty magazine from the depot.
1827 emp = umem_depot_alloc(cp, &cp->cache_empty);
1829 if (ccp->cc_ploaded != NULL)
1830 umem_depot_free(cp, &cp->cache_full,
1832 umem_cpu_reload(ccp, emp, 0);
1837 * There are no empty magazines in the depot,
1838 * so try to allocate a new one. We must drop all locks
1839 * across umem_cache_alloc() because lower layers may
1840 * attempt to allocate from this cache.
1842 mtp = cp->cache_magtype;
1843 (void) mutex_unlock(&ccp->cc_lock);
1844 emp = _umem_cache_alloc(mtp->mt_cache, UMEM_DEFAULT);
1845 (void) mutex_lock(&ccp->cc_lock);
1849 * We successfully allocated an empty magazine.
1850 * However, we had to drop ccp->cc_lock to do it,
1851 * so the cache's magazine size may have changed.
1852 * If so, free the magazine and try again.
1854 if (ccp->cc_magsize != mtp->mt_magsize) {
1855 (void) mutex_unlock(&ccp->cc_lock);
1856 _umem_cache_free(mtp->mt_cache, emp);
1857 (void) mutex_lock(&ccp->cc_lock);
1862 * We got a magazine of the right size. Add it to
1863 * the depot and try the whole dance again.
1865 umem_depot_free(cp, &cp->cache_empty, emp);
1870 * We couldn't allocate an empty magazine,
1871 * so fall through to the slab layer.
1875 (void) mutex_unlock(&ccp->cc_lock);
1878 * We couldn't free our constructed object to the magazine layer,
1879 * so apply its destructor and free it to the slab layer.
1880 * Note that if UMF_BUFTAG is in effect, umem_cache_free_debug()
1881 * will have already applied the destructor.
1883 if (!(cp->cache_flags & UMF_BUFTAG) && cp->cache_destructor != NULL)
1884 cp->cache_destructor(buf, cp->cache_private);
1886 umem_slab_free(cp, buf);
1889 #ifndef NO_WEAK_SYMBOLS
1890 #pragma weak umem_zalloc = _umem_zalloc
1893 _umem_zalloc(size_t size, int umflag)
1895 size_t index = (size - 1) >> UMEM_ALIGN_SHIFT;
1899 if (index < UMEM_MAXBUF >> UMEM_ALIGN_SHIFT) {
1900 umem_cache_t *cp = umem_alloc_table[index];
1901 buf = _umem_cache_alloc(cp, umflag);
1903 if (cp->cache_flags & UMF_BUFTAG) {
1904 umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1905 ((uint8_t *)buf)[size] = UMEM_REDZONE_BYTE;
1906 ((uint32_t *)btp)[1] = UMEM_SIZE_ENCODE(size);
1909 } else if (umem_alloc_retry(cp, umflag))
1912 buf = _umem_alloc(size, umflag); /* handles failure */
1919 #ifndef NO_WEAK_SYMBOLS
1920 #pragma weak umem_alloc = _umem_alloc
1923 _umem_alloc(size_t size, int umflag)
1925 size_t index = (size - 1) >> UMEM_ALIGN_SHIFT;
1928 if (index < UMEM_MAXBUF >> UMEM_ALIGN_SHIFT) {
1929 umem_cache_t *cp = umem_alloc_table[index];
1930 buf = _umem_cache_alloc(cp, umflag);
1931 if ((cp->cache_flags & UMF_BUFTAG) && buf != NULL) {
1932 umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
1933 ((uint8_t *)buf)[size] = UMEM_REDZONE_BYTE;
1934 ((uint32_t *)btp)[1] = UMEM_SIZE_ENCODE(size);
1936 if (buf == NULL && umem_alloc_retry(cp, umflag))
1937 goto umem_alloc_retry;
1942 if (umem_oversize_arena == NULL) {
1944 ASSERT(umem_oversize_arena != NULL);
1948 buf = vmem_alloc(umem_oversize_arena, size, UMEM_VMFLAGS(umflag));
1950 umem_log_event(umem_failure_log, NULL, NULL, (void *)size);
1951 if (umem_alloc_retry(NULL, umflag))
1952 goto umem_alloc_retry;
1957 #ifndef NO_WEAK_SYMBOLS
1958 #pragma weak umem_alloc_align = _umem_alloc_align
1961 _umem_alloc_align(size_t size, size_t align, int umflag)
1967 if ((align & (align - 1)) != 0)
1969 if (align < UMEM_ALIGN)
1972 umem_alloc_align_retry:
1973 if (umem_memalign_arena == NULL) {
1975 ASSERT(umem_oversize_arena != NULL);
1979 buf = vmem_xalloc(umem_memalign_arena, size, align, 0, 0, NULL, NULL,
1980 UMEM_VMFLAGS(umflag));
1982 umem_log_event(umem_failure_log, NULL, NULL, (void *)size);
1983 if (umem_alloc_retry(NULL, umflag))
1984 goto umem_alloc_align_retry;
1989 #ifndef NO_WEAK_SYMBOLS
1990 #pragma weak umem_free = _umem_free
1993 _umem_free(void *buf, size_t size)
1995 size_t index = (size - 1) >> UMEM_ALIGN_SHIFT;
1997 if (index < UMEM_MAXBUF >> UMEM_ALIGN_SHIFT) {
1998 umem_cache_t *cp = umem_alloc_table[index];
1999 if (cp->cache_flags & UMF_BUFTAG) {
2000 umem_buftag_t *btp = UMEM_BUFTAG(cp, buf);
2001 uint32_t *ip = (uint32_t *)btp;
2002 if (ip[1] != UMEM_SIZE_ENCODE(size)) {
2003 if (*(uint64_t *)buf == UMEM_FREE_PATTERN) {
2004 umem_error(UMERR_DUPFREE, cp, buf);
2007 if (UMEM_SIZE_VALID(ip[1])) {
2008 ip[0] = UMEM_SIZE_ENCODE(size);
2009 umem_error(UMERR_BADSIZE, cp, buf);
2011 umem_error(UMERR_REDZONE, cp, buf);
2015 if (((uint8_t *)buf)[size] != UMEM_REDZONE_BYTE) {
2016 umem_error(UMERR_REDZONE, cp, buf);
2019 btp->bt_redzone = UMEM_REDZONE_PATTERN;
2021 _umem_cache_free(cp, buf);
2023 if (buf == NULL && size == 0)
2025 vmem_free(umem_oversize_arena, buf, size);
2029 #ifndef NO_WEAK_SYMBOLS
2030 #pragma weak umem_free_align = _umem_free_align
2033 _umem_free_align(void *buf, size_t size)
2035 if (buf == NULL && size == 0)
2037 vmem_xfree(umem_memalign_arena, buf, size);
2041 umem_firewall_va_alloc(vmem_t *vmp, size_t size, int vmflag)
2043 size_t realsize = size + vmp->vm_quantum;
2046 * Annoying edge case: if 'size' is just shy of ULONG_MAX, adding
2047 * vm_quantum will cause integer wraparound. Check for this, and
2048 * blow off the firewall page in this case. Note that such a
2049 * giant allocation (the entire address space) can never be
2050 * satisfied, so it will either fail immediately (VM_NOSLEEP)
2051 * or sleep forever (VM_SLEEP). Thus, there is no need for a
2052 * corresponding check in umem_firewall_va_free().
2054 if (realsize < size)
2057 return (vmem_alloc(vmp, realsize, vmflag | VM_NEXTFIT));
2061 umem_firewall_va_free(vmem_t *vmp, void *addr, size_t size)
2063 vmem_free(vmp, addr, size + vmp->vm_quantum);
2067 * Reclaim all unused memory from a cache.
2070 umem_cache_reap(umem_cache_t *cp)
2073 * Ask the cache's owner to free some memory if possible.
2074 * The idea is to handle things like the inode cache, which
2075 * typically sits on a bunch of memory that it doesn't truly
2076 * *need*. Reclaim policy is entirely up to the owner; this
2077 * callback is just an advisory plea for help.
2079 if (cp->cache_reclaim != NULL)
2080 cp->cache_reclaim(cp->cache_private);
2082 umem_depot_ws_reap(cp);
2086 * Purge all magazines from a cache and set its magazine limit to zero.
2087 * All calls are serialized by being done by the update thread, except for
2088 * the final call from umem_cache_destroy().
2091 umem_cache_magazine_purge(umem_cache_t *cp)
2093 umem_cpu_cache_t *ccp;
2094 umem_magazine_t *mp, *pmp;
2095 int rounds, prounds, cpu_seqid;
2097 ASSERT(cp->cache_next == NULL || IN_UPDATE());
2099 for (cpu_seqid = 0; cpu_seqid < umem_max_ncpus; cpu_seqid++) {
2100 ccp = &cp->cache_cpu[cpu_seqid];
2102 (void) mutex_lock(&ccp->cc_lock);
2103 mp = ccp->cc_loaded;
2104 pmp = ccp->cc_ploaded;
2105 rounds = ccp->cc_rounds;
2106 prounds = ccp->cc_prounds;
2107 ccp->cc_loaded = NULL;
2108 ccp->cc_ploaded = NULL;
2109 ccp->cc_rounds = -1;
2110 ccp->cc_prounds = -1;
2111 ccp->cc_magsize = 0;
2112 (void) mutex_unlock(&ccp->cc_lock);
2115 umem_magazine_destroy(cp, mp, rounds);
2117 umem_magazine_destroy(cp, pmp, prounds);
2121 * Updating the working set statistics twice in a row has the
2122 * effect of setting the working set size to zero, so everything
2123 * is eligible for reaping.
2125 umem_depot_ws_update(cp);
2126 umem_depot_ws_update(cp);
2128 umem_depot_ws_reap(cp);
2132 * Enable per-cpu magazines on a cache.
2135 umem_cache_magazine_enable(umem_cache_t *cp)
2139 if (cp->cache_flags & UMF_NOMAGAZINE)
2142 for (cpu_seqid = 0; cpu_seqid < umem_max_ncpus; cpu_seqid++) {
2143 umem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
2144 (void) mutex_lock(&ccp->cc_lock);
2145 ccp->cc_magsize = cp->cache_magtype->mt_magsize;
2146 (void) mutex_unlock(&ccp->cc_lock);
2152 * Recompute a cache's magazine size. The trade-off is that larger magazines
2153 * provide a higher transfer rate with the depot, while smaller magazines
2154 * reduce memory consumption. Magazine resizing is an expensive operation;
2155 * it should not be done frequently.
2157 * Changes to the magazine size are serialized by only having one thread
2158 * doing updates. (the update thread)
2160 * Note: at present this only grows the magazine size. It might be useful
2161 * to allow shrinkage too.
2164 umem_cache_magazine_resize(umem_cache_t *cp)
2166 umem_magtype_t *mtp = cp->cache_magtype;
2168 ASSERT(IN_UPDATE());
2170 if (cp->cache_chunksize < mtp->mt_maxbuf) {
2171 umem_cache_magazine_purge(cp);
2172 (void) mutex_lock(&cp->cache_depot_lock);
2173 cp->cache_magtype = ++mtp;
2174 cp->cache_depot_contention_prev =
2175 cp->cache_depot_contention + INT_MAX;
2176 (void) mutex_unlock(&cp->cache_depot_lock);
2177 umem_cache_magazine_enable(cp);
2182 * Rescale a cache's hash table, so that the table size is roughly the
2183 * cache size. We want the average lookup time to be extremely small.
2186 umem_hash_rescale(umem_cache_t *cp)
2188 umem_bufctl_t **old_table, **new_table, *bcp;
2189 size_t old_size, new_size, h;
2191 ASSERT(IN_UPDATE());
2193 new_size = MAX(UMEM_HASH_INITIAL,
2194 1 << (highbit(3 * cp->cache_buftotal + 4) - 2));
2195 old_size = cp->cache_hash_mask + 1;
2197 if ((old_size >> 1) <= new_size && new_size <= (old_size << 1))
2200 new_table = vmem_alloc(umem_hash_arena, new_size * sizeof (void *),
2202 if (new_table == NULL)
2204 bzero(new_table, new_size * sizeof (void *));
2206 (void) mutex_lock(&cp->cache_lock);
2208 old_size = cp->cache_hash_mask + 1;
2209 old_table = cp->cache_hash_table;
2211 cp->cache_hash_mask = new_size - 1;
2212 cp->cache_hash_table = new_table;
2213 cp->cache_rescale++;
2215 for (h = 0; h < old_size; h++) {
2217 while (bcp != NULL) {
2218 void *addr = bcp->bc_addr;
2219 umem_bufctl_t *next_bcp = bcp->bc_next;
2220 umem_bufctl_t **hash_bucket = UMEM_HASH(cp, addr);
2221 bcp->bc_next = *hash_bucket;
2227 (void) mutex_unlock(&cp->cache_lock);
2229 vmem_free(umem_hash_arena, old_table, old_size * sizeof (void *));
2233 * Perform periodic maintenance on a cache: hash rescaling,
2234 * depot working-set update, and magazine resizing.
2237 umem_cache_update(umem_cache_t *cp)
2239 int update_flags = 0;
2241 ASSERT(MUTEX_HELD(&umem_cache_lock));
2244 * If the cache has become much larger or smaller than its hash table,
2245 * fire off a request to rescale the hash table.
2247 (void) mutex_lock(&cp->cache_lock);
2249 if ((cp->cache_flags & UMF_HASH) &&
2250 (cp->cache_buftotal > (cp->cache_hash_mask << 1) ||
2251 (cp->cache_buftotal < (cp->cache_hash_mask >> 1) &&
2252 cp->cache_hash_mask > UMEM_HASH_INITIAL)))
2253 update_flags |= UMU_HASH_RESCALE;
2255 (void) mutex_unlock(&cp->cache_lock);
2258 * Update the depot working set statistics.
2260 umem_depot_ws_update(cp);
2263 * If there's a lot of contention in the depot,
2264 * increase the magazine size.
2266 (void) mutex_lock(&cp->cache_depot_lock);
2268 if (cp->cache_chunksize < cp->cache_magtype->mt_maxbuf &&
2269 (int)(cp->cache_depot_contention -
2270 cp->cache_depot_contention_prev) > umem_depot_contention)
2271 update_flags |= UMU_MAGAZINE_RESIZE;
2273 cp->cache_depot_contention_prev = cp->cache_depot_contention;
2275 (void) mutex_unlock(&cp->cache_depot_lock);
2278 umem_add_update(cp, update_flags);
2282 * Runs all pending updates.
2284 * The update lock must be held on entrance, and will be held on exit.
2287 umem_process_updates(void)
2289 ASSERT(MUTEX_HELD(&umem_update_lock));
2291 while (umem_null_cache.cache_unext != &umem_null_cache) {
2293 umem_cache_t *cp = umem_null_cache.cache_unext;
2295 cp->cache_uprev->cache_unext = cp->cache_unext;
2296 cp->cache_unext->cache_uprev = cp->cache_uprev;
2297 cp->cache_uprev = cp->cache_unext = NULL;
2299 ASSERT(!(cp->cache_uflags & UMU_ACTIVE));
2301 while (cp->cache_uflags) {
2302 int uflags = (cp->cache_uflags |= UMU_ACTIVE);
2303 (void) mutex_unlock(&umem_update_lock);
2306 * The order here is important. Each step can speed up
2310 if (uflags & UMU_HASH_RESCALE)
2311 umem_hash_rescale(cp);
2313 if (uflags & UMU_MAGAZINE_RESIZE)
2314 umem_cache_magazine_resize(cp);
2316 if (uflags & UMU_REAP)
2317 umem_cache_reap(cp);
2319 (void) mutex_lock(&umem_update_lock);
2322 * check if anyone has requested notification
2324 if (cp->cache_uflags & UMU_NOTIFY) {
2325 uflags |= UMU_NOTIFY;
2328 cp->cache_uflags &= ~uflags;
2331 (void) cond_broadcast(&umem_update_cv);
2335 #ifndef UMEM_STANDALONE
2337 umem_st_update(void)
2339 ASSERT(MUTEX_HELD(&umem_update_lock));
2340 ASSERT(umem_update_thr == 0 && umem_st_update_thr == 0);
2342 umem_st_update_thr = thr_self();
2344 (void) mutex_unlock(&umem_update_lock);
2347 umem_cache_applyall(umem_cache_update);
2349 (void) mutex_lock(&umem_update_lock);
2351 umem_process_updates(); /* does all of the requested work */
2353 umem_reap_next = gethrtime() +
2354 (hrtime_t)umem_reap_interval * NANOSEC;
2356 umem_reaping = UMEM_REAP_DONE;
2358 umem_st_update_thr = 0;
2363 * Reclaim all unused memory from all caches. Called from vmem when memory
2364 * gets tight. Must be called with no locks held.
2366 * This just requests a reap on all caches, and notifies the update thread.
2371 #ifndef UMEM_STANDALONE
2372 extern int __nthreads(void);
2375 if (umem_ready != UMEM_READY || umem_reaping != UMEM_REAP_DONE ||
2376 gethrtime() < umem_reap_next)
2379 (void) mutex_lock(&umem_update_lock);
2381 if (umem_reaping != UMEM_REAP_DONE || gethrtime() < umem_reap_next) {
2382 (void) mutex_unlock(&umem_update_lock);
2386 umem_reaping = UMEM_REAP_ADDING; /* lock out other reaps */
2388 (void) mutex_unlock(&umem_update_lock);
2390 umem_updateall(UMU_REAP);
2392 (void) mutex_lock(&umem_update_lock);
2394 umem_reaping = UMEM_REAP_ACTIVE;
2396 /* Standalone is single-threaded */
2397 #ifndef UMEM_STANDALONE
2398 if (umem_update_thr == 0) {
2400 * The update thread does not exist. If the process is
2401 * multi-threaded, create it. If not, or the creation fails,
2402 * do the update processing inline.
2404 ASSERT(umem_st_update_thr == 0);
2406 if (__nthreads() <= 1 || umem_create_update_thread() == 0)
2410 (void) cond_broadcast(&umem_update_cv); /* wake up the update thread */
2413 (void) mutex_unlock(&umem_update_lock);
2418 char *name, /* descriptive name for this cache */
2419 size_t bufsize, /* size of the objects it manages */
2420 size_t align, /* required object alignment */
2421 umem_constructor_t *constructor, /* object constructor */
2422 umem_destructor_t *destructor, /* object destructor */
2423 umem_reclaim_t *reclaim, /* memory reclaim callback */
2424 void *private, /* pass-thru arg for constr/destr/reclaim */
2425 vmem_t *vmp, /* vmem source for slab allocation */
2426 int cflags) /* cache creation flags */
2430 umem_cache_t *cp, *cnext, *cprev;
2431 umem_magtype_t *mtp;
2436 * The init thread is allowed to create internal and quantum caches.
2438 * Other threads must wait until until initialization is complete.
2440 if (umem_init_thr == thr_self())
2441 ASSERT((cflags & (UMC_INTERNAL | UMC_QCACHE)) != 0);
2443 ASSERT(!(cflags & UMC_INTERNAL));
2444 if (umem_ready != UMEM_READY && umem_init() == 0) {
2450 csize = UMEM_CACHE_SIZE(umem_max_ncpus);
2451 phase = P2NPHASE(csize, UMEM_CPU_CACHE_SIZE);
2454 vmp = umem_default_arena;
2456 ASSERT(P2PHASE(phase, UMEM_ALIGN) == 0);
2459 * Check that the arguments are reasonable
2461 if ((align & (align - 1)) != 0 || align > vmp->vm_quantum ||
2462 ((cflags & UMC_NOHASH) && (cflags & UMC_NOTOUCH)) ||
2463 name == NULL || bufsize == 0) {
2469 * If align == 0, we set it to the minimum required alignment.
2471 * If align < UMEM_ALIGN, we round it up to UMEM_ALIGN, unless
2472 * UMC_NOTOUCH was passed.
2475 if (P2ROUNDUP(bufsize, UMEM_ALIGN) >= UMEM_SECOND_ALIGN)
2476 align = UMEM_SECOND_ALIGN;
2479 } else if (align < UMEM_ALIGN && (cflags & UMC_NOTOUCH) == 0)
2484 * Get a umem_cache structure. We arrange that cp->cache_cpu[]
2485 * is aligned on a UMEM_CPU_CACHE_SIZE boundary to prevent
2486 * false sharing of per-CPU data.
2488 cp = vmem_xalloc(umem_cache_arena, csize, UMEM_CPU_CACHE_SIZE, phase,
2489 0, NULL, NULL, VM_NOSLEEP);
2498 (void) mutex_lock(&umem_flags_lock);
2499 if (umem_flags & UMF_RANDOMIZE)
2500 umem_flags = (((umem_flags | ~UMF_RANDOM) + 1) & UMF_RANDOM) |
2502 cp->cache_flags = umem_flags | (cflags & UMF_DEBUG);
2503 (void) mutex_unlock(&umem_flags_lock);
2506 * Make sure all the various flags are reasonable.
2508 if (cp->cache_flags & UMF_LITE) {
2509 if (bufsize >= umem_lite_minsize &&
2510 align <= umem_lite_maxalign &&
2511 P2PHASE(bufsize, umem_lite_maxalign) != 0) {
2512 cp->cache_flags |= UMF_BUFTAG;
2513 cp->cache_flags &= ~(UMF_AUDIT | UMF_FIREWALL);
2515 cp->cache_flags &= ~UMF_DEBUG;
2519 if ((cflags & UMC_QCACHE) && (cp->cache_flags & UMF_AUDIT))
2520 cp->cache_flags |= UMF_NOMAGAZINE;
2522 if (cflags & UMC_NODEBUG)
2523 cp->cache_flags &= ~UMF_DEBUG;
2525 if (cflags & UMC_NOTOUCH)
2526 cp->cache_flags &= ~UMF_TOUCH;
2528 if (cflags & UMC_NOHASH)
2529 cp->cache_flags &= ~(UMF_AUDIT | UMF_FIREWALL);
2531 if (cflags & UMC_NOMAGAZINE)
2532 cp->cache_flags |= UMF_NOMAGAZINE;
2534 if ((cp->cache_flags & UMF_AUDIT) && !(cflags & UMC_NOTOUCH))
2535 cp->cache_flags |= UMF_REDZONE;
2537 if ((cp->cache_flags & UMF_BUFTAG) && bufsize >= umem_minfirewall &&
2538 !(cp->cache_flags & UMF_LITE) && !(cflags & UMC_NOHASH))
2539 cp->cache_flags |= UMF_FIREWALL;
2541 if (vmp != umem_default_arena || umem_firewall_arena == NULL)
2542 cp->cache_flags &= ~UMF_FIREWALL;
2544 if (cp->cache_flags & UMF_FIREWALL) {
2545 cp->cache_flags &= ~UMF_BUFTAG;
2546 cp->cache_flags |= UMF_NOMAGAZINE;
2547 ASSERT(vmp == umem_default_arena);
2548 vmp = umem_firewall_arena;
2552 * Set cache properties.
2554 (void) strncpy(cp->cache_name, name, sizeof (cp->cache_name) - 1);
2555 cp->cache_bufsize = bufsize;
2556 cp->cache_align = align;
2557 cp->cache_constructor = constructor;
2558 cp->cache_destructor = destructor;
2559 cp->cache_reclaim = reclaim;
2560 cp->cache_private = private;
2561 cp->cache_arena = vmp;
2562 cp->cache_cflags = cflags;
2563 cp->cache_cpu_mask = umem_cpu_mask;
2566 * Determine the chunk size.
2568 chunksize = bufsize;
2570 if (align >= UMEM_ALIGN) {
2571 chunksize = P2ROUNDUP(chunksize, UMEM_ALIGN);
2572 cp->cache_bufctl = chunksize - UMEM_ALIGN;
2575 if (cp->cache_flags & UMF_BUFTAG) {
2576 cp->cache_bufctl = chunksize;
2577 cp->cache_buftag = chunksize;
2578 chunksize += sizeof (umem_buftag_t);
2581 if (cp->cache_flags & UMF_DEADBEEF) {
2582 cp->cache_verify = MIN(cp->cache_buftag, umem_maxverify);
2583 if (cp->cache_flags & UMF_LITE)
2584 cp->cache_verify = MIN(cp->cache_verify, UMEM_ALIGN);
2587 cp->cache_contents = MIN(cp->cache_bufctl, umem_content_maxsave);
2589 cp->cache_chunksize = chunksize = P2ROUNDUP(chunksize, align);
2591 if (chunksize < bufsize) {
2597 * Now that we know the chunk size, determine the optimal slab size.
2599 if (vmp == umem_firewall_arena) {
2600 cp->cache_slabsize = P2ROUNDUP(chunksize, vmp->vm_quantum);
2601 cp->cache_mincolor = cp->cache_slabsize - chunksize;
2602 cp->cache_maxcolor = cp->cache_mincolor;
2603 cp->cache_flags |= UMF_HASH;
2604 ASSERT(!(cp->cache_flags & UMF_BUFTAG));
2605 } else if ((cflags & UMC_NOHASH) || (!(cflags & UMC_NOTOUCH) &&
2606 !(cp->cache_flags & UMF_AUDIT) &&
2607 chunksize < vmp->vm_quantum / UMEM_VOID_FRACTION)) {
2608 cp->cache_slabsize = vmp->vm_quantum;
2609 cp->cache_mincolor = 0;
2610 cp->cache_maxcolor =
2611 (cp->cache_slabsize - sizeof (umem_slab_t)) % chunksize;
2613 if (chunksize + sizeof (umem_slab_t) > cp->cache_slabsize) {
2617 ASSERT(!(cp->cache_flags & UMF_AUDIT));
2619 size_t chunks, bestfit, waste, slabsize;
2620 size_t minwaste = LONG_MAX;
2622 for (chunks = 1; chunks <= UMEM_VOID_FRACTION; chunks++) {
2623 slabsize = P2ROUNDUP(chunksize * chunks,
2626 * check for overflow
2628 if ((slabsize / chunks) < chunksize) {
2632 chunks = slabsize / chunksize;
2633 waste = (slabsize % chunksize) / chunks;
2634 if (waste < minwaste) {
2639 if (cflags & UMC_QCACHE)
2640 bestfit = MAX(1 << highbit(3 * vmp->vm_qcache_max), 64);
2641 cp->cache_slabsize = bestfit;
2642 cp->cache_mincolor = 0;
2643 cp->cache_maxcolor = bestfit % chunksize;
2644 cp->cache_flags |= UMF_HASH;
2647 if (cp->cache_flags & UMF_HASH) {
2648 ASSERT(!(cflags & UMC_NOHASH));
2649 cp->cache_bufctl_cache = (cp->cache_flags & UMF_AUDIT) ?
2650 umem_bufctl_audit_cache : umem_bufctl_cache;
2653 if (cp->cache_maxcolor >= vmp->vm_quantum)
2654 cp->cache_maxcolor = vmp->vm_quantum - 1;
2656 cp->cache_color = cp->cache_mincolor;
2659 * Initialize the rest of the slab layer.
2661 (void) mutex_init(&cp->cache_lock, USYNC_THREAD, NULL);
2663 cp->cache_freelist = &cp->cache_nullslab;
2664 cp->cache_nullslab.slab_cache = cp;
2665 cp->cache_nullslab.slab_refcnt = -1;
2666 cp->cache_nullslab.slab_next = &cp->cache_nullslab;
2667 cp->cache_nullslab.slab_prev = &cp->cache_nullslab;
2669 if (cp->cache_flags & UMF_HASH) {
2670 cp->cache_hash_table = vmem_alloc(umem_hash_arena,
2671 UMEM_HASH_INITIAL * sizeof (void *), VM_NOSLEEP);
2672 if (cp->cache_hash_table == NULL) {
2676 bzero(cp->cache_hash_table,
2677 UMEM_HASH_INITIAL * sizeof (void *));
2678 cp->cache_hash_mask = UMEM_HASH_INITIAL - 1;
2679 cp->cache_hash_shift = highbit((ulong_t)chunksize) - 1;
2683 * Initialize the depot.
2685 (void) mutex_init(&cp->cache_depot_lock, USYNC_THREAD, NULL);
2687 for (mtp = umem_magtype; chunksize <= mtp->mt_minbuf; mtp++)
2690 cp->cache_magtype = mtp;
2693 * Initialize the CPU layer.
2695 for (cpu_seqid = 0; cpu_seqid < umem_max_ncpus; cpu_seqid++) {
2696 umem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
2697 (void) mutex_init(&ccp->cc_lock, USYNC_THREAD, NULL);
2698 ccp->cc_flags = cp->cache_flags;
2699 ccp->cc_rounds = -1;
2700 ccp->cc_prounds = -1;
2704 * Add the cache to the global list. This makes it visible
2705 * to umem_update(), so the cache must be ready for business.
2707 (void) mutex_lock(&umem_cache_lock);
2708 cp->cache_next = cnext = &umem_null_cache;
2709 cp->cache_prev = cprev = umem_null_cache.cache_prev;
2710 cnext->cache_prev = cp;
2711 cprev->cache_next = cp;
2712 (void) mutex_unlock(&umem_cache_lock);
2714 if (umem_ready == UMEM_READY)
2715 umem_cache_magazine_enable(cp);
2720 (void) mutex_destroy(&cp->cache_lock);
2722 vmem_xfree(umem_cache_arena, cp, csize);
2727 umem_cache_destroy(umem_cache_t *cp)
2732 * Remove the cache from the global cache list so that no new updates
2733 * will be scheduled on its behalf, wait for any pending tasks to
2734 * complete, purge the cache, and then destroy it.
2736 (void) mutex_lock(&umem_cache_lock);
2737 cp->cache_prev->cache_next = cp->cache_next;
2738 cp->cache_next->cache_prev = cp->cache_prev;
2739 cp->cache_prev = cp->cache_next = NULL;
2740 (void) mutex_unlock(&umem_cache_lock);
2742 umem_remove_updates(cp);
2744 umem_cache_magazine_purge(cp);
2746 (void) mutex_lock(&cp->cache_lock);
2747 if (cp->cache_buftotal != 0)
2748 log_message("umem_cache_destroy: '%s' (%p) not empty\n",
2749 cp->cache_name, (void *)cp);
2750 cp->cache_reclaim = NULL;
2752 * The cache is now dead. There should be no further activity.
2753 * We enforce this by setting land mines in the constructor and
2754 * destructor routines that induce a segmentation fault if invoked.
2756 cp->cache_constructor = (umem_constructor_t *)1;
2757 cp->cache_destructor = (umem_destructor_t *)2;
2758 (void) mutex_unlock(&cp->cache_lock);
2760 if (cp->cache_hash_table != NULL)
2761 vmem_free(umem_hash_arena, cp->cache_hash_table,
2762 (cp->cache_hash_mask + 1) * sizeof (void *));
2764 for (cpu_seqid = 0; cpu_seqid < umem_max_ncpus; cpu_seqid++)
2765 (void) mutex_destroy(&cp->cache_cpu[cpu_seqid].cc_lock);
2767 (void) mutex_destroy(&cp->cache_depot_lock);
2768 (void) mutex_destroy(&cp->cache_lock);
2770 vmem_free(umem_cache_arena, cp, UMEM_CACHE_SIZE(umem_max_ncpus));
2774 umem_cache_init(void)
2777 size_t size, max_size;
2779 umem_magtype_t *mtp;
2780 char name[UMEM_CACHE_NAMELEN + 1];
2781 umem_cache_t *umem_alloc_caches[NUM_ALLOC_SIZES];
2783 for (i = 0; i < sizeof (umem_magtype) / sizeof (*mtp); i++) {
2784 mtp = &umem_magtype[i];
2785 (void) snprintf(name, sizeof (name), "umem_magazine_%d",
2787 mtp->mt_cache = umem_cache_create(name,
2788 (mtp->mt_magsize + 1) * sizeof (void *),
2789 mtp->mt_align, NULL, NULL, NULL, NULL,
2790 umem_internal_arena, UMC_NOHASH | UMC_INTERNAL);
2791 if (mtp->mt_cache == NULL)
2795 umem_slab_cache = umem_cache_create("umem_slab_cache",
2796 sizeof (umem_slab_t), 0, NULL, NULL, NULL, NULL,
2797 umem_internal_arena, UMC_NOHASH | UMC_INTERNAL);
2799 if (umem_slab_cache == NULL)
2802 umem_bufctl_cache = umem_cache_create("umem_bufctl_cache",
2803 sizeof (umem_bufctl_t), 0, NULL, NULL, NULL, NULL,
2804 umem_internal_arena, UMC_NOHASH | UMC_INTERNAL);
2806 if (umem_bufctl_cache == NULL)
2810 * The size of the umem_bufctl_audit structure depends upon
2811 * umem_stack_depth. See umem_impl.h for details on the size
2815 size = UMEM_BUFCTL_AUDIT_SIZE_DEPTH(umem_stack_depth);
2816 max_size = UMEM_BUFCTL_AUDIT_MAX_SIZE;
2818 if (size > max_size) { /* too large -- truncate */
2819 int max_frames = UMEM_MAX_STACK_DEPTH;
2821 ASSERT(UMEM_BUFCTL_AUDIT_SIZE_DEPTH(max_frames) <= max_size);
2823 umem_stack_depth = max_frames;
2824 size = UMEM_BUFCTL_AUDIT_SIZE_DEPTH(umem_stack_depth);
2827 umem_bufctl_audit_cache = umem_cache_create("umem_bufctl_audit_cache",
2828 size, 0, NULL, NULL, NULL, NULL, umem_internal_arena,
2829 UMC_NOHASH | UMC_INTERNAL);
2831 if (umem_bufctl_audit_cache == NULL)
2834 if (vmem_backend & VMEM_BACKEND_MMAP)
2835 umem_va_arena = vmem_create("umem_va",
2837 vmem_alloc, vmem_free, heap_arena,
2838 8 * pagesize, VM_NOSLEEP);
2840 umem_va_arena = heap_arena;
2842 if (umem_va_arena == NULL)
2845 umem_default_arena = vmem_create("umem_default",
2847 heap_alloc, heap_free, umem_va_arena,
2850 if (umem_default_arena == NULL)
2854 * make sure the umem_alloc table initializer is correct
2856 i = sizeof (umem_alloc_table) / sizeof (*umem_alloc_table);
2857 ASSERT(umem_alloc_table[i - 1] == &umem_null_cache);
2860 * Create the default caches to back umem_alloc()
2862 for (i = 0; i < NUM_ALLOC_SIZES; i++) {
2863 size_t cache_size = umem_alloc_sizes[i];
2866 * If they allocate a multiple of the coherency granularity,
2867 * they get a coherency-granularity-aligned address.
2869 if (IS_P2ALIGNED(cache_size, 64))
2871 if (IS_P2ALIGNED(cache_size, pagesize))
2873 (void) snprintf(name, sizeof (name), "umem_alloc_%lu",
2876 cp = umem_cache_create(name, cache_size, align,
2877 NULL, NULL, NULL, NULL, NULL, UMC_INTERNAL);
2881 umem_alloc_caches[i] = cp;
2885 * Initialization cannot fail at this point. Make the caches
2886 * visible to umem_alloc() and friends.
2889 for (i = 0; i < NUM_ALLOC_SIZES; i++) {
2890 size_t cache_size = umem_alloc_sizes[i];
2892 cp = umem_alloc_caches[i];
2894 while (size <= cache_size) {
2895 umem_alloc_table[(size - 1) >> UMEM_ALIGN_SHIFT] = cp;
2903 * umem_startup() is called early on, and must be called explicitly if we're
2904 * the standalone version.
2907 umem_startup() __attribute__((constructor));
2912 caddr_t start = NULL;
2914 size_t pagesize = 0;
2916 #ifdef UMEM_STANDALONE
2918 /* Standalone doesn't fork */
2920 umem_forkhandler_init(); /* register the fork handler */
2924 /* make lint happy */
2925 minstack = maxstack;
2928 #ifdef UMEM_STANDALONE
2929 umem_ready = UMEM_READY_STARTUP;
2930 umem_init_env_ready = 0;
2932 umem_min_stack = minstack;
2933 umem_max_stack = maxstack;
2935 nofail_callback = NULL;
2936 umem_slab_cache = NULL;
2937 umem_bufctl_cache = NULL;
2938 umem_bufctl_audit_cache = NULL;
2942 umem_internal_arena = NULL;
2943 umem_cache_arena = NULL;
2944 umem_hash_arena = NULL;
2945 umem_log_arena = NULL;
2946 umem_oversize_arena = NULL;
2947 umem_va_arena = NULL;
2948 umem_default_arena = NULL;
2949 umem_firewall_va_arena = NULL;
2950 umem_firewall_arena = NULL;
2951 umem_memalign_arena = NULL;
2952 umem_transaction_log = NULL;
2953 umem_content_log = NULL;
2954 umem_failure_log = NULL;
2955 umem_slab_log = NULL;
2958 umem_cpus = &umem_startup_cpu;
2959 umem_startup_cpu.cpu_cache_offset = UMEM_CACHE_SIZE(0);
2960 umem_startup_cpu.cpu_number = 0;
2962 bcopy(&umem_null_cache_template, &umem_null_cache,
2963 sizeof (umem_cache_t));
2965 for (idx = 0; idx < (UMEM_MAXBUF >> UMEM_ALIGN_SHIFT); idx++)
2966 umem_alloc_table[idx] = &umem_null_cache;
2970 * Perform initialization specific to the way we've been compiled
2971 * (library or standalone)
2973 umem_type_init(start, len, pagesize);
2981 size_t maxverify, minfirewall;
2984 umem_cpu_t *new_cpus;
2986 vmem_t *memalign_arena, *oversize_arena;
2988 if (thr_self() != umem_init_thr) {
2990 * The usual case -- non-recursive invocation of umem_init().
2992 (void) mutex_lock(&umem_init_lock);
2993 if (umem_ready != UMEM_READY_STARTUP) {
2995 * someone else beat us to initializing umem. Wait
2996 * for them to complete, then return.
2998 while (umem_ready == UMEM_READY_INITING)
2999 (void) _cond_wait(&umem_init_cv,
3001 ASSERT(umem_ready == UMEM_READY ||
3002 umem_ready == UMEM_READY_INIT_FAILED);
3003 (void) mutex_unlock(&umem_init_lock);
3004 return (umem_ready == UMEM_READY);
3007 ASSERT(umem_ready == UMEM_READY_STARTUP);
3008 ASSERT(umem_init_env_ready == 0);
3010 umem_ready = UMEM_READY_INITING;
3011 umem_init_thr = thr_self();
3013 (void) mutex_unlock(&umem_init_lock);
3014 umem_setup_envvars(0); /* can recurse -- see below */
3015 if (umem_init_env_ready) {
3017 * initialization was completed already
3019 ASSERT(umem_ready == UMEM_READY ||
3020 umem_ready == UMEM_READY_INIT_FAILED);
3021 ASSERT(umem_init_thr == 0);
3022 return (umem_ready == UMEM_READY);
3024 } else if (!umem_init_env_ready) {
3026 * The umem_setup_envvars() call (above) makes calls into
3027 * the dynamic linker and directly into user-supplied code.
3028 * Since we cannot know what that code will do, we could be
3029 * recursively invoked (by, say, a malloc() call in the code
3030 * itself, or in a (C++) _init section it causes to be fired).
3032 * This code is where we end up if such recursion occurs. We
3033 * first clean up any partial results in the envvar code, then
3034 * proceed to finish initialization processing in the recursive
3035 * call. The original call will notice this, and return
3038 umem_setup_envvars(1); /* clean up any partial state */
3041 "recursive allocation while initializing umem\n");
3043 umem_init_env_ready = 1;
3046 * From this point until we finish, recursion into umem_init() will
3047 * cause a umem_panic().
3049 maxverify = minfirewall = ULONG_MAX;
3051 /* LINTED constant condition */
3052 if (sizeof (umem_cpu_cache_t) != UMEM_CPU_CACHE_SIZE) {
3053 umem_panic("sizeof (umem_cpu_cache_t) = %d, should be %d\n",
3054 sizeof (umem_cpu_cache_t), UMEM_CPU_CACHE_SIZE);
3057 umem_max_ncpus = umem_get_max_ncpus();
3060 * load tunables from environment
3062 umem_process_envvars();
3070 if (!(umem_flags & UMF_AUDIT))
3073 heap_arena = vmem_heap_arena(&heap_alloc, &heap_free);
3075 pagesize = heap_arena->vm_quantum;
3077 umem_internal_arena = vmem_create("umem_internal", NULL, 0, pagesize,
3078 heap_alloc, heap_free, heap_arena, 0, VM_NOSLEEP);
3080 umem_default_arena = umem_internal_arena;
3082 if (umem_internal_arena == NULL)
3085 umem_cache_arena = vmem_create("umem_cache", NULL, 0, UMEM_ALIGN,
3086 vmem_alloc, vmem_free, umem_internal_arena, 0, VM_NOSLEEP);
3088 umem_hash_arena = vmem_create("umem_hash", NULL, 0, UMEM_ALIGN,
3089 vmem_alloc, vmem_free, umem_internal_arena, 0, VM_NOSLEEP);
3091 umem_log_arena = vmem_create("umem_log", NULL, 0, UMEM_ALIGN,
3092 heap_alloc, heap_free, heap_arena, 0, VM_NOSLEEP);
3094 umem_firewall_va_arena = vmem_create("umem_firewall_va",
3096 umem_firewall_va_alloc, umem_firewall_va_free, heap_arena,
3099 if (umem_cache_arena == NULL || umem_hash_arena == NULL ||
3100 umem_log_arena == NULL || umem_firewall_va_arena == NULL)
3103 umem_firewall_arena = vmem_create("umem_firewall", NULL, 0, pagesize,
3104 heap_alloc, heap_free, umem_firewall_va_arena, 0,
3107 if (umem_firewall_arena == NULL)
3110 oversize_arena = vmem_create("umem_oversize", NULL, 0, pagesize,
3111 heap_alloc, heap_free, minfirewall < ULONG_MAX ?
3112 umem_firewall_va_arena : heap_arena, 0, VM_NOSLEEP);
3114 memalign_arena = vmem_create("umem_memalign", NULL, 0, UMEM_ALIGN,
3115 heap_alloc, heap_free, minfirewall < ULONG_MAX ?
3116 umem_firewall_va_arena : heap_arena, 0, VM_NOSLEEP);
3118 if (oversize_arena == NULL || memalign_arena == NULL)
3121 if (umem_max_ncpus > CPUHINT_MAX())
3122 umem_max_ncpus = CPUHINT_MAX();
3124 while ((umem_max_ncpus & (umem_max_ncpus - 1)) != 0)
3127 if (umem_max_ncpus == 0)
3130 size = umem_max_ncpus * sizeof (umem_cpu_t);
3131 new_cpus = vmem_alloc(umem_internal_arena, size, VM_NOSLEEP);
3132 if (new_cpus == NULL)
3135 bzero(new_cpus, size);
3136 for (idx = 0; idx < umem_max_ncpus; idx++) {
3137 new_cpus[idx].cpu_number = idx;
3138 new_cpus[idx].cpu_cache_offset = UMEM_CACHE_SIZE(idx);
3140 umem_cpus = new_cpus;
3141 umem_cpu_mask = (umem_max_ncpus - 1);
3143 if (umem_maxverify == 0)
3144 umem_maxverify = maxverify;
3146 if (umem_minfirewall == 0)
3147 umem_minfirewall = minfirewall;
3150 * Set up updating and reaping
3152 umem_reap_next = gethrtime() + NANOSEC;
3154 #ifndef UMEM_STANDALONE
3155 (void) gettimeofday(&umem_update_next, NULL);
3159 * Set up logging -- failure here is okay, since it will just disable
3163 umem_transaction_log = umem_log_init(umem_transaction_log_size);
3164 umem_content_log = umem_log_init(umem_content_log_size);
3165 umem_failure_log = umem_log_init(umem_failure_log_size);
3166 umem_slab_log = umem_log_init(umem_slab_log_size);
3170 * Set up caches -- if successful, initialization cannot fail, since
3171 * allocations from other threads can now succeed.
3173 if (umem_cache_init() == 0) {
3174 log_message("unable to create initial caches\n");
3177 umem_oversize_arena = oversize_arena;
3178 umem_memalign_arena = memalign_arena;
3180 umem_cache_applyall(umem_cache_magazine_enable);
3183 * initialization done, ready to go
3185 (void) mutex_lock(&umem_init_lock);
3186 umem_ready = UMEM_READY;
3188 (void) cond_broadcast(&umem_init_cv);
3189 (void) mutex_unlock(&umem_init_lock);
3193 log_message("umem initialization failed\n");
3195 (void) mutex_lock(&umem_init_lock);
3196 umem_ready = UMEM_READY_INIT_FAILED;
3198 (void) cond_broadcast(&umem_init_cv);
3199 (void) mutex_unlock(&umem_init_lock);
3204 umem_cache_get_bufsize(umem_cache_t *cache)
3206 return cache->cache_bufsize;