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.
89 * The value of the environment variable MALLOC_OPTIONS is a character string
90 * containing various flags to tune nmalloc.
92 * 'U' / ['u'] Generate / do not generate utrace entries for ktrace(1)
93 * This will generate utrace events for all malloc,
94 * realloc, and free calls. There are tools (mtrplay) to
95 * replay and allocation pattern or to graph heap structure
96 * (mtrgraph) which can interpret these logs.
97 * 'Z' / ['z'] Zero out / do not zero all allocations.
98 * Each new byte of memory allocated by malloc, realloc, or
99 * reallocf will be initialized to 0. This is intended for
100 * debugging and will affect performance negatively.
101 * 'H' / ['h'] Pass a hint to the kernel about pages unused by the
102 * allocation functions.
105 /* cc -shared -fPIC -g -O -I/usr/src/lib/libc/include -o nmalloc.so nmalloc.c */
107 #include "libc_private.h"
109 #include <sys/param.h>
110 #include <sys/types.h>
111 #include <sys/mman.h>
112 #include <sys/queue.h>
114 #include <sys/ktrace.h>
126 #include "spinlock.h"
127 #include "un-namespace.h"
130 * Linked list of large allocations
132 typedef struct bigalloc {
133 struct bigalloc *next; /* hash link */
134 void *base; /* base pointer */
135 u_long bytes; /* bytes allocated */
139 * Note that any allocations which are exact multiples of PAGE_SIZE, or
140 * which are >= ZALLOC_ZONE_LIMIT, will fall through to the kmem subsystem.
142 #define ZALLOC_ZONE_LIMIT (16 * 1024) /* max slab-managed alloc */
143 #define ZALLOC_MIN_ZONE_SIZE (32 * 1024) /* minimum zone size */
144 #define ZALLOC_MAX_ZONE_SIZE (128 * 1024) /* maximum zone size */
145 #define ZALLOC_ZONE_SIZE (64 * 1024)
146 #define ZALLOC_SLAB_MAGIC 0x736c6162 /* magic sanity */
147 #define ZALLOC_SLAB_SLIDE 20 /* L1-cache skip */
149 #if ZALLOC_ZONE_LIMIT == 16384
151 #elif ZALLOC_ZONE_LIMIT == 32768
154 #error "I couldn't figure out NZONES"
158 * Chunk structure for free elements
160 typedef struct slchunk {
161 struct slchunk *c_Next;
165 * The IN-BAND zone header is placed at the beginning of each zone.
169 typedef struct slzone {
170 int32_t z_Magic; /* magic number for sanity check */
171 int z_NFree; /* total free chunks / ualloc space */
172 struct slzone *z_Next; /* ZoneAry[] link if z_NFree non-zero */
173 int z_NMax; /* maximum free chunks */
174 char *z_BasePtr; /* pointer to start of chunk array */
175 int z_UIndex; /* current initial allocation index */
176 int z_UEndIndex; /* last (first) allocation index */
177 int z_ChunkSize; /* chunk size for validation */
178 int z_FirstFreePg; /* chunk list on a page-by-page basis */
181 struct slchunk *z_PageAry[ZALLOC_ZONE_SIZE / PAGE_SIZE];
182 #if defined(INVARIANTS)
183 __uint32_t z_Bitmap[]; /* bitmap of free chunks / sanity */
187 typedef struct slglobaldata {
189 slzone_t ZoneAry[NZONES];/* linked list of zones NFree > 0 */
193 #define SLZF_UNOTZEROD 0x0001
195 #define FASTSLABREALLOC 0x02
198 * Misc constants. Note that allocations that are exact multiples of
199 * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
200 * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
202 #define MIN_CHUNK_SIZE 8 /* in bytes */
203 #define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
204 #define IN_SAME_PAGE_MASK (~(intptr_t)PAGE_MASK | MIN_CHUNK_MASK)
207 * The WEIRD_ADDR is used as known text to copy into free objects to
208 * try to create deterministic failure cases if the data is accessed after
211 * WARNING: A limited number of spinlocks are available, BIGXSIZE should
212 * not be larger then 64.
214 #define WEIRD_ADDR 0xdeadc0de
215 #define MAX_COPY sizeof(weirdary)
216 #define ZERO_LENGTH_PTR ((void *)&malloc_dummy_pointer)
218 #define BIGHSHIFT 10 /* bigalloc hash table */
219 #define BIGHSIZE (1 << BIGHSHIFT)
220 #define BIGHMASK (BIGHSIZE - 1)
221 #define BIGXSIZE (BIGHSIZE / 16) /* bigalloc lock table */
222 #define BIGXMASK (BIGXSIZE - 1)
224 #define SAFLAG_ZERO 0x0001
225 #define SAFLAG_PASSIVE 0x0002
231 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
233 #define MASSERT(exp) do { if (__predict_false(!(exp))) \
234 _mpanic("assertion: %s in %s", \
242 #define M_MAX_ROUNDS 64
243 #define M_ZONE_ROUNDS 64
244 #define M_LOW_ROUNDS 32
245 #define M_INIT_ROUNDS 8
246 #define M_BURST_FACTOR 8
247 #define M_BURST_NSCALE 2
249 #define M_BURST 0x0001
250 #define M_BURST_EARLY 0x0002
253 SLIST_ENTRY(magazine) nextmagazine;
256 int capacity; /* Max rounds in this magazine */
257 int rounds; /* Current number of free rounds */
258 int burst_factor; /* Number of blocks to prefill with */
259 int low_factor; /* Free till low_factor from full mag */
260 void *objects[M_MAX_ROUNDS];
263 SLIST_HEAD(magazinelist, magazine);
265 static spinlock_t zone_mag_lock;
266 static struct magazine zone_magazine = {
267 .flags = M_BURST | M_BURST_EARLY,
268 .capacity = M_ZONE_ROUNDS,
270 .burst_factor = M_BURST_FACTOR,
271 .low_factor = M_LOW_ROUNDS
274 #define MAGAZINE_FULL(mp) (mp->rounds == mp->capacity)
275 #define MAGAZINE_NOTFULL(mp) (mp->rounds < mp->capacity)
276 #define MAGAZINE_EMPTY(mp) (mp->rounds == 0)
277 #define MAGAZINE_NOTEMPTY(mp) (mp->rounds != 0)
279 /* Each thread will have a pair of magazines per size-class (NZONES)
280 * The loaded magazine will support immediate allocations, the previous
281 * magazine will either be full or empty and can be swapped at need */
282 typedef struct magazine_pair {
283 struct magazine *loaded;
284 struct magazine *prev;
287 /* A depot is a collection of magazines for a single zone. */
288 typedef struct magazine_depot {
289 struct magazinelist full;
290 struct magazinelist empty;
294 typedef struct thr_mags {
295 magazine_pair mags[NZONES];
296 struct magazine *newmag;
300 /* With this attribute set, do not require a function call for accessing
301 * this variable when the code is compiled -fPIC */
302 #define TLS_ATTRIBUTE __attribute__ ((tls_model ("initial-exec")));
304 static int mtmagazine_free_live;
305 static __thread thr_mags thread_mags TLS_ATTRIBUTE;
306 static pthread_key_t thread_mags_key;
307 static pthread_once_t thread_mags_once = PTHREAD_ONCE_INIT;
308 static magazine_depot depots[NZONES];
311 * Fixed globals (not per-cpu)
313 static const int ZoneSize = ZALLOC_ZONE_SIZE;
314 static const int ZoneLimit = ZALLOC_ZONE_LIMIT;
315 static const int ZonePageCount = ZALLOC_ZONE_SIZE / PAGE_SIZE;
316 static const int ZoneMask = ZALLOC_ZONE_SIZE - 1;
318 static int opt_madvise = 0;
319 static int opt_utrace = 0;
320 static int g_malloc_flags = 0;
321 static struct slglobaldata SLGlobalData;
322 static bigalloc_t bigalloc_array[BIGHSIZE];
323 static spinlock_t bigspin_array[BIGXSIZE];
324 static int malloc_panic;
325 static int malloc_dummy_pointer;
327 static const int32_t weirdary[16] = {
328 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
329 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
330 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR,
331 WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR, WEIRD_ADDR
334 static void *_slaballoc(size_t size, int flags);
335 static void *_slabrealloc(void *ptr, size_t size);
336 static void _slabfree(void *ptr, int, bigalloc_t *);
337 static void *_vmem_alloc(size_t bytes, size_t align, int flags);
338 static void _vmem_free(void *ptr, size_t bytes);
339 static void *magazine_alloc(struct magazine *, int *);
340 static int magazine_free(struct magazine *, void *);
341 static void *mtmagazine_alloc(int zi);
342 static int mtmagazine_free(int zi, void *);
343 static void mtmagazine_init(void);
344 static void mtmagazine_destructor(void *);
345 static slzone_t zone_alloc(int flags);
346 static void zone_free(void *z);
347 static void _mpanic(const char *ctl, ...) __printflike(1, 2);
348 static void malloc_init(void) __constructor(0);
349 #if defined(INVARIANTS)
350 static void chunk_mark_allocated(slzone_t z, void *chunk);
351 static void chunk_mark_free(slzone_t z, void *chunk);
354 struct nmalloc_utrace {
360 #define UTRACE(a, b, c) \
362 struct nmalloc_utrace ut = { \
367 utrace(&ut, sizeof(ut)); \
372 * If enabled any memory allocated without M_ZERO is initialized to -1.
374 static int use_malloc_pattern;
380 const char *p = NULL;
382 if (issetugid() == 0)
383 p = getenv("MALLOC_OPTIONS");
385 for (; p != NULL && *p != '\0'; p++) {
387 case 'u': opt_utrace = 0; break;
388 case 'U': opt_utrace = 1; break;
389 case 'h': opt_madvise = 0; break;
390 case 'H': opt_madvise = 1; break;
391 case 'z': g_malloc_flags = 0; break;
392 case 'Z': g_malloc_flags = SAFLAG_ZERO; break;
398 UTRACE((void *) -1, 0, NULL);
402 * We have to install a handler for nmalloc thread teardowns when
403 * the thread is created. We cannot delay this because destructors in
404 * sophisticated userland programs can call malloc() for the first time
405 * during their thread exit.
407 * This routine is called directly from pthreads.
410 _nmalloc_thr_init(void)
415 * Disallow mtmagazine operations until the mtmagazine is
421 if (mtmagazine_free_live == 0) {
422 mtmagazine_free_live = 1;
423 pthread_once(&thread_mags_once, mtmagazine_init);
425 pthread_setspecific(thread_mags_key, tp);
433 slgd_lock(slglobaldata_t slgd)
436 _SPINLOCK(&slgd->Spinlock);
440 slgd_unlock(slglobaldata_t slgd)
443 _SPINUNLOCK(&slgd->Spinlock);
447 depot_lock(magazine_depot *dp)
450 _SPINLOCK(&dp->lock);
454 depot_unlock(magazine_depot *dp)
457 _SPINUNLOCK(&dp->lock);
461 zone_magazine_lock(void)
464 _SPINLOCK(&zone_mag_lock);
468 zone_magazine_unlock(void)
471 _SPINUNLOCK(&zone_mag_lock);
475 swap_mags(magazine_pair *mp)
477 struct magazine *tmp;
479 mp->loaded = mp->prev;
484 * bigalloc hashing and locking support.
486 * Return an unmasked hash code for the passed pointer.
489 _bigalloc_hash(void *ptr)
493 hv = ((int)(intptr_t)ptr >> PAGE_SHIFT) ^
494 ((int)(intptr_t)ptr >> (PAGE_SHIFT + BIGHSHIFT));
500 * Lock the hash chain and return a pointer to its base for the specified
503 static __inline bigalloc_t *
504 bigalloc_lock(void *ptr)
506 int hv = _bigalloc_hash(ptr);
509 bigp = &bigalloc_array[hv & BIGHMASK];
511 _SPINLOCK(&bigspin_array[hv & BIGXMASK]);
516 * Lock the hash chain and return a pointer to its base for the specified
519 * BUT, if the hash chain is empty, just return NULL and do not bother
522 static __inline bigalloc_t *
523 bigalloc_check_and_lock(void *ptr)
525 int hv = _bigalloc_hash(ptr);
528 bigp = &bigalloc_array[hv & BIGHMASK];
532 _SPINLOCK(&bigspin_array[hv & BIGXMASK]);
538 bigalloc_unlock(void *ptr)
543 hv = _bigalloc_hash(ptr);
544 _SPINUNLOCK(&bigspin_array[hv & BIGXMASK]);
549 * Calculate the zone index for the allocation request size and set the
550 * allocation request size to that particular zone's chunk size.
553 zoneindex(size_t *bytes, size_t *chunking)
555 size_t n = (unsigned int)*bytes; /* unsigned for shift opt */
557 *bytes = n = (n + 7) & ~7;
559 return(n / 8 - 1); /* 8 byte chunks, 16 zones */
562 *bytes = n = (n + 15) & ~15;
568 *bytes = n = (n + 31) & ~31;
573 *bytes = n = (n + 63) & ~63;
578 *bytes = n = (n + 127) & ~127;
580 return(n / 128 + 31);
583 *bytes = n = (n + 255) & ~255;
585 return(n / 256 + 39);
587 *bytes = n = (n + 511) & ~511;
589 return(n / 512 + 47);
591 #if ZALLOC_ZONE_LIMIT > 8192
593 *bytes = n = (n + 1023) & ~1023;
595 return(n / 1024 + 55);
598 #if ZALLOC_ZONE_LIMIT > 16384
600 *bytes = n = (n + 2047) & ~2047;
602 return(n / 2048 + 63);
605 _mpanic("Unexpected byte count %d", n);
610 * malloc() - call internal slab allocator
617 ptr = _slaballoc(size, 0);
621 UTRACE(0, size, ptr);
626 * calloc() - call internal slab allocator
629 calloc(size_t number, size_t size)
633 ptr = _slaballoc(number * size, SAFLAG_ZERO);
637 UTRACE(0, number * size, ptr);
642 * realloc() (SLAB ALLOCATOR)
644 * We do not attempt to optimize this routine beyond reusing the same
645 * pointer if the new size fits within the chunking of the old pointer's
649 realloc(void *ptr, size_t size)
652 ret = _slabrealloc(ptr, size);
656 UTRACE(ptr, size, ret);
663 * Allocate (size) bytes with a alignment of (alignment), where (alignment)
664 * is a power of 2 >= sizeof(void *).
666 * The slab allocator will allocate on power-of-2 boundaries up to
667 * at least PAGE_SIZE. We use the zoneindex mechanic to find a
668 * zone matching the requirements, and _vmem_alloc() otherwise.
671 posix_memalign(void **memptr, size_t alignment, size_t size)
679 * OpenGroup spec issue 6 checks
681 if ((alignment | (alignment - 1)) + 1 != (alignment << 1)) {
685 if (alignment < sizeof(void *)) {
691 * Our zone mechanism guarantees same-sized alignment for any
692 * power-of-2 allocation. If size is a power-of-2 and reasonable
693 * we can just call _slaballoc() and be done. We round size up
694 * to the nearest alignment boundary to improve our odds of
695 * it becoming a power-of-2 if it wasn't before.
697 if (size <= alignment)
700 size = (size + alignment - 1) & ~(size_t)(alignment - 1);
701 if (size < PAGE_SIZE && (size | (size - 1)) + 1 == (size << 1)) {
702 *memptr = _slaballoc(size, 0);
703 return(*memptr ? 0 : ENOMEM);
707 * Otherwise locate a zone with a chunking that matches
708 * the requested alignment, within reason. Consider two cases:
710 * (1) A 1K allocation on a 32-byte alignment. The first zoneindex
711 * we find will be the best fit because the chunking will be
712 * greater or equal to the alignment.
714 * (2) A 513 allocation on a 256-byte alignment. In this case
715 * the first zoneindex we find will be for 576 byte allocations
716 * with a chunking of 64, which is not sufficient. To fix this
717 * we simply find the nearest power-of-2 >= size and use the
718 * same side-effect of _slaballoc() which guarantees
719 * same-alignment on a power-of-2 allocation.
721 if (size < PAGE_SIZE) {
722 zi = zoneindex(&size, &chunking);
723 if (chunking >= alignment) {
724 *memptr = _slaballoc(size, 0);
725 return(*memptr ? 0 : ENOMEM);
731 while (alignment < size)
733 *memptr = _slaballoc(alignment, 0);
734 return(*memptr ? 0 : ENOMEM);
738 * If the slab allocator cannot handle it use vmem_alloc().
740 * Alignment must be adjusted up to at least PAGE_SIZE in this case.
742 if (alignment < PAGE_SIZE)
743 alignment = PAGE_SIZE;
744 if (size < alignment)
746 size = (size + PAGE_MASK) & ~(size_t)PAGE_MASK;
747 *memptr = _vmem_alloc(size, alignment, 0);
751 big = _slaballoc(sizeof(struct bigalloc), 0);
753 _vmem_free(*memptr, size);
757 bigp = bigalloc_lock(*memptr);
762 bigalloc_unlock(*memptr);
768 * free() (SLAB ALLOCATOR) - do the obvious
774 _slabfree(ptr, 0, NULL);
778 * _slaballoc() (SLAB ALLOCATOR)
780 * Allocate memory via the slab allocator. If the request is too large,
781 * or if it page-aligned beyond a certain size, we fall back to the
785 _slaballoc(size_t size, int flags)
799 * Handle the degenerate size == 0 case. Yes, this does happen.
800 * Return a special pointer. This is to maintain compatibility with
801 * the original malloc implementation. Certain devices, such as the
802 * adaptec driver, not only allocate 0 bytes, they check for NULL and
803 * also realloc() later on. Joy.
806 return(ZERO_LENGTH_PTR);
808 /* Capture global flags */
809 flags |= g_malloc_flags;
812 * Handle large allocations directly. There should not be very many
813 * of these so performance is not a big issue.
815 * The backend allocator is pretty nasty on a SMP system. Use the
816 * slab allocator for one and two page-sized chunks even though we
817 * lose some efficiency.
819 if (size >= ZoneLimit ||
820 ((size & PAGE_MASK) == 0 && size > PAGE_SIZE*2)) {
824 size = (size + PAGE_MASK) & ~(size_t)PAGE_MASK;
825 chunk = _vmem_alloc(size, PAGE_SIZE, flags);
829 big = _slaballoc(sizeof(struct bigalloc), 0);
831 _vmem_free(chunk, size);
834 bigp = bigalloc_lock(chunk);
839 bigalloc_unlock(chunk);
844 /* Compute allocation zone; zoneindex will panic on excessive sizes */
845 zi = zoneindex(&size, &chunking);
846 MASSERT(zi < NZONES);
848 obj = mtmagazine_alloc(zi);
850 if (flags & SAFLAG_ZERO)
855 slgd = &SLGlobalData;
859 * Attempt to allocate out of an existing zone. If all zones are
860 * exhausted pull one off the free list or allocate a new one.
862 if ((z = slgd->ZoneAry[zi]) == NULL) {
863 z = zone_alloc(flags);
868 * How big is the base structure?
870 #if defined(INVARIANTS)
872 * Make room for z_Bitmap. An exact calculation is
873 * somewhat more complicated so don't make an exact
876 off = offsetof(struct slzone,
877 z_Bitmap[(ZoneSize / size + 31) / 32]);
878 bzero(z->z_Bitmap, (ZoneSize / size + 31) / 8);
880 off = sizeof(struct slzone);
884 * Align the storage in the zone based on the chunking.
886 * Guarantee power-of-2 alignment for power-of-2-sized
887 * chunks. Otherwise align based on the chunking size
888 * (typically 8 or 16 bytes for small allocations).
890 * NOTE: Allocations >= ZoneLimit are governed by the
891 * bigalloc code and typically only guarantee page-alignment.
893 * Set initial conditions for UIndex near the zone header
894 * to reduce unecessary page faults, vs semi-randomization
895 * to improve L1 cache saturation.
897 if ((size | (size - 1)) + 1 == (size << 1))
898 off = (off + size - 1) & ~(size - 1);
900 off = (off + chunking - 1) & ~(chunking - 1);
901 z->z_Magic = ZALLOC_SLAB_MAGIC;
903 z->z_NMax = (ZoneSize - off) / size;
904 z->z_NFree = z->z_NMax;
905 z->z_BasePtr = (char *)z + off;
906 z->z_UIndex = z->z_UEndIndex = 0;
907 z->z_ChunkSize = size;
908 z->z_FirstFreePg = ZonePageCount;
909 z->z_Next = slgd->ZoneAry[zi];
910 slgd->ZoneAry[zi] = z;
911 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
912 flags &= ~SAFLAG_ZERO; /* already zero'd */
913 flags |= SAFLAG_PASSIVE;
917 * Slide the base index for initial allocations out of the
918 * next zone we create so we do not over-weight the lower
919 * part of the cpu memory caches.
921 slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
922 & (ZALLOC_MAX_ZONE_SIZE - 1);
926 * Ok, we have a zone from which at least one chunk is available.
928 * Remove us from the ZoneAry[] when we become empty
930 MASSERT(z->z_NFree > 0);
932 if (--z->z_NFree == 0) {
933 slgd->ZoneAry[zi] = z->z_Next;
938 * Locate a chunk in a free page. This attempts to localize
939 * reallocations into earlier pages without us having to sort
940 * the chunk list. A chunk may still overlap a page boundary.
942 while (z->z_FirstFreePg < ZonePageCount) {
943 if ((chunk = z->z_PageAry[z->z_FirstFreePg]) != NULL) {
946 * Diagnostic: c_Next is not total garbage.
948 MASSERT(chunk->c_Next == NULL ||
949 ((intptr_t)chunk->c_Next & IN_SAME_PAGE_MASK) ==
950 ((intptr_t)chunk & IN_SAME_PAGE_MASK));
953 chunk_mark_allocated(z, chunk);
955 MASSERT((uintptr_t)chunk & ZoneMask);
956 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
963 * No chunks are available but NFree said we had some memory,
964 * so it must be available in the never-before-used-memory
965 * area governed by UIndex. The consequences are very
966 * serious if our zone got corrupted so we use an explicit
967 * panic rather then a KASSERT.
969 chunk = (slchunk_t)(z->z_BasePtr + z->z_UIndex * size);
971 if (++z->z_UIndex == z->z_NMax)
973 if (z->z_UIndex == z->z_UEndIndex) {
975 _mpanic("slaballoc: corrupted zone");
978 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
979 flags &= ~SAFLAG_ZERO;
980 flags |= SAFLAG_PASSIVE;
982 #if defined(INVARIANTS)
983 chunk_mark_allocated(z, chunk);
988 if (flags & SAFLAG_ZERO) {
991 } else if ((flags & (SAFLAG_ZERO|SAFLAG_PASSIVE)) == 0) {
992 if (use_malloc_pattern) {
993 for (i = 0; i < size; i += sizeof(int)) {
994 *(int *)((char *)chunk + i) = -1;
997 /* avoid accidental double-free check */
998 chunk->c_Next = (void *)-1;
1008 * Reallocate memory within the chunk
1011 _slabrealloc(void *ptr, size_t size)
1018 if (ptr == NULL || ptr == ZERO_LENGTH_PTR) {
1019 return(_slaballoc(size, 0));
1024 return(ZERO_LENGTH_PTR);
1028 * Handle oversized allocations.
1030 if ((bigp = bigalloc_check_and_lock(ptr)) != NULL) {
1034 while ((big = *bigp) != NULL) {
1035 if (big->base == ptr) {
1036 size = (size + PAGE_MASK) & ~(size_t)PAGE_MASK;
1037 bigbytes = big->bytes;
1038 if (bigbytes == size) {
1039 bigalloc_unlock(ptr);
1043 bigalloc_unlock(ptr);
1044 if ((nptr = _slaballoc(size, 0)) == NULL) {
1046 bigp = bigalloc_lock(ptr);
1049 bigalloc_unlock(ptr);
1052 if (size > bigbytes)
1054 bcopy(ptr, nptr, size);
1055 _slabfree(ptr, FASTSLABREALLOC, &big);
1060 bigalloc_unlock(ptr);
1064 * Get the original allocation's zone. If the new request winds
1065 * up using the same chunk size we do not have to do anything.
1067 * NOTE: We don't have to lock the globaldata here, the fields we
1068 * access here will not change at least as long as we have control
1069 * over the allocation.
1071 z = (slzone_t)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
1072 MASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
1075 * Use zoneindex() to chunk-align the new size, as long as the
1076 * new size is not too large.
1078 if (size < ZoneLimit) {
1079 zoneindex(&size, &chunking);
1080 if (z->z_ChunkSize == size) {
1086 * Allocate memory for the new request size and copy as appropriate.
1088 if ((nptr = _slaballoc(size, 0)) != NULL) {
1089 if (size > z->z_ChunkSize)
1090 size = z->z_ChunkSize;
1091 bcopy(ptr, nptr, size);
1092 _slabfree(ptr, 0, NULL);
1099 * free (SLAB ALLOCATOR)
1101 * Free a memory block previously allocated by malloc. Note that we do not
1102 * attempt to uplodate ks_loosememuse as MP races could prevent us from
1103 * checking memory limits in malloc.
1106 * FASTSLABREALLOC Fast call from realloc, *rbigp already
1112 _slabfree(void *ptr, int flags, bigalloc_t *rbigp)
1118 slglobaldata_t slgd;
1123 /* Fast realloc path for big allocations */
1124 if (flags & FASTSLABREALLOC) {
1126 goto fastslabrealloc;
1130 * Handle NULL frees and special 0-byte allocations
1134 if (ptr == ZERO_LENGTH_PTR)
1138 * Handle oversized allocations.
1140 if ((bigp = bigalloc_check_and_lock(ptr)) != NULL) {
1141 while ((big = *bigp) != NULL) {
1142 if (big->base == ptr) {
1144 bigalloc_unlock(ptr);
1147 _slabfree(big, 0, NULL);
1149 MASSERT(sizeof(weirdary) <= size);
1150 bcopy(weirdary, ptr, sizeof(weirdary));
1152 _vmem_free(ptr, size);
1157 bigalloc_unlock(ptr);
1161 * Zone case. Figure out the zone based on the fact that it is
1164 z = (slzone_t)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
1165 MASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
1167 size = z->z_ChunkSize;
1168 zi = z->z_ZoneIndex;
1170 if (g_malloc_flags & SAFLAG_ZERO)
1173 if (mtmagazine_free(zi, ptr) == 0)
1176 pgno = ((char *)ptr - (char *)z) >> PAGE_SHIFT;
1178 slgd = &SLGlobalData;
1183 * Attempt to detect a double-free. To reduce overhead we only check
1184 * if there appears to be link pointer at the base of the data.
1186 if (((intptr_t)chunk->c_Next - (intptr_t)z) >> PAGE_SHIFT == pgno) {
1189 for (scan = z->z_PageAry[pgno]; scan; scan = scan->c_Next) {
1191 _mpanic("Double free at %p", chunk);
1194 chunk_mark_free(z, chunk);
1198 * Put weird data into the memory to detect modifications after
1199 * freeing, illegal pointer use after freeing (we should fault on
1200 * the odd address), and so forth.
1203 if (z->z_ChunkSize < sizeof(weirdary))
1204 bcopy(weirdary, chunk, z->z_ChunkSize);
1206 bcopy(weirdary, chunk, sizeof(weirdary));
1210 * Add this free non-zero'd chunk to a linked list for reuse, adjust
1213 chunk->c_Next = z->z_PageAry[pgno];
1214 z->z_PageAry[pgno] = chunk;
1215 if (z->z_FirstFreePg > pgno)
1216 z->z_FirstFreePg = pgno;
1219 * Bump the number of free chunks. If it becomes non-zero the zone
1220 * must be added back onto the appropriate list.
1222 if (z->z_NFree++ == 0) {
1223 z->z_Next = slgd->ZoneAry[z->z_ZoneIndex];
1224 slgd->ZoneAry[z->z_ZoneIndex] = z;
1228 * If the zone becomes totally free then release it.
1230 if (z->z_NFree == z->z_NMax) {
1233 pz = &slgd->ZoneAry[z->z_ZoneIndex];
1235 pz = &(*pz)->z_Next;
1240 /* slgd lock released */
1246 #if defined(INVARIANTS)
1248 * Helper routines for sanity checks
1252 chunk_mark_allocated(slzone_t z, void *chunk)
1254 int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
1257 MASSERT(bitdex >= 0 && bitdex < z->z_NMax);
1258 bitptr = &z->z_Bitmap[bitdex >> 5];
1260 MASSERT((*bitptr & (1 << bitdex)) == 0);
1261 *bitptr |= 1 << bitdex;
1266 chunk_mark_free(slzone_t z, void *chunk)
1268 int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
1271 MASSERT(bitdex >= 0 && bitdex < z->z_NMax);
1272 bitptr = &z->z_Bitmap[bitdex >> 5];
1274 MASSERT((*bitptr & (1 << bitdex)) != 0);
1275 *bitptr &= ~(1 << bitdex);
1281 * Allocate and return a magazine. NULL is returned and *burst is adjusted
1282 * if the magazine is empty.
1284 static __inline void *
1285 magazine_alloc(struct magazine *mp, int *burst)
1291 if (MAGAZINE_NOTEMPTY(mp)) {
1292 obj = mp->objects[--mp->rounds];
1297 * Return burst factor to caller along with NULL
1299 if ((mp->flags & M_BURST) && (burst != NULL)) {
1300 *burst = mp->burst_factor;
1302 /* Reduce burst factor by NSCALE; if it hits 1, disable BURST */
1303 if ((mp->flags & M_BURST) && (mp->flags & M_BURST_EARLY) &&
1305 mp->burst_factor -= M_BURST_NSCALE;
1306 if (mp->burst_factor <= 1) {
1307 mp->burst_factor = 1;
1308 mp->flags &= ~(M_BURST);
1309 mp->flags &= ~(M_BURST_EARLY);
1316 magazine_free(struct magazine *mp, void *p)
1318 if (mp != NULL && MAGAZINE_NOTFULL(mp)) {
1319 mp->objects[mp->rounds++] = p;
1327 mtmagazine_alloc(int zi)
1330 struct magazine *mp, *emptymag;
1335 * Do not try to access per-thread magazines while the mtmagazine
1336 * is being initialized or destroyed.
1343 * Primary per-thread allocation loop
1347 * If the loaded magazine has rounds, allocate and return
1349 mp = tp->mags[zi].loaded;
1350 obj = magazine_alloc(mp, NULL);
1355 * If the prev magazine is full, swap with the loaded
1356 * magazine and retry.
1358 mp = tp->mags[zi].prev;
1359 if (mp && MAGAZINE_FULL(mp)) {
1360 MASSERT(mp->rounds != 0);
1361 swap_mags(&tp->mags[zi]); /* prev now empty */
1366 * Try to get a full magazine from the depot. Cycle
1367 * through depot(full)->loaded->prev->depot(empty).
1368 * Retry if a full magazine was available from the depot.
1370 * Return NULL (caller will fall through) if no magazines
1371 * can be found anywhere.
1375 emptymag = tp->mags[zi].prev;
1377 SLIST_INSERT_HEAD(&d->empty, emptymag, nextmagazine);
1378 tp->mags[zi].prev = tp->mags[zi].loaded;
1379 mp = SLIST_FIRST(&d->full); /* loaded magazine */
1380 tp->mags[zi].loaded = mp;
1382 SLIST_REMOVE_HEAD(&d->full, nextmagazine);
1383 MASSERT(MAGAZINE_NOTEMPTY(mp));
1395 mtmagazine_free(int zi, void *ptr)
1398 struct magazine *mp, *loadedmag;
1403 * Do not try to access per-thread magazines while the mtmagazine
1404 * is being initialized or destroyed.
1411 * Primary per-thread freeing loop
1415 * Make sure a new magazine is available in case we have
1416 * to use it. Staging the newmag allows us to avoid
1417 * some locking/reentrancy complexity.
1419 * Temporarily disable the per-thread caches for this
1420 * allocation to avoid reentrancy and/or to avoid a
1421 * stack overflow if the [zi] happens to be the same that
1422 * would be used to allocate the new magazine.
1424 if (tp->newmag == NULL) {
1426 tp->newmag = _slaballoc(sizeof(struct magazine),
1429 if (tp->newmag == NULL) {
1436 * If the loaded magazine has space, free directly to it
1438 rc = magazine_free(tp->mags[zi].loaded, ptr);
1443 * If the prev magazine is empty, swap with the loaded
1444 * magazine and retry.
1446 mp = tp->mags[zi].prev;
1447 if (mp && MAGAZINE_EMPTY(mp)) {
1448 MASSERT(mp->rounds == 0);
1449 swap_mags(&tp->mags[zi]); /* prev now full */
1454 * Try to get an empty magazine from the depot. Cycle
1455 * through depot(empty)->loaded->prev->depot(full).
1456 * Retry if an empty magazine was available from the depot.
1461 if ((loadedmag = tp->mags[zi].prev) != NULL)
1462 SLIST_INSERT_HEAD(&d->full, loadedmag, nextmagazine);
1463 tp->mags[zi].prev = tp->mags[zi].loaded;
1464 mp = SLIST_FIRST(&d->empty);
1466 tp->mags[zi].loaded = mp;
1467 SLIST_REMOVE_HEAD(&d->empty, nextmagazine);
1468 MASSERT(MAGAZINE_NOTFULL(mp));
1472 mp->capacity = M_MAX_ROUNDS;
1475 tp->mags[zi].loaded = mp;
1484 mtmagazine_init(void)
1488 error = pthread_key_create(&thread_mags_key, mtmagazine_destructor);
1494 * This function is only used by the thread exit destructor
1497 mtmagazine_drain(struct magazine *mp)
1501 while (MAGAZINE_NOTEMPTY(mp)) {
1502 obj = magazine_alloc(mp, NULL);
1503 _slabfree(obj, 0, NULL);
1508 * mtmagazine_destructor()
1510 * When a thread exits, we reclaim all its resources; all its magazines are
1511 * drained and the structures are freed.
1513 * WARNING! The destructor can be called multiple times if the larger user
1514 * program has its own destructors which run after ours which
1515 * allocate or free memory.
1518 mtmagazine_destructor(void *thrp)
1520 thr_mags *tp = thrp;
1521 struct magazine *mp;
1525 * Prevent further use of mtmagazines while we are destructing
1526 * them, as well as for any destructors which are run after us
1527 * prior to the thread actually being destroyed.
1531 for (i = 0; i < NZONES; i++) {
1532 mp = tp->mags[i].loaded;
1533 tp->mags[i].loaded = NULL;
1535 if (MAGAZINE_NOTEMPTY(mp))
1536 mtmagazine_drain(mp);
1537 _slabfree(mp, 0, NULL);
1540 mp = tp->mags[i].prev;
1541 tp->mags[i].prev = NULL;
1543 if (MAGAZINE_NOTEMPTY(mp))
1544 mtmagazine_drain(mp);
1545 _slabfree(mp, 0, NULL);
1552 _slabfree(mp, 0, NULL);
1559 * Attempt to allocate a zone from the zone magazine; the zone magazine has
1560 * M_BURST_EARLY enabled, so honor the burst request from the magazine.
1563 zone_alloc(int flags)
1565 slglobaldata_t slgd = &SLGlobalData;
1570 zone_magazine_lock();
1573 z = magazine_alloc(&zone_magazine, &burst);
1574 if (z == NULL && burst == 1) {
1575 zone_magazine_unlock();
1576 z = _vmem_alloc(ZoneSize * burst, ZoneSize, flags);
1577 } else if (z == NULL) {
1578 z = _vmem_alloc(ZoneSize * burst, ZoneSize, flags);
1580 for (i = 1; i < burst; i++) {
1581 j = magazine_free(&zone_magazine,
1582 (char *) z + (ZoneSize * i));
1586 zone_magazine_unlock();
1588 z->z_Flags |= SLZF_UNOTZEROD;
1589 zone_magazine_unlock();
1598 * Release a zone and unlock the slgd lock.
1603 slglobaldata_t slgd = &SLGlobalData;
1604 void *excess[M_ZONE_ROUNDS - M_LOW_ROUNDS] = {};
1607 zone_magazine_lock();
1610 bzero(z, sizeof(struct slzone));
1613 madvise(z, ZoneSize, MADV_FREE);
1615 i = magazine_free(&zone_magazine, z);
1618 * If we failed to free, collect excess magazines; release the zone
1619 * magazine lock, and then free to the system via _vmem_free. Re-enable
1620 * BURST mode for the magazine.
1623 j = zone_magazine.rounds - zone_magazine.low_factor;
1624 for (i = 0; i < j; i++) {
1625 excess[i] = magazine_alloc(&zone_magazine, NULL);
1626 MASSERT(excess[i] != NULL);
1629 zone_magazine_unlock();
1631 for (i = 0; i < j; i++)
1632 _vmem_free(excess[i], ZoneSize);
1634 _vmem_free(z, ZoneSize);
1636 zone_magazine_unlock();
1643 * Directly map memory in PAGE_SIZE'd chunks with the specified
1646 * Alignment must be a multiple of PAGE_SIZE.
1648 * Size must be >= alignment.
1651 _vmem_alloc(size_t size, size_t align, int flags)
1658 * Map anonymous private memory.
1660 addr = mmap(NULL, size, PROT_READ|PROT_WRITE,
1661 MAP_PRIVATE|MAP_ANON, -1, 0);
1662 if (addr == MAP_FAILED)
1666 * Check alignment. The misaligned offset is also the excess
1667 * amount. If misaligned unmap the excess so we have a chance of
1668 * mapping at the next alignment point and recursively try again.
1670 * BBBBBBBBBBB BBBBBBBBBBB BBBBBBBBBBB block alignment
1671 * aaaaaaaaa aaaaaaaaaaa aa mis-aligned allocation
1672 * xxxxxxxxx final excess calculation
1673 * ^ returned address
1675 excess = (uintptr_t)addr & (align - 1);
1678 excess = align - excess;
1681 munmap(save + excess, size - excess);
1682 addr = _vmem_alloc(size, align, flags);
1683 munmap(save, excess);
1685 return((void *)addr);
1691 * Free a chunk of memory allocated with _vmem_alloc()
1694 _vmem_free(void *ptr, size_t size)
1700 * Panic on fatal conditions
1703 _mpanic(const char *ctl, ...)
1707 if (malloc_panic == 0) {
1710 vfprintf(stderr, ctl, va);
1711 fprintf(stderr, "\n");