2 * DMALLOC.C - Dillon's malloc
4 * Copyright (c) 2011 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>.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
19 * 3. Neither the name of The DragonFly Project nor the names of its
20 * contributors may be used to endorse or promote products derived
21 * from this software without specific, prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
31 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * This module implements a modified slab allocator drop-in replacement for
38 * the libc malloc(). The slab algorithm has been adjusted to support dynamic
39 * sizing of slabs which effectively allows slabs to be used for allocations of
40 * any size. Because of this we neither have a small-block allocator or a
41 * big-block allocator and the code paths are simplified to the point where
42 * allocations, caching, and freeing, is screaming fast.
44 * There is very little interaction between threads. A global depot accessed
45 * via atomic cmpxchg instructions (only! no spinlocks!) is used as a
46 * catch-all and to deal with thread exits and such.
48 * To support dynamic slab sizing available user virtual memory is broken
49 * down into ~1024 regions. Each region has fixed slab size whos value is
50 * set when the region is opened up for use. The free() path simply applies
51 * a mask based on the region to the pointer to acquire the base of the
52 * governing slab structure.
54 * Regions[NREGIONS] (1024)
56 * Slab management and locking is done on a per-zone basis.
58 * Alloc Size Chunking Number of zones
69 * ... continues unlimited ... 4 zones
71 * For a 2^63 memory space each doubling >= 64K is broken down into
72 * 4 chunking zones, so we support 88 + (48 * 4) = 280 zones.
74 * API FEATURES AND SIDE EFFECTS
76 * + power-of-2 sized allocations up to a page will be power-of-2 aligned.
77 * Above that power-of-2 sized allocations are page-aligned. Non
78 * power-of-2 sized allocations are aligned the same as the chunk
79 * size for their zone.
80 * + malloc(0) returns a special non-NULL value
81 * + ability to allocate arbitrarily large chunks of memory
82 * + realloc will reuse the passed pointer if possible, within the
83 * limitations of the zone chunking.
87 * + [better] garbage collection
88 * + better initial sizing.
92 * The value of the environment variable MALLOC_OPTIONS is a character string
93 * containing various flags to tune nmalloc. Upper case letters enabled
94 * or increase the feature, lower case disables or decreases the feature.
96 * U Enable UTRACE for all operations, observable with ktrace.
97 * Diasbled by default.
99 * Z Zero out allocations, otherwise allocations (except for
100 * calloc) will contain garbage.
101 * Disabled by default.
103 * H Pass a hint with madvise() about unused pages.
104 * Disabled by default.
105 * Not currently implemented.
107 * F Disable local per-thread caching.
108 * Disabled by default.
110 * C Increase (decrease) how much excess cache to retain.
111 * Set to 4 by default.
114 /* cc -shared -fPIC -g -O -I/usr/src/lib/libc/include -o dmalloc.so dmalloc.c */
116 #ifndef STANDALONE_DEBUG
117 #include "libc_private.h"
120 #include <sys/param.h>
121 #include <sys/types.h>
122 #include <sys/mman.h>
123 #include <sys/queue.h>
125 #include <sys/ktrace.h>
138 #include <machine/atomic.h>
139 #include <machine/cpufunc.h>
141 #ifdef STANDALONE_DEBUG
142 void _nmalloc_thr_init(void);
144 #include "spinlock.h"
145 #include "un-namespace.h"
148 #ifndef MAP_SIZEALIGN
149 #define MAP_SIZEALIGN 0
152 #if SSIZE_MAX == 0x7FFFFFFF
154 #define UVM_BITS 32 /* worst case */
157 #define UVM_BITS 48 /* worst case XXX */
160 #if LONG_MAX == 0x7FFFFFFF
162 #define LONG_BITS_SHIFT 5
165 #define LONG_BITS_SHIFT 6
168 #define LOCKEDPTR ((void *)(intptr_t)-1)
173 #define NREGIONS_BITS 10
174 #define NREGIONS (1 << NREGIONS_BITS)
175 #define NREGIONS_MASK (NREGIONS - 1)
176 #define NREGIONS_SHIFT (UVM_BITS - NREGIONS_BITS)
177 #define NREGIONS_SIZE (1LU << NREGIONS_SHIFT)
179 typedef struct region *region_t;
180 typedef struct slglobaldata *slglobaldata_t;
181 typedef struct slab *slab_t;
185 slab_t slab; /* conditional out of band slab */
188 static struct region Regions[NREGIONS];
191 * Number of chunking zones available
193 #define CHUNKFACTOR 8
195 #define NZONES (16 + 9 * CHUNKFACTOR + 16 * CHUNKFACTOR)
197 #define NZONES (16 + 9 * CHUNKFACTOR + 48 * CHUNKFACTOR)
200 static int MaxChunks[NZONES];
202 #define NDEPOTS 8 /* must be power of 2 */
205 * Maximum number of chunks per slab, governed by the allocation bitmap in
206 * each slab. The maximum is reduced for large chunk sizes.
208 #define MAXCHUNKS (LONG_BITS * LONG_BITS)
209 #define MAXCHUNKS_BITS (LONG_BITS_SHIFT * LONG_BITS_SHIFT)
210 #define LITSLABSIZE (32 * 1024)
211 #define NOMSLABSIZE (2 * 1024 * 1024)
212 #define BIGSLABSIZE (128 * 1024 * 1024)
214 #define ZALLOC_SLAB_MAGIC 0x736c6162 /* magic sanity */
216 TAILQ_HEAD(slab_list, slab);
222 struct slab *next; /* slabs with available space */
223 TAILQ_ENTRY(slab) entry;
224 int32_t magic; /* magic number for sanity check */
225 u_int navail; /* number of free elements available */
227 u_int free_bit; /* free hint bitno */
228 u_int free_index; /* free hint index */
229 u_long bitmap[LONG_BITS]; /* free chunks */
230 size_t slab_size; /* size of entire slab */
231 size_t chunk_size; /* chunk size for validation */
233 enum { UNKNOWN, AVAIL, EMPTY, FULL } state;
235 region_t region; /* related region */
236 char *chunks; /* chunk base */
243 struct slglobaldata {
250 struct slab_list full_zones; /* via entry */
254 slglobaldata_t sldepot;
257 #define SLAB_ZEROD 0x0001
260 * Misc constants. Note that allocations that are exact multiples of
261 * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
262 * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
264 #define MIN_CHUNK_SIZE 8 /* in bytes */
265 #define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
267 #define SAFLAG_ZERO 0x00000001
270 * The WEIRD_ADDR is used as known text to copy into free objects to
271 * try to create deterministic failure cases if the data is accessed after
274 * WARNING: A limited number of spinlocks are available, BIGXSIZE should
275 * not be larger then 64.
277 #define WEIRD_ADDR 0xdeadc0de
278 #define MAX_COPY sizeof(weirdary)
280 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
286 #define MASSERT(exp) do { if (__predict_false(!(exp))) \
287 _mpanic("assertion: %s in %s", \
291 /* With this attribute set, do not require a function call for accessing
292 * this variable when the code is compiled -fPIC */
293 #define TLS_ATTRIBUTE __attribute__ ((tls_model ("initial-exec")));
295 static __thread struct slglobaldata slglobal TLS_ATTRIBUTE;
296 static pthread_key_t thread_malloc_key;
297 static pthread_once_t thread_malloc_once = PTHREAD_ONCE_INIT;
298 static struct slglobaldata sldepots[NDEPOTS];
300 static int opt_madvise = 0;
301 static int opt_free = 0;
302 static int opt_cache = 4;
303 static int opt_utrace = 0;
304 static int g_malloc_flags = 0;
305 static int malloc_panic;
307 static const int32_t weirdary[16] = {
308 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
309 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
310 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
311 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR
314 static void *memalloc(size_t size, int flags);
315 static void *memrealloc(void *ptr, size_t size);
316 static void memfree(void *ptr, int);
317 static slab_t slaballoc(int zi, size_t chunking, size_t chunk_size);
318 static void slabfree(slab_t slab);
319 static void slabterm(slglobaldata_t slgd, slab_t slab);
320 static void *_vmem_alloc(int ri, size_t slab_size);
321 static void _vmem_free(void *ptr, size_t slab_size);
322 static void _mpanic(const char *ctl, ...) __printflike(1, 2);
323 #ifndef STANDALONE_DEBUG
324 static void malloc_init(void) __constructor(0);
326 static void malloc_init(void) __constructor(101);
329 struct nmalloc_utrace {
335 #define UTRACE(a, b, c) \
337 struct nmalloc_utrace ut = { \
342 utrace(&ut, sizeof(ut)); \
347 * If enabled any memory allocated without M_ZERO is initialized to -1.
349 static int use_malloc_pattern;
355 const char *p = NULL;
357 Regions[0].mask = -1; /* disallow activity in lowest region */
359 if (issetugid() == 0)
360 p = getenv("MALLOC_OPTIONS");
362 for (; p != NULL && *p != '\0'; p++) {
393 g_malloc_flags = SAFLAG_ZERO;
400 UTRACE((void *) -1, 0, NULL);
405 * We have to install a handler for nmalloc thread teardowns when
406 * the thread is created. We cannot delay this because destructors in
407 * sophisticated userland programs can call malloc() for the first time
408 * during their thread exit.
410 * This routine is called directly from pthreads.
412 static void _nmalloc_thr_init_once(void);
413 static void _nmalloc_thr_destructor(void *thrp);
416 _nmalloc_thr_init(void)
424 TAILQ_INIT(&slglobal.full_zones);
425 slglobal.sldepot = &sldepots[slgi & (NDEPOTS - 1)];
430 pthread_once(&thread_malloc_once, _nmalloc_thr_init_once);
432 pthread_setspecific(thread_malloc_key, &slglobal);
440 _nmalloc_thr_init_once(void)
444 error = pthread_key_create(&thread_malloc_key, _nmalloc_thr_destructor);
450 * Called for each thread undergoing exit
452 * Move all of the thread's slabs into a depot.
455 _nmalloc_thr_destructor(void *thrp)
457 slglobaldata_t slgd = thrp;
463 for (i = 0; i <= slgd->biggest_index; i++) {
464 while ((slab = slgd->zone[i].empty_base) != NULL) {
465 slgd->zone[i].empty_base = slab->next;
466 slabterm(slgd, slab);
469 while ((slab = slgd->zone[i].avail_base) != NULL) {
470 slgd->zone[i].avail_base = slab->next;
471 slabterm(slgd, slab);
474 while ((slab = TAILQ_FIRST(&slgd->full_zones)) != NULL) {
475 TAILQ_REMOVE(&slgd->full_zones, slab, entry);
476 slabterm(slgd, slab);
482 * Calculate the zone index for the allocation request size and set the
483 * allocation request size to that particular zone's chunk size.
486 zoneindex(size_t *bytes, size_t *chunking)
488 size_t n = (size_t)*bytes;
494 *bytes = n = (n + 7) & ~7;
496 return(n / 8); /* 8 byte chunks, 16 zones */
500 c = x / (CHUNKFACTOR * 2);
504 c = x / (CHUNKFACTOR * 2);
505 i = 16 + CHUNKFACTOR * 5; /* 256->512,1024,2048,4096,8192 */
512 _mpanic("slaballoc: byte value too high");
514 *bytes = n = (n + c - 1) & ~(c - 1);
516 return (i + n / c - CHUNKFACTOR);
518 *bytes = n = (n + c - 1) & ~(c - 1);
523 *bytes = n = (n + 15) & ~15;
525 return(n / (CHUNKINGLO*2) + CHUNKINGLO*1 - 1);
529 *bytes = n = (n + 31) & ~31;
531 return(n / (CHUNKINGLO*4) + CHUNKINGLO*2 - 1);
534 *bytes = n = (n + 63) & ~63;
536 return(n / (CHUNKINGLO*8) + CHUNKINGLO*3 - 1);
539 *bytes = n = (n + 127) & ~127;
541 return(n / (CHUNKINGLO*16) + CHUNKINGLO*4 - 1);
544 *bytes = n = (n + 255) & ~255;
546 return(n / (CHUNKINGLO*32) + CHUNKINGLO*5 - 1);
548 *bytes = n = (n + 511) & ~511;
550 return(n / (CHUNKINGLO*64) + CHUNKINGLO*6 - 1);
553 *bytes = n = (n + 1023) & ~1023;
555 return(n / (CHUNKINGLO*128) + CHUNKINGLO*7 - 1);
557 if (n < 32768) { /* 16384-32767 */
558 *bytes = n = (n + 2047) & ~2047;
560 return(n / (CHUNKINGLO*256) + CHUNKINGLO*8 - 1);
563 *bytes = n = (n + 4095) & ~4095; /* 32768-65535 */
565 return(n / (CHUNKINGLO*512) + CHUNKINGLO*9 - 1);
570 i = CHUNKINGLO*10 - 1;
577 _mpanic("slaballoc: byte value too high");
579 *bytes = n = (n + c - 1) & ~(c - 1);
586 * malloc() - call internal slab allocator
593 ptr = memalloc(size, 0);
597 UTRACE(0, size, ptr);
602 * calloc() - call internal slab allocator
605 calloc(size_t number, size_t size)
609 ptr = memalloc(number * size, SAFLAG_ZERO);
613 UTRACE(0, number * size, ptr);
618 * realloc() (SLAB ALLOCATOR)
620 * We do not attempt to optimize this routine beyond reusing the same
621 * pointer if the new size fits within the chunking of the old pointer's
625 realloc(void *ptr, size_t size)
630 ret = memalloc(size, 0);
632 ret = memrealloc(ptr, size);
636 UTRACE(ptr, size, ret);
643 * Allocate (size) bytes with a alignment of (alignment), where (alignment)
644 * is a power of 2 >= sizeof(void *).
646 * The slab allocator will allocate on power-of-2 boundaries up to at least
647 * PAGE_SIZE. Otherwise we use the zoneindex mechanic to find a zone
648 * matching the requirements.
651 posix_memalign(void **memptr, size_t alignment, size_t size)
657 * OpenGroup spec issue 6 checks
659 if ((alignment | (alignment - 1)) + 1 != (alignment << 1)) {
663 if (alignment < sizeof(void *)) {
669 * XXX for now just find the nearest power of 2 >= size and also
670 * >= alignment and allocate that.
672 while (alignment < size) {
675 _mpanic("posix_memalign: byte value too high");
677 *memptr = memalloc(alignment, 0);
678 return(*memptr ? 0 : ENOMEM);
682 * free() (SLAB ALLOCATOR) - do the obvious
694 * memalloc() (SLAB ALLOCATOR)
696 * Allocate memory via the slab allocator.
699 memalloc(size_t size, int flags)
702 struct zoneinfo *zinfo;
716 * If 0 bytes is requested we have to return a unique pointer, allocate
722 /* Capture global flags */
723 flags |= g_malloc_flags;
725 /* Compute allocation zone; zoneindex will panic on excessive sizes */
726 zi = zoneindex(&size, &chunking);
727 MASSERT(zi < NZONES);
732 * Locate a slab with available space. If no slabs are available
733 * back-off to the empty list and if we still come up dry allocate
734 * a new slab (which will try the depot first).
738 zinfo = &slgd->zone[zi];
739 if ((slab = zinfo->avail_base) == NULL) {
740 if ((slab = zinfo->empty_base) == NULL) {
744 slab = slaballoc(zi, chunking, size);
747 slab->next = zinfo->avail_base;
748 zinfo->avail_base = slab;
750 if (slgd->biggest_index < zi)
751 slgd->biggest_index = zi;
755 * Pulled from empty list
757 zinfo->empty_base = slab->next;
758 slab->next = zinfo->avail_base;
759 zinfo->avail_base = slab;
761 --zinfo->empty_count;
766 * Allocate a chunk out of the slab. HOT PATH
768 * Only the thread owning the slab can allocate out of it.
770 * NOTE: The last bit in the bitmap is always marked allocated so
771 * we cannot overflow here.
773 bno = slab->free_bit;
774 bmi = slab->free_index;
775 bmp = &slab->bitmap[bmi];
776 if (*bmp & (1LU << bno)) {
777 atomic_clear_long(bmp, 1LU << bno);
778 obj = slab->chunks + ((bmi << LONG_BITS_SHIFT) + bno) * size;
779 slab->free_bit = (bno + 1) & (LONG_BITS - 1);
780 atomic_add_int(&slab->navail, -1);
781 if (flags & SAFLAG_ZERO)
787 * Allocate a chunk out of a slab. COLD PATH
789 if (slab->navail == 0) {
790 zinfo->avail_base = slab->next;
792 TAILQ_INSERT_TAIL(&slgd->full_zones, slab, entry);
796 while (bmi < LONG_BITS) {
797 bmp = &slab->bitmap[bmi];
800 atomic_clear_long(bmp, 1LU << bno);
801 obj = slab->chunks + ((bmi << LONG_BITS_SHIFT) + bno) *
803 slab->free_index = bmi;
804 slab->free_bit = (bno + 1) & (LONG_BITS - 1);
805 atomic_add_int(&slab->navail, -1);
806 if (flags & SAFLAG_ZERO)
813 while (bmi < LONG_BITS) {
814 bmp = &slab->bitmap[bmi];
817 atomic_clear_long(bmp, 1LU << bno);
818 obj = slab->chunks + ((bmi << LONG_BITS_SHIFT) + bno) *
820 slab->free_index = bmi;
821 slab->free_bit = (bno + 1) & (LONG_BITS - 1);
822 atomic_add_int(&slab->navail, -1);
823 if (flags & SAFLAG_ZERO)
829 _mpanic("slaballoc: corrupted zone: navail %d", slab->navail);
835 * Reallocate memory within the chunk
838 memrealloc(void *ptr, size_t nsize)
848 * If 0 bytes is requested we have to return a unique pointer, allocate
854 /* Capture global flags */
855 flags |= g_malloc_flags;
858 * Locate the zone by looking up the dynamic slab size mask based
859 * on the memory region the allocation resides in.
861 region = &Regions[((uintptr_t)ptr >> NREGIONS_SHIFT) & NREGIONS_MASK];
862 if ((slab = region->slab) == NULL)
863 slab = (void *)((uintptr_t)ptr & region->mask);
864 MASSERT(slab->magic == ZALLOC_SLAB_MAGIC);
865 osize = slab->chunk_size;
866 if (nsize <= osize) {
867 if (osize < 32 || nsize >= osize / 2) {
869 if ((flags & SAFLAG_ZERO) && nsize < osize)
870 bzero(obj + nsize, osize - nsize);
876 * Otherwise resize the object
878 obj = memalloc(nsize, 0);
882 bcopy(ptr, obj, nsize);
889 * free (SLAB ALLOCATOR)
891 * Free a memory block previously allocated by malloc.
896 memfree(void *ptr, int flags)
909 * Locate the zone by looking up the dynamic slab size mask based
910 * on the memory region the allocation resides in.
912 * WARNING! The slab may be owned by another thread!
914 region = &Regions[((uintptr_t)ptr >> NREGIONS_SHIFT) & NREGIONS_MASK];
915 if ((slab = region->slab) == NULL)
916 slab = (void *)((uintptr_t)ptr & region->mask);
917 MASSERT(slab != NULL);
918 MASSERT(slab->magic == ZALLOC_SLAB_MAGIC);
922 * Put weird data into the memory to detect modifications after
923 * freeing, illegal pointer use after freeing (we should fault on
924 * the odd address), and so forth.
926 if (slab->chunk_size < sizeof(weirdary))
927 bcopy(weirdary, ptr, slab->chunk_size);
929 bcopy(weirdary, ptr, sizeof(weirdary));
932 bno = ((uintptr_t)ptr - (uintptr_t)slab->chunks) / slab->chunk_size;
933 bmi = bno >> LONG_BITS_SHIFT;
934 bno &= (LONG_BITS - 1);
935 bmp = &slab->bitmap[bmi];
937 MASSERT(bmi >= 0 && bmi < slab->nmax);
938 MASSERT((*bmp & (1LU << bno)) == 0);
939 atomic_set_long(bmp, 1LU << bno);
940 atomic_add_int(&slab->navail, 1);
943 * We can only do the following if we own the slab
946 if (slab->slgd == slgd) {
947 struct zoneinfo *zinfo;
949 if (slab->free_index > bmi) {
950 slab->free_index = bmi;
951 slab->free_bit = bno;
952 } else if (slab->free_index == bmi &&
953 slab->free_bit > bno) {
954 slab->free_bit = bno;
956 zinfo = &slgd->zone[slab->zone_index];
959 * Freeing an object from a full slab will move it to the
960 * available list. If the available list already has a
961 * slab we terminate the full slab instead, moving it to
964 if (slab->state == FULL) {
965 TAILQ_REMOVE(&slgd->full_zones, slab, entry);
966 if (zinfo->avail_base == NULL) {
968 stmp = zinfo->avail_base;
970 zinfo->avail_base = slab;
972 slabterm(slgd, slab);
978 * If the slab becomes completely empty dispose of it in
979 * some manner. By default each thread caches up to 4
980 * empty slabs. Only small slabs are cached.
982 if (slab->navail == slab->nmax && slab->state == AVAIL) {
984 * Remove slab from available queue
986 slabp = &zinfo->avail_base;
987 while ((stmp = *slabp) != slab)
991 if (opt_free || opt_cache == 0) {
993 * If local caching is disabled cache the
994 * slab in the depot (or free it).
996 slabterm(slgd, slab);
997 } else if (slab->slab_size > BIGSLABSIZE) {
999 * We do not try to retain large slabs
1000 * in per-thread caches.
1002 slabterm(slgd, slab);
1003 } else if (zinfo->empty_count > opt_cache) {
1005 * We have too many slabs cached, but
1006 * instead of freeing this one free
1007 * an empty slab that's been idle longer.
1009 * (empty_count does not change)
1011 stmp = zinfo->empty_base;
1012 slab->state = EMPTY;
1013 slab->next = stmp->next;
1014 zinfo->empty_base = slab;
1015 slabterm(slgd, stmp);
1018 * Cache the empty slab in our thread local
1021 ++zinfo->empty_count;
1022 slab->state = EMPTY;
1023 slab->next = zinfo->empty_base;
1024 zinfo->empty_base = slab;
1033 * Allocate a new slab holding objects of size chunk_size.
1036 slaballoc(int zi, size_t chunking, size_t chunk_size)
1038 slglobaldata_t slgd;
1039 slglobaldata_t sldepot;
1040 struct zoneinfo *zinfo;
1048 uintptr_t chunk_offset;
1059 * First look in the depot. Any given zone in the depot may be
1060 * locked by being set to -1. We have to do this instead of simply
1061 * removing the entire chain because removing the entire chain can
1062 * cause racing threads to allocate local slabs for large objects,
1063 * resulting in a large VSZ.
1066 sldepot = slgd->sldepot;
1067 zinfo = &sldepot->zone[zi];
1069 while ((slab = zinfo->avail_base) != NULL) {
1070 if ((void *)slab == LOCKEDPTR) {
1074 if (atomic_cmpset_ptr(&zinfo->avail_base, slab, LOCKEDPTR)) {
1075 MASSERT(slab->slgd == NULL);
1077 zinfo->avail_base = slab->next;
1083 * Nothing in the depot, allocate a new slab by locating or assigning
1084 * a region and then using the system virtual memory allocator.
1089 * Calculate the start of the data chunks relative to the start
1092 if ((chunk_size ^ (chunk_size - 1)) == (chunk_size << 1) - 1) {
1094 chunk_offset = (sizeof(*slab) + (chunk_size - 1)) &
1098 chunk_offset = sizeof(*slab) + chunking - 1;
1099 chunk_offset -= chunk_offset % chunking;
1103 * Calculate a reasonable number of chunks for the slab.
1105 * Once initialized the MaxChunks[] array can only ever be
1106 * reinitialized to the same value.
1108 maxchunks = MaxChunks[zi];
1109 if (maxchunks == 0) {
1111 * First calculate how many chunks would fit in 1/1024
1112 * available memory. This is around 2MB on a 32 bit
1113 * system and 128G on a 64-bit (48-bits available) system.
1115 maxchunks = (ssize_t)(NREGIONS_SIZE - chunk_offset) /
1116 (ssize_t)chunk_size;
1121 * A slab cannot handle more than MAXCHUNKS chunks, but
1122 * limit us to approximately MAXCHUNKS / 2 here because
1123 * we may have to expand maxchunks when we calculate the
1124 * actual power-of-2 slab.
1126 if (maxchunks > MAXCHUNKS / 2)
1127 maxchunks = MAXCHUNKS / 2;
1130 * Try to limit the slabs to BIGSLABSIZE (~128MB). Larger
1131 * slabs will be created if the allocation does not fit.
1133 if (chunk_offset + chunk_size * maxchunks > BIGSLABSIZE) {
1134 tmpchunks = (ssize_t)(BIGSLABSIZE - chunk_offset) /
1135 (ssize_t)chunk_size;
1138 if (maxchunks > tmpchunks)
1139 maxchunks = tmpchunks;
1143 * If the slab calculates to greater than 2MB see if we
1144 * can cut it down to ~2MB. This controls VSZ but has
1145 * no effect on run-time size or performance.
1147 * This is very important in case you core dump and also
1148 * important to reduce unnecessary region allocations.
1150 if (chunk_offset + chunk_size * maxchunks > NOMSLABSIZE) {
1151 tmpchunks = (ssize_t)(NOMSLABSIZE - chunk_offset) /
1152 (ssize_t)chunk_size;
1155 if (maxchunks > tmpchunks)
1156 maxchunks = tmpchunks;
1160 * If the slab calculates to greater than 128K see if we
1161 * can cut it down to ~128K while still maintaining a
1162 * reasonably large number of chunks in each slab. This
1163 * controls VSZ but has no effect on run-time size or
1166 * This is very important in case you core dump and also
1167 * important to reduce unnecessary region allocations.
1169 if (chunk_offset + chunk_size * maxchunks > LITSLABSIZE) {
1170 tmpchunks = (ssize_t)(LITSLABSIZE - chunk_offset) /
1171 (ssize_t)chunk_size;
1174 if (maxchunks > tmpchunks)
1175 maxchunks = tmpchunks;
1178 MaxChunks[zi] = maxchunks;
1180 MASSERT(maxchunks > 0 && maxchunks <= MAXCHUNKS);
1183 * Calculate the actual slab size. maxchunks will be recalculated
1186 slab_desire = chunk_offset + chunk_size * maxchunks;
1187 slab_size = 8 * MAXCHUNKS;
1188 power = 3 + MAXCHUNKS_BITS;
1189 while (slab_size < slab_desire) {
1195 * Do a quick recalculation based on the actual slab size but not
1196 * yet dealing with whether the slab header is in-band or out-of-band.
1197 * The purpose here is to see if we can reasonably reduce slab_size
1198 * to a power of 4 to allow more chunk sizes to use the same slab
1201 if ((power & 1) && slab_size > 32768) {
1202 maxchunks = (slab_size - chunk_offset) / chunk_size;
1203 if (maxchunks >= MAXCHUNKS / 8) {
1208 if ((power & 2) && slab_size > 32768 * 4) {
1209 maxchunks = (slab_size - chunk_offset) / chunk_size;
1210 if (maxchunks >= MAXCHUNKS / 4) {
1216 * This case occurs when the slab_size is larger than 1/1024 available
1219 nswath = slab_size / NREGIONS_SIZE;
1220 if (nswath > NREGIONS)
1225 * Try to allocate from our current best region for this zi
1227 region_mask = ~(slab_size - 1);
1228 ri = slgd->zone[zi].best_region;
1229 if (Regions[ri].mask == region_mask) {
1230 if ((slab = _vmem_alloc(ri, slab_size)) != NULL)
1235 * Try to find an existing region to allocate from. The normal
1236 * case will be for allocations that are less than 1/1024 available
1237 * UVM, which fit into a single Regions[] entry.
1239 while (slab_size <= NREGIONS_SIZE) {
1241 for (ri = 0; ri < NREGIONS; ++ri) {
1242 if (rx < 0 && Regions[ri].mask == 0)
1244 if (Regions[ri].mask == region_mask) {
1245 slab = _vmem_alloc(ri, slab_size);
1247 slgd->zone[zi].best_region = ri;
1257 * This can fail, retry either way
1259 atomic_cmpset_ptr((void **)&Regions[rx].mask,
1261 (void *)region_mask);
1266 for (ri = 0; ri < NREGIONS; ri += nswath) {
1267 if (Regions[ri].mask == region_mask) {
1268 slab = _vmem_alloc(ri, slab_size);
1270 slgd->zone[zi].best_region = ri;
1275 for (j = nswath - 1; j >= 0; --j) {
1276 if (Regions[ri+j].mask != 0)
1285 * We found a candidate, try to allocate it backwards so
1286 * another thread racing a slaballoc() does not see the
1287 * mask in the base index position until we are done.
1289 * We can safely zero-out any partial allocations because
1290 * the mask is only accessed from the base index. Any other
1291 * threads racing us will fail prior to us clearing the mask.
1295 for (j = nswath - 1; j >= 0; --j) {
1296 if (!atomic_cmpset_ptr((void **)&Regions[rx+j].mask,
1297 NULL, (void *)region_mask)) {
1298 while (++j < nswath)
1299 Regions[rx+j].mask = 0;
1307 * Fill in the new slab in region ri. If the slab_size completely
1308 * fills one or more region slots we move the slab structure out of
1309 * band which should optimize the chunking (particularly for a power
1313 region = &Regions[ri];
1314 MASSERT(region->slab == NULL);
1315 if (slab_size >= NREGIONS_SIZE) {
1317 slab = memalloc(sizeof(*slab), 0);
1318 bzero(slab, sizeof(*slab));
1319 slab->chunks = save;
1320 for (j = 0; j < nswath; ++j)
1321 region[j].slab = slab;
1324 bzero(slab, sizeof(*slab));
1325 slab->chunks = (char *)slab + chunk_offset;
1329 * Calculate the start of the chunks memory and recalculate the
1330 * actual number of chunks the slab can hold.
1332 maxchunks = (slab_size - chunk_offset) / chunk_size;
1333 if (maxchunks > MAXCHUNKS)
1334 maxchunks = MAXCHUNKS;
1337 * And fill in the rest
1339 slab->magic = ZALLOC_SLAB_MAGIC;
1340 slab->navail = maxchunks;
1341 slab->nmax = maxchunks;
1342 slab->slab_size = slab_size;
1343 slab->chunk_size = chunk_size;
1344 slab->zone_index = zi;
1346 slab->state = UNKNOWN;
1347 slab->region = region;
1349 for (ri = 0; ri < maxchunks; ri += LONG_BITS) {
1350 if (ri + LONG_BITS <= maxchunks)
1351 slab->bitmap[ri >> LONG_BITS_SHIFT] = ULONG_MAX;
1353 slab->bitmap[ri >> LONG_BITS_SHIFT] =
1354 (1LU << (maxchunks - ri)) - 1;
1363 slabfree(slab_t slab)
1368 if (slab->region->slab == slab) {
1372 nswath = slab->slab_size / NREGIONS_SIZE;
1373 for (j = 0; j < nswath; ++j)
1374 slab->region[j].slab = NULL;
1376 _vmem_free(slab->chunks, slab->slab_size);
1383 _vmem_free(slab, slab->slab_size);
1388 * Terminate a slab's use in the current thread. The slab may still have
1389 * outstanding allocations and thus not be deallocatable.
1392 slabterm(slglobaldata_t slgd, slab_t slab)
1394 slglobaldata_t sldepot = slgd->sldepot;
1395 struct zoneinfo *zinfo;
1397 int zi = slab->zone_index;
1401 zinfo = &sldepot->zone[zi];
1404 * If the slab can be freed and the depot is either locked or not
1405 * empty, then free the slab.
1407 if (slab->navail == slab->nmax && zinfo->avail_base) {
1408 slab->state = UNKNOWN;
1412 slab->state = AVAIL;
1415 * Link the slab into the depot
1418 dnext = zinfo->avail_base;
1420 if ((void *)dnext == LOCKEDPTR) {
1425 if (atomic_cmpset_ptr(&zinfo->avail_base, dnext, slab))
1433 * Directly map memory in PAGE_SIZE'd chunks with the specified
1436 * Alignment must be a multiple of PAGE_SIZE.
1438 * Size must be >= alignment.
1441 _vmem_alloc(int ri, size_t slab_size)
1443 char *baddr = (void *)((uintptr_t)ri << NREGIONS_SHIFT);
1449 if (slab_size < NREGIONS_SIZE)
1450 eaddr = baddr + NREGIONS_SIZE;
1452 eaddr = baddr + slab_size;
1455 * This usually just works but might not.
1457 addr = mmap(baddr, slab_size, PROT_READ|PROT_WRITE,
1458 MAP_PRIVATE | MAP_ANON | MAP_SIZEALIGN, -1, 0);
1459 if (addr == MAP_FAILED) {
1462 if (addr < baddr || addr + slab_size > eaddr) {
1463 munmap(addr, slab_size);
1468 * Check alignment. The misaligned offset is also the excess
1469 * amount. If misaligned unmap the excess so we have a chance of
1470 * mapping at the next alignment point and recursively try again.
1472 * BBBBBBBBBBB BBBBBBBBBBB BBBBBBBBBBB block alignment
1473 * aaaaaaaaa aaaaaaaaaaa aa mis-aligned allocation
1474 * xxxxxxxxx final excess calculation
1475 * ^ returned address
1477 excess = (uintptr_t)addr & (slab_size - 1);
1479 excess = slab_size - excess;
1482 munmap(save + excess, slab_size - excess);
1483 addr = _vmem_alloc(ri, slab_size);
1484 munmap(save, excess);
1487 if (addr < baddr || addr + slab_size > eaddr) {
1488 munmap(addr, slab_size);
1491 excess = (uintptr_t)addr & (slab_size - 1);
1499 * Free a chunk of memory allocated with _vmem_alloc()
1502 _vmem_free(void *ptr, size_t size)
1508 * Panic on fatal conditions
1511 _mpanic(const char *ctl, ...)
1515 if (malloc_panic == 0) {
1518 vfprintf(stderr, ctl, va);
1519 fprintf(stderr, "\n");