#define MALLOC_PRODUCTION
#ifndef MALLOC_PRODUCTION
# define MALLOC_DEBUG
#endif
#include <sys/cdefs.h>
__RCSID("$NetBSD: jemalloc.c,v 1.64 2023/12/13 23:53:50 mrg Exp $");
#include "namespace.h"
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/rbtree.h>
#include <sys/uio.h>
#include <sys/ktrace.h>
#include <errno.h>
#include <limits.h>
#include <pthread.h>
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <malloc.h>
#include <reentrant.h>
#include "extern.h"
#define STRERROR_R(a, b, c) strerror_r_ss(a, b, c);
#ifndef MALLOC_PRODUCTION
# define MALLOC_STATS
#endif
#ifdef MALLOC_DEBUG
# ifdef NDEBUG
# undef NDEBUG
# endif
#else
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
#include <assert.h>
#ifdef MALLOC_DEBUG
# define inline
#endif
static inline int
ptrcmp(const void *pa, const void *pb)
{
#ifdef _LP64
const uintptr_t a = (uintptr_t)pa, b = (uintptr_t)pb;
const uintptr_t diff = a - b;
assert(((a | b) & 1) == 0);
return (int)(diff >> 32) | ((unsigned)diff >> 1);
#else
return (intptr_t)pa - (intptr_t)pb;
#endif
}
#define STRERROR_BUF 64
#ifdef __i386__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
# define USE_BRK
#endif
#ifdef __ia64__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
#endif
#ifdef __aarch64__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
# define TINY_MIN_2POW 3
#endif
#ifdef __alpha__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
# define TINY_MIN_2POW 3
#endif
#ifdef __sparc64__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
# define TINY_MIN_2POW 3
#endif
#ifdef __amd64__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
# define TINY_MIN_2POW 3
#endif
#ifdef __arm__
# define QUANTUM_2POW_MIN 3
# define SIZEOF_PTR_2POW 2
# define USE_BRK
# ifdef __ARM_EABI__
# define TINY_MIN_2POW 3
# endif
#endif
#ifdef __powerpc__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
# define USE_BRK
# define TINY_MIN_2POW 3
#endif
#if defined(__sparc__) && !defined(__sparc64__)
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
# define USE_BRK
#endif
#ifdef __or1k__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
# define USE_BRK
#endif
#ifdef __vax__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
# define USE_BRK
#endif
#ifdef __sh__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
# define USE_BRK
#endif
#ifdef __m68k__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
# define USE_BRK
#endif
#if defined(__mips__)
# ifdef _LP64
# define SIZEOF_PTR_2POW 3
# define TINY_MIN_2POW 3
# else
# define SIZEOF_PTR_2POW 2
# endif
# define QUANTUM_2POW_MIN 4
# define USE_BRK
#endif
#if defined(__riscv__)
# ifdef _LP64
# define SIZEOF_PTR_2POW 3
# define TINY_MIN_2POW 3
# else
# define SIZEOF_PTR_2POW 2
# endif
# define QUANTUM_2POW_MIN 4
# define USE_BRK
#endif
#ifdef __hppa__
# define QUANTUM_2POW_MIN 4
# define TINY_MIN_2POW 4
# define SIZEOF_PTR_2POW 2
# define USE_BRK
#endif
#define SIZEOF_PTR (1 << SIZEOF_PTR_2POW)
#ifndef SIZEOF_INT_2POW
# define SIZEOF_INT_2POW 2
#endif
#define CHUNK_2POW_DEFAULT 20
#define CACHELINE_2POW 6
#define CACHELINE ((size_t)(1 << CACHELINE_2POW))
#ifndef TINY_MIN_2POW
#define TINY_MIN_2POW 2
#endif
#define SMALL_MAX_2POW_DEFAULT 9
#define SMALL_MAX_DEFAULT (1 << SMALL_MAX_2POW_DEFAULT)
#define RUN_BFP 12
#define RUN_MAX_OVRHD 0x0000003dU
#define RUN_MAX_OVRHD_RELAX 0x00001800U
#define RUN_MAX_SMALL_2POW 15
#define RUN_MAX_SMALL (1 << RUN_MAX_SMALL_2POW)
#define malloc_mutex_t mutex_t
static bool malloc_initialized = false;
#ifdef _REENTRANT
static mutex_t init_lock = MUTEX_INITIALIZER;
#endif
#ifdef MALLOC_STATS
typedef struct malloc_bin_stats_s malloc_bin_stats_t;
struct malloc_bin_stats_s {
uint64_t nrequests;
uint64_t nruns;
uint64_t reruns;
unsigned long highruns;
unsigned long curruns;
};
typedef struct arena_stats_s arena_stats_t;
struct arena_stats_s {
size_t mapped;
size_t allocated_small;
uint64_t nmalloc_small;
uint64_t ndalloc_small;
size_t allocated_large;
uint64_t nmalloc_large;
uint64_t ndalloc_large;
};
typedef struct chunk_stats_s chunk_stats_t;
struct chunk_stats_s {
uint64_t nchunks;
unsigned long highchunks;
unsigned long curchunks;
};
#endif
typedef struct chunk_node_s chunk_node_t;
struct chunk_node_s {
rb_node_t link;
void *chunk;
size_t size;
};
typedef struct chunk_tree_s chunk_tree_t;
static int chunk_comp(void *, const void *, const void *);
static const rb_tree_ops_t chunk_tree_ops = {
.rbto_compare_nodes = chunk_comp,
.rbto_compare_key = chunk_comp,
.rbto_node_offset = offsetof(struct chunk_node_s, link),
};
typedef struct arena_s arena_t;
typedef struct arena_bin_s arena_bin_t;
typedef struct arena_chunk_map_s arena_chunk_map_t;
struct arena_chunk_map_s {
uint32_t npages;
#define POS_FREE ((uint32_t)0xffffffffU)
uint32_t pos;
};
typedef struct arena_chunk_s arena_chunk_t;
struct arena_chunk_s {
rb_node_t link;
arena_t *arena;
uint32_t pages_used;
uint32_t max_frun_npages;
uint32_t min_frun_ind;
arena_chunk_map_t map[1];
};
typedef struct arena_chunk_tree_s arena_chunk_tree_t;
static int arena_chunk_comp(void *, const void *, const void *);
static const rb_tree_ops_t arena_chunk_tree_ops = {
.rbto_compare_nodes = arena_chunk_comp,
.rbto_compare_key = arena_chunk_comp,
.rbto_node_offset = offsetof(struct arena_chunk_s, link),
};
typedef struct arena_run_s arena_run_t;
struct arena_run_s {
rb_node_t link;
#ifdef MALLOC_DEBUG
uint32_t magic;
# define ARENA_RUN_MAGIC 0x384adf93
#endif
arena_bin_t *bin;
unsigned regs_minelm;
unsigned nfree;
unsigned regs_mask[1];
};
typedef struct arena_run_tree_s arena_run_tree_t;
static int arena_run_comp(void *, const void *, const void *);
static const rb_tree_ops_t arena_run_tree_ops = {
.rbto_compare_nodes = arena_run_comp,
.rbto_compare_key = arena_run_comp,
.rbto_node_offset = offsetof(struct arena_run_s, link),
};
struct arena_bin_s {
arena_run_t *runcur;
rb_tree_t runs;
size_t reg_size;
size_t run_size;
uint32_t nregs;
uint32_t regs_mask_nelms;
uint32_t reg0_offset;
#ifdef MALLOC_STATS
malloc_bin_stats_t stats;
#endif
};
struct arena_s {
#ifdef MALLOC_DEBUG
uint32_t magic;
# define ARENA_MAGIC 0x947d3d24
#endif
malloc_mutex_t mtx;
#ifdef MALLOC_STATS
arena_stats_t stats;
#endif
rb_tree_t chunks;
arena_chunk_t *spare;
arena_bin_t bins[1];
};
static unsigned ncpus;
static size_t pagesize;
static size_t pagesize_mask;
static int pagesize_2pow;
static size_t bin_maxclass;
static unsigned ntbins;
static unsigned nqbins;
static unsigned nsbins;
static size_t small_min;
static size_t small_max;
static size_t quantum;
static size_t quantum_mask;
static size_t chunksize;
static size_t chunksize_mask;
static int chunksize_2pow;
static unsigned chunk_npages;
static unsigned arena_chunk_header_npages;
static size_t arena_maxclass;
#ifdef _REENTRANT
static malloc_mutex_t chunks_mtx;
#endif
static rb_tree_t huge;
#ifdef USE_BRK
#ifdef _REENTRANT
static malloc_mutex_t brk_mtx;
#endif
static void *brk_base;
static void *brk_prev;
static void *brk_max;
#endif
#ifdef MALLOC_STATS
static uint64_t huge_nmalloc;
static uint64_t huge_ndalloc;
static uint64_t huge_nralloc;
static size_t huge_allocated;
#endif
static rb_tree_t old_chunks;
static void *base_pages;
static void *base_next_addr;
static void *base_past_addr;
static chunk_node_t *base_chunk_nodes;
#ifdef _REENTRANT
static malloc_mutex_t base_mtx;
#endif
#ifdef MALLOC_STATS
static size_t base_mapped;
#endif
static arena_t **arenas;
#ifdef _REENTRANT
static malloc_mutex_t arenas_mtx;
#endif
#ifdef MALLOC_STATS
static chunk_stats_t stats_chunks;
#endif
const char *_malloc_options;
#ifndef MALLOC_PRODUCTION
static bool opt_abort = true;
static bool opt_junk = true;
#else
static bool opt_abort = false;
static bool opt_junk = false;
#endif
static bool opt_hint = false;
static bool opt_print_stats = false;
static int opt_quantum_2pow = QUANTUM_2POW_MIN;
static int opt_small_max_2pow = SMALL_MAX_2POW_DEFAULT;
static int opt_chunk_2pow = CHUNK_2POW_DEFAULT;
static bool opt_utrace = false;
static bool opt_sysv = false;
static bool opt_xmalloc = false;
static bool opt_zero = false;
typedef struct {
void *p;
size_t s;
void *r;
} malloc_utrace_t;
#define OPT(a) __predict_false(opt_##a)
#define NOT_OPT(a) __predict_true(!opt_##a)
#define UTRACE(a, b, c) \
if (OPT(utrace)) { \
malloc_utrace_t ut; \
ut.p = a; \
ut.s = b; \
ut.r = c; \
utrace("malloc", &ut, sizeof(ut)); \
}
static void wrtmessage(const char *p1, const char *p2, const char *p3,
const char *p4);
#ifdef MALLOC_STATS
static void malloc_printf(const char *format, ...);
#endif
static char *size_t2s(size_t x, char *s);
static bool base_pages_alloc(size_t minsize);
static void *base_alloc(size_t size);
static chunk_node_t *base_chunk_node_alloc(void);
static void base_chunk_node_dealloc(chunk_node_t *node);
#ifdef MALLOC_STATS
static void stats_print(arena_t *arena);
#endif
static void *pages_map(void *addr, size_t size);
static void *pages_map_align(void *addr, size_t size, int align);
static void pages_unmap(void *addr, size_t size);
static void *chunk_alloc(size_t size);
static void chunk_dealloc(void *chunk, size_t size);
static void arena_run_split(arena_t *arena, arena_run_t *run, size_t size);
static arena_chunk_t *arena_chunk_alloc(arena_t *arena);
static void arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk);
static arena_run_t *arena_run_alloc(arena_t *arena, size_t size);
static void arena_run_dalloc(arena_t *arena, arena_run_t *run, size_t size);
static arena_run_t *arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin);
static void *arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin);
static size_t arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size);
static void *arena_malloc(arena_t *arena, size_t size);
static void *arena_palloc(arena_t *arena, size_t alignment, size_t size,
size_t alloc_size);
static size_t arena_salloc(const void *ptr);
static void *arena_ralloc(void *ptr, size_t size, size_t oldsize);
static void arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr);
static void arena_new(arena_t *arena);
static arena_t *arenas_extend(void);
static void *huge_malloc(size_t size);
static void *huge_palloc(size_t alignment, size_t size);
static void *huge_ralloc(void *ptr, size_t size, size_t oldsize);
static void huge_dalloc(void *ptr);
static void *imalloc(size_t size);
static void *ipalloc(size_t alignment, size_t size);
static void *icalloc(size_t size);
static size_t isalloc(const void *ptr);
static void *iralloc(void *ptr, size_t size);
static void idalloc(void *ptr);
static void malloc_print_stats(void);
static bool malloc_init_hard(void);
#define malloc_mutex_init(m) mutex_init(m, NULL)
#define malloc_mutex_lock(m) mutex_lock(m)
#define malloc_mutex_unlock(m) mutex_unlock(m)
#define CHUNK_ADDR2BASE(a) \
((void *)((uintptr_t)(a) & ~chunksize_mask))
#define CHUNK_ADDR2OFFSET(a) \
((size_t)((uintptr_t)(a) & chunksize_mask))
#define CHUNK_CEILING(s) \
(((s) + chunksize_mask) & ~chunksize_mask)
#define CACHELINE_CEILING(s) \
(((s) + (CACHELINE - 1)) & ~(CACHELINE - 1))
#define QUANTUM_CEILING(a) \
(((a) + quantum_mask) & ~quantum_mask)
#define PAGE_CEILING(s) \
(((s) + pagesize_mask) & ~pagesize_mask)
static inline size_t
pow2_ceil(size_t x)
{
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
#if (SIZEOF_PTR == 8)
x |= x >> 32;
#endif
x++;
return (x);
}
static void
wrtmessage(const char *p1, const char *p2, const char *p3, const char *p4)
{
write(STDERR_FILENO, p1, strlen(p1));
write(STDERR_FILENO, p2, strlen(p2));
write(STDERR_FILENO, p3, strlen(p3));
write(STDERR_FILENO, p4, strlen(p4));
}
void (*_malloc_message)(const char *p1, const char *p2, const char *p3,
const char *p4) = wrtmessage;
#ifdef MALLOC_STATS
static void
malloc_printf(const char *format, ...)
{
char buf[4096];
va_list ap;
va_start(ap, format);
vsnprintf(buf, sizeof(buf), format, ap);
va_end(ap);
_malloc_message(buf, "", "", "");
}
#endif
#define UMAX2S_BUFSIZE 21
static char *
size_t2s(size_t x, char *s)
{
unsigned i;
assert(sizeof(size_t) <= 8);
i = UMAX2S_BUFSIZE - 1;
s[i] = '\0';
do {
i--;
s[i] = "0123456789"[(int)x % 10];
x /= (uintmax_t)10LL;
} while (x > 0);
return (&s[i]);
}
static bool
base_pages_alloc(size_t minsize)
{
size_t csize = 0;
#ifdef USE_BRK
if (brk_prev != (void *)-1) {
void *brk_cur;
intptr_t incr;
if (minsize != 0)
csize = CHUNK_CEILING(minsize);
malloc_mutex_lock(&brk_mtx);
do {
brk_cur = sbrk(0);
incr = (intptr_t)chunksize
- (intptr_t)CHUNK_ADDR2OFFSET(brk_cur);
assert(incr >= 0);
if ((size_t)incr < minsize)
incr += csize;
brk_prev = sbrk(incr);
if (brk_prev == brk_cur) {
malloc_mutex_unlock(&brk_mtx);
base_pages = brk_cur;
base_next_addr = base_pages;
base_past_addr = (void *)((uintptr_t)base_pages
+ incr);
#ifdef MALLOC_STATS
base_mapped += incr;
#endif
return (false);
}
} while (brk_prev != (void *)-1);
malloc_mutex_unlock(&brk_mtx);
}
if (minsize == 0) {
return (true);
}
#endif
assert(minsize != 0);
csize = PAGE_CEILING(minsize);
base_pages = pages_map(NULL, csize);
if (base_pages == NULL)
return (true);
base_next_addr = base_pages;
base_past_addr = (void *)((uintptr_t)base_pages + csize);
#ifdef MALLOC_STATS
base_mapped += csize;
#endif
return (false);
}
static void *
base_alloc(size_t size)
{
void *ret;
size_t csize;
csize = CACHELINE_CEILING(size);
malloc_mutex_lock(&base_mtx);
if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) {
if (base_pages_alloc(csize)) {
ret = NULL;
goto RETURN;
}
}
ret = base_next_addr;
base_next_addr = (void *)((uintptr_t)base_next_addr + csize);
RETURN:
malloc_mutex_unlock(&base_mtx);
return (ret);
}
static chunk_node_t *
base_chunk_node_alloc(void)
{
chunk_node_t *ret;
malloc_mutex_lock(&base_mtx);
if (base_chunk_nodes != NULL) {
ret = base_chunk_nodes;
base_chunk_nodes = *(chunk_node_t **)ret;
malloc_mutex_unlock(&base_mtx);
} else {
malloc_mutex_unlock(&base_mtx);
ret = (chunk_node_t *)base_alloc(sizeof(chunk_node_t));
}
return (ret);
}
static void
base_chunk_node_dealloc(chunk_node_t *node)
{
malloc_mutex_lock(&base_mtx);
*(chunk_node_t **)node = base_chunk_nodes;
base_chunk_nodes = node;
malloc_mutex_unlock(&base_mtx);
}
#ifdef MALLOC_STATS
static void
stats_print(arena_t *arena)
{
const unsigned minusone = (unsigned)-1;
unsigned i, gap_start;
malloc_printf(
" allocated/mapped nmalloc ndalloc\n");
malloc_printf("small: %12zu %-12s %12llu %12llu\n",
arena->stats.allocated_small, "", arena->stats.nmalloc_small,
arena->stats.ndalloc_small);
malloc_printf("large: %12zu %-12s %12llu %12llu\n",
arena->stats.allocated_large, "", arena->stats.nmalloc_large,
arena->stats.ndalloc_large);
malloc_printf("total: %12zu/%-12zu %12llu %12llu\n",
arena->stats.allocated_small + arena->stats.allocated_large,
arena->stats.mapped,
arena->stats.nmalloc_small + arena->stats.nmalloc_large,
arena->stats.ndalloc_small + arena->stats.ndalloc_large);
malloc_printf("bins: bin size regs pgs requests newruns"
" reruns maxruns curruns\n");
for (i = 0, gap_start = minusone; i < ntbins + nqbins + nsbins; i++) {
if (arena->bins[i].stats.nrequests == 0) {
if (gap_start == minusone)
gap_start = i;
} else {
if (gap_start != minusone) {
if (i > gap_start + 1) {
malloc_printf("[%u..%u]\n",
gap_start, i - 1);
} else {
malloc_printf("[%u]\n", gap_start);
}
gap_start = minusone;
}
malloc_printf(
"%13u %1s %4u %4u %3u %9llu %9llu"
" %9llu %7lu %7lu\n",
i,
i < ntbins ? "T" : i < ntbins + nqbins ? "Q" : "S",
arena->bins[i].reg_size,
arena->bins[i].nregs,
arena->bins[i].run_size >> pagesize_2pow,
arena->bins[i].stats.nrequests,
arena->bins[i].stats.nruns,
arena->bins[i].stats.reruns,
arena->bins[i].stats.highruns,
arena->bins[i].stats.curruns);
}
}
if (gap_start != minusone) {
if (i > gap_start + 1) {
malloc_printf("[%u..%u]\n", gap_start, i - 1);
} else {
malloc_printf("[%u]\n", gap_start);
}
}
}
#endif
static int
chunk_comp(void *context, const void *va, const void *vb)
{
const chunk_node_t *a = va, *b = vb;
assert(a != NULL);
assert(b != NULL);
return ptrcmp(a->chunk, b->chunk);
}
static void *
pages_map_align(void *addr, size_t size, int align)
{
void *ret;
ret = mmap(addr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_ALIGNED(align), -1, 0);
assert(ret != NULL);
if (ret == MAP_FAILED)
ret = NULL;
else if (addr != NULL && ret != addr) {
if (munmap(ret, size) == -1) {
char buf[STRERROR_BUF];
STRERROR_R(errno, buf, sizeof(buf));
_malloc_message(getprogname(),
": (malloc) Error in munmap(): ", buf, "\n");
if (OPT(abort))
abort();
}
ret = NULL;
}
assert(ret == NULL || (addr == NULL && ret != addr)
|| (addr != NULL && ret == addr));
return (ret);
}
static void *
pages_map(void *addr, size_t size)
{
return pages_map_align(addr, size, 0);
}
static void
pages_unmap(void *addr, size_t size)
{
if (munmap(addr, size) == -1) {
char buf[STRERROR_BUF];
STRERROR_R(errno, buf, sizeof(buf));
_malloc_message(getprogname(),
": (malloc) Error in munmap(): ", buf, "\n");
if (OPT(abort))
abort();
}
}
static void *
chunk_alloc(size_t size)
{
void *ret, *chunk;
chunk_node_t *tchunk, *delchunk;
assert(size != 0);
assert((size & chunksize_mask) == 0);
malloc_mutex_lock(&chunks_mtx);
if (size == chunksize) {
tchunk = RB_TREE_MIN(&old_chunks);
while (tchunk != NULL) {
chunk = tchunk->chunk;
delchunk = tchunk;
tchunk = RB_TREE_NEXT(&old_chunks, delchunk);
rb_tree_remove_node(&old_chunks, delchunk);
base_chunk_node_dealloc(delchunk);
#ifdef USE_BRK
if ((uintptr_t)chunk >= (uintptr_t)brk_base
&& (uintptr_t)chunk < (uintptr_t)brk_max) {
ret = chunk;
goto RETURN;
}
#endif
if ((ret = pages_map(chunk, size)) != NULL) {
goto RETURN;
}
}
}
if (size + chunksize > size) {
if ((ret = pages_map_align(NULL, size, chunksize_2pow))
!= NULL) {
goto RETURN;
}
}
#ifdef USE_BRK
if (brk_prev != (void *)-1) {
void *brk_cur;
intptr_t incr;
malloc_mutex_lock(&brk_mtx);
do {
brk_cur = sbrk(0);
incr = (intptr_t)size
- (intptr_t)CHUNK_ADDR2OFFSET(brk_cur);
if (incr == (intptr_t)size) {
ret = brk_cur;
} else {
ret = (void *)((intptr_t)brk_cur + incr);
incr += size;
}
brk_prev = sbrk(incr);
if (brk_prev == brk_cur) {
malloc_mutex_unlock(&brk_mtx);
brk_max = (void *)((intptr_t)ret + size);
goto RETURN;
}
} while (brk_prev != (void *)-1);
malloc_mutex_unlock(&brk_mtx);
}
#endif
ret = NULL;
RETURN:
if (ret != NULL) {
chunk_node_t key;
key.chunk = ret;
tchunk = rb_tree_find_node_geq(&old_chunks, &key);
while (tchunk != NULL
&& (uintptr_t)tchunk->chunk >= (uintptr_t)ret
&& (uintptr_t)tchunk->chunk < (uintptr_t)ret + size) {
delchunk = tchunk;
tchunk = RB_TREE_NEXT(&old_chunks, delchunk);
rb_tree_remove_node(&old_chunks, delchunk);
base_chunk_node_dealloc(delchunk);
}
}
#ifdef MALLOC_STATS
if (ret != NULL) {
stats_chunks.nchunks += (size / chunksize);
stats_chunks.curchunks += (size / chunksize);
}
if (stats_chunks.curchunks > stats_chunks.highchunks)
stats_chunks.highchunks = stats_chunks.curchunks;
#endif
malloc_mutex_unlock(&chunks_mtx);
assert(CHUNK_ADDR2BASE(ret) == ret);
return (ret);
}
static void
chunk_dealloc(void *chunk, size_t size)
{
chunk_node_t *node;
assert(chunk != NULL);
assert(CHUNK_ADDR2BASE(chunk) == chunk);
assert(size != 0);
assert((size & chunksize_mask) == 0);
malloc_mutex_lock(&chunks_mtx);
#ifdef USE_BRK
if ((uintptr_t)chunk >= (uintptr_t)brk_base
&& (uintptr_t)chunk < (uintptr_t)brk_max) {
void *brk_cur;
malloc_mutex_lock(&brk_mtx);
brk_cur = sbrk(0);
if (brk_cur == brk_max
&& (void *)((uintptr_t)chunk + size) == brk_max
&& sbrk(-(intptr_t)size) == brk_max) {
malloc_mutex_unlock(&brk_mtx);
if (brk_prev == brk_max) {
brk_prev = (void *)((intptr_t)brk_max
- (intptr_t)size);
brk_max = brk_prev;
}
} else {
size_t offset;
malloc_mutex_unlock(&brk_mtx);
madvise(chunk, size, MADV_FREE);
for (offset = 0; offset < size; offset += chunksize) {
node = base_chunk_node_alloc();
if (node == NULL)
break;
node->chunk = (void *)((uintptr_t)chunk
+ (uintptr_t)offset);
node->size = chunksize;
rb_tree_insert_node(&old_chunks, node);
}
}
} else {
#endif
pages_unmap(chunk, size);
if (size == chunksize) {
node = base_chunk_node_alloc();
if (node != NULL) {
node->chunk = (void *)(uintptr_t)chunk;
node->size = chunksize;
rb_tree_insert_node(&old_chunks, node);
}
}
#ifdef USE_BRK
}
#endif
#ifdef MALLOC_STATS
stats_chunks.curchunks -= (size / chunksize);
#endif
malloc_mutex_unlock(&chunks_mtx);
}
static __noinline arena_t *
choose_arena_hard(void)
{
assert(arenas[0] != NULL);
malloc_mutex_lock(&arenas_mtx);
for (unsigned i = 1; i < ncpus; i++)
if (arenas[i] == NULL)
arenas[i] = arenas_extend();
malloc_mutex_unlock(&arenas_mtx);
return arenas[thr_curcpu()];
}
static inline arena_t *
choose_arena(void)
{
arena_t *arena;
arena = arenas[thr_curcpu()];
if (__predict_true(arena != NULL))
return arena;
return choose_arena_hard();
}
static int
arena_chunk_comp(void *context, const void *va, const void *vb)
{
const arena_chunk_t *a = va, *b = vb;
int diff;
assert(a != NULL);
assert(b != NULL);
if ((diff = a->max_frun_npages - b->max_frun_npages) != 0)
return diff;
return ptrcmp(a, b);
}
static int
arena_run_comp(void *context, const void *a, const void *b)
{
assert(a != NULL);
assert(b != NULL);
return ptrcmp(a, b);
}
static inline void *
arena_run_reg_alloc(arena_run_t *run, arena_bin_t *bin)
{
void *ret;
unsigned i, mask, bit, regind;
assert(run->magic == ARENA_RUN_MAGIC);
assert(run->regs_minelm < bin->regs_mask_nelms);
i = run->regs_minelm;
mask = run->regs_mask[i];
if (mask != 0) {
bit = ffs((int)mask) - 1;
regind = ((i << (SIZEOF_INT_2POW + 3)) + bit);
ret = (void *)(((uintptr_t)run) + bin->reg0_offset
+ (bin->reg_size * regind));
mask ^= (1U << bit);
run->regs_mask[i] = mask;
return (ret);
}
for (i++; i < bin->regs_mask_nelms; i++) {
mask = run->regs_mask[i];
if (mask != 0) {
bit = ffs((int)mask) - 1;
regind = ((i << (SIZEOF_INT_2POW + 3)) + bit);
ret = (void *)(((uintptr_t)run) + bin->reg0_offset
+ (bin->reg_size * regind));
mask ^= (1U << bit);
run->regs_mask[i] = mask;
run->regs_minelm = i;
return (ret);
}
}
assert(0);
return (NULL);
}
static inline void
arena_run_reg_dalloc(arena_run_t *run, arena_bin_t *bin, void *ptr, size_t size)
{
#define SIZE_INV_SHIFT 21
#define SIZE_INV(s) (((1 << SIZE_INV_SHIFT) / (s << QUANTUM_2POW_MIN)) + 1)
static const unsigned size_invs[] = {
SIZE_INV(3),
SIZE_INV(4), SIZE_INV(5), SIZE_INV(6), SIZE_INV(7),
SIZE_INV(8), SIZE_INV(9), SIZE_INV(10), SIZE_INV(11),
SIZE_INV(12),SIZE_INV(13), SIZE_INV(14), SIZE_INV(15),
SIZE_INV(16),SIZE_INV(17), SIZE_INV(18), SIZE_INV(19),
SIZE_INV(20),SIZE_INV(21), SIZE_INV(22), SIZE_INV(23),
SIZE_INV(24),SIZE_INV(25), SIZE_INV(26), SIZE_INV(27),
SIZE_INV(28),SIZE_INV(29), SIZE_INV(30), SIZE_INV(31)
#if (QUANTUM_2POW_MIN < 4)
,
SIZE_INV(32), SIZE_INV(33), SIZE_INV(34), SIZE_INV(35),
SIZE_INV(36), SIZE_INV(37), SIZE_INV(38), SIZE_INV(39),
SIZE_INV(40), SIZE_INV(41), SIZE_INV(42), SIZE_INV(43),
SIZE_INV(44), SIZE_INV(45), SIZE_INV(46), SIZE_INV(47),
SIZE_INV(48), SIZE_INV(49), SIZE_INV(50), SIZE_INV(51),
SIZE_INV(52), SIZE_INV(53), SIZE_INV(54), SIZE_INV(55),
SIZE_INV(56), SIZE_INV(57), SIZE_INV(58), SIZE_INV(59),
SIZE_INV(60), SIZE_INV(61), SIZE_INV(62), SIZE_INV(63)
#endif
};
unsigned diff, regind, elm, bit;
assert(run->magic == ARENA_RUN_MAGIC);
assert(((sizeof(size_invs)) / sizeof(unsigned)) + 3
>= (SMALL_MAX_DEFAULT >> QUANTUM_2POW_MIN));
diff = (unsigned)((uintptr_t)ptr - (uintptr_t)run - bin->reg0_offset);
if ((size & (size - 1)) == 0) {
static const unsigned char log2_table[] = {
0, 1, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7
};
if (size <= 128)
regind = (diff >> log2_table[size - 1]);
else if (size <= 32768)
regind = diff >> (8 + log2_table[(size >> 8) - 1]);
else {
regind = (unsigned)(diff / size);
}
} else if (size <= (((sizeof(size_invs) / sizeof(unsigned)) + 2)
<< QUANTUM_2POW_MIN)) {
regind = size_invs[(size >> QUANTUM_2POW_MIN) - 3] * diff;
regind >>= SIZE_INV_SHIFT;
} else {
regind = (unsigned)(diff / size);
};
assert(diff == regind * size);
assert(regind < bin->nregs);
elm = regind >> (SIZEOF_INT_2POW + 3);
if (elm < run->regs_minelm)
run->regs_minelm = elm;
bit = regind - (elm << (SIZEOF_INT_2POW + 3));
assert((run->regs_mask[elm] & (1U << bit)) == 0);
run->regs_mask[elm] |= (1U << bit);
#undef SIZE_INV
#undef SIZE_INV_SHIFT
}
static void
arena_run_split(arena_t *arena, arena_run_t *run, size_t size)
{
arena_chunk_t *chunk;
unsigned run_ind, map_offset, total_pages, need_pages, rem_pages;
unsigned i;
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk)
>> pagesize_2pow);
total_pages = chunk->map[run_ind].npages;
need_pages = (unsigned)(size >> pagesize_2pow);
assert(need_pages <= total_pages);
rem_pages = total_pages - need_pages;
map_offset = run_ind;
for (i = 0; i < need_pages; i++) {
chunk->map[map_offset + i].npages = need_pages;
chunk->map[map_offset + i].pos = i;
}
if (rem_pages > 0) {
map_offset += need_pages;
chunk->map[map_offset].npages = rem_pages;
chunk->map[map_offset].pos = POS_FREE;
chunk->map[map_offset + rem_pages - 1].npages = rem_pages;
chunk->map[map_offset + rem_pages - 1].pos = POS_FREE;
}
chunk->pages_used += need_pages;
}
static arena_chunk_t *
arena_chunk_alloc(arena_t *arena)
{
arena_chunk_t *chunk;
if (arena->spare != NULL) {
chunk = arena->spare;
arena->spare = NULL;
rb_tree_insert_node(&arena->chunks, chunk);
} else {
chunk = (arena_chunk_t *)chunk_alloc(chunksize);
if (chunk == NULL)
return (NULL);
#ifdef MALLOC_STATS
arena->stats.mapped += chunksize;
#endif
chunk->arena = arena;
chunk->pages_used = 0;
chunk->max_frun_npages = chunk_npages -
arena_chunk_header_npages;
chunk->min_frun_ind = arena_chunk_header_npages;
chunk->map[arena_chunk_header_npages].npages = chunk_npages -
arena_chunk_header_npages;
chunk->map[arena_chunk_header_npages].pos = POS_FREE;
chunk->map[chunk_npages - 1].npages = chunk_npages -
arena_chunk_header_npages;
chunk->map[chunk_npages - 1].pos = POS_FREE;
rb_tree_insert_node(&arena->chunks, chunk);
}
return (chunk);
}
static void
arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk)
{
rb_tree_remove_node(&chunk->arena->chunks, chunk);
if (NOT_OPT(hint)) {
if (arena->spare != NULL) {
chunk_dealloc((void *)arena->spare, chunksize);
#ifdef MALLOC_STATS
arena->stats.mapped -= chunksize;
#endif
}
arena->spare = chunk;
} else {
assert(arena->spare == NULL);
chunk_dealloc((void *)chunk, chunksize);
#ifdef MALLOC_STATS
arena->stats.mapped -= chunksize;
#endif
}
}
static arena_run_t *
arena_run_alloc(arena_t *arena, size_t size)
{
arena_chunk_t *chunk;
arena_run_t *run;
unsigned need_npages;
assert(size <= (chunksize - (arena_chunk_header_npages <<
pagesize_2pow)));
assert((size & pagesize_mask) == 0);
need_npages = (unsigned)(size >> pagesize_2pow);
for (;;) {
rb_node_t *node = arena->chunks.rbt_root;
chunk = NULL;
while (!RB_SENTINEL_P(node)) {
assert(offsetof(struct arena_chunk_s, link) == 0);
arena_chunk_t *chunk_tmp = (arena_chunk_t *)node;
if (chunk_tmp->max_frun_npages == need_npages) {
chunk = chunk_tmp;
break;
}
if (chunk_tmp->max_frun_npages < need_npages) {
node = node->rb_nodes[1];
continue;
}
chunk = chunk_tmp;
node = node->rb_nodes[0];
}
if (chunk == NULL)
break;
assert(need_npages <= chunk->max_frun_npages);
{
arena_chunk_map_t *mapelm;
unsigned i;
unsigned max_frun_npages = 0;
unsigned min_frun_ind = chunk_npages;
assert(chunk->min_frun_ind >=
arena_chunk_header_npages);
for (i = chunk->min_frun_ind; i < chunk_npages;) {
mapelm = &chunk->map[i];
if (mapelm->pos == POS_FREE) {
if (mapelm->npages >= need_npages) {
run = (arena_run_t *)
((uintptr_t)chunk + (i <<
pagesize_2pow));
arena_run_split(arena, run,
size);
return (run);
}
if (mapelm->npages >
max_frun_npages) {
max_frun_npages =
mapelm->npages;
}
if (i < min_frun_ind) {
min_frun_ind = i;
if (i < chunk->min_frun_ind)
chunk->min_frun_ind = i;
}
}
i += mapelm->npages;
}
rb_tree_remove_node(&arena->chunks, chunk);
chunk->max_frun_npages = max_frun_npages;
rb_tree_insert_node(&arena->chunks, chunk);
}
}
chunk = arena_chunk_alloc(arena);
if (chunk == NULL)
return (NULL);
run = (arena_run_t *)((uintptr_t)chunk + (arena_chunk_header_npages <<
pagesize_2pow));
arena_run_split(arena, run, size);
return (run);
}
static void
arena_run_dalloc(arena_t *arena, arena_run_t *run, size_t size)
{
arena_chunk_t *chunk;
unsigned run_ind, run_pages;
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk)
>> pagesize_2pow);
assert(run_ind >= arena_chunk_header_npages);
assert(run_ind < (chunksize >> pagesize_2pow));
run_pages = (unsigned)(size >> pagesize_2pow);
assert(run_pages == chunk->map[run_ind].npages);
chunk->pages_used -= run_pages;
assert(chunk->map[run_ind].npages == run_pages);
chunk->map[run_ind].pos = POS_FREE;
assert(chunk->map[run_ind + run_pages - 1].npages == run_pages);
chunk->map[run_ind + run_pages - 1].pos = POS_FREE;
if (OPT(hint))
madvise(run, size, MADV_FREE);
if (run_ind > arena_chunk_header_npages &&
chunk->map[run_ind - 1].pos == POS_FREE) {
unsigned prev_npages;
prev_npages = chunk->map[run_ind - 1].npages;
run_ind -= prev_npages;
assert(chunk->map[run_ind].npages == prev_npages);
assert(chunk->map[run_ind].pos == POS_FREE);
run_pages += prev_npages;
chunk->map[run_ind].npages = run_pages;
assert(chunk->map[run_ind].pos == POS_FREE);
chunk->map[run_ind + run_pages - 1].npages = run_pages;
assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
}
if (run_ind + run_pages < chunk_npages &&
chunk->map[run_ind + run_pages].pos == POS_FREE) {
unsigned next_npages;
next_npages = chunk->map[run_ind + run_pages].npages;
run_pages += next_npages;
assert(chunk->map[run_ind + run_pages - 1].npages ==
next_npages);
assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
chunk->map[run_ind].npages = run_pages;
chunk->map[run_ind].pos = POS_FREE;
chunk->map[run_ind + run_pages - 1].npages = run_pages;
assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
}
if (chunk->map[run_ind].npages > chunk->max_frun_npages) {
rb_tree_remove_node(&arena->chunks, chunk);
chunk->max_frun_npages = chunk->map[run_ind].npages;
rb_tree_insert_node(&arena->chunks, chunk);
}
if (run_ind < chunk->min_frun_ind)
chunk->min_frun_ind = run_ind;
if (chunk->pages_used == 0)
arena_chunk_dealloc(arena, chunk);
}
static arena_run_t *
arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin)
{
arena_run_t *run;
unsigned i, remainder;
if ((run = RB_TREE_MIN(&bin->runs)) != NULL) {
rb_tree_remove_node(&bin->runs, run);
#ifdef MALLOC_STATS
bin->stats.reruns++;
#endif
return (run);
}
run = arena_run_alloc(arena, bin->run_size);
if (run == NULL)
return (NULL);
run->bin = bin;
for (i = 0; i < bin->regs_mask_nelms; i++)
run->regs_mask[i] = UINT_MAX;
remainder = bin->nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1);
if (remainder != 0) {
run->regs_mask[i] = (UINT_MAX >> ((1 << (SIZEOF_INT_2POW + 3))
- remainder));
}
run->regs_minelm = 0;
run->nfree = bin->nregs;
#ifdef MALLOC_DEBUG
run->magic = ARENA_RUN_MAGIC;
#endif
#ifdef MALLOC_STATS
bin->stats.nruns++;
bin->stats.curruns++;
if (bin->stats.curruns > bin->stats.highruns)
bin->stats.highruns = bin->stats.curruns;
#endif
return (run);
}
static inline void *
arena_bin_malloc_easy(arena_t *arena, arena_bin_t *bin, arena_run_t *run)
{
void *ret;
assert(run->magic == ARENA_RUN_MAGIC);
assert(run->nfree > 0);
ret = arena_run_reg_alloc(run, bin);
assert(ret != NULL);
run->nfree--;
return (ret);
}
static void *
arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin)
{
bin->runcur = arena_bin_nonfull_run_get(arena, bin);
if (bin->runcur == NULL)
return (NULL);
assert(bin->runcur->magic == ARENA_RUN_MAGIC);
assert(bin->runcur->nfree > 0);
return (arena_bin_malloc_easy(arena, bin, bin->runcur));
}
static size_t
arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size)
{
size_t try_run_size, good_run_size;
unsigned good_nregs, good_mask_nelms, good_reg0_offset;
unsigned try_nregs, try_mask_nelms, try_reg0_offset;
assert(min_run_size >= pagesize);
assert(min_run_size <= arena_maxclass);
assert(min_run_size <= RUN_MAX_SMALL);
try_run_size = min_run_size;
try_nregs = (unsigned)(((try_run_size - sizeof(arena_run_t)) /
bin->reg_size) + 1);
do {
try_nregs--;
try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) +
((try_nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1)) ? 1 : 0);
try_reg0_offset = (unsigned)(try_run_size -
(try_nregs * bin->reg_size));
} while (sizeof(arena_run_t) + (sizeof(unsigned) * (try_mask_nelms - 1))
> try_reg0_offset);
do {
good_run_size = try_run_size;
good_nregs = try_nregs;
good_mask_nelms = try_mask_nelms;
good_reg0_offset = try_reg0_offset;
try_run_size += pagesize;
try_nregs = (unsigned)(((try_run_size - sizeof(arena_run_t)) /
bin->reg_size) + 1);
do {
try_nregs--;
try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) +
((try_nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1)) ?
1 : 0);
try_reg0_offset = (unsigned)(try_run_size - (try_nregs *
bin->reg_size));
} while (sizeof(arena_run_t) + (sizeof(unsigned) *
(try_mask_nelms - 1)) > try_reg0_offset);
} while (try_run_size <= arena_maxclass && try_run_size <= RUN_MAX_SMALL
&& RUN_MAX_OVRHD * (bin->reg_size << 3) > RUN_MAX_OVRHD_RELAX
&& (try_reg0_offset << RUN_BFP) > RUN_MAX_OVRHD * try_run_size);
assert(sizeof(arena_run_t) + (sizeof(unsigned) * (good_mask_nelms - 1))
<= good_reg0_offset);
assert((good_mask_nelms << (SIZEOF_INT_2POW + 3)) >= good_nregs);
bin->run_size = good_run_size;
bin->nregs = good_nregs;
bin->regs_mask_nelms = good_mask_nelms;
bin->reg0_offset = good_reg0_offset;
return (good_run_size);
}
static void *
arena_malloc(arena_t *arena, size_t size)
{
void *ret;
assert(arena != NULL);
assert(arena->magic == ARENA_MAGIC);
assert(size != 0);
assert(QUANTUM_CEILING(size) <= arena_maxclass);
if (size <= bin_maxclass) {
arena_bin_t *bin;
arena_run_t *run;
if (size < small_min) {
size = pow2_ceil(size);
bin = &arena->bins[ffs((int)(size >> (TINY_MIN_2POW +
1)))];
#if (!defined(NDEBUG) || defined(MALLOC_STATS))
if (size < (1 << TINY_MIN_2POW))
size = (1 << TINY_MIN_2POW);
#endif
} else if (size <= small_max) {
size = QUANTUM_CEILING(size);
bin = &arena->bins[ntbins + (size >> opt_quantum_2pow)
- 1];
} else {
size = pow2_ceil(size);
bin = &arena->bins[ntbins + nqbins
+ (ffs((int)(size >> opt_small_max_2pow)) - 2)];
}
assert(size == bin->reg_size);
malloc_mutex_lock(&arena->mtx);
if ((run = bin->runcur) != NULL && run->nfree > 0)
ret = arena_bin_malloc_easy(arena, bin, run);
else
ret = arena_bin_malloc_hard(arena, bin);
if (ret == NULL) {
malloc_mutex_unlock(&arena->mtx);
return (NULL);
}
#ifdef MALLOC_STATS
bin->stats.nrequests++;
arena->stats.nmalloc_small++;
arena->stats.allocated_small += size;
#endif
} else {
size = PAGE_CEILING(size);
malloc_mutex_lock(&arena->mtx);
ret = (void *)arena_run_alloc(arena, size);
if (ret == NULL) {
malloc_mutex_unlock(&arena->mtx);
return (NULL);
}
#ifdef MALLOC_STATS
arena->stats.nmalloc_large++;
arena->stats.allocated_large += size;
#endif
}
malloc_mutex_unlock(&arena->mtx);
if (OPT(junk))
memset(ret, 0xa5, size);
else if (OPT(zero))
memset(ret, 0, size);
return (ret);
}
static inline void
arena_palloc_trim(arena_t *arena, arena_chunk_t *chunk, unsigned pageind,
unsigned npages)
{
unsigned i;
assert(npages > 0);
for (i = 0; i < npages; i++) {
chunk->map[pageind + i].npages = npages;
chunk->map[pageind + i].pos = i;
}
arena_run_dalloc(arena, (arena_run_t *)((uintptr_t)chunk + (pageind <<
pagesize_2pow)), npages << pagesize_2pow);
}
static void *
arena_palloc(arena_t *arena, size_t alignment, size_t size, size_t alloc_size)
{
void *ret;
size_t offset;
arena_chunk_t *chunk;
unsigned pageind, i, npages;
assert((size & pagesize_mask) == 0);
assert((alignment & pagesize_mask) == 0);
npages = (unsigned)(size >> pagesize_2pow);
malloc_mutex_lock(&arena->mtx);
ret = (void *)arena_run_alloc(arena, alloc_size);
if (ret == NULL) {
malloc_mutex_unlock(&arena->mtx);
return (NULL);
}
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret);
offset = (uintptr_t)ret & (alignment - 1);
assert((offset & pagesize_mask) == 0);
assert(offset < alloc_size);
if (offset == 0) {
pageind = (unsigned)(((uintptr_t)ret - (uintptr_t)chunk) >>
pagesize_2pow);
for (i = 0; i < npages; i++) {
chunk->map[pageind + i].npages = npages;
assert(chunk->map[pageind + i].pos == i);
}
arena_palloc_trim(arena, chunk, pageind + npages,
(unsigned)((alloc_size - size) >> pagesize_2pow));
} else {
size_t leadsize, trailsize;
leadsize = alignment - offset;
ret = (void *)((uintptr_t)ret + leadsize);
pageind = (unsigned)(((uintptr_t)ret - (uintptr_t)chunk) >>
pagesize_2pow);
for (i = 0; i < npages; i++) {
chunk->map[pageind + i].npages = npages;
chunk->map[pageind + i].pos = i;
}
arena_palloc_trim(arena, chunk,
(unsigned)(pageind - (leadsize >> pagesize_2pow)),
(unsigned)(leadsize >> pagesize_2pow));
trailsize = alloc_size - leadsize - size;
if (trailsize != 0) {
assert(trailsize < alloc_size);
arena_palloc_trim(arena, chunk, pageind + npages,
(unsigned)(trailsize >> pagesize_2pow));
}
}
#ifdef MALLOC_STATS
arena->stats.nmalloc_large++;
arena->stats.allocated_large += size;
#endif
malloc_mutex_unlock(&arena->mtx);
if (OPT(junk))
memset(ret, 0xa5, size);
else if (OPT(zero))
memset(ret, 0, size);
return (ret);
}
static size_t
arena_salloc(const void *ptr)
{
size_t ret;
arena_chunk_t *chunk;
arena_chunk_map_t *mapelm;
unsigned pageind;
assert(ptr != NULL);
assert(CHUNK_ADDR2BASE(ptr) != ptr);
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
pageind = (unsigned)(((uintptr_t)ptr - (uintptr_t)chunk) >>
pagesize_2pow);
mapelm = &chunk->map[pageind];
if (mapelm->pos != 0 || ptr != (char *)((uintptr_t)chunk) + (pageind <<
pagesize_2pow)) {
arena_run_t *run;
pageind -= mapelm->pos;
run = (arena_run_t *)((uintptr_t)chunk + (pageind <<
pagesize_2pow));
assert(run->magic == ARENA_RUN_MAGIC);
ret = run->bin->reg_size;
} else
ret = mapelm->npages << pagesize_2pow;
return (ret);
}
static void *
arena_ralloc(void *ptr, size_t size, size_t oldsize)
{
void *ret;
if (size < small_min) {
if (oldsize < small_min &&
ffs((int)(pow2_ceil(size) >> (TINY_MIN_2POW + 1)))
== ffs((int)(pow2_ceil(oldsize) >> (TINY_MIN_2POW + 1))))
goto IN_PLACE;
} else if (size <= small_max) {
if (oldsize >= small_min && oldsize <= small_max &&
(QUANTUM_CEILING(size) >> opt_quantum_2pow)
== (QUANTUM_CEILING(oldsize) >> opt_quantum_2pow))
goto IN_PLACE;
} else {
if (oldsize > small_max && PAGE_CEILING(size) == oldsize)
goto IN_PLACE;
}
ret = arena_malloc(choose_arena(), size);
if (ret == NULL)
return (NULL);
if (size < oldsize)
memcpy(ret, ptr, size);
else
memcpy(ret, ptr, oldsize);
idalloc(ptr);
return (ret);
IN_PLACE:
if (OPT(junk) && size < oldsize)
memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - size);
else if (OPT(zero) && size > oldsize)
memset((void *)((uintptr_t)ptr + oldsize), 0, size - oldsize);
return (ptr);
}
static void
arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr)
{
unsigned pageind;
arena_chunk_map_t *mapelm;
size_t size;
assert(arena != NULL);
assert(arena->magic == ARENA_MAGIC);
assert(chunk->arena == arena);
assert(ptr != NULL);
assert(CHUNK_ADDR2BASE(ptr) != ptr);
pageind = (unsigned)(((uintptr_t)ptr - (uintptr_t)chunk) >>
pagesize_2pow);
mapelm = &chunk->map[pageind];
if (mapelm->pos != 0 || ptr != (char *)((uintptr_t)chunk) + (pageind <<
pagesize_2pow)) {
arena_run_t *run;
arena_bin_t *bin;
pageind -= mapelm->pos;
run = (arena_run_t *)((uintptr_t)chunk + (pageind <<
pagesize_2pow));
assert(run->magic == ARENA_RUN_MAGIC);
bin = run->bin;
size = bin->reg_size;
if (OPT(junk))
memset(ptr, 0x5a, size);
malloc_mutex_lock(&arena->mtx);
arena_run_reg_dalloc(run, bin, ptr, size);
run->nfree++;
if (run->nfree == bin->nregs) {
if (run == bin->runcur)
bin->runcur = NULL;
else if (bin->nregs != 1) {
rb_tree_remove_node(&bin->runs, run);
}
#ifdef MALLOC_DEBUG
run->magic = 0;
#endif
arena_run_dalloc(arena, run, bin->run_size);
#ifdef MALLOC_STATS
bin->stats.curruns--;
#endif
} else if (run->nfree == 1 && run != bin->runcur) {
if (bin->runcur == NULL)
bin->runcur = run;
else if ((uintptr_t)run < (uintptr_t)bin->runcur) {
if (bin->runcur->nfree > 0) {
rb_tree_insert_node(&bin->runs, bin->runcur);
}
bin->runcur = run;
} else {
rb_tree_insert_node(&bin->runs, run);
}
}
#ifdef MALLOC_STATS
arena->stats.allocated_small -= size;
arena->stats.ndalloc_small++;
#endif
} else {
size = mapelm->npages << pagesize_2pow;
assert((((uintptr_t)ptr) & pagesize_mask) == 0);
if (OPT(junk))
memset(ptr, 0x5a, size);
malloc_mutex_lock(&arena->mtx);
arena_run_dalloc(arena, (arena_run_t *)ptr, size);
#ifdef MALLOC_STATS
arena->stats.allocated_large -= size;
arena->stats.ndalloc_large++;
#endif
}
malloc_mutex_unlock(&arena->mtx);
}
static void
arena_new(arena_t *arena)
{
unsigned i;
arena_bin_t *bin;
size_t prev_run_size;
malloc_mutex_init(&arena->mtx);
#ifdef MALLOC_STATS
memset(&arena->stats, 0, sizeof(arena_stats_t));
#endif
rb_tree_init(&arena->chunks, &arena_chunk_tree_ops);
arena->spare = NULL;
prev_run_size = pagesize;
for (i = 0; i < ntbins; i++) {
bin = &arena->bins[i];
bin->runcur = NULL;
rb_tree_init(&bin->runs, &arena_run_tree_ops);
bin->reg_size = (1 << (TINY_MIN_2POW + i));
prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
#ifdef MALLOC_STATS
memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
#endif
}
for (; i < ntbins + nqbins; i++) {
bin = &arena->bins[i];
bin->runcur = NULL;
rb_tree_init(&bin->runs, &arena_run_tree_ops);
bin->reg_size = quantum * (i - ntbins + 1);
prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
#ifdef MALLOC_STATS
memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
#endif
}
for (; i < ntbins + nqbins + nsbins; i++) {
bin = &arena->bins[i];
bin->runcur = NULL;
rb_tree_init(&bin->runs, &arena_run_tree_ops);
bin->reg_size = (small_max << (i - (ntbins + nqbins) + 1));
prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
#ifdef MALLOC_STATS
memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
#endif
}
#ifdef MALLOC_DEBUG
arena->magic = ARENA_MAGIC;
#endif
}
static arena_t *
arenas_extend(void)
{
arena_t *ret;
ret = (arena_t *)base_alloc(sizeof(arena_t)
+ (sizeof(arena_bin_t) * (ntbins + nqbins + nsbins - 1)));
if (ret != NULL) {
arena_new(ret);
return (ret);
}
_malloc_message(getprogname(),
": (malloc) Error initializing arena\n", "", "");
if (OPT(abort))
abort();
return (arenas[0]);
}
static void *
huge_malloc(size_t size)
{
void *ret;
size_t csize;
chunk_node_t *node;
csize = CHUNK_CEILING(size);
if (csize == 0) {
return (NULL);
}
node = base_chunk_node_alloc();
if (node == NULL)
return (NULL);
ret = chunk_alloc(csize);
if (ret == NULL) {
base_chunk_node_dealloc(node);
return (NULL);
}
node->chunk = ret;
node->size = csize;
malloc_mutex_lock(&chunks_mtx);
rb_tree_insert_node(&huge, node);
#ifdef MALLOC_STATS
huge_nmalloc++;
huge_allocated += csize;
#endif
malloc_mutex_unlock(&chunks_mtx);
if (OPT(junk))
memset(ret, 0xa5, csize);
else if (OPT(zero))
memset(ret, 0, csize);
return (ret);
}
static void *
huge_palloc(size_t alignment, size_t size)
{
void *ret;
size_t alloc_size, chunk_size, offset;
chunk_node_t *node;
assert(alignment >= chunksize);
chunk_size = CHUNK_CEILING(size);
if (size >= alignment)
alloc_size = chunk_size + alignment - chunksize;
else
alloc_size = (alignment << 1) - chunksize;
node = base_chunk_node_alloc();
if (node == NULL)
return (NULL);
ret = chunk_alloc(alloc_size);
if (ret == NULL) {
base_chunk_node_dealloc(node);
return (NULL);
}
offset = (uintptr_t)ret & (alignment - 1);
assert((offset & chunksize_mask) == 0);
assert(offset < alloc_size);
if (offset == 0) {
chunk_dealloc((void *)((uintptr_t)ret + chunk_size), alloc_size
- chunk_size);
} else {
size_t trailsize;
chunk_dealloc(ret, alignment - offset);
ret = (void *)((uintptr_t)ret + (alignment - offset));
trailsize = alloc_size - (alignment - offset) - chunk_size;
if (trailsize != 0) {
assert(trailsize < alloc_size);
chunk_dealloc((void *)((uintptr_t)ret + chunk_size),
trailsize);
}
}
node->chunk = ret;
node->size = chunk_size;
malloc_mutex_lock(&chunks_mtx);
rb_tree_insert_node(&huge, node);
#ifdef MALLOC_STATS
huge_nmalloc++;
huge_allocated += chunk_size;
#endif
malloc_mutex_unlock(&chunks_mtx);
if (OPT(junk))
memset(ret, 0xa5, chunk_size);
else if (OPT(zero))
memset(ret, 0, chunk_size);
return (ret);
}
static void *
huge_ralloc(void *ptr, size_t size, size_t oldsize)
{
void *ret;
if (oldsize > arena_maxclass &&
CHUNK_CEILING(size) == CHUNK_CEILING(oldsize)) {
if (OPT(junk) && size < oldsize) {
memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize
- size);
} else if (OPT(zero) && size > oldsize) {
memset((void *)((uintptr_t)ptr + oldsize), 0, size
- oldsize);
}
return (ptr);
}
if (CHUNK_ADDR2BASE(ptr) == ptr
#ifdef USE_BRK
&& ((uintptr_t)ptr < (uintptr_t)brk_base
|| (uintptr_t)ptr >= (uintptr_t)brk_max)
#endif
) {
chunk_node_t *node, key;
void *newptr;
size_t oldcsize;
size_t newcsize;
newcsize = CHUNK_CEILING(size);
oldcsize = CHUNK_CEILING(oldsize);
assert(oldcsize != newcsize);
if (newcsize == 0) {
return (NULL);
}
malloc_mutex_lock(&chunks_mtx);
key.chunk = __UNCONST(ptr);
node = rb_tree_find_node(&huge, &key);
assert(node != NULL);
assert(node->chunk == ptr);
assert(node->size == oldcsize);
rb_tree_remove_node(&huge, node);
malloc_mutex_unlock(&chunks_mtx);
newptr = mremap(ptr, oldcsize, NULL, newcsize,
MAP_ALIGNED(chunksize_2pow));
if (newptr == MAP_FAILED) {
malloc_mutex_lock(&chunks_mtx);
rb_tree_insert_node(&huge, node);
malloc_mutex_unlock(&chunks_mtx);
} else {
assert(CHUNK_ADDR2BASE(newptr) == newptr);
malloc_mutex_lock(&chunks_mtx);
node->size = newcsize;
node->chunk = newptr;
rb_tree_insert_node(&huge, node);
#ifdef MALLOC_STATS
huge_nralloc++;
huge_allocated += newcsize - oldcsize;
if (newcsize > oldcsize) {
stats_chunks.curchunks +=
(newcsize - oldcsize) / chunksize;
if (stats_chunks.curchunks >
stats_chunks.highchunks)
stats_chunks.highchunks =
stats_chunks.curchunks;
} else {
stats_chunks.curchunks -=
(oldcsize - newcsize) / chunksize;
}
#endif
malloc_mutex_unlock(&chunks_mtx);
if (OPT(junk) && size < oldsize) {
memset((void *)((uintptr_t)newptr + size), 0x5a,
newcsize - size);
} else if (OPT(zero) && size > oldsize) {
memset((void *)((uintptr_t)newptr + oldsize), 0,
size - oldsize);
}
return (newptr);
}
}
ret = huge_malloc(size);
if (ret == NULL)
return (NULL);
if (CHUNK_ADDR2BASE(ptr) == ptr) {
if (size < oldsize)
memcpy(ret, ptr, size);
else
memcpy(ret, ptr, oldsize);
} else {
assert(oldsize < size);
memcpy(ret, ptr, oldsize);
}
idalloc(ptr);
return (ret);
}
static void
huge_dalloc(void *ptr)
{
chunk_node_t key;
chunk_node_t *node;
malloc_mutex_lock(&chunks_mtx);
key.chunk = ptr;
node = rb_tree_find_node(&huge, &key);
assert(node != NULL);
assert(node->chunk == ptr);
rb_tree_remove_node(&huge, node);
#ifdef MALLOC_STATS
huge_ndalloc++;
huge_allocated -= node->size;
#endif
malloc_mutex_unlock(&chunks_mtx);
#ifdef USE_BRK
if (OPT(junk))
memset(node->chunk, 0x5a, node->size);
#endif
chunk_dealloc(node->chunk, node->size);
base_chunk_node_dealloc(node);
}
static void *
imalloc(size_t size)
{
void *ret;
assert(size != 0);
if (size <= arena_maxclass)
ret = arena_malloc(choose_arena(), size);
else
ret = huge_malloc(size);
return (ret);
}
static void *
ipalloc(size_t alignment, size_t size)
{
void *ret;
size_t ceil_size;
ceil_size = (size + (alignment - 1)) & (-alignment);
if (ceil_size < size) {
return (NULL);
}
if (ceil_size <= pagesize || (alignment <= pagesize
&& ceil_size <= arena_maxclass))
ret = arena_malloc(choose_arena(), ceil_size);
else {
size_t run_size;
alignment = PAGE_CEILING(alignment);
ceil_size = PAGE_CEILING(size);
if (ceil_size < size || ceil_size + alignment < ceil_size) {
return (NULL);
}
if (ceil_size >= alignment)
run_size = ceil_size + alignment - pagesize;
else {
run_size = (alignment << 1) - pagesize;
}
if (run_size <= arena_maxclass) {
ret = arena_palloc(choose_arena(), alignment, ceil_size,
run_size);
} else if (alignment <= chunksize)
ret = huge_malloc(ceil_size);
else
ret = huge_palloc(alignment, ceil_size);
}
assert(((uintptr_t)ret & (alignment - 1)) == 0);
return (ret);
}
static void *
icalloc(size_t size)
{
void *ret;
if (size <= arena_maxclass) {
ret = arena_malloc(choose_arena(), size);
if (ret == NULL)
return (NULL);
memset(ret, 0, size);
} else {
ret = huge_malloc(size);
if (ret == NULL)
return (NULL);
if (OPT(junk))
memset(ret, 0, size);
#ifdef USE_BRK
else if ((uintptr_t)ret >= (uintptr_t)brk_base
&& (uintptr_t)ret < (uintptr_t)brk_max) {
memset(ret, 0, size);
}
#endif
}
return (ret);
}
static size_t
isalloc(const void *ptr)
{
size_t ret;
arena_chunk_t *chunk;
assert(ptr != NULL);
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
if (chunk != ptr) {
assert(chunk->arena->magic == ARENA_MAGIC);
ret = arena_salloc(ptr);
} else {
chunk_node_t *node, key;
malloc_mutex_lock(&chunks_mtx);
key.chunk = __UNCONST(ptr);
node = rb_tree_find_node(&huge, &key);
assert(node != NULL);
ret = node->size;
malloc_mutex_unlock(&chunks_mtx);
}
return (ret);
}
static void *
iralloc(void *ptr, size_t size)
{
void *ret;
size_t oldsize;
assert(ptr != NULL);
assert(size != 0);
oldsize = isalloc(ptr);
if (size <= arena_maxclass)
ret = arena_ralloc(ptr, size, oldsize);
else
ret = huge_ralloc(ptr, size, oldsize);
return (ret);
}
static void
idalloc(void *ptr)
{
arena_chunk_t *chunk;
assert(ptr != NULL);
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
if (chunk != ptr) {
arena_dalloc(chunk->arena, chunk, ptr);
} else
huge_dalloc(ptr);
}
static void
malloc_print_stats(void)
{
if (OPT(print_stats)) {
char s[UMAX2S_BUFSIZE];
_malloc_message("___ Begin malloc statistics ___\n", "", "",
"");
_malloc_message("Assertions ",
#ifdef NDEBUG
"disabled",
#else
"enabled",
#endif
"\n", "");
_malloc_message("Boolean MALLOC_OPTIONS: ",
opt_abort ? "A" : "a",
opt_junk ? "J" : "j",
opt_hint ? "H" : "h");
_malloc_message(OPT(utrace) ? "PU" : "Pu",
opt_sysv ? "V" : "v",
opt_xmalloc ? "X" : "x",
opt_zero ? "Z\n" : "z\n");
_malloc_message("CPUs: ", size_t2s(ncpus, s), "\n", "");
_malloc_message("Pointer size: ", size_t2s(sizeof(void *), s),
"\n", "");
_malloc_message("Quantum size: ", size_t2s(quantum, s), "\n", "");
_malloc_message("Max small size: ", size_t2s(small_max, s), "\n",
"");
_malloc_message("Chunk size: ", size_t2s(chunksize, s), "", "");
_malloc_message(" (2^", size_t2s((size_t)opt_chunk_2pow, s),
")\n", "");
#ifdef MALLOC_STATS
{
size_t allocated, mapped;
unsigned i;
arena_t *arena;
for (i = 0, allocated = 0; i < ncpus; i++) {
if (arenas[i] != NULL) {
malloc_mutex_lock(&arenas[i]->mtx);
allocated +=
arenas[i]->stats.allocated_small;
allocated +=
arenas[i]->stats.allocated_large;
malloc_mutex_unlock(&arenas[i]->mtx);
}
}
malloc_mutex_lock(&chunks_mtx);
allocated += huge_allocated;
mapped = stats_chunks.curchunks * chunksize;
malloc_mutex_unlock(&chunks_mtx);
malloc_mutex_lock(&base_mtx);
mapped += base_mapped;
malloc_mutex_unlock(&base_mtx);
malloc_printf("Allocated: %zu, mapped: %zu\n",
allocated, mapped);
{
chunk_stats_t chunks_stats;
malloc_mutex_lock(&chunks_mtx);
chunks_stats = stats_chunks;
malloc_mutex_unlock(&chunks_mtx);
malloc_printf("chunks: nchunks "
"highchunks curchunks\n");
malloc_printf(" %13llu%13lu%13lu\n",
chunks_stats.nchunks,
chunks_stats.highchunks,
chunks_stats.curchunks);
}
malloc_printf(
"huge: nmalloc ndalloc "
"nralloc allocated\n");
malloc_printf(" %12llu %12llu %12llu %12zu\n",
huge_nmalloc, huge_ndalloc, huge_nralloc,
huge_allocated);
for (i = 0; i < ncpus; i++) {
arena = arenas[i];
if (arena != NULL) {
malloc_printf(
"\narenas[%u] @ %p\n", i, arena);
malloc_mutex_lock(&arena->mtx);
stats_print(arena);
malloc_mutex_unlock(&arena->mtx);
}
}
}
#endif
_malloc_message("--- End malloc statistics ---\n", "", "", "");
}
}
static inline bool
malloc_init(void)
{
if (__predict_false(malloc_initialized == false))
return (malloc_init_hard());
return (false);
}
static bool
malloc_init_hard(void)
{
unsigned i, j;
ssize_t linklen;
char buf[PATH_MAX + 1];
const char *opts = "";
int serrno;
malloc_mutex_lock(&init_lock);
if (malloc_initialized) {
malloc_mutex_unlock(&init_lock);
return (false);
}
serrno = errno;
{
int mib[2];
size_t len;
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpus);
if (sysctl(mib, 2, &ncpus, &len, (void *) 0, 0) == -1) {
ncpus = 1;
}
}
{
long result;
result = getpagesize();
assert(result != -1);
pagesize = (unsigned) result;
assert(((result - 1) & result) == 0);
pagesize_mask = result - 1;
pagesize_2pow = ffs((int)result) - 1;
}
for (i = 0; i < 3; i++) {
switch (i) {
case 0:
if ((linklen = readlink("/etc/malloc.conf", buf,
sizeof(buf) - 1)) != -1) {
buf[linklen] = '\0';
opts = buf;
} else {
buf[0] = '\0';
opts = buf;
}
break;
case 1:
if ((opts = getenv("MALLOC_OPTIONS")) != NULL &&
issetugid() == 0) {
} else {
buf[0] = '\0';
opts = buf;
}
break;
case 2:
if (_malloc_options != NULL) {
opts = _malloc_options;
} else {
buf[0] = '\0';
opts = buf;
}
break;
default:
assert(false);
}
for (j = 0; opts[j] != '\0'; j++) {
switch (opts[j]) {
case 'a':
opt_abort = false;
break;
case 'A':
opt_abort = true;
break;
case 'h':
opt_hint = false;
break;
case 'H':
opt_hint = true;
break;
case 'j':
opt_junk = false;
break;
case 'J':
opt_junk = true;
break;
case 'k':
if (opt_chunk_2pow > pagesize_2pow + 1)
opt_chunk_2pow--;
break;
case 'K':
if (opt_chunk_2pow + 1 <
(int)(sizeof(size_t) << 3))
opt_chunk_2pow++;
break;
case 'p':
opt_print_stats = false;
break;
case 'P':
opt_print_stats = true;
break;
case 'q':
if (opt_quantum_2pow > QUANTUM_2POW_MIN)
opt_quantum_2pow--;
break;
case 'Q':
if (opt_quantum_2pow < pagesize_2pow - 1)
opt_quantum_2pow++;
break;
case 's':
if (opt_small_max_2pow > QUANTUM_2POW_MIN)
opt_small_max_2pow--;
break;
case 'S':
if (opt_small_max_2pow < pagesize_2pow - 1)
opt_small_max_2pow++;
break;
case 'u':
opt_utrace = false;
break;
case 'U':
opt_utrace = true;
break;
case 'v':
opt_sysv = false;
break;
case 'V':
opt_sysv = true;
break;
case 'x':
opt_xmalloc = false;
break;
case 'X':
opt_xmalloc = true;
break;
case 'z':
opt_zero = false;
break;
case 'Z':
opt_zero = true;
break;
default: {
char cbuf[2];
cbuf[0] = opts[j];
cbuf[1] = '\0';
_malloc_message(getprogname(),
": (malloc) Unsupported character in "
"malloc options: '", cbuf, "'\n");
}
}
}
}
errno = serrno;
if (OPT(print_stats)) {
atexit(malloc_print_stats);
}
if (opt_small_max_2pow < opt_quantum_2pow)
opt_small_max_2pow = opt_quantum_2pow;
small_max = (1U << opt_small_max_2pow);
bin_maxclass = (pagesize >> 1);
assert(opt_quantum_2pow >= TINY_MIN_2POW);
ntbins = (unsigned)(opt_quantum_2pow - TINY_MIN_2POW);
assert(ntbins <= (unsigned)opt_quantum_2pow);
nqbins = (unsigned)(small_max >> opt_quantum_2pow);
nsbins = (unsigned)(pagesize_2pow - opt_small_max_2pow - 1);
quantum = (1 << opt_quantum_2pow);
quantum_mask = quantum - 1;
if (ntbins > 0)
small_min = (quantum >> 1) + 1;
else
small_min = 1;
assert(small_min <= quantum);
chunksize = (1LU << opt_chunk_2pow);
chunksize_mask = chunksize - 1;
chunksize_2pow = (unsigned)opt_chunk_2pow;
chunk_npages = (unsigned)(chunksize >> pagesize_2pow);
{
unsigned header_size;
header_size = (unsigned)(sizeof(arena_chunk_t) +
(sizeof(arena_chunk_map_t) * (chunk_npages - 1)));
arena_chunk_header_npages = (header_size >> pagesize_2pow);
if ((header_size & pagesize_mask) != 0)
arena_chunk_header_npages++;
}
arena_maxclass = chunksize - (arena_chunk_header_npages <<
pagesize_2pow);
UTRACE(0, 0, 0);
#ifdef MALLOC_STATS
memset(&stats_chunks, 0, sizeof(chunk_stats_t));
#endif
assert(quantum >= sizeof(void *));
assert(quantum <= pagesize);
assert(chunksize >= pagesize);
assert(quantum * 4 <= chunksize);
malloc_mutex_init(&chunks_mtx);
rb_tree_init(&huge, &chunk_tree_ops);
#ifdef USE_BRK
malloc_mutex_init(&brk_mtx);
brk_base = sbrk(0);
brk_prev = brk_base;
brk_max = brk_base;
#endif
#ifdef MALLOC_STATS
huge_nmalloc = 0;
huge_ndalloc = 0;
huge_nralloc = 0;
huge_allocated = 0;
#endif
rb_tree_init(&old_chunks, &chunk_tree_ops);
#ifdef MALLOC_STATS
base_mapped = 0;
#endif
#ifdef USE_BRK
base_pages_alloc(0);
#endif
base_chunk_nodes = NULL;
malloc_mutex_init(&base_mtx);
arenas = (arena_t **)base_alloc(sizeof(arena_t *) * ncpus);
if (arenas == NULL) {
malloc_mutex_unlock(&init_lock);
return (true);
}
memset(arenas, 0, sizeof(arena_t *) * ncpus);
if ((arenas[0] = arenas_extend()) == NULL) {
malloc_mutex_unlock(&init_lock);
return (true);
}
malloc_mutex_init(&arenas_mtx);
malloc_initialized = true;
malloc_mutex_unlock(&init_lock);
return (false);
}
void *
malloc(size_t size)
{
void *ret;
if (__predict_false(malloc_init())) {
ret = NULL;
goto RETURN;
}
if (__predict_false(size == 0)) {
if (NOT_OPT(sysv))
size = 1;
else {
ret = NULL;
goto RETURN;
}
}
ret = imalloc(size);
RETURN:
if (__predict_false(ret == NULL)) {
if (OPT(xmalloc)) {
_malloc_message(getprogname(),
": (malloc) Error in malloc(): out of memory\n", "",
"");
abort();
}
errno = ENOMEM;
}
UTRACE(0, size, ret);
return (ret);
}
int
posix_memalign(void **memptr, size_t alignment, size_t size)
{
int ret;
void *result;
if (__predict_false(malloc_init()))
result = NULL;
else {
if (((alignment - 1) & alignment) != 0
|| alignment < sizeof(void *)) {
if (OPT(xmalloc)) {
_malloc_message(getprogname(),
": (malloc) Error in posix_memalign(): "
"invalid alignment\n", "", "");
abort();
}
result = NULL;
ret = EINVAL;
goto RETURN;
}
if (size == 0) {
if (NOT_OPT(sysv))
size = 1;
else {
result = NULL;
ret = 0;
goto RETURN;
}
}
result = ipalloc(alignment, size);
}
if (__predict_false(result == NULL)) {
if (OPT(xmalloc)) {
_malloc_message(getprogname(),
": (malloc) Error in posix_memalign(): out of memory\n",
"", "");
abort();
}
ret = ENOMEM;
goto RETURN;
}
*memptr = result;
ret = 0;
RETURN:
UTRACE(0, size, result);
return (ret);
}
void *
calloc(size_t num, size_t size)
{
void *ret;
size_t num_size;
if (__predict_false(malloc_init())) {
num_size = 0;
ret = NULL;
goto RETURN;
}
num_size = num * size;
if (__predict_false(num_size == 0)) {
if (NOT_OPT(sysv) && ((num == 0) || (size == 0)))
num_size = 1;
else {
ret = NULL;
goto RETURN;
}
} else if ((unsigned long long)((num | size) &
((unsigned long long)SIZE_T_MAX << (sizeof(size_t) << 2))) &&
(num_size / size != num)) {
ret = NULL;
goto RETURN;
}
ret = icalloc(num_size);
RETURN:
if (__predict_false(ret == NULL)) {
if (OPT(xmalloc)) {
_malloc_message(getprogname(),
": (malloc) Error in calloc(): out of memory\n", "",
"");
abort();
}
errno = ENOMEM;
}
UTRACE(0, num_size, ret);
return (ret);
}
void *
realloc(void *ptr, size_t size)
{
void *ret;
if (__predict_false(size == 0)) {
if (NOT_OPT(sysv))
size = 1;
else {
if (ptr != NULL)
idalloc(ptr);
ret = NULL;
goto RETURN;
}
}
if (__predict_true(ptr != NULL)) {
assert(malloc_initialized);
ret = iralloc(ptr, size);
if (__predict_false(ret == NULL)) {
if (OPT(xmalloc)) {
_malloc_message(getprogname(),
": (malloc) Error in realloc(): out of "
"memory\n", "", "");
abort();
}
errno = ENOMEM;
}
} else {
if (__predict_false(malloc_init()))
ret = NULL;
else
ret = imalloc(size);
if (__predict_false(ret == NULL)) {
if (OPT(xmalloc)) {
_malloc_message(getprogname(),
": (malloc) Error in realloc(): out of "
"memory\n", "", "");
abort();
}
errno = ENOMEM;
}
}
RETURN:
UTRACE(ptr, size, ret);
return (ret);
}
void
free(void *ptr)
{
UTRACE(ptr, 0, 0);
if (__predict_true(ptr != NULL)) {
assert(malloc_initialized);
idalloc(ptr);
}
}
size_t
malloc_usable_size(const void *ptr)
{
assert(ptr != NULL);
return (isalloc(ptr));
}
void
_malloc_prefork(void)
{
unsigned i;
malloc_mutex_lock(&init_lock);
malloc_mutex_lock(&arenas_mtx);
for (i = 0; i < ncpus; i++) {
if (arenas[i] != NULL)
malloc_mutex_lock(&arenas[i]->mtx);
}
malloc_mutex_lock(&chunks_mtx);
malloc_mutex_lock(&base_mtx);
#ifdef USE_BRK
malloc_mutex_lock(&brk_mtx);
#endif
}
void
_malloc_postfork(void)
{
unsigned i;
#ifdef USE_BRK
malloc_mutex_unlock(&brk_mtx);
#endif
malloc_mutex_unlock(&base_mtx);
malloc_mutex_unlock(&chunks_mtx);
for (i = ncpus; i-- > 0; ) {
if (arenas[i] != NULL)
malloc_mutex_unlock(&arenas[i]->mtx);
}
malloc_mutex_unlock(&arenas_mtx);
malloc_mutex_unlock(&init_lock);
}
void
_malloc_postfork_child(void)
{
unsigned i;
#ifdef USE_BRK
malloc_mutex_init(&brk_mtx);
#endif
malloc_mutex_init(&base_mtx);
malloc_mutex_init(&chunks_mtx);
for (i = ncpus; i-- > 0; ) {
if (arenas[i] != NULL)
malloc_mutex_init(&arenas[i]->mtx);
}
malloc_mutex_init(&arenas_mtx);
malloc_mutex_init(&init_lock);
}