2 * NMALLOC.C - New Malloc (ported from kernel slab allocator)
4 * Copyright (c) 2003,2004,2009,2010 The DragonFly Project. All rights reserved.
6 * This code is derived from software contributed to The DragonFly Project
7 * by Matthew Dillon <dillon@backplane.com> and by
8 * Venkatesh Srinivas <me@endeavour.zapto.org>.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the
20 * 3. Neither the name of The DragonFly Project nor the names of its
21 * contributors may be used to endorse or promote products derived
22 * from this software without specific, prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
32 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
34 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * $Id: nmalloc.c,v 1.37 2010/07/23 08:20:35 vsrinivas Exp $
40 * This module implements a slab allocator drop-in replacement for the
43 * A slab allocator reserves a ZONE for each chunk size, then lays the
44 * chunks out in an array within the zone. Allocation and deallocation
45 * is nearly instantaneous, and overhead losses are limited to a fixed
48 * The slab allocator does not have to pre-initialize the list of
49 * free chunks for each zone, and the underlying VM will not be
50 * touched at all beyond the zone header until an actual allocation
53 * Slab management and locking is done on a per-zone basis.
55 * Alloc Size Chunking Number of zones
66 * Allocations >= ZoneLimit (16K) go directly to mmap and a hash table
67 * is used to locate for free. One and Two-page allocations use the
68 * zone mechanic to avoid excessive mmap()/munmap() calls.
70 * API FEATURES AND SIDE EFFECTS
72 * + power-of-2 sized allocations up to a page will be power-of-2 aligned.
73 * Above that power-of-2 sized allocations are page-aligned. Non
74 * power-of-2 sized allocations are aligned the same as the chunk
75 * size for their zone.
76 * + malloc(0) returns a special non-NULL value
77 * + ability to allocate arbitrarily large chunks of memory
78 * + realloc will reuse the passed pointer if possible, within the
79 * limitations of the zone chunking.
81 * Multithreaded enhancements for small allocations introduced August 2010.
82 * These are in the spirit of 'libumem'. See:
83 * Bonwick, J.; Adams, J. (2001). "Magazines and Vmem: Extending the
84 * slab allocator to many CPUs and arbitrary resources". In Proc. 2001
85 * USENIX Technical Conference. USENIX Association.
87 * Oversized allocations employ the BIGCACHE mechanic whereby large
88 * allocations may be handed significantly larger buffers, allowing them
89 * to avoid mmap/munmap operations even through significant realloc()s.
90 * The excess space is only trimmed if too many large allocations have been
91 * given this treatment.
95 * The value of the environment variable MALLOC_OPTIONS is a character string
96 * containing various flags to tune nmalloc.
98 * 'U' / ['u'] Generate / do not generate utrace entries for ktrace(1)
99 * This will generate utrace events for all malloc,
100 * realloc, and free calls. There are tools (mtrplay) to
101 * replay and allocation pattern or to graph heap structure
102 * (mtrgraph) which can interpret these logs.
103 * 'Z' / ['z'] Zero out / do not zero all allocations.
104 * Each new byte of memory allocated by malloc, realloc, or
105 * reallocf will be initialized to 0. This is intended for
106 * debugging and will affect performance negatively.
107 * 'H' / ['h'] Pass a hint to the kernel about pages unused by the
108 * allocation functions.
111 /* cc -shared -fPIC -g -O -I/usr/src/lib/libc/include -o nmalloc.so nmalloc.c */
113 #include "libc_private.h"
115 #include <sys/param.h>
116 #include <sys/types.h>
117 #include <sys/mman.h>
118 #include <sys/queue.h>
120 #include <sys/ktrace.h>
131 #include <machine/atomic.h>
133 #include "spinlock.h"
134 #include "un-namespace.h"
138 * Linked list of large allocations
140 typedef struct bigalloc {
141 struct bigalloc *next; /* hash link */
142 void *base; /* base pointer */
143 u_long active; /* bytes active */
144 u_long bytes; /* bytes allocated */
148 * Note that any allocations which are exact multiples of PAGE_SIZE, or
149 * which are >= ZALLOC_ZONE_LIMIT, will fall through to the kmem subsystem.
151 #define ZALLOC_ZONE_LIMIT (16 * 1024) /* max slab-managed alloc */
152 #define ZALLOC_MIN_ZONE_SIZE (32 * 1024) /* minimum zone size */
153 #define ZALLOC_MAX_ZONE_SIZE (128 * 1024) /* maximum zone size */
154 #define ZALLOC_ZONE_SIZE (64 * 1024)
155 #define ZALLOC_SLAB_MAGIC 0x736c6162 /* magic sanity */
156 #define ZALLOC_SLAB_SLIDE 20 /* L1-cache skip */
158 #if ZALLOC_ZONE_LIMIT == 16384
160 #elif ZALLOC_ZONE_LIMIT == 32768
163 #error "I couldn't figure out NZONES"
167 * Chunk structure for free elements
169 typedef struct slchunk {
170 struct slchunk *c_Next;
174 * The IN-BAND zone header is placed at the beginning of each zone.
178 typedef struct slzone {
179 int32_t z_Magic; /* magic number for sanity check */
180 int z_NFree; /* total free chunks / ualloc space */
181 struct slzone *z_Next; /* ZoneAry[] link if z_NFree non-zero */
182 int z_NMax; /* maximum free chunks */
183 char *z_BasePtr; /* pointer to start of chunk array */
184 int z_UIndex; /* current initial allocation index */
185 int z_UEndIndex; /* last (first) allocation index */
186 int z_ChunkSize; /* chunk size for validation */
187 int z_FirstFreePg; /* chunk list on a page-by-page basis */
190 struct slchunk *z_PageAry[ZALLOC_ZONE_SIZE / PAGE_SIZE];
191 #if defined(INVARIANTS)
192 __uint32_t z_Bitmap[]; /* bitmap of free chunks / sanity */
196 typedef struct slglobaldata {
198 slzone_t ZoneAry[NZONES];/* linked list of zones NFree > 0 */
202 #define SLZF_UNOTZEROD 0x0001
204 #define FASTSLABREALLOC 0x02
207 * Misc constants. Note that allocations that are exact multiples of
208 * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
209 * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
211 #define MIN_CHUNK_SIZE 8 /* in bytes */
212 #define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
213 #define IN_SAME_PAGE_MASK (~(intptr_t)PAGE_MASK | MIN_CHUNK_MASK)
216 * The WEIRD_ADDR is used as known text to copy into free objects to
217 * try to create deterministic failure cases if the data is accessed after
220 * WARNING: A limited number of spinlocks are available, BIGXSIZE should
221 * not be larger then 64.
223 #define WEIRD_ADDR 0xdeadc0de
224 #define MAX_COPY sizeof(weirdary)
225 #define ZERO_LENGTH_PTR ((void *)&malloc_dummy_pointer)
227 #define BIGHSHIFT 10 /* bigalloc hash table */
228 #define BIGHSIZE (1 << BIGHSHIFT)
229 #define BIGHMASK (BIGHSIZE - 1)
230 #define BIGXSIZE (BIGHSIZE / 16) /* bigalloc lock table */
231 #define BIGXMASK (BIGXSIZE - 1)
234 * BIGCACHE caches oversized allocations. Note that a linear search is
235 * performed, so do not make the cache too large.
237 * BIGCACHE will garbage-collect excess space when the excess exceeds the
238 * specified value. A relatively large number should be used here because
239 * garbage collection is expensive.
242 #define BIGCACHE_MASK (BIGCACHE - 1)
243 #define BIGCACHE_LIMIT (1024 * 1024) /* size limit */
244 #define BIGCACHE_EXCESS (16 * 1024 * 1024) /* garbage collect */
246 #define SAFLAG_ZERO 0x0001
247 #define SAFLAG_PASSIVE 0x0002
253 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
255 #define MASSERT(exp) do { if (__predict_false(!(exp))) \
256 _mpanic("assertion: %s in %s", \
264 #define M_MAX_ROUNDS 64
265 #define M_ZONE_ROUNDS 64
266 #define M_LOW_ROUNDS 32
267 #define M_INIT_ROUNDS 8
268 #define M_BURST_FACTOR 8
269 #define M_BURST_NSCALE 2
271 #define M_BURST 0x0001
272 #define M_BURST_EARLY 0x0002
275 SLIST_ENTRY(magazine) nextmagazine;
278 int capacity; /* Max rounds in this magazine */
279 int rounds; /* Current number of free rounds */
280 int burst_factor; /* Number of blocks to prefill with */
281 int low_factor; /* Free till low_factor from full mag */
282 void *objects[M_MAX_ROUNDS];
285 SLIST_HEAD(magazinelist, magazine);
287 static spinlock_t zone_mag_lock;
288 static struct magazine zone_magazine = {
289 .flags = M_BURST | M_BURST_EARLY,
290 .capacity = M_ZONE_ROUNDS,
292 .burst_factor = M_BURST_FACTOR,
293 .low_factor = M_LOW_ROUNDS
296 #define MAGAZINE_FULL(mp) (mp->rounds == mp->capacity)
297 #define MAGAZINE_NOTFULL(mp) (mp->rounds < mp->capacity)
298 #define MAGAZINE_EMPTY(mp) (mp->rounds == 0)
299 #define MAGAZINE_NOTEMPTY(mp) (mp->rounds != 0)
302 * Each thread will have a pair of magazines per size-class (NZONES)
303 * The loaded magazine will support immediate allocations, the previous
304 * magazine will either be full or empty and can be swapped at need
306 typedef struct magazine_pair {
307 struct magazine *loaded;
308 struct magazine *prev;
311 /* A depot is a collection of magazines for a single zone. */
312 typedef struct magazine_depot {
313 struct magazinelist full;
314 struct magazinelist empty;
318 typedef struct thr_mags {
319 magazine_pair mags[NZONES];
320 struct magazine *newmag;
325 * With this attribute set, do not require a function call for accessing
326 * this variable when the code is compiled -fPIC. Empty for libc_rtld
330 #define TLS_ATTRIBUTE
332 #define TLS_ATTRIBUTE __attribute__ ((tls_model ("initial-exec")))
335 static int mtmagazine_free_live;
336 static __thread thr_mags thread_mags TLS_ATTRIBUTE;
337 static pthread_key_t thread_mags_key;
338 static pthread_once_t thread_mags_once = PTHREAD_ONCE_INIT;
339 static magazine_depot depots[NZONES];
342 * Fixed globals (not per-cpu)
344 static const int ZoneSize = ZALLOC_ZONE_SIZE;
345 static const int ZoneLimit = ZALLOC_ZONE_LIMIT;
346 static const int ZonePageCount = ZALLOC_ZONE_SIZE / PAGE_SIZE;
347 static const int ZoneMask = ZALLOC_ZONE_SIZE - 1;
349 static int opt_madvise = 0;
350 static int opt_utrace = 0;
351 static int g_malloc_flags = 0;
352 static struct slglobaldata SLGlobalData;
353 static bigalloc_t bigalloc_array[BIGHSIZE];
354 static spinlock_t bigspin_array[BIGXSIZE];
355 static volatile void *bigcache_array[BIGCACHE]; /* atomic swap */
356 static volatile size_t bigcache_size_array[BIGCACHE]; /* SMP races ok */
357 static volatile int bigcache_index; /* SMP races ok */
358 static int malloc_panic;
359 static int malloc_dummy_pointer;
360 static size_t excess_alloc; /* excess big allocs */
362 static const int32_t weirdary[16] = {
363 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
364 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
365 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
366 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR
369 static void *_slaballoc(size_t size, int flags);
370 static void *_slabrealloc(void *ptr, size_t size);
371 static void _slabfree(void *ptr, int, bigalloc_t *);
372 static void *_vmem_alloc(size_t bytes, size_t align, int flags);
373 static void _vmem_free(void *ptr, size_t bytes);
374 static void *magazine_alloc(struct magazine *, int *);
375 static int magazine_free(struct magazine *, void *);
376 static void *mtmagazine_alloc(int zi);
377 static int mtmagazine_free(int zi, void *);
378 static void mtmagazine_init(void);
379 static void mtmagazine_destructor(void *);
380 static slzone_t zone_alloc(int flags);
381 static void zone_free(void *z);
382 static void _mpanic(const char *ctl, ...) __printflike(1, 2);
383 static void malloc_init(void) __constructor(101);
384 #if defined(INVARIANTS)
385 static void chunk_mark_allocated(slzone_t z, void *chunk);
386 static void chunk_mark_free(slzone_t z, void *chunk);
389 struct nmalloc_utrace {
395 #define UTRACE(a, b, c) \
397 struct nmalloc_utrace ut = { \
402 utrace(&ut, sizeof(ut)); \
407 * If enabled any memory allocated without M_ZERO is initialized to -1.
409 static int use_malloc_pattern;
415 const char *p = NULL;
417 if (issetugid() == 0)
418 p = getenv("MALLOC_OPTIONS");
420 for (; p != NULL && *p != '\0'; p++) {
422 case 'u': opt_utrace = 0; break;
423 case 'U': opt_utrace = 1; break;
424 case 'h': opt_madvise = 0; break;
425 case 'H': opt_madvise = 1; break;
426 case 'z': g_malloc_flags = 0; break;
427 case 'Z': g_malloc_flags = SAFLAG_ZERO; break;
433 UTRACE((void *) -1, 0, NULL);
437 * We have to install a handler for nmalloc thread teardowns when
438 * the thread is created. We cannot delay this because destructors in
439 * sophisticated userland programs can call malloc() for the first time
440 * during their thread exit.
442 * This routine is called directly from pthreads.
445 _nmalloc_thr_init(void)
450 * Disallow mtmagazine operations until the mtmagazine is
456 if (mtmagazine_free_live == 0) {
457 mtmagazine_free_live = 1;
458 pthread_once(&thread_mags_once, mtmagazine_init);
460 pthread_setspecific(thread_mags_key, tp);
468 slgd_lock(slglobaldata_t slgd)
471 _SPINLOCK(&slgd->Spinlock);
475 slgd_unlock(slglobaldata_t slgd)
478 _SPINUNLOCK(&slgd->Spinlock);
482 depot_lock(magazine_depot *dp)
485 _SPINLOCK(&dp->lock);
489 depot_unlock(magazine_depot *dp)
492 _SPINUNLOCK(&dp->lock);
496 zone_magazine_lock(void)
499 _SPINLOCK(&zone_mag_lock);
503 zone_magazine_unlock(void)
506 _SPINUNLOCK(&zone_mag_lock);
510 swap_mags(magazine_pair *mp)
512 struct magazine *tmp;
514 mp->loaded = mp->prev;
519 * bigalloc hashing and locking support.
521 * Return an unmasked hash code for the passed pointer.
524 _bigalloc_hash(void *ptr)
528 hv = ((int)(intptr_t)ptr >> PAGE_SHIFT) ^
529 ((int)(intptr_t)ptr >> (PAGE_SHIFT + BIGHSHIFT));
535 * Lock the hash chain and return a pointer to its base for the specified
538 static __inline bigalloc_t *
539 bigalloc_lock(void *ptr)
541 int hv = _bigalloc_hash(ptr);
544 bigp = &bigalloc_array[hv & BIGHMASK];
546 _SPINLOCK(&bigspin_array[hv & BIGXMASK]);
551 * Lock the hash chain and return a pointer to its base for the specified
554 * BUT, if the hash chain is empty, just return NULL and do not bother
557 static __inline bigalloc_t *
558 bigalloc_check_and_lock(void *ptr)
560 int hv = _bigalloc_hash(ptr);
563 bigp = &bigalloc_array[hv & BIGHMASK];
567 _SPINLOCK(&bigspin_array[hv & BIGXMASK]);
573 bigalloc_unlock(void *ptr)
578 hv = _bigalloc_hash(ptr);
579 _SPINUNLOCK(&bigspin_array[hv & BIGXMASK]);
584 * Find a bigcache entry that might work for the allocation. SMP races are
585 * ok here except for the swap (that is, it is ok if bigcache_size_array[i]
586 * is wrong or if a NULL or too-small big is returned).
588 * Generally speaking it is ok to find a large entry even if the bytes
589 * requested are relatively small (but still oversized), because we really
590 * don't know *what* the application is going to do with the buffer.
594 bigcache_find_alloc(size_t bytes)
596 bigalloc_t big = NULL;
600 for (i = 0; i < BIGCACHE; ++i) {
601 test = bigcache_size_array[i];
603 bigcache_size_array[i] = 0;
604 big = atomic_swap_ptr(&bigcache_array[i], NULL);
612 * Free a bigcache entry, possibly returning one that the caller really must
613 * free. This is used to cache recent oversized memory blocks. Only
614 * big blocks smaller than BIGCACHE_LIMIT will be cached this way, so try
615 * to collect the biggest ones we can that are under the limit.
619 bigcache_find_free(bigalloc_t big)
625 b = ++bigcache_index;
626 for (i = 0; i < BIGCACHE; ++i) {
627 j = (b + i) & BIGCACHE_MASK;
628 if (bigcache_size_array[j] < big->bytes) {
629 bigcache_size_array[j] = big->bytes;
630 big = atomic_swap_ptr(&bigcache_array[j], big);
639 handle_excess_big(void)
645 if (excess_alloc <= BIGCACHE_EXCESS)
648 for (i = 0; i < BIGHSIZE; ++i) {
649 bigp = &bigalloc_array[i];
653 _SPINLOCK(&bigspin_array[i & BIGXMASK]);
654 for (big = *bigp; big; big = big->next) {
655 if (big->active < big->bytes) {
656 MASSERT((big->active & PAGE_MASK) == 0);
657 MASSERT((big->bytes & PAGE_MASK) == 0);
658 munmap((char *)big->base + big->active,
659 big->bytes - big->active);
660 atomic_add_long(&excess_alloc,
661 big->active - big->bytes);
662 big->bytes = big->active;
666 _SPINUNLOCK(&bigspin_array[i & BIGXMASK]);
671 * Calculate the zone index for the allocation request size and set the
672 * allocation request size to that particular zone's chunk size.
675 zoneindex(size_t *bytes, size_t *chunking)
677 size_t n = (unsigned int)*bytes; /* unsigned for shift opt */
679 *bytes = n = (n + 7) & ~7;
681 return(n / 8 - 1); /* 8 byte chunks, 16 zones */
684 *bytes = n = (n + 15) & ~15;
690 *bytes = n = (n + 31) & ~31;
695 *bytes = n = (n + 63) & ~63;
700 *bytes = n = (n + 127) & ~127;
702 return(n / 128 + 31);
705 *bytes = n = (n + 255) & ~255;
707 return(n / 256 + 39);
709 *bytes = n = (n + 511) & ~511;
711 return(n / 512 + 47);
713 #if ZALLOC_ZONE_LIMIT > 8192
715 *bytes = n = (n + 1023) & ~1023;
717 return(n / 1024 + 55);
720 #if ZALLOC_ZONE_LIMIT > 16384
722 *bytes = n = (n + 2047) & ~2047;
724 return(n / 2048 + 63);
727 _mpanic("Unexpected byte count %zu", n);
732 * malloc() - call internal slab allocator
739 ptr = _slaballoc(size, 0);
743 UTRACE(0, size, ptr);
747 #define MUL_NO_OVERFLOW (1UL << (sizeof(size_t) * 4))
750 * calloc() - call internal slab allocator
753 calloc(size_t number, size_t size)
757 if ((number >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
758 number > 0 && SIZE_MAX / number < size) {
763 ptr = _slaballoc(number * size, SAFLAG_ZERO);
767 UTRACE(0, number * size, ptr);
772 * realloc() (SLAB ALLOCATOR)
774 * We do not attempt to optimize this routine beyond reusing the same
775 * pointer if the new size fits within the chunking of the old pointer's
779 realloc(void *ptr, size_t size)
782 ret = _slabrealloc(ptr, size);
786 UTRACE(ptr, size, ret);
793 * Allocate (size) bytes with a alignment of (alignment), where (alignment)
794 * is a power of 2 >= sizeof(void *).
796 * The slab allocator will allocate on power-of-2 boundaries up to
797 * at least PAGE_SIZE. We use the zoneindex mechanic to find a
798 * zone matching the requirements, and _vmem_alloc() otherwise.
801 posix_memalign(void **memptr, size_t alignment, size_t size)
809 * OpenGroup spec issue 6 checks
811 if ((alignment | (alignment - 1)) + 1 != (alignment << 1)) {
815 if (alignment < sizeof(void *)) {
821 * Our zone mechanism guarantees same-sized alignment for any
822 * power-of-2 allocation. If size is a power-of-2 and reasonable
823 * we can just call _slaballoc() and be done. We round size up
824 * to the nearest alignment boundary to improve our odds of
825 * it becoming a power-of-2 if it wasn't before.
827 if (size <= alignment)
830 size = (size + alignment - 1) & ~(size_t)(alignment - 1);
831 if (size < PAGE_SIZE && (size | (size - 1)) + 1 == (size << 1)) {
832 *memptr = _slaballoc(size, 0);
833 return(*memptr ? 0 : ENOMEM);
837 * Otherwise locate a zone with a chunking that matches
838 * the requested alignment, within reason. Consider two cases:
840 * (1) A 1K allocation on a 32-byte alignment. The first zoneindex
841 * we find will be the best fit because the chunking will be
842 * greater or equal to the alignment.
844 * (2) A 513 allocation on a 256-byte alignment. In this case
845 * the first zoneindex we find will be for 576 byte allocations
846 * with a chunking of 64, which is not sufficient. To fix this
847 * we simply find the nearest power-of-2 >= size and use the
848 * same side-effect of _slaballoc() which guarantees
849 * same-alignment on a power-of-2 allocation.
851 if (size < PAGE_SIZE) {
852 zi = zoneindex(&size, &chunking);
853 if (chunking >= alignment) {
854 *memptr = _slaballoc(size, 0);
855 return(*memptr ? 0 : ENOMEM);
861 while (alignment < size)
863 *memptr = _slaballoc(alignment, 0);
864 return(*memptr ? 0 : ENOMEM);
868 * If the slab allocator cannot handle it use vmem_alloc().
870 * Alignment must be adjusted up to at least PAGE_SIZE in this case.
872 if (alignment < PAGE_SIZE)
873 alignment = PAGE_SIZE;
874 if (size < alignment)
876 size = (size + PAGE_MASK) & ~(size_t)PAGE_MASK;
877 *memptr = _vmem_alloc(size, alignment, 0);
881 big = _slaballoc(sizeof(struct bigalloc), 0);
883 _vmem_free(*memptr, size);
887 bigp = bigalloc_lock(*memptr);
890 big->bytes = size; /* no excess */
893 bigalloc_unlock(*memptr);
899 * free() (SLAB ALLOCATOR) - do the obvious
905 _slabfree(ptr, 0, NULL);
909 * _slaballoc() (SLAB ALLOCATOR)
911 * Allocate memory via the slab allocator. If the request is too large,
912 * or if it page-aligned beyond a certain size, we fall back to the
916 _slaballoc(size_t size, int flags)
930 * Handle the degenerate size == 0 case. Yes, this does happen.
931 * Return a special pointer. This is to maintain compatibility with
932 * the original malloc implementation. Certain devices, such as the
933 * adaptec driver, not only allocate 0 bytes, they check for NULL and
934 * also realloc() later on. Joy.
937 return(ZERO_LENGTH_PTR);
939 /* Capture global flags */
940 flags |= g_malloc_flags;
943 * Handle large allocations directly. There should not be very many
944 * of these so performance is not a big issue.
946 * The backend allocator is pretty nasty on a SMP system. Use the
947 * slab allocator for one and two page-sized chunks even though we
948 * lose some efficiency.
950 if (size >= ZoneLimit ||
951 ((size & PAGE_MASK) == 0 && size > PAGE_SIZE*2)) {
956 * Page-align and cache-color in case of virtually indexed
957 * physically tagged L1 caches (aka SandyBridge). No sweat
958 * otherwise, so just do it.
960 * (don't count as excess).
962 size = (size + PAGE_MASK) & ~(size_t)PAGE_MASK;
963 if ((size & (PAGE_SIZE * 2 - 1)) == 0)
967 * Try to reuse a cached big block to avoid mmap'ing. If it
968 * turns out not to fit our requirements we throw it away
969 * and allocate normally.
972 if (size <= BIGCACHE_LIMIT) {
973 big = bigcache_find_alloc(size);
974 if (big && big->bytes < size) {
975 _slabfree(big->base, FASTSLABREALLOC, &big);
981 if (flags & SAFLAG_ZERO)
984 chunk = _vmem_alloc(size, PAGE_SIZE, flags);
988 big = _slaballoc(sizeof(struct bigalloc), 0);
990 _vmem_free(chunk, size);
998 bigp = bigalloc_lock(chunk);
999 if (big->active < big->bytes) {
1000 atomic_add_long(&excess_alloc,
1001 big->bytes - big->active);
1005 bigalloc_unlock(chunk);
1006 handle_excess_big();
1011 /* Compute allocation zone; zoneindex will panic on excessive sizes */
1012 zi = zoneindex(&size, &chunking);
1013 MASSERT(zi < NZONES);
1015 obj = mtmagazine_alloc(zi);
1017 if (flags & SAFLAG_ZERO)
1022 slgd = &SLGlobalData;
1026 * Attempt to allocate out of an existing zone. If all zones are
1027 * exhausted pull one off the free list or allocate a new one.
1029 if ((z = slgd->ZoneAry[zi]) == NULL) {
1030 z = zone_alloc(flags);
1035 * How big is the base structure?
1037 #if defined(INVARIANTS)
1039 * Make room for z_Bitmap. An exact calculation is
1040 * somewhat more complicated so don't make an exact
1043 off = offsetof(struct slzone,
1044 z_Bitmap[(ZoneSize / size + 31) / 32]);
1045 bzero(z->z_Bitmap, (ZoneSize / size + 31) / 8);
1047 off = sizeof(struct slzone);
1051 * Align the storage in the zone based on the chunking.
1053 * Guarantee power-of-2 alignment for power-of-2-sized
1054 * chunks. Otherwise align based on the chunking size
1055 * (typically 8 or 16 bytes for small allocations).
1057 * NOTE: Allocations >= ZoneLimit are governed by the
1058 * bigalloc code and typically only guarantee page-alignment.
1060 * Set initial conditions for UIndex near the zone header
1061 * to reduce unecessary page faults, vs semi-randomization
1062 * to improve L1 cache saturation.
1064 if ((size | (size - 1)) + 1 == (size << 1))
1065 off = roundup2(off, size);
1067 off = roundup2(off, chunking);
1068 z->z_Magic = ZALLOC_SLAB_MAGIC;
1069 z->z_ZoneIndex = zi;
1070 z->z_NMax = (ZoneSize - off) / size;
1071 z->z_NFree = z->z_NMax;
1072 z->z_BasePtr = (char *)z + off;
1073 z->z_UIndex = z->z_UEndIndex = 0;
1074 z->z_ChunkSize = size;
1075 z->z_FirstFreePg = ZonePageCount;
1076 z->z_Next = slgd->ZoneAry[zi];
1077 slgd->ZoneAry[zi] = z;
1078 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
1079 flags &= ~SAFLAG_ZERO; /* already zero'd */
1080 flags |= SAFLAG_PASSIVE;
1084 * Slide the base index for initial allocations out of the
1085 * next zone we create so we do not over-weight the lower
1086 * part of the cpu memory caches.
1088 slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
1089 & (ZALLOC_MAX_ZONE_SIZE - 1);
1093 * Ok, we have a zone from which at least one chunk is available.
1095 * Remove us from the ZoneAry[] when we become empty
1097 MASSERT(z->z_NFree > 0);
1099 if (--z->z_NFree == 0) {
1100 slgd->ZoneAry[zi] = z->z_Next;
1105 * Locate a chunk in a free page. This attempts to localize
1106 * reallocations into earlier pages without us having to sort
1107 * the chunk list. A chunk may still overlap a page boundary.
1109 while (z->z_FirstFreePg < ZonePageCount) {
1110 if ((chunk = z->z_PageAry[z->z_FirstFreePg]) != NULL) {
1113 * Diagnostic: c_Next is not total garbage.
1115 MASSERT(chunk->c_Next == NULL ||
1116 ((intptr_t)chunk->c_Next & IN_SAME_PAGE_MASK) ==
1117 ((intptr_t)chunk & IN_SAME_PAGE_MASK));
1120 chunk_mark_allocated(z, chunk);
1122 MASSERT((uintptr_t)chunk & ZoneMask);
1123 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
1130 * No chunks are available but NFree said we had some memory,
1131 * so it must be available in the never-before-used-memory
1132 * area governed by UIndex. The consequences are very
1133 * serious if our zone got corrupted so we use an explicit
1134 * panic rather then a KASSERT.
1136 chunk = (slchunk_t)(z->z_BasePtr + z->z_UIndex * size);
1138 if (++z->z_UIndex == z->z_NMax)
1140 if (z->z_UIndex == z->z_UEndIndex) {
1141 if (z->z_NFree != 0)
1142 _mpanic("slaballoc: corrupted zone");
1145 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
1146 flags &= ~SAFLAG_ZERO;
1147 flags |= SAFLAG_PASSIVE;
1149 #if defined(INVARIANTS)
1150 chunk_mark_allocated(z, chunk);
1155 if (flags & SAFLAG_ZERO) {
1158 } else if ((flags & (SAFLAG_ZERO|SAFLAG_PASSIVE)) == 0) {
1159 if (use_malloc_pattern) {
1160 for (i = 0; i < size; i += sizeof(int)) {
1161 *(int *)((char *)chunk + i) = -1;
1164 /* avoid accidental double-free check */
1165 chunk->c_Next = (void *)-1;
1175 * Reallocate memory within the chunk
1178 _slabrealloc(void *ptr, size_t size)
1185 if (ptr == NULL || ptr == ZERO_LENGTH_PTR) {
1186 return(_slaballoc(size, 0));
1191 return(ZERO_LENGTH_PTR);
1195 * Handle oversized allocations.
1197 if ((bigp = bigalloc_check_and_lock(ptr)) != NULL) {
1201 while ((big = *bigp) != NULL) {
1202 if (big->base == ptr) {
1203 size = (size + PAGE_MASK) & ~(size_t)PAGE_MASK;
1204 bigbytes = big->bytes;
1207 * If it already fits determine if it makes
1208 * sense to shrink/reallocate. Try to optimize
1209 * programs which stupidly make incremental
1210 * reallocations larger or smaller by scaling
1211 * the allocation. Also deal with potential
1214 if (size >= (bigbytes >> 1) &&
1216 if (big->active != size) {
1217 atomic_add_long(&excess_alloc,
1222 bigalloc_unlock(ptr);
1227 * For large reallocations, allocate more space
1228 * than we need to try to avoid excessive
1229 * reallocations later on.
1231 chunking = size + (size >> 3);
1232 chunking = (chunking + PAGE_MASK) &
1236 * Try to allocate adjacently in case the
1237 * program is idiotically realloc()ing a
1238 * huge memory block just slightly bigger.
1239 * (llvm's llc tends to do this a lot).
1241 * (MAP_TRYFIXED forces mmap to fail if there
1242 * is already something at the address).
1244 if (chunking > bigbytes) {
1246 int errno_save = errno;
1248 addr = mmap((char *)ptr + bigbytes,
1249 chunking - bigbytes,
1250 PROT_READ|PROT_WRITE,
1251 MAP_PRIVATE|MAP_ANON|
1255 if (addr == (char *)ptr + bigbytes) {
1256 atomic_add_long(&excess_alloc,
1261 big->bytes = chunking;
1263 bigalloc_unlock(ptr);
1267 MASSERT((void *)addr == MAP_FAILED);
1271 * Failed, unlink big and allocate fresh.
1272 * (note that we have to leave (big) intact
1273 * in case the slaballoc fails).
1276 bigalloc_unlock(ptr);
1277 if ((nptr = _slaballoc(size, 0)) == NULL) {
1279 bigp = bigalloc_lock(ptr);
1282 bigalloc_unlock(ptr);
1285 if (size > bigbytes)
1287 bcopy(ptr, nptr, size);
1288 atomic_add_long(&excess_alloc, big->active -
1290 _slabfree(ptr, FASTSLABREALLOC, &big);
1296 bigalloc_unlock(ptr);
1297 handle_excess_big();
1301 * Get the original allocation's zone. If the new request winds
1302 * up using the same chunk size we do not have to do anything.
1304 * NOTE: We don't have to lock the globaldata here, the fields we
1305 * access here will not change at least as long as we have control
1306 * over the allocation.
1308 z = (slzone_t)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
1309 MASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
1312 * Use zoneindex() to chunk-align the new size, as long as the
1313 * new size is not too large.
1315 if (size < ZoneLimit) {
1316 zoneindex(&size, &chunking);
1317 if (z->z_ChunkSize == size) {
1323 * Allocate memory for the new request size and copy as appropriate.
1325 if ((nptr = _slaballoc(size, 0)) != NULL) {
1326 if (size > z->z_ChunkSize)
1327 size = z->z_ChunkSize;
1328 bcopy(ptr, nptr, size);
1329 _slabfree(ptr, 0, NULL);
1336 * free (SLAB ALLOCATOR)
1338 * Free a memory block previously allocated by malloc. Note that we do not
1339 * attempt to uplodate ks_loosememuse as MP races could prevent us from
1340 * checking memory limits in malloc.
1343 * FASTSLABREALLOC Fast call from realloc, *rbigp already
1349 _slabfree(void *ptr, int flags, bigalloc_t *rbigp)
1355 slglobaldata_t slgd;
1360 /* Fast realloc path for big allocations */
1361 if (flags & FASTSLABREALLOC) {
1363 goto fastslabrealloc;
1367 * Handle NULL frees and special 0-byte allocations
1371 if (ptr == ZERO_LENGTH_PTR)
1375 * Handle oversized allocations.
1377 if ((bigp = bigalloc_check_and_lock(ptr)) != NULL) {
1378 while ((big = *bigp) != NULL) {
1379 if (big->base == ptr) {
1381 atomic_add_long(&excess_alloc, big->active -
1383 bigalloc_unlock(ptr);
1386 * Try to stash the block we are freeing,
1387 * potentially receiving another block in
1388 * return which must be freed.
1391 if (big->bytes <= BIGCACHE_LIMIT) {
1392 big = bigcache_find_free(big);
1396 ptr = big->base; /* reload */
1398 _slabfree(big, 0, NULL);
1400 MASSERT(sizeof(weirdary) <= size);
1401 bcopy(weirdary, ptr, sizeof(weirdary));
1403 _vmem_free(ptr, size);
1408 bigalloc_unlock(ptr);
1409 handle_excess_big();
1413 * Zone case. Figure out the zone based on the fact that it is
1416 z = (slzone_t)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
1417 MASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
1419 size = z->z_ChunkSize;
1420 zi = z->z_ZoneIndex;
1422 if (g_malloc_flags & SAFLAG_ZERO)
1425 if (mtmagazine_free(zi, ptr) == 0)
1428 pgno = ((char *)ptr - (char *)z) >> PAGE_SHIFT;
1430 slgd = &SLGlobalData;
1435 * Attempt to detect a double-free. To reduce overhead we only check
1436 * if there appears to be link pointer at the base of the data.
1438 if (((intptr_t)chunk->c_Next - (intptr_t)z) >> PAGE_SHIFT == pgno) {
1441 for (scan = z->z_PageAry[pgno]; scan; scan = scan->c_Next) {
1443 _mpanic("Double free at %p", chunk);
1446 chunk_mark_free(z, chunk);
1450 * Put weird data into the memory to detect modifications after
1451 * freeing, illegal pointer use after freeing (we should fault on
1452 * the odd address), and so forth.
1455 if (z->z_ChunkSize < sizeof(weirdary))
1456 bcopy(weirdary, chunk, z->z_ChunkSize);
1458 bcopy(weirdary, chunk, sizeof(weirdary));
1462 * Add this free non-zero'd chunk to a linked list for reuse, adjust
1465 chunk->c_Next = z->z_PageAry[pgno];
1466 z->z_PageAry[pgno] = chunk;
1467 if (z->z_FirstFreePg > pgno)
1468 z->z_FirstFreePg = pgno;
1471 * Bump the number of free chunks. If it becomes non-zero the zone
1472 * must be added back onto the appropriate list.
1474 if (z->z_NFree++ == 0) {
1475 z->z_Next = slgd->ZoneAry[z->z_ZoneIndex];
1476 slgd->ZoneAry[z->z_ZoneIndex] = z;
1480 * If the zone becomes totally free then release it.
1482 if (z->z_NFree == z->z_NMax) {
1485 pz = &slgd->ZoneAry[z->z_ZoneIndex];
1487 pz = &(*pz)->z_Next;
1492 /* slgd lock released */
1498 #if defined(INVARIANTS)
1500 * Helper routines for sanity checks
1504 chunk_mark_allocated(slzone_t z, void *chunk)
1506 int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
1509 MASSERT(bitdex >= 0 && bitdex < z->z_NMax);
1510 bitptr = &z->z_Bitmap[bitdex >> 5];
1512 MASSERT((*bitptr & (1 << bitdex)) == 0);
1513 *bitptr |= 1 << bitdex;
1518 chunk_mark_free(slzone_t z, void *chunk)
1520 int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
1523 MASSERT(bitdex >= 0 && bitdex < z->z_NMax);
1524 bitptr = &z->z_Bitmap[bitdex >> 5];
1526 MASSERT((*bitptr & (1 << bitdex)) != 0);
1527 *bitptr &= ~(1 << bitdex);
1533 * Allocate and return a magazine. NULL is returned and *burst is adjusted
1534 * if the magazine is empty.
1536 static __inline void *
1537 magazine_alloc(struct magazine *mp, int *burst)
1543 if (MAGAZINE_NOTEMPTY(mp)) {
1544 obj = mp->objects[--mp->rounds];
1549 * Return burst factor to caller along with NULL
1551 if ((mp->flags & M_BURST) && (burst != NULL)) {
1552 *burst = mp->burst_factor;
1554 /* Reduce burst factor by NSCALE; if it hits 1, disable BURST */
1555 if ((mp->flags & M_BURST) && (mp->flags & M_BURST_EARLY) &&
1557 mp->burst_factor -= M_BURST_NSCALE;
1558 if (mp->burst_factor <= 1) {
1559 mp->burst_factor = 1;
1560 mp->flags &= ~(M_BURST);
1561 mp->flags &= ~(M_BURST_EARLY);
1568 magazine_free(struct magazine *mp, void *p)
1570 if (mp != NULL && MAGAZINE_NOTFULL(mp)) {
1571 mp->objects[mp->rounds++] = p;
1579 mtmagazine_alloc(int zi)
1582 struct magazine *mp, *emptymag;
1587 * Do not try to access per-thread magazines while the mtmagazine
1588 * is being initialized or destroyed.
1595 * Primary per-thread allocation loop
1599 * If the loaded magazine has rounds, allocate and return
1601 mp = tp->mags[zi].loaded;
1602 obj = magazine_alloc(mp, NULL);
1607 * If the prev magazine is full, swap with the loaded
1608 * magazine and retry.
1610 mp = tp->mags[zi].prev;
1611 if (mp && MAGAZINE_FULL(mp)) {
1612 MASSERT(mp->rounds != 0);
1613 swap_mags(&tp->mags[zi]); /* prev now empty */
1618 * Try to get a full magazine from the depot. Cycle
1619 * through depot(full)->loaded->prev->depot(empty).
1620 * Retry if a full magazine was available from the depot.
1622 * Return NULL (caller will fall through) if no magazines
1623 * can be found anywhere.
1627 emptymag = tp->mags[zi].prev;
1629 SLIST_INSERT_HEAD(&d->empty, emptymag, nextmagazine);
1630 tp->mags[zi].prev = tp->mags[zi].loaded;
1631 mp = SLIST_FIRST(&d->full); /* loaded magazine */
1632 tp->mags[zi].loaded = mp;
1634 SLIST_REMOVE_HEAD(&d->full, nextmagazine);
1635 MASSERT(MAGAZINE_NOTEMPTY(mp));
1647 mtmagazine_free(int zi, void *ptr)
1650 struct magazine *mp, *loadedmag;
1655 * Do not try to access per-thread magazines while the mtmagazine
1656 * is being initialized or destroyed.
1663 * Primary per-thread freeing loop
1667 * Make sure a new magazine is available in case we have
1668 * to use it. Staging the newmag allows us to avoid
1669 * some locking/reentrancy complexity.
1671 * Temporarily disable the per-thread caches for this
1672 * allocation to avoid reentrancy and/or to avoid a
1673 * stack overflow if the [zi] happens to be the same that
1674 * would be used to allocate the new magazine.
1676 if (tp->newmag == NULL) {
1678 tp->newmag = _slaballoc(sizeof(struct magazine),
1681 if (tp->newmag == NULL) {
1688 * If the loaded magazine has space, free directly to it
1690 rc = magazine_free(tp->mags[zi].loaded, ptr);
1695 * If the prev magazine is empty, swap with the loaded
1696 * magazine and retry.
1698 mp = tp->mags[zi].prev;
1699 if (mp && MAGAZINE_EMPTY(mp)) {
1700 MASSERT(mp->rounds == 0);
1701 swap_mags(&tp->mags[zi]); /* prev now full */
1706 * Try to get an empty magazine from the depot. Cycle
1707 * through depot(empty)->loaded->prev->depot(full).
1708 * Retry if an empty magazine was available from the depot.
1713 if ((loadedmag = tp->mags[zi].prev) != NULL)
1714 SLIST_INSERT_HEAD(&d->full, loadedmag, nextmagazine);
1715 tp->mags[zi].prev = tp->mags[zi].loaded;
1716 mp = SLIST_FIRST(&d->empty);
1718 tp->mags[zi].loaded = mp;
1719 SLIST_REMOVE_HEAD(&d->empty, nextmagazine);
1720 MASSERT(MAGAZINE_NOTFULL(mp));
1724 mp->capacity = M_MAX_ROUNDS;
1727 tp->mags[zi].loaded = mp;
1736 mtmagazine_init(void)
1740 error = pthread_key_create(&thread_mags_key, mtmagazine_destructor);
1746 * This function is only used by the thread exit destructor
1749 mtmagazine_drain(struct magazine *mp)
1753 while (MAGAZINE_NOTEMPTY(mp)) {
1754 obj = magazine_alloc(mp, NULL);
1755 _slabfree(obj, 0, NULL);
1760 * mtmagazine_destructor()
1762 * When a thread exits, we reclaim all its resources; all its magazines are
1763 * drained and the structures are freed.
1765 * WARNING! The destructor can be called multiple times if the larger user
1766 * program has its own destructors which run after ours which
1767 * allocate or free memory.
1770 mtmagazine_destructor(void *thrp)
1772 thr_mags *tp = thrp;
1773 struct magazine *mp;
1777 * Prevent further use of mtmagazines while we are destructing
1778 * them, as well as for any destructors which are run after us
1779 * prior to the thread actually being destroyed.
1783 for (i = 0; i < NZONES; i++) {
1784 mp = tp->mags[i].loaded;
1785 tp->mags[i].loaded = NULL;
1787 if (MAGAZINE_NOTEMPTY(mp))
1788 mtmagazine_drain(mp);
1789 _slabfree(mp, 0, NULL);
1792 mp = tp->mags[i].prev;
1793 tp->mags[i].prev = NULL;
1795 if (MAGAZINE_NOTEMPTY(mp))
1796 mtmagazine_drain(mp);
1797 _slabfree(mp, 0, NULL);
1804 _slabfree(mp, 0, NULL);
1811 * Attempt to allocate a zone from the zone magazine; the zone magazine has
1812 * M_BURST_EARLY enabled, so honor the burst request from the magazine.
1815 zone_alloc(int flags)
1817 slglobaldata_t slgd = &SLGlobalData;
1822 zone_magazine_lock();
1825 z = magazine_alloc(&zone_magazine, &burst);
1826 if (z == NULL && burst == 1) {
1827 zone_magazine_unlock();
1828 z = _vmem_alloc(ZoneSize * burst, ZoneSize, flags);
1829 } else if (z == NULL) {
1830 z = _vmem_alloc(ZoneSize * burst, ZoneSize, flags);
1832 for (i = 1; i < burst; i++) {
1833 j = magazine_free(&zone_magazine,
1834 (char *) z + (ZoneSize * i));
1838 zone_magazine_unlock();
1840 z->z_Flags |= SLZF_UNOTZEROD;
1841 zone_magazine_unlock();
1850 * Release a zone and unlock the slgd lock.
1855 slglobaldata_t slgd = &SLGlobalData;
1856 void *excess[M_ZONE_ROUNDS - M_LOW_ROUNDS] = {};
1859 zone_magazine_lock();
1862 bzero(z, sizeof(struct slzone));
1865 madvise(z, ZoneSize, MADV_FREE);
1867 i = magazine_free(&zone_magazine, z);
1870 * If we failed to free, collect excess magazines; release the zone
1871 * magazine lock, and then free to the system via _vmem_free. Re-enable
1872 * BURST mode for the magazine.
1875 j = zone_magazine.rounds - zone_magazine.low_factor;
1876 for (i = 0; i < j; i++) {
1877 excess[i] = magazine_alloc(&zone_magazine, NULL);
1878 MASSERT(excess[i] != NULL);
1881 zone_magazine_unlock();
1883 for (i = 0; i < j; i++)
1884 _vmem_free(excess[i], ZoneSize);
1886 _vmem_free(z, ZoneSize);
1888 zone_magazine_unlock();
1895 * Directly map memory in PAGE_SIZE'd chunks with the specified
1898 * Alignment must be a multiple of PAGE_SIZE.
1900 * Size must be >= alignment.
1903 _vmem_alloc(size_t size, size_t align, int flags)
1910 * Map anonymous private memory.
1912 addr = mmap(NULL, size, PROT_READ|PROT_WRITE,
1913 MAP_PRIVATE|MAP_ANON, -1, 0);
1914 if (addr == MAP_FAILED)
1918 * Check alignment. The misaligned offset is also the excess
1919 * amount. If misaligned unmap the excess so we have a chance of
1920 * mapping at the next alignment point and recursively try again.
1922 * BBBBBBBBBBB BBBBBBBBBBB BBBBBBBBBBB block alignment
1923 * aaaaaaaaa aaaaaaaaaaa aa mis-aligned allocation
1924 * xxxxxxxxx final excess calculation
1925 * ^ returned address
1927 excess = (uintptr_t)addr & (align - 1);
1930 excess = align - excess;
1933 munmap(save + excess, size - excess);
1934 addr = _vmem_alloc(size, align, flags);
1935 munmap(save, excess);
1937 return((void *)addr);
1943 * Free a chunk of memory allocated with _vmem_alloc()
1946 _vmem_free(void *ptr, size_t size)
1952 * Panic on fatal conditions
1955 _mpanic(const char *ctl, ...)
1959 if (malloc_panic == 0) {
1962 vfprintf(stderr, ctl, va);
1963 fprintf(stderr, "\n");