michael@0: /* -*- Mode: C; tab-width: 8; c-basic-offset: 8; indent-tabs-mode: t -*- */ michael@0: /* vim:set softtabstop=8 shiftwidth=8 noet: */ michael@0: /*- michael@0: * Copyright (C) 2006-2008 Jason Evans . michael@0: * All rights reserved. michael@0: * michael@0: * Redistribution and use in source and binary forms, with or without michael@0: * modification, are permitted provided that the following conditions michael@0: * are met: michael@0: * 1. Redistributions of source code must retain the above copyright michael@0: * notice(s), this list of conditions and the following disclaimer as michael@0: * the first lines of this file unmodified other than the possible michael@0: * addition of one or more copyright notices. michael@0: * 2. Redistributions in binary form must reproduce the above copyright michael@0: * notice(s), this list of conditions and the following disclaimer in michael@0: * the documentation and/or other materials provided with the michael@0: * distribution. michael@0: * michael@0: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY michael@0: * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE michael@0: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR michael@0: * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE michael@0: * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR michael@0: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF michael@0: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR michael@0: * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, michael@0: * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE michael@0: * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, michael@0: * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: * michael@0: ******************************************************************************* michael@0: * michael@0: * This allocator implementation is designed to provide scalable performance michael@0: * for multi-threaded programs on multi-processor systems. The following michael@0: * features are included for this purpose: michael@0: * michael@0: * + Multiple arenas are used if there are multiple CPUs, which reduces lock michael@0: * contention and cache sloshing. michael@0: * michael@0: * + Cache line sharing between arenas is avoided for internal data michael@0: * structures. michael@0: * michael@0: * + Memory is managed in chunks and runs (chunks can be split into runs), michael@0: * rather than as individual pages. This provides a constant-time michael@0: * mechanism for associating allocations with particular arenas. michael@0: * michael@0: * Allocation requests are rounded up to the nearest size class, and no record michael@0: * of the original request size is maintained. Allocations are broken into michael@0: * categories according to size class. Assuming runtime defaults, 4 kB pages michael@0: * and a 16 byte quantum on a 32-bit system, the size classes in each category michael@0: * are as follows: michael@0: * michael@0: * |=====================================| michael@0: * | Category | Subcategory | Size | michael@0: * |=====================================| michael@0: * | Small | Tiny | 2 | michael@0: * | | | 4 | michael@0: * | | | 8 | michael@0: * | |----------------+---------| michael@0: * | | Quantum-spaced | 16 | michael@0: * | | | 32 | michael@0: * | | | 48 | michael@0: * | | | ... | michael@0: * | | | 480 | michael@0: * | | | 496 | michael@0: * | | | 512 | michael@0: * | |----------------+---------| michael@0: * | | Sub-page | 1 kB | michael@0: * | | | 2 kB | michael@0: * |=====================================| michael@0: * | Large | 4 kB | michael@0: * | | 8 kB | michael@0: * | | 12 kB | michael@0: * | | ... | michael@0: * | | 1012 kB | michael@0: * | | 1016 kB | michael@0: * | | 1020 kB | michael@0: * |=====================================| michael@0: * | Huge | 1 MB | michael@0: * | | 2 MB | michael@0: * | | 3 MB | michael@0: * | | ... | michael@0: * |=====================================| michael@0: * michael@0: * NOTE: Due to Mozilla bug 691003, we cannot reserve less than one word for an michael@0: * allocation on Linux or Mac. So on 32-bit *nix, the smallest bucket size is michael@0: * 4 bytes, and on 64-bit, the smallest bucket size is 8 bytes. michael@0: * michael@0: * A different mechanism is used for each category: michael@0: * michael@0: * Small : Each size class is segregated into its own set of runs. Each run michael@0: * maintains a bitmap of which regions are free/allocated. michael@0: * michael@0: * Large : Each allocation is backed by a dedicated run. Metadata are stored michael@0: * in the associated arena chunk header maps. michael@0: * michael@0: * Huge : Each allocation is backed by a dedicated contiguous set of chunks. michael@0: * Metadata are stored in a separate red-black tree. michael@0: * michael@0: ******************************************************************************* michael@0: */ michael@0: michael@0: #ifdef MOZ_MEMORY_ANDROID michael@0: #define NO_TLS michael@0: #define _pthread_self() pthread_self() michael@0: #endif michael@0: michael@0: /* michael@0: * On Linux, we use madvise(MADV_DONTNEED) to release memory back to the michael@0: * operating system. If we release 1MB of live pages with MADV_DONTNEED, our michael@0: * RSS will decrease by 1MB (almost) immediately. michael@0: * michael@0: * On Mac, we use madvise(MADV_FREE). Unlike MADV_DONTNEED on Linux, MADV_FREE michael@0: * on Mac doesn't cause the OS to release the specified pages immediately; the michael@0: * OS keeps them in our process until the machine comes under memory pressure. michael@0: * michael@0: * It's therefore difficult to measure the process's RSS on Mac, since, in the michael@0: * absence of memory pressure, the contribution from the heap to RSS will not michael@0: * decrease due to our madvise calls. michael@0: * michael@0: * We therefore define MALLOC_DOUBLE_PURGE on Mac. This causes jemalloc to michael@0: * track which pages have been MADV_FREE'd. You can then call michael@0: * jemalloc_purge_freed_pages(), which will force the OS to release those michael@0: * MADV_FREE'd pages, making the process's RSS reflect its true memory usage. michael@0: * michael@0: * The jemalloc_purge_freed_pages definition in memory/build/mozmemory.h needs michael@0: * to be adjusted if MALLOC_DOUBLE_PURGE is ever enabled on Linux. michael@0: */ michael@0: #ifdef MOZ_MEMORY_DARWIN michael@0: #define MALLOC_DOUBLE_PURGE michael@0: #endif michael@0: michael@0: /* michael@0: * MALLOC_PRODUCTION disables assertions and statistics gathering. It also michael@0: * defaults the A and J runtime options to off. These settings are appropriate michael@0: * for production systems. michael@0: */ michael@0: #ifndef MOZ_MEMORY_DEBUG michael@0: # define MALLOC_PRODUCTION michael@0: #endif michael@0: michael@0: /* michael@0: * Use only one arena by default. Mozilla does not currently make extensive michael@0: * use of concurrent allocation, so the increased fragmentation associated with michael@0: * multiple arenas is not warranted. michael@0: */ michael@0: #define MOZ_MEMORY_NARENAS_DEFAULT_ONE michael@0: michael@0: /* michael@0: * Pass this set of options to jemalloc as its default. It does not override michael@0: * the options passed via the MALLOC_OPTIONS environment variable but is michael@0: * applied in addition to them. michael@0: */ michael@0: #ifdef MOZ_B2G michael@0: /* Reduce the amount of unused dirty pages to 1MiB on B2G */ michael@0: # define MOZ_MALLOC_OPTIONS "ff" michael@0: #else michael@0: # define MOZ_MALLOC_OPTIONS "" michael@0: #endif michael@0: michael@0: /* michael@0: * MALLOC_STATS enables statistics calculation, and is required for michael@0: * jemalloc_stats(). michael@0: */ michael@0: #define MALLOC_STATS michael@0: michael@0: /* Memory filling (junk/poison/zero). */ michael@0: #define MALLOC_FILL michael@0: michael@0: #ifndef MALLOC_PRODUCTION michael@0: /* michael@0: * MALLOC_DEBUG enables assertions and other sanity checks, and disables michael@0: * inline functions. michael@0: */ michael@0: # define MALLOC_DEBUG michael@0: michael@0: /* Allocation tracing. */ michael@0: # ifndef MOZ_MEMORY_WINDOWS michael@0: # define MALLOC_UTRACE michael@0: # endif michael@0: michael@0: /* Support optional abort() on OOM. */ michael@0: # define MALLOC_XMALLOC michael@0: michael@0: /* Support SYSV semantics. */ michael@0: # define MALLOC_SYSV michael@0: #endif michael@0: michael@0: /* michael@0: * MALLOC_VALIDATE causes malloc_usable_size() to perform some pointer michael@0: * validation. There are many possible errors that validation does not even michael@0: * attempt to detect. michael@0: */ michael@0: #define MALLOC_VALIDATE michael@0: michael@0: /* Embed no-op macros that support memory allocation tracking via valgrind. */ michael@0: #ifdef MOZ_VALGRIND michael@0: # define MALLOC_VALGRIND michael@0: #endif michael@0: #ifdef MALLOC_VALGRIND michael@0: # include michael@0: #else michael@0: # define VALGRIND_MALLOCLIKE_BLOCK(addr, sizeB, rzB, is_zeroed) michael@0: # define VALGRIND_FREELIKE_BLOCK(addr, rzB) michael@0: #endif michael@0: michael@0: /* michael@0: * MALLOC_BALANCE enables monitoring of arena lock contention and dynamically michael@0: * re-balances arena load if exponentially averaged contention exceeds a michael@0: * certain threshold. michael@0: */ michael@0: /* #define MALLOC_BALANCE */ michael@0: michael@0: /* michael@0: * MALLOC_PAGEFILE causes all mmap()ed memory to be backed by temporary michael@0: * files, so that if a chunk is mapped, it is guaranteed to be swappable. michael@0: * This avoids asynchronous OOM failures that are due to VM over-commit. michael@0: */ michael@0: /* #define MALLOC_PAGEFILE */ michael@0: michael@0: #ifdef MALLOC_PAGEFILE michael@0: /* Write size when initializing a page file. */ michael@0: # define MALLOC_PAGEFILE_WRITE_SIZE 512 michael@0: #endif michael@0: michael@0: #if defined(MOZ_MEMORY_LINUX) && !defined(MOZ_MEMORY_ANDROID) michael@0: #define _GNU_SOURCE /* For mremap(2). */ michael@0: #define issetugid() 0 michael@0: #if 0 /* Enable in order to test decommit code on Linux. */ michael@0: # define MALLOC_DECOMMIT michael@0: #endif michael@0: #endif michael@0: michael@0: #include michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: michael@0: /* Some defines from the CRT internal headers that we need here. */ michael@0: #define _CRT_SPINCOUNT 5000 michael@0: #define __crtInitCritSecAndSpinCount InitializeCriticalSectionAndSpinCount michael@0: #include michael@0: #include michael@0: michael@0: #pragma warning( disable: 4267 4996 4146 ) michael@0: michael@0: #define bool BOOL michael@0: #define false FALSE michael@0: #define true TRUE michael@0: #define inline __inline michael@0: #define SIZE_T_MAX SIZE_MAX michael@0: #define STDERR_FILENO 2 michael@0: #define PATH_MAX MAX_PATH michael@0: #define vsnprintf _vsnprintf michael@0: michael@0: #ifndef NO_TLS michael@0: static unsigned long tlsIndex = 0xffffffff; michael@0: #endif michael@0: michael@0: #define __thread michael@0: #define _pthread_self() __threadid() michael@0: #define issetugid() 0 michael@0: michael@0: /* use MSVC intrinsics */ michael@0: #pragma intrinsic(_BitScanForward) michael@0: static __forceinline int michael@0: ffs(int x) michael@0: { michael@0: unsigned long i; michael@0: michael@0: if (_BitScanForward(&i, x) != 0) michael@0: return (i + 1); michael@0: michael@0: return (0); michael@0: } michael@0: michael@0: /* Implement getenv without using malloc */ michael@0: static char mozillaMallocOptionsBuf[64]; michael@0: michael@0: #define getenv xgetenv michael@0: static char * michael@0: getenv(const char *name) michael@0: { michael@0: michael@0: if (GetEnvironmentVariableA(name, (LPSTR)&mozillaMallocOptionsBuf, michael@0: sizeof(mozillaMallocOptionsBuf)) > 0) michael@0: return (mozillaMallocOptionsBuf); michael@0: michael@0: return (NULL); michael@0: } michael@0: michael@0: typedef unsigned char uint8_t; michael@0: typedef unsigned uint32_t; michael@0: typedef unsigned long long uint64_t; michael@0: typedef unsigned long long uintmax_t; michael@0: #if defined(_WIN64) michael@0: typedef long long ssize_t; michael@0: #else michael@0: typedef long ssize_t; michael@0: #endif michael@0: michael@0: #define MALLOC_DECOMMIT michael@0: #endif michael@0: michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: #ifndef MOZ_MEMORY_SOLARIS michael@0: #include michael@0: #endif michael@0: #ifndef __DECONST michael@0: # define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var)) michael@0: #endif michael@0: #ifndef MOZ_MEMORY michael@0: __FBSDID("$FreeBSD: head/lib/libc/stdlib/malloc.c 180599 2008-07-18 19:35:44Z jasone $"); michael@0: #include "libc_private.h" michael@0: #ifdef MALLOC_DEBUG michael@0: # define _LOCK_DEBUG michael@0: #endif michael@0: #include "spinlock.h" michael@0: #include "namespace.h" michael@0: #endif michael@0: #include michael@0: #ifndef MADV_FREE michael@0: # define MADV_FREE MADV_DONTNEED michael@0: #endif michael@0: #ifndef MAP_NOSYNC michael@0: # define MAP_NOSYNC 0 michael@0: #endif michael@0: #include michael@0: #ifndef MOZ_MEMORY michael@0: #include michael@0: #endif michael@0: #include michael@0: #include michael@0: #if !defined(MOZ_MEMORY_SOLARIS) && !defined(MOZ_MEMORY_ANDROID) michael@0: #include michael@0: #endif michael@0: #include michael@0: #ifndef MOZ_MEMORY michael@0: #include /* Must come after several other sys/ includes. */ michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #endif michael@0: michael@0: #include michael@0: #include michael@0: #ifndef SIZE_T_MAX michael@0: # define SIZE_T_MAX SIZE_MAX michael@0: #endif michael@0: #include michael@0: #ifdef MOZ_MEMORY_DARWIN michael@0: #define _pthread_self pthread_self michael@0: #define _pthread_mutex_init pthread_mutex_init michael@0: #define _pthread_mutex_trylock pthread_mutex_trylock michael@0: #define _pthread_mutex_lock pthread_mutex_lock michael@0: #define _pthread_mutex_unlock pthread_mutex_unlock michael@0: #endif michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #ifndef MOZ_MEMORY_DARWIN michael@0: #include michael@0: #endif michael@0: #include michael@0: michael@0: #ifdef MOZ_MEMORY_DARWIN michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #endif michael@0: michael@0: #ifndef MOZ_MEMORY michael@0: #include "un-namespace.h" michael@0: #endif michael@0: michael@0: #endif michael@0: michael@0: #include "jemalloc_types.h" michael@0: #include "linkedlist.h" michael@0: #include "mozmemory_wrap.h" michael@0: michael@0: /* Some tools, such as /dev/dsp wrappers, LD_PRELOAD libraries that michael@0: * happen to override mmap() and call dlsym() from their overridden michael@0: * mmap(). The problem is that dlsym() calls malloc(), and this ends michael@0: * up in a dead lock in jemalloc. michael@0: * On these systems, we prefer to directly use the system call. michael@0: * We do that for Linux systems and kfreebsd with GNU userland. michael@0: * Note sanity checks are not done (alignment of offset, ...) because michael@0: * the uses of mmap are pretty limited, in jemalloc. michael@0: * michael@0: * On Alpha, glibc has a bug that prevents syscall() to work for system michael@0: * calls with 6 arguments michael@0: */ michael@0: #if (defined(MOZ_MEMORY_LINUX) && !defined(__alpha__)) || \ michael@0: (defined(MOZ_MEMORY_BSD) && defined(__GLIBC__)) michael@0: #include michael@0: #if defined(SYS_mmap) || defined(SYS_mmap2) michael@0: static inline michael@0: void *_mmap(void *addr, size_t length, int prot, int flags, michael@0: int fd, off_t offset) michael@0: { michael@0: /* S390 only passes one argument to the mmap system call, which is a michael@0: * pointer to a structure containing the arguments */ michael@0: #ifdef __s390__ michael@0: struct { michael@0: void *addr; michael@0: size_t length; michael@0: long prot; michael@0: long flags; michael@0: long fd; michael@0: off_t offset; michael@0: } args = { addr, length, prot, flags, fd, offset }; michael@0: return (void *) syscall(SYS_mmap, &args); michael@0: #else michael@0: #ifdef SYS_mmap2 michael@0: return (void *) syscall(SYS_mmap2, addr, length, prot, flags, michael@0: fd, offset >> 12); michael@0: #else michael@0: return (void *) syscall(SYS_mmap, addr, length, prot, flags, michael@0: fd, offset); michael@0: #endif michael@0: #endif michael@0: } michael@0: #define mmap _mmap michael@0: #define munmap(a, l) syscall(SYS_munmap, a, l) michael@0: #endif michael@0: #endif michael@0: michael@0: #ifdef MOZ_MEMORY_DARWIN michael@0: static const bool isthreaded = true; michael@0: #endif michael@0: michael@0: #if defined(MOZ_MEMORY_SOLARIS) && defined(MAP_ALIGN) && !defined(JEMALLOC_NEVER_USES_MAP_ALIGN) michael@0: #define JEMALLOC_USES_MAP_ALIGN /* Required on Solaris 10. Might improve performance elsewhere. */ michael@0: #endif michael@0: michael@0: #define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var)) michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: /* MSVC++ does not support C99 variable-length arrays. */ michael@0: # define RB_NO_C99_VARARRAYS michael@0: #endif michael@0: #include "rb.h" michael@0: michael@0: #ifdef MALLOC_DEBUG michael@0: /* Disable inlining to make debugging easier. */ michael@0: #ifdef inline michael@0: #undef inline michael@0: #endif michael@0: michael@0: # define inline michael@0: #endif michael@0: michael@0: /* Size of stack-allocated buffer passed to strerror_r(). */ michael@0: #define STRERROR_BUF 64 michael@0: michael@0: /* Minimum alignment of non-tiny allocations is 2^QUANTUM_2POW_MIN bytes. */ michael@0: # define QUANTUM_2POW_MIN 4 michael@0: #if defined(_WIN64) || defined(__LP64__) michael@0: # define SIZEOF_PTR_2POW 3 michael@0: #else michael@0: # define SIZEOF_PTR_2POW 2 michael@0: #endif michael@0: #define PIC michael@0: #ifndef MOZ_MEMORY_DARWIN michael@0: static const bool isthreaded = true; michael@0: #else michael@0: # define NO_TLS michael@0: #endif michael@0: #if 0 michael@0: #ifdef __i386__ michael@0: # define QUANTUM_2POW_MIN 4 michael@0: # define SIZEOF_PTR_2POW 2 michael@0: # define CPU_SPINWAIT __asm__ volatile("pause") michael@0: #endif michael@0: #ifdef __ia64__ michael@0: # define QUANTUM_2POW_MIN 4 michael@0: # define SIZEOF_PTR_2POW 3 michael@0: #endif michael@0: #ifdef __alpha__ michael@0: # define QUANTUM_2POW_MIN 4 michael@0: # define SIZEOF_PTR_2POW 3 michael@0: # define NO_TLS michael@0: #endif michael@0: #ifdef __sparc64__ michael@0: # define QUANTUM_2POW_MIN 4 michael@0: # define SIZEOF_PTR_2POW 3 michael@0: # define NO_TLS michael@0: #endif michael@0: #ifdef __amd64__ michael@0: # define QUANTUM_2POW_MIN 4 michael@0: # define SIZEOF_PTR_2POW 3 michael@0: # define CPU_SPINWAIT __asm__ volatile("pause") michael@0: #endif michael@0: #ifdef __arm__ michael@0: # define QUANTUM_2POW_MIN 3 michael@0: # define SIZEOF_PTR_2POW 2 michael@0: # define NO_TLS michael@0: #endif michael@0: #ifdef __mips__ michael@0: # define QUANTUM_2POW_MIN 3 michael@0: # define SIZEOF_PTR_2POW 2 michael@0: # define NO_TLS michael@0: #endif michael@0: #ifdef __powerpc__ michael@0: # define QUANTUM_2POW_MIN 4 michael@0: # define SIZEOF_PTR_2POW 2 michael@0: #endif michael@0: #endif michael@0: michael@0: #define SIZEOF_PTR (1U << SIZEOF_PTR_2POW) michael@0: michael@0: /* sizeof(int) == (1U << SIZEOF_INT_2POW). */ michael@0: #ifndef SIZEOF_INT_2POW michael@0: # define SIZEOF_INT_2POW 2 michael@0: #endif michael@0: michael@0: /* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */ michael@0: #if (!defined(PIC) && !defined(NO_TLS)) michael@0: # define NO_TLS michael@0: #endif michael@0: michael@0: #ifdef NO_TLS michael@0: /* MALLOC_BALANCE requires TLS. */ michael@0: # ifdef MALLOC_BALANCE michael@0: # undef MALLOC_BALANCE michael@0: # endif michael@0: #endif michael@0: michael@0: /* michael@0: * Size and alignment of memory chunks that are allocated by the OS's virtual michael@0: * memory system. michael@0: */ michael@0: #define CHUNK_2POW_DEFAULT 20 michael@0: /* Maximum number of dirty pages per arena. */ michael@0: #define DIRTY_MAX_DEFAULT (1U << 10) michael@0: michael@0: /* michael@0: * Maximum size of L1 cache line. This is used to avoid cache line aliasing, michael@0: * so over-estimates are okay (up to a point), but under-estimates will michael@0: * negatively affect performance. michael@0: */ michael@0: #define CACHELINE_2POW 6 michael@0: #define CACHELINE ((size_t)(1U << CACHELINE_2POW)) michael@0: michael@0: /* michael@0: * Smallest size class to support. On Linux and Mac, even malloc(1) must michael@0: * reserve a word's worth of memory (see Mozilla bug 691003). michael@0: */ michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: #define TINY_MIN_2POW 1 michael@0: #else michael@0: #define TINY_MIN_2POW (sizeof(void*) == 8 ? 3 : 2) michael@0: #endif michael@0: michael@0: /* michael@0: * Maximum size class that is a multiple of the quantum, but not (necessarily) michael@0: * a power of 2. Above this size, allocations are rounded up to the nearest michael@0: * power of 2. michael@0: */ michael@0: #define SMALL_MAX_2POW_DEFAULT 9 michael@0: #define SMALL_MAX_DEFAULT (1U << SMALL_MAX_2POW_DEFAULT) michael@0: michael@0: /* michael@0: * RUN_MAX_OVRHD indicates maximum desired run header overhead. Runs are sized michael@0: * as small as possible such that this setting is still honored, without michael@0: * violating other constraints. The goal is to make runs as small as possible michael@0: * without exceeding a per run external fragmentation threshold. michael@0: * michael@0: * We use binary fixed point math for overhead computations, where the binary michael@0: * point is implicitly RUN_BFP bits to the left. michael@0: * michael@0: * Note that it is possible to set RUN_MAX_OVRHD low enough that it cannot be michael@0: * honored for some/all object sizes, since there is one bit of header overhead michael@0: * per object (plus a constant). This constraint is relaxed (ignored) for runs michael@0: * that are so small that the per-region overhead is greater than: michael@0: * michael@0: * (RUN_MAX_OVRHD / (reg_size << (3+RUN_BFP)) michael@0: */ michael@0: #define RUN_BFP 12 michael@0: /* \/ Implicit binary fixed point. */ michael@0: #define RUN_MAX_OVRHD 0x0000003dU michael@0: #define RUN_MAX_OVRHD_RELAX 0x00001800U michael@0: michael@0: /* Put a cap on small object run size. This overrides RUN_MAX_OVRHD. */ michael@0: #define RUN_MAX_SMALL_2POW 15 michael@0: #define RUN_MAX_SMALL (1U << RUN_MAX_SMALL_2POW) michael@0: michael@0: /* michael@0: * Hyper-threaded CPUs may need a special instruction inside spin loops in michael@0: * order to yield to another virtual CPU. If no such instruction is defined michael@0: * above, make CPU_SPINWAIT a no-op. michael@0: */ michael@0: #ifndef CPU_SPINWAIT michael@0: # define CPU_SPINWAIT michael@0: #endif michael@0: michael@0: /* michael@0: * Adaptive spinning must eventually switch to blocking, in order to avoid the michael@0: * potential for priority inversion deadlock. Backing off past a certain point michael@0: * can actually waste time. michael@0: */ michael@0: #define SPIN_LIMIT_2POW 11 michael@0: michael@0: /* michael@0: * Conversion from spinning to blocking is expensive; we use (1U << michael@0: * BLOCK_COST_2POW) to estimate how many more times costly blocking is than michael@0: * worst-case spinning. michael@0: */ michael@0: #define BLOCK_COST_2POW 4 michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: /* michael@0: * We use an exponential moving average to track recent lock contention, michael@0: * where the size of the history window is N, and alpha=2/(N+1). michael@0: * michael@0: * Due to integer math rounding, very small values here can cause michael@0: * substantial degradation in accuracy, thus making the moving average decay michael@0: * faster than it would with precise calculation. michael@0: */ michael@0: # define BALANCE_ALPHA_INV_2POW 9 michael@0: michael@0: /* michael@0: * Threshold value for the exponential moving contention average at which to michael@0: * re-assign a thread. michael@0: */ michael@0: # define BALANCE_THRESHOLD_DEFAULT (1U << (SPIN_LIMIT_2POW-4)) michael@0: #endif michael@0: michael@0: /******************************************************************************/ michael@0: michael@0: /* MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive. */ michael@0: #if defined(MALLOC_DECOMMIT) && defined(MALLOC_DOUBLE_PURGE) michael@0: #error MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive. michael@0: #endif michael@0: michael@0: /* michael@0: * Mutexes based on spinlocks. We can't use normal pthread spinlocks in all michael@0: * places, because they require malloc()ed memory, which causes bootstrapping michael@0: * issues in some cases. michael@0: */ michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: #define malloc_mutex_t CRITICAL_SECTION michael@0: #define malloc_spinlock_t CRITICAL_SECTION michael@0: #elif defined(MOZ_MEMORY_DARWIN) michael@0: typedef struct { michael@0: OSSpinLock lock; michael@0: } malloc_mutex_t; michael@0: typedef struct { michael@0: OSSpinLock lock; michael@0: } malloc_spinlock_t; michael@0: #elif defined(MOZ_MEMORY) michael@0: typedef pthread_mutex_t malloc_mutex_t; michael@0: typedef pthread_mutex_t malloc_spinlock_t; michael@0: #else michael@0: /* XXX these should #ifdef these for freebsd (and linux?) only */ michael@0: typedef struct { michael@0: spinlock_t lock; michael@0: } malloc_mutex_t; michael@0: typedef malloc_spinlock_t malloc_mutex_t; michael@0: #endif michael@0: michael@0: /* Set to true once the allocator has been initialized. */ michael@0: static bool malloc_initialized = false; michael@0: michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: /* No init lock for Windows. */ michael@0: #elif defined(MOZ_MEMORY_DARWIN) michael@0: static malloc_mutex_t init_lock = {OS_SPINLOCK_INIT}; michael@0: #elif defined(MOZ_MEMORY_LINUX) && !defined(MOZ_MEMORY_ANDROID) michael@0: static malloc_mutex_t init_lock = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP; michael@0: #elif defined(MOZ_MEMORY) michael@0: static malloc_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER; michael@0: #else michael@0: static malloc_mutex_t init_lock = {_SPINLOCK_INITIALIZER}; michael@0: #endif michael@0: michael@0: /******************************************************************************/ michael@0: /* michael@0: * Statistics data structures. michael@0: */ michael@0: michael@0: #ifdef MALLOC_STATS michael@0: michael@0: typedef struct malloc_bin_stats_s malloc_bin_stats_t; michael@0: struct malloc_bin_stats_s { michael@0: /* michael@0: * Number of allocation requests that corresponded to the size of this michael@0: * bin. michael@0: */ michael@0: uint64_t nrequests; michael@0: michael@0: /* Total number of runs created for this bin's size class. */ michael@0: uint64_t nruns; michael@0: michael@0: /* michael@0: * Total number of runs reused by extracting them from the runs tree for michael@0: * this bin's size class. michael@0: */ michael@0: uint64_t reruns; michael@0: michael@0: /* High-water mark for this bin. */ michael@0: unsigned long highruns; michael@0: michael@0: /* Current number of runs in this bin. */ michael@0: unsigned long curruns; michael@0: }; michael@0: michael@0: typedef struct arena_stats_s arena_stats_t; michael@0: struct arena_stats_s { michael@0: /* Number of bytes currently mapped. */ michael@0: size_t mapped; michael@0: michael@0: /* michael@0: * Total number of purge sweeps, total number of madvise calls made, michael@0: * and total pages purged in order to keep dirty unused memory under michael@0: * control. michael@0: */ michael@0: uint64_t npurge; michael@0: uint64_t nmadvise; michael@0: uint64_t purged; michael@0: #ifdef MALLOC_DECOMMIT michael@0: /* michael@0: * Total number of decommit/commit operations, and total number of michael@0: * pages decommitted. michael@0: */ michael@0: uint64_t ndecommit; michael@0: uint64_t ncommit; michael@0: uint64_t decommitted; michael@0: #endif michael@0: michael@0: /* Current number of committed pages. */ michael@0: size_t committed; michael@0: michael@0: /* Per-size-category statistics. */ michael@0: size_t allocated_small; michael@0: uint64_t nmalloc_small; michael@0: uint64_t ndalloc_small; michael@0: michael@0: size_t allocated_large; michael@0: uint64_t nmalloc_large; michael@0: uint64_t ndalloc_large; michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: /* Number of times this arena reassigned a thread due to contention. */ michael@0: uint64_t nbalance; michael@0: #endif michael@0: }; michael@0: michael@0: #endif /* #ifdef MALLOC_STATS */ michael@0: michael@0: /******************************************************************************/ michael@0: /* michael@0: * Extent data structures. michael@0: */ michael@0: michael@0: /* Tree of extents. */ michael@0: typedef struct extent_node_s extent_node_t; michael@0: struct extent_node_s { michael@0: /* Linkage for the size/address-ordered tree. */ michael@0: rb_node(extent_node_t) link_szad; michael@0: michael@0: /* Linkage for the address-ordered tree. */ michael@0: rb_node(extent_node_t) link_ad; michael@0: michael@0: /* Pointer to the extent that this tree node is responsible for. */ michael@0: void *addr; michael@0: michael@0: /* Total region size. */ michael@0: size_t size; michael@0: }; michael@0: typedef rb_tree(extent_node_t) extent_tree_t; michael@0: michael@0: /******************************************************************************/ michael@0: /* michael@0: * Radix tree data structures. michael@0: */ michael@0: michael@0: #ifdef MALLOC_VALIDATE michael@0: /* michael@0: * Size of each radix tree node (must be a power of 2). This impacts tree michael@0: * depth. michael@0: */ michael@0: # if (SIZEOF_PTR == 4) michael@0: # define MALLOC_RTREE_NODESIZE (1U << 14) michael@0: # else michael@0: # define MALLOC_RTREE_NODESIZE CACHELINE michael@0: # endif michael@0: michael@0: typedef struct malloc_rtree_s malloc_rtree_t; michael@0: struct malloc_rtree_s { michael@0: malloc_spinlock_t lock; michael@0: void **root; michael@0: unsigned height; michael@0: unsigned level2bits[1]; /* Dynamically sized. */ michael@0: }; michael@0: #endif michael@0: michael@0: /******************************************************************************/ michael@0: /* michael@0: * Arena data structures. michael@0: */ michael@0: michael@0: typedef struct arena_s arena_t; michael@0: typedef struct arena_bin_s arena_bin_t; michael@0: michael@0: /* Each element of the chunk map corresponds to one page within the chunk. */ michael@0: typedef struct arena_chunk_map_s arena_chunk_map_t; michael@0: struct arena_chunk_map_s { michael@0: /* michael@0: * Linkage for run trees. There are two disjoint uses: michael@0: * michael@0: * 1) arena_t's runs_avail tree. michael@0: * 2) arena_run_t conceptually uses this linkage for in-use non-full michael@0: * runs, rather than directly embedding linkage. michael@0: */ michael@0: rb_node(arena_chunk_map_t) link; michael@0: michael@0: /* michael@0: * Run address (or size) and various flags are stored together. The bit michael@0: * layout looks like (assuming 32-bit system): michael@0: * michael@0: * ???????? ???????? ????---- -mckdzla michael@0: * michael@0: * ? : Unallocated: Run address for first/last pages, unset for internal michael@0: * pages. michael@0: * Small: Run address. michael@0: * Large: Run size for first page, unset for trailing pages. michael@0: * - : Unused. michael@0: * m : MADV_FREE/MADV_DONTNEED'ed? michael@0: * c : decommitted? michael@0: * k : key? michael@0: * d : dirty? michael@0: * z : zeroed? michael@0: * l : large? michael@0: * a : allocated? michael@0: * michael@0: * Following are example bit patterns for the three types of runs. michael@0: * michael@0: * r : run address michael@0: * s : run size michael@0: * x : don't care michael@0: * - : 0 michael@0: * [cdzla] : bit set michael@0: * michael@0: * Unallocated: michael@0: * ssssssss ssssssss ssss---- --c----- michael@0: * xxxxxxxx xxxxxxxx xxxx---- ----d--- michael@0: * ssssssss ssssssss ssss---- -----z-- michael@0: * michael@0: * Small: michael@0: * rrrrrrrr rrrrrrrr rrrr---- -------a michael@0: * rrrrrrrr rrrrrrrr rrrr---- -------a michael@0: * rrrrrrrr rrrrrrrr rrrr---- -------a michael@0: * michael@0: * Large: michael@0: * ssssssss ssssssss ssss---- ------la michael@0: * -------- -------- -------- ------la michael@0: * -------- -------- -------- ------la michael@0: */ michael@0: size_t bits; michael@0: michael@0: /* Note that CHUNK_MAP_DECOMMITTED's meaning varies depending on whether michael@0: * MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are defined. michael@0: * michael@0: * If MALLOC_DECOMMIT is defined, a page which is CHUNK_MAP_DECOMMITTED must be michael@0: * re-committed with pages_commit() before it may be touched. If michael@0: * MALLOC_DECOMMIT is defined, MALLOC_DOUBLE_PURGE may not be defined. michael@0: * michael@0: * If neither MALLOC_DECOMMIT nor MALLOC_DOUBLE_PURGE is defined, pages which michael@0: * are madvised (with either MADV_DONTNEED or MADV_FREE) are marked with michael@0: * CHUNK_MAP_MADVISED. michael@0: * michael@0: * Otherwise, if MALLOC_DECOMMIT is not defined and MALLOC_DOUBLE_PURGE is michael@0: * defined, then a page which is madvised is marked as CHUNK_MAP_MADVISED. michael@0: * When it's finally freed with jemalloc_purge_freed_pages, the page is marked michael@0: * as CHUNK_MAP_DECOMMITTED. michael@0: */ michael@0: #if defined(MALLOC_DECOMMIT) || defined(MALLOC_STATS) || defined(MALLOC_DOUBLE_PURGE) michael@0: #define CHUNK_MAP_MADVISED ((size_t)0x40U) michael@0: #define CHUNK_MAP_DECOMMITTED ((size_t)0x20U) michael@0: #define CHUNK_MAP_MADVISED_OR_DECOMMITTED (CHUNK_MAP_MADVISED | CHUNK_MAP_DECOMMITTED) michael@0: #endif michael@0: #define CHUNK_MAP_KEY ((size_t)0x10U) michael@0: #define CHUNK_MAP_DIRTY ((size_t)0x08U) michael@0: #define CHUNK_MAP_ZEROED ((size_t)0x04U) michael@0: #define CHUNK_MAP_LARGE ((size_t)0x02U) michael@0: #define CHUNK_MAP_ALLOCATED ((size_t)0x01U) michael@0: }; michael@0: typedef rb_tree(arena_chunk_map_t) arena_avail_tree_t; michael@0: typedef rb_tree(arena_chunk_map_t) arena_run_tree_t; michael@0: michael@0: /* Arena chunk header. */ michael@0: typedef struct arena_chunk_s arena_chunk_t; michael@0: struct arena_chunk_s { michael@0: /* Arena that owns the chunk. */ michael@0: arena_t *arena; michael@0: michael@0: /* Linkage for the arena's chunks_dirty tree. */ michael@0: rb_node(arena_chunk_t) link_dirty; michael@0: michael@0: #ifdef MALLOC_DOUBLE_PURGE michael@0: /* If we're double-purging, we maintain a linked list of chunks which michael@0: * have pages which have been madvise(MADV_FREE)'d but not explicitly michael@0: * purged. michael@0: * michael@0: * We're currently lazy and don't remove a chunk from this list when michael@0: * all its madvised pages are recommitted. */ michael@0: LinkedList chunks_madvised_elem; michael@0: #endif michael@0: michael@0: /* Number of dirty pages. */ michael@0: size_t ndirty; michael@0: michael@0: /* Map of pages within chunk that keeps track of free/large/small. */ michael@0: arena_chunk_map_t map[1]; /* Dynamically sized. */ michael@0: }; michael@0: typedef rb_tree(arena_chunk_t) arena_chunk_tree_t; michael@0: michael@0: typedef struct arena_run_s arena_run_t; michael@0: struct arena_run_s { michael@0: #if defined(MALLOC_DEBUG) || defined(MOZ_JEMALLOC_HARD_ASSERTS) michael@0: uint32_t magic; michael@0: # define ARENA_RUN_MAGIC 0x384adf93 michael@0: #endif michael@0: michael@0: /* Bin this run is associated with. */ michael@0: arena_bin_t *bin; michael@0: michael@0: /* Index of first element that might have a free region. */ michael@0: unsigned regs_minelm; michael@0: michael@0: /* Number of free regions in run. */ michael@0: unsigned nfree; michael@0: michael@0: /* Bitmask of in-use regions (0: in use, 1: free). */ michael@0: unsigned regs_mask[1]; /* Dynamically sized. */ michael@0: }; michael@0: michael@0: struct arena_bin_s { michael@0: /* michael@0: * Current run being used to service allocations of this bin's size michael@0: * class. michael@0: */ michael@0: arena_run_t *runcur; michael@0: michael@0: /* michael@0: * Tree of non-full runs. This tree is used when looking for an michael@0: * existing run when runcur is no longer usable. We choose the michael@0: * non-full run that is lowest in memory; this policy tends to keep michael@0: * objects packed well, and it can also help reduce the number of michael@0: * almost-empty chunks. michael@0: */ michael@0: arena_run_tree_t runs; michael@0: michael@0: /* Size of regions in a run for this bin's size class. */ michael@0: size_t reg_size; michael@0: michael@0: /* Total size of a run for this bin's size class. */ michael@0: size_t run_size; michael@0: michael@0: /* Total number of regions in a run for this bin's size class. */ michael@0: uint32_t nregs; michael@0: michael@0: /* Number of elements in a run's regs_mask for this bin's size class. */ michael@0: uint32_t regs_mask_nelms; michael@0: michael@0: /* Offset of first region in a run for this bin's size class. */ michael@0: uint32_t reg0_offset; michael@0: michael@0: #ifdef MALLOC_STATS michael@0: /* Bin statistics. */ michael@0: malloc_bin_stats_t stats; michael@0: #endif michael@0: }; michael@0: michael@0: struct arena_s { michael@0: #if defined(MALLOC_DEBUG) || defined(MOZ_JEMALLOC_HARD_ASSERTS) michael@0: uint32_t magic; michael@0: # define ARENA_MAGIC 0x947d3d24 michael@0: #endif michael@0: michael@0: /* All operations on this arena require that lock be locked. */ michael@0: #ifdef MOZ_MEMORY michael@0: malloc_spinlock_t lock; michael@0: #else michael@0: pthread_mutex_t lock; michael@0: #endif michael@0: michael@0: #ifdef MALLOC_STATS michael@0: arena_stats_t stats; michael@0: #endif michael@0: michael@0: /* Tree of dirty-page-containing chunks this arena manages. */ michael@0: arena_chunk_tree_t chunks_dirty; michael@0: michael@0: #ifdef MALLOC_DOUBLE_PURGE michael@0: /* Head of a linked list of MADV_FREE'd-page-containing chunks this michael@0: * arena manages. */ michael@0: LinkedList chunks_madvised; michael@0: #endif michael@0: michael@0: /* michael@0: * In order to avoid rapid chunk allocation/deallocation when an arena michael@0: * oscillates right on the cusp of needing a new chunk, cache the most michael@0: * recently freed chunk. The spare is left in the arena's chunk trees michael@0: * until it is deleted. michael@0: * michael@0: * There is one spare chunk per arena, rather than one spare total, in michael@0: * order to avoid interactions between multiple threads that could make michael@0: * a single spare inadequate. michael@0: */ michael@0: arena_chunk_t *spare; michael@0: michael@0: /* michael@0: * Current count of pages within unused runs that are potentially michael@0: * dirty, and for which madvise(... MADV_FREE) has not been called. By michael@0: * tracking this, we can institute a limit on how much dirty unused michael@0: * memory is mapped for each arena. michael@0: */ michael@0: size_t ndirty; michael@0: michael@0: /* michael@0: * Size/address-ordered tree of this arena's available runs. This tree michael@0: * is used for first-best-fit run allocation. michael@0: */ michael@0: arena_avail_tree_t runs_avail; michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: /* michael@0: * The arena load balancing machinery needs to keep track of how much michael@0: * lock contention there is. This value is exponentially averaged. michael@0: */ michael@0: uint32_t contention; michael@0: #endif michael@0: michael@0: /* michael@0: * bins is used to store rings of free regions of the following sizes, michael@0: * assuming a 16-byte quantum, 4kB pagesize, and default MALLOC_OPTIONS. michael@0: * michael@0: * bins[i] | size | michael@0: * --------+------+ michael@0: * 0 | 2 | michael@0: * 1 | 4 | michael@0: * 2 | 8 | michael@0: * --------+------+ michael@0: * 3 | 16 | michael@0: * 4 | 32 | michael@0: * 5 | 48 | michael@0: * 6 | 64 | michael@0: * : : michael@0: * : : michael@0: * 33 | 496 | michael@0: * 34 | 512 | michael@0: * --------+------+ michael@0: * 35 | 1024 | michael@0: * 36 | 2048 | michael@0: * --------+------+ michael@0: */ michael@0: arena_bin_t bins[1]; /* Dynamically sized. */ michael@0: }; michael@0: michael@0: /******************************************************************************/ michael@0: /* michael@0: * Data. michael@0: */ michael@0: michael@0: #ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE michael@0: /* Number of CPUs. */ michael@0: static unsigned ncpus; michael@0: #endif michael@0: michael@0: /* michael@0: * When MALLOC_STATIC_SIZES is defined most of the parameters michael@0: * controlling the malloc behavior are defined as compile-time constants michael@0: * for best performance and cannot be altered at runtime. michael@0: */ michael@0: #if !defined(__ia64__) && !defined(__sparc__) && !defined(__mips__) michael@0: #define MALLOC_STATIC_SIZES 1 michael@0: #endif michael@0: michael@0: #ifdef MALLOC_STATIC_SIZES michael@0: michael@0: /* michael@0: * VM page size. It must divide the runtime CPU page size or the code michael@0: * will abort. michael@0: * Platform specific page size conditions copied from js/public/HeapAPI.h michael@0: */ michael@0: #if (defined(SOLARIS) || defined(__FreeBSD__)) && \ michael@0: (defined(__sparc) || defined(__sparcv9) || defined(__ia64)) michael@0: #define pagesize_2pow ((size_t) 13) michael@0: #elif defined(__powerpc64__) || defined(__aarch64__) michael@0: #define pagesize_2pow ((size_t) 16) michael@0: #else michael@0: #define pagesize_2pow ((size_t) 12) michael@0: #endif michael@0: #define pagesize ((size_t) 1 << pagesize_2pow) michael@0: #define pagesize_mask (pagesize - 1) michael@0: michael@0: /* Various quantum-related settings. */ michael@0: michael@0: #define QUANTUM_DEFAULT ((size_t) 1 << QUANTUM_2POW_MIN) michael@0: static const size_t quantum = QUANTUM_DEFAULT; michael@0: static const size_t quantum_mask = QUANTUM_DEFAULT - 1; michael@0: michael@0: /* Various bin-related settings. */ michael@0: michael@0: static const size_t small_min = (QUANTUM_DEFAULT >> 1) + 1; michael@0: static const size_t small_max = (size_t) SMALL_MAX_DEFAULT; michael@0: michael@0: /* Max size class for bins. */ michael@0: static const size_t bin_maxclass = pagesize >> 1; michael@0: michael@0: /* Number of (2^n)-spaced tiny bins. */ michael@0: static const unsigned ntbins = (unsigned) michael@0: (QUANTUM_2POW_MIN - TINY_MIN_2POW); michael@0: michael@0: /* Number of quantum-spaced bins. */ michael@0: static const unsigned nqbins = (unsigned) michael@0: (SMALL_MAX_DEFAULT >> QUANTUM_2POW_MIN); michael@0: michael@0: /* Number of (2^n)-spaced sub-page bins. */ michael@0: static const unsigned nsbins = (unsigned) michael@0: (pagesize_2pow - michael@0: SMALL_MAX_2POW_DEFAULT - 1); michael@0: michael@0: #else /* !MALLOC_STATIC_SIZES */ michael@0: michael@0: /* VM page size. */ michael@0: static size_t pagesize; michael@0: static size_t pagesize_mask; michael@0: static size_t pagesize_2pow; michael@0: michael@0: /* Various bin-related settings. */ michael@0: static size_t bin_maxclass; /* Max size class for bins. */ michael@0: static unsigned ntbins; /* Number of (2^n)-spaced tiny bins. */ michael@0: static unsigned nqbins; /* Number of quantum-spaced bins. */ michael@0: static unsigned nsbins; /* Number of (2^n)-spaced sub-page bins. */ michael@0: static size_t small_min; michael@0: static size_t small_max; michael@0: michael@0: /* Various quantum-related settings. */ michael@0: static size_t quantum; michael@0: static size_t quantum_mask; /* (quantum - 1). */ michael@0: michael@0: #endif michael@0: michael@0: /* Various chunk-related settings. */ michael@0: michael@0: /* michael@0: * Compute the header size such that it is large enough to contain the page map michael@0: * and enough nodes for the worst case: one node per non-header page plus one michael@0: * extra for situations where we briefly have one more node allocated than we michael@0: * will need. michael@0: */ michael@0: #define calculate_arena_header_size() \ michael@0: (sizeof(arena_chunk_t) + sizeof(arena_chunk_map_t) * (chunk_npages - 1)) michael@0: michael@0: #define calculate_arena_header_pages() \ michael@0: ((calculate_arena_header_size() >> pagesize_2pow) + \ michael@0: ((calculate_arena_header_size() & pagesize_mask) ? 1 : 0)) michael@0: michael@0: /* Max size class for arenas. */ michael@0: #define calculate_arena_maxclass() \ michael@0: (chunksize - (arena_chunk_header_npages << pagesize_2pow)) michael@0: michael@0: #ifdef MALLOC_STATIC_SIZES michael@0: #define CHUNKSIZE_DEFAULT ((size_t) 1 << CHUNK_2POW_DEFAULT) michael@0: static const size_t chunksize = CHUNKSIZE_DEFAULT; michael@0: static const size_t chunksize_mask =CHUNKSIZE_DEFAULT - 1; michael@0: static const size_t chunk_npages = CHUNKSIZE_DEFAULT >> pagesize_2pow; michael@0: #define arena_chunk_header_npages calculate_arena_header_pages() michael@0: #define arena_maxclass calculate_arena_maxclass() michael@0: #else michael@0: static size_t chunksize; michael@0: static size_t chunksize_mask; /* (chunksize - 1). */ michael@0: static size_t chunk_npages; michael@0: static size_t arena_chunk_header_npages; michael@0: static size_t arena_maxclass; /* Max size class for arenas. */ michael@0: #endif michael@0: michael@0: /********/ michael@0: /* michael@0: * Chunks. michael@0: */ michael@0: michael@0: #ifdef MALLOC_VALIDATE michael@0: static malloc_rtree_t *chunk_rtree; michael@0: #endif michael@0: michael@0: /* Protects chunk-related data structures. */ michael@0: static malloc_mutex_t huge_mtx; michael@0: michael@0: /* Tree of chunks that are stand-alone huge allocations. */ michael@0: static extent_tree_t huge; michael@0: michael@0: #ifdef MALLOC_STATS michael@0: /* Huge allocation statistics. */ michael@0: static uint64_t huge_nmalloc; michael@0: static uint64_t huge_ndalloc; michael@0: static size_t huge_allocated; michael@0: static size_t huge_mapped; michael@0: #endif michael@0: michael@0: #ifdef MALLOC_PAGEFILE michael@0: static char pagefile_templ[PATH_MAX]; michael@0: #endif michael@0: michael@0: /****************************/ michael@0: /* michael@0: * base (internal allocation). michael@0: */ michael@0: michael@0: /* michael@0: * Current pages that are being used for internal memory allocations. These michael@0: * pages are carved up in cacheline-size quanta, so that there is no chance of michael@0: * false cache line sharing. michael@0: */ michael@0: static void *base_pages; michael@0: static void *base_next_addr; michael@0: #if defined(MALLOC_DECOMMIT) || defined(MALLOC_STATS) michael@0: static void *base_next_decommitted; michael@0: #endif michael@0: static void *base_past_addr; /* Addr immediately past base_pages. */ michael@0: static extent_node_t *base_nodes; michael@0: static malloc_mutex_t base_mtx; michael@0: #ifdef MALLOC_STATS michael@0: static size_t base_mapped; michael@0: static size_t base_committed; michael@0: #endif michael@0: michael@0: /********/ michael@0: /* michael@0: * Arenas. michael@0: */ michael@0: michael@0: /* michael@0: * Arenas that are used to service external requests. Not all elements of the michael@0: * arenas array are necessarily used; arenas are created lazily as needed. michael@0: */ michael@0: static arena_t **arenas; michael@0: static unsigned narenas; michael@0: #ifndef NO_TLS michael@0: # ifdef MALLOC_BALANCE michael@0: static unsigned narenas_2pow; michael@0: # else michael@0: static unsigned next_arena; michael@0: # endif michael@0: #endif michael@0: #ifdef MOZ_MEMORY michael@0: static malloc_spinlock_t arenas_lock; /* Protects arenas initialization. */ michael@0: #else michael@0: static pthread_mutex_t arenas_lock; /* Protects arenas initialization. */ michael@0: #endif michael@0: michael@0: #ifndef NO_TLS michael@0: /* michael@0: * Map of pthread_self() --> arenas[???], used for selecting an arena to use michael@0: * for allocations. michael@0: */ michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: static __thread arena_t *arenas_map; michael@0: #endif michael@0: #endif michael@0: michael@0: /*******************************/ michael@0: /* michael@0: * Runtime configuration options. michael@0: */ michael@0: MOZ_JEMALLOC_API michael@0: const char *_malloc_options = MOZ_MALLOC_OPTIONS; michael@0: michael@0: #ifndef MALLOC_PRODUCTION michael@0: static bool opt_abort = true; michael@0: #ifdef MALLOC_FILL michael@0: static bool opt_junk = true; michael@0: static bool opt_poison = true; michael@0: static bool opt_zero = false; michael@0: #endif michael@0: #else michael@0: static bool opt_abort = false; michael@0: #ifdef MALLOC_FILL michael@0: static const bool opt_junk = false; michael@0: static const bool opt_poison = true; michael@0: static const bool opt_zero = false; michael@0: #endif michael@0: #endif michael@0: michael@0: static size_t opt_dirty_max = DIRTY_MAX_DEFAULT; michael@0: #ifdef MALLOC_BALANCE michael@0: static uint64_t opt_balance_threshold = BALANCE_THRESHOLD_DEFAULT; michael@0: #endif michael@0: static bool opt_print_stats = false; michael@0: #ifdef MALLOC_STATIC_SIZES michael@0: #define opt_quantum_2pow QUANTUM_2POW_MIN michael@0: #define opt_small_max_2pow SMALL_MAX_2POW_DEFAULT michael@0: #define opt_chunk_2pow CHUNK_2POW_DEFAULT michael@0: #else michael@0: static size_t opt_quantum_2pow = QUANTUM_2POW_MIN; michael@0: static size_t opt_small_max_2pow = SMALL_MAX_2POW_DEFAULT; michael@0: static size_t opt_chunk_2pow = CHUNK_2POW_DEFAULT; michael@0: #endif michael@0: #ifdef MALLOC_PAGEFILE michael@0: static bool opt_pagefile = false; michael@0: #endif michael@0: #ifdef MALLOC_UTRACE michael@0: static bool opt_utrace = false; michael@0: #endif michael@0: #ifdef MALLOC_SYSV michael@0: static bool opt_sysv = false; michael@0: #endif michael@0: #ifdef MALLOC_XMALLOC michael@0: static bool opt_xmalloc = false; michael@0: #endif michael@0: static int opt_narenas_lshift = 0; michael@0: michael@0: #ifdef MALLOC_UTRACE michael@0: typedef struct { michael@0: void *p; michael@0: size_t s; michael@0: void *r; michael@0: } malloc_utrace_t; michael@0: michael@0: #define UTRACE(a, b, c) \ michael@0: if (opt_utrace) { \ michael@0: malloc_utrace_t ut; \ michael@0: ut.p = (a); \ michael@0: ut.s = (b); \ michael@0: ut.r = (c); \ michael@0: utrace(&ut, sizeof(ut)); \ michael@0: } michael@0: #else michael@0: #define UTRACE(a, b, c) michael@0: #endif michael@0: michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin function prototypes for non-inline static functions. michael@0: */ michael@0: michael@0: static char *umax2s(uintmax_t x, unsigned base, char *s); michael@0: static bool malloc_mutex_init(malloc_mutex_t *mutex); michael@0: static bool malloc_spin_init(malloc_spinlock_t *lock); michael@0: static void wrtmessage(const char *p1, const char *p2, const char *p3, michael@0: const char *p4); michael@0: #ifdef MALLOC_STATS michael@0: #ifdef MOZ_MEMORY_DARWIN michael@0: /* Avoid namespace collision with OS X's malloc APIs. */ michael@0: #define malloc_printf moz_malloc_printf michael@0: #endif michael@0: static void malloc_printf(const char *format, ...); michael@0: #endif michael@0: static bool base_pages_alloc_mmap(size_t minsize); michael@0: static bool base_pages_alloc(size_t minsize); michael@0: static void *base_alloc(size_t size); michael@0: static void *base_calloc(size_t number, size_t size); michael@0: static extent_node_t *base_node_alloc(void); michael@0: static void base_node_dealloc(extent_node_t *node); michael@0: #ifdef MALLOC_STATS michael@0: static void stats_print(arena_t *arena); michael@0: #endif michael@0: static void *pages_map(void *addr, size_t size, int pfd); michael@0: static void pages_unmap(void *addr, size_t size); michael@0: static void *chunk_alloc_mmap(size_t size, bool pagefile); michael@0: #ifdef MALLOC_PAGEFILE michael@0: static int pagefile_init(size_t size); michael@0: static void pagefile_close(int pfd); michael@0: #endif michael@0: static void *chunk_alloc(size_t size, bool zero, bool pagefile); michael@0: static void chunk_dealloc_mmap(void *chunk, size_t size); michael@0: static void chunk_dealloc(void *chunk, size_t size); michael@0: #ifndef NO_TLS michael@0: static arena_t *choose_arena_hard(void); michael@0: #endif michael@0: static void arena_run_split(arena_t *arena, arena_run_t *run, size_t size, michael@0: bool large, bool zero); michael@0: static void arena_chunk_init(arena_t *arena, arena_chunk_t *chunk); michael@0: static void arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk); michael@0: static arena_run_t *arena_run_alloc(arena_t *arena, arena_bin_t *bin, michael@0: size_t size, bool large, bool zero); michael@0: static void arena_purge(arena_t *arena, bool all); michael@0: static void arena_run_dalloc(arena_t *arena, arena_run_t *run, bool dirty); michael@0: static void arena_run_trim_head(arena_t *arena, arena_chunk_t *chunk, michael@0: arena_run_t *run, size_t oldsize, size_t newsize); michael@0: static void arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk, michael@0: arena_run_t *run, size_t oldsize, size_t newsize, bool dirty); michael@0: static arena_run_t *arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin); michael@0: static void *arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin); michael@0: static size_t arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size); michael@0: #ifdef MALLOC_BALANCE michael@0: static void arena_lock_balance_hard(arena_t *arena); michael@0: #endif michael@0: static void *arena_malloc_large(arena_t *arena, size_t size, bool zero); michael@0: static void *arena_palloc(arena_t *arena, size_t alignment, size_t size, michael@0: size_t alloc_size); michael@0: static size_t arena_salloc(const void *ptr); michael@0: static void arena_dalloc_large(arena_t *arena, arena_chunk_t *chunk, michael@0: void *ptr); michael@0: static void arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk, michael@0: void *ptr, size_t size, size_t oldsize); michael@0: static bool arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk, michael@0: void *ptr, size_t size, size_t oldsize); michael@0: static bool arena_ralloc_large(void *ptr, size_t size, size_t oldsize); michael@0: static void *arena_ralloc(void *ptr, size_t size, size_t oldsize); michael@0: static bool arena_new(arena_t *arena); michael@0: static arena_t *arenas_extend(unsigned ind); michael@0: static void *huge_malloc(size_t size, bool zero); michael@0: static void *huge_palloc(size_t alignment, size_t size); michael@0: static void *huge_ralloc(void *ptr, size_t size, size_t oldsize); michael@0: static void huge_dalloc(void *ptr); michael@0: static void malloc_print_stats(void); michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: static michael@0: #endif michael@0: bool malloc_init_hard(void); michael@0: michael@0: static void _malloc_prefork(void); michael@0: static void _malloc_postfork(void); michael@0: michael@0: #ifdef MOZ_MEMORY_DARWIN michael@0: /* michael@0: * MALLOC_ZONE_T_NOTE michael@0: * michael@0: * On Darwin, we hook into the memory allocator using a malloc_zone_t struct. michael@0: * We must be very careful around this struct because of different behaviour on michael@0: * different versions of OSX. michael@0: * michael@0: * Each of OSX 10.5, 10.6 and 10.7 use different versions of the struct michael@0: * (with version numbers 3, 6 and 8 respectively). The binary we use on each of michael@0: * these platforms will not necessarily be built using the correct SDK [1]. michael@0: * This means we need to statically know the correct struct size to use on all michael@0: * OSX releases, and have a fallback for unknown future versions. The struct michael@0: * sizes defined in osx_zone_types.h. michael@0: * michael@0: * For OSX 10.8 and later, we may expect the malloc_zone_t struct to change michael@0: * again, and need to dynamically account for this. By simply leaving michael@0: * malloc_zone_t alone, we don't quite deal with the problem, because there michael@0: * remain calls to jemalloc through the mozalloc interface. We check this michael@0: * dynamically on each allocation, using the CHECK_DARWIN macro and michael@0: * osx_use_jemalloc. michael@0: * michael@0: * michael@0: * [1] Mozilla is built as a universal binary on Mac, supporting i386 and michael@0: * x86_64. The i386 target is built using the 10.5 SDK, even if it runs on michael@0: * 10.6. The x86_64 target is built using the 10.6 SDK, even if it runs on michael@0: * 10.7 or later, or 10.5. michael@0: * michael@0: * FIXME: michael@0: * When later versions of OSX come out (10.8 and up), we need to check their michael@0: * malloc_zone_t versions. If they're greater than 8, we need a new version michael@0: * of malloc_zone_t adapted into osx_zone_types.h. michael@0: */ michael@0: michael@0: #ifndef MOZ_REPLACE_MALLOC michael@0: #include "osx_zone_types.h" michael@0: michael@0: #define LEOPARD_MALLOC_ZONE_T_VERSION 3 michael@0: #define SNOW_LEOPARD_MALLOC_ZONE_T_VERSION 6 michael@0: #define LION_MALLOC_ZONE_T_VERSION 8 michael@0: michael@0: static bool osx_use_jemalloc = false; michael@0: michael@0: michael@0: static lion_malloc_zone l_szone; michael@0: static malloc_zone_t * szone = (malloc_zone_t*)(&l_szone); michael@0: michael@0: static lion_malloc_introspection l_ozone_introspect; michael@0: static malloc_introspection_t * const ozone_introspect = michael@0: (malloc_introspection_t*)(&l_ozone_introspect); michael@0: static void szone2ozone(malloc_zone_t *zone, size_t size); michael@0: static size_t zone_version_size(int version); michael@0: #else michael@0: static const bool osx_use_jemalloc = true; michael@0: #endif michael@0: michael@0: #endif michael@0: michael@0: /* michael@0: * End function prototypes. michael@0: */ michael@0: /******************************************************************************/ michael@0: michael@0: /* michael@0: * umax2s() provides minimal integer printing functionality, which is michael@0: * especially useful for situations where allocation in vsnprintf() calls would michael@0: * potentially cause deadlock. michael@0: */ michael@0: #define UMAX2S_BUFSIZE 65 michael@0: char * michael@0: umax2s(uintmax_t x, unsigned base, char *s) michael@0: { michael@0: unsigned i; michael@0: michael@0: i = UMAX2S_BUFSIZE - 1; michael@0: s[i] = '\0'; michael@0: switch (base) { michael@0: case 10: michael@0: do { michael@0: i--; michael@0: s[i] = "0123456789"[x % 10]; michael@0: x /= 10; michael@0: } while (x > 0); michael@0: break; michael@0: case 16: michael@0: do { michael@0: i--; michael@0: s[i] = "0123456789abcdef"[x & 0xf]; michael@0: x >>= 4; michael@0: } while (x > 0); michael@0: break; michael@0: default: michael@0: do { michael@0: i--; michael@0: s[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[x % base]; michael@0: x /= base; michael@0: } while (x > 0); michael@0: } michael@0: michael@0: return (&s[i]); michael@0: } michael@0: michael@0: static void michael@0: wrtmessage(const char *p1, const char *p2, const char *p3, const char *p4) michael@0: { michael@0: #if defined(MOZ_MEMORY) && !defined(MOZ_MEMORY_WINDOWS) michael@0: #define _write write michael@0: #endif michael@0: _write(STDERR_FILENO, p1, (unsigned int) strlen(p1)); michael@0: _write(STDERR_FILENO, p2, (unsigned int) strlen(p2)); michael@0: _write(STDERR_FILENO, p3, (unsigned int) strlen(p3)); michael@0: _write(STDERR_FILENO, p4, (unsigned int) strlen(p4)); michael@0: } michael@0: michael@0: MOZ_JEMALLOC_API michael@0: void (*_malloc_message)(const char *p1, const char *p2, const char *p3, michael@0: const char *p4) = wrtmessage; michael@0: michael@0: #ifdef MALLOC_DEBUG michael@0: # define assert(e) do { \ michael@0: if (!(e)) { \ michael@0: char line_buf[UMAX2S_BUFSIZE]; \ michael@0: _malloc_message(__FILE__, ":", umax2s(__LINE__, 10, \ michael@0: line_buf), ": Failed assertion: "); \ michael@0: _malloc_message("\"", #e, "\"\n", ""); \ michael@0: abort(); \ michael@0: } \ michael@0: } while (0) michael@0: #else michael@0: #define assert(e) michael@0: #endif michael@0: michael@0: #include michael@0: #include michael@0: michael@0: /* RELEASE_ASSERT calls jemalloc_crash() instead of calling MOZ_CRASH() michael@0: * directly because we want crashing to add a frame to the stack. This makes michael@0: * it easier to find the failing assertion in crash stacks. */ michael@0: MOZ_NEVER_INLINE static void michael@0: jemalloc_crash() michael@0: { michael@0: MOZ_CRASH(); michael@0: } michael@0: michael@0: #if defined(MOZ_JEMALLOC_HARD_ASSERTS) michael@0: # define RELEASE_ASSERT(assertion) do { \ michael@0: if (!(assertion)) { \ michael@0: jemalloc_crash(); \ michael@0: } \ michael@0: } while (0) michael@0: #else michael@0: # define RELEASE_ASSERT(assertion) assert(assertion) michael@0: #endif michael@0: michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin mutex. We can't use normal pthread mutexes in all places, because michael@0: * they require malloc()ed memory, which causes bootstrapping issues in some michael@0: * cases. michael@0: */ michael@0: michael@0: static bool michael@0: malloc_mutex_init(malloc_mutex_t *mutex) michael@0: { michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: if (isthreaded) michael@0: if (! __crtInitCritSecAndSpinCount(mutex, _CRT_SPINCOUNT)) michael@0: return (true); michael@0: #elif defined(MOZ_MEMORY_DARWIN) michael@0: mutex->lock = OS_SPINLOCK_INIT; michael@0: #elif defined(MOZ_MEMORY_LINUX) && !defined(MOZ_MEMORY_ANDROID) michael@0: pthread_mutexattr_t attr; michael@0: if (pthread_mutexattr_init(&attr) != 0) michael@0: return (true); michael@0: pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP); michael@0: if (pthread_mutex_init(mutex, &attr) != 0) { michael@0: pthread_mutexattr_destroy(&attr); michael@0: return (true); michael@0: } michael@0: pthread_mutexattr_destroy(&attr); michael@0: #elif defined(MOZ_MEMORY) michael@0: if (pthread_mutex_init(mutex, NULL) != 0) michael@0: return (true); michael@0: #else michael@0: static const spinlock_t lock = _SPINLOCK_INITIALIZER; michael@0: michael@0: mutex->lock = lock; michael@0: #endif michael@0: return (false); michael@0: } michael@0: michael@0: static inline void michael@0: malloc_mutex_lock(malloc_mutex_t *mutex) michael@0: { michael@0: michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: EnterCriticalSection(mutex); michael@0: #elif defined(MOZ_MEMORY_DARWIN) michael@0: OSSpinLockLock(&mutex->lock); michael@0: #elif defined(MOZ_MEMORY) michael@0: pthread_mutex_lock(mutex); michael@0: #else michael@0: if (isthreaded) michael@0: _SPINLOCK(&mutex->lock); michael@0: #endif michael@0: } michael@0: michael@0: static inline void michael@0: malloc_mutex_unlock(malloc_mutex_t *mutex) michael@0: { michael@0: michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: LeaveCriticalSection(mutex); michael@0: #elif defined(MOZ_MEMORY_DARWIN) michael@0: OSSpinLockUnlock(&mutex->lock); michael@0: #elif defined(MOZ_MEMORY) michael@0: pthread_mutex_unlock(mutex); michael@0: #else michael@0: if (isthreaded) michael@0: _SPINUNLOCK(&mutex->lock); michael@0: #endif michael@0: } michael@0: michael@0: static bool michael@0: malloc_spin_init(malloc_spinlock_t *lock) michael@0: { michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: if (isthreaded) michael@0: if (! __crtInitCritSecAndSpinCount(lock, _CRT_SPINCOUNT)) michael@0: return (true); michael@0: #elif defined(MOZ_MEMORY_DARWIN) michael@0: lock->lock = OS_SPINLOCK_INIT; michael@0: #elif defined(MOZ_MEMORY_LINUX) && !defined(MOZ_MEMORY_ANDROID) michael@0: pthread_mutexattr_t attr; michael@0: if (pthread_mutexattr_init(&attr) != 0) michael@0: return (true); michael@0: pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP); michael@0: if (pthread_mutex_init(lock, &attr) != 0) { michael@0: pthread_mutexattr_destroy(&attr); michael@0: return (true); michael@0: } michael@0: pthread_mutexattr_destroy(&attr); michael@0: #elif defined(MOZ_MEMORY) michael@0: if (pthread_mutex_init(lock, NULL) != 0) michael@0: return (true); michael@0: #else michael@0: lock->lock = _SPINLOCK_INITIALIZER; michael@0: #endif michael@0: return (false); michael@0: } michael@0: michael@0: static inline void michael@0: malloc_spin_lock(malloc_spinlock_t *lock) michael@0: { michael@0: michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: EnterCriticalSection(lock); michael@0: #elif defined(MOZ_MEMORY_DARWIN) michael@0: OSSpinLockLock(&lock->lock); michael@0: #elif defined(MOZ_MEMORY) michael@0: pthread_mutex_lock(lock); michael@0: #else michael@0: if (isthreaded) michael@0: _SPINLOCK(&lock->lock); michael@0: #endif michael@0: } michael@0: michael@0: static inline void michael@0: malloc_spin_unlock(malloc_spinlock_t *lock) michael@0: { michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: LeaveCriticalSection(lock); michael@0: #elif defined(MOZ_MEMORY_DARWIN) michael@0: OSSpinLockUnlock(&lock->lock); michael@0: #elif defined(MOZ_MEMORY) michael@0: pthread_mutex_unlock(lock); michael@0: #else michael@0: if (isthreaded) michael@0: _SPINUNLOCK(&lock->lock); michael@0: #endif michael@0: } michael@0: michael@0: /* michael@0: * End mutex. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin spin lock. Spin locks here are actually adaptive mutexes that block michael@0: * after a period of spinning, because unbounded spinning would allow for michael@0: * priority inversion. michael@0: */ michael@0: michael@0: #if defined(MOZ_MEMORY) && !defined(MOZ_MEMORY_DARWIN) michael@0: # define malloc_spin_init malloc_mutex_init michael@0: # define malloc_spin_lock malloc_mutex_lock michael@0: # define malloc_spin_unlock malloc_mutex_unlock michael@0: #endif michael@0: michael@0: #ifndef MOZ_MEMORY michael@0: /* michael@0: * We use an unpublished interface to initialize pthread mutexes with an michael@0: * allocation callback, in order to avoid infinite recursion. michael@0: */ michael@0: int _pthread_mutex_init_calloc_cb(pthread_mutex_t *mutex, michael@0: void *(calloc_cb)(size_t, size_t)); michael@0: michael@0: __weak_reference(_pthread_mutex_init_calloc_cb_stub, michael@0: _pthread_mutex_init_calloc_cb); michael@0: michael@0: int michael@0: _pthread_mutex_init_calloc_cb_stub(pthread_mutex_t *mutex, michael@0: void *(calloc_cb)(size_t, size_t)) michael@0: { michael@0: michael@0: return (0); michael@0: } michael@0: michael@0: static bool michael@0: malloc_spin_init(pthread_mutex_t *lock) michael@0: { michael@0: michael@0: if (_pthread_mutex_init_calloc_cb(lock, base_calloc) != 0) michael@0: return (true); michael@0: michael@0: return (false); michael@0: } michael@0: michael@0: static inline unsigned michael@0: malloc_spin_lock(pthread_mutex_t *lock) michael@0: { michael@0: unsigned ret = 0; michael@0: michael@0: if (isthreaded) { michael@0: if (_pthread_mutex_trylock(lock) != 0) { michael@0: unsigned i; michael@0: volatile unsigned j; michael@0: michael@0: /* Exponentially back off. */ michael@0: for (i = 1; i <= SPIN_LIMIT_2POW; i++) { michael@0: for (j = 0; j < (1U << i); j++) michael@0: ret++; michael@0: michael@0: CPU_SPINWAIT; michael@0: if (_pthread_mutex_trylock(lock) == 0) michael@0: return (ret); michael@0: } michael@0: michael@0: /* michael@0: * Spinning failed. Block until the lock becomes michael@0: * available, in order to avoid indefinite priority michael@0: * inversion. michael@0: */ michael@0: _pthread_mutex_lock(lock); michael@0: assert((ret << BLOCK_COST_2POW) != 0); michael@0: return (ret << BLOCK_COST_2POW); michael@0: } michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static inline void michael@0: malloc_spin_unlock(pthread_mutex_t *lock) michael@0: { michael@0: michael@0: if (isthreaded) michael@0: _pthread_mutex_unlock(lock); michael@0: } michael@0: #endif michael@0: michael@0: /* michael@0: * End spin lock. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin Utility functions/macros. michael@0: */ michael@0: michael@0: /* Return the chunk address for allocation address a. */ michael@0: #define CHUNK_ADDR2BASE(a) \ michael@0: ((void *)((uintptr_t)(a) & ~chunksize_mask)) michael@0: michael@0: /* Return the chunk offset of address a. */ michael@0: #define CHUNK_ADDR2OFFSET(a) \ michael@0: ((size_t)((uintptr_t)(a) & chunksize_mask)) michael@0: michael@0: /* Return the smallest chunk multiple that is >= s. */ michael@0: #define CHUNK_CEILING(s) \ michael@0: (((s) + chunksize_mask) & ~chunksize_mask) michael@0: michael@0: /* Return the smallest cacheline multiple that is >= s. */ michael@0: #define CACHELINE_CEILING(s) \ michael@0: (((s) + (CACHELINE - 1)) & ~(CACHELINE - 1)) michael@0: michael@0: /* Return the smallest quantum multiple that is >= a. */ michael@0: #define QUANTUM_CEILING(a) \ michael@0: (((a) + quantum_mask) & ~quantum_mask) michael@0: michael@0: /* Return the smallest pagesize multiple that is >= s. */ michael@0: #define PAGE_CEILING(s) \ michael@0: (((s) + pagesize_mask) & ~pagesize_mask) michael@0: michael@0: /* Compute the smallest power of 2 that is >= x. */ michael@0: static inline size_t michael@0: pow2_ceil(size_t x) michael@0: { michael@0: michael@0: x--; michael@0: x |= x >> 1; michael@0: x |= x >> 2; michael@0: x |= x >> 4; michael@0: x |= x >> 8; michael@0: x |= x >> 16; michael@0: #if (SIZEOF_PTR == 8) michael@0: x |= x >> 32; michael@0: #endif michael@0: x++; michael@0: return (x); michael@0: } michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: /* michael@0: * Use a simple linear congruential pseudo-random number generator: michael@0: * michael@0: * prn(y) = (a*x + c) % m michael@0: * michael@0: * where the following constants ensure maximal period: michael@0: * michael@0: * a == Odd number (relatively prime to 2^n), and (a-1) is a multiple of 4. michael@0: * c == Odd number (relatively prime to 2^n). michael@0: * m == 2^32 michael@0: * michael@0: * See Knuth's TAOCP 3rd Ed., Vol. 2, pg. 17 for details on these constraints. michael@0: * michael@0: * This choice of m has the disadvantage that the quality of the bits is michael@0: * proportional to bit position. For example. the lowest bit has a cycle of 2, michael@0: * the next has a cycle of 4, etc. For this reason, we prefer to use the upper michael@0: * bits. michael@0: */ michael@0: # define PRN_DEFINE(suffix, var, a, c) \ michael@0: static inline void \ michael@0: sprn_##suffix(uint32_t seed) \ michael@0: { \ michael@0: var = seed; \ michael@0: } \ michael@0: \ michael@0: static inline uint32_t \ michael@0: prn_##suffix(uint32_t lg_range) \ michael@0: { \ michael@0: uint32_t ret, x; \ michael@0: \ michael@0: assert(lg_range > 0); \ michael@0: assert(lg_range <= 32); \ michael@0: \ michael@0: x = (var * (a)) + (c); \ michael@0: var = x; \ michael@0: ret = x >> (32 - lg_range); \ michael@0: \ michael@0: return (ret); \ michael@0: } michael@0: # define SPRN(suffix, seed) sprn_##suffix(seed) michael@0: # define PRN(suffix, lg_range) prn_##suffix(lg_range) michael@0: #endif michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: /* Define the PRNG used for arena assignment. */ michael@0: static __thread uint32_t balance_x; michael@0: PRN_DEFINE(balance, balance_x, 1297, 1301) michael@0: #endif michael@0: michael@0: #ifdef MALLOC_UTRACE michael@0: static int michael@0: utrace(const void *addr, size_t len) michael@0: { michael@0: malloc_utrace_t *ut = (malloc_utrace_t *)addr; michael@0: char buf_a[UMAX2S_BUFSIZE]; michael@0: char buf_b[UMAX2S_BUFSIZE]; michael@0: michael@0: assert(len == sizeof(malloc_utrace_t)); michael@0: michael@0: if (ut->p == NULL && ut->s == 0 && ut->r == NULL) { michael@0: _malloc_message( michael@0: umax2s(getpid(), 10, buf_a), michael@0: " x USER malloc_init()\n", "", ""); michael@0: } else if (ut->p == NULL && ut->r != NULL) { michael@0: _malloc_message( michael@0: umax2s(getpid(), 10, buf_a), michael@0: " x USER 0x", michael@0: umax2s((uintptr_t)ut->r, 16, buf_b), michael@0: " = malloc("); michael@0: _malloc_message( michael@0: umax2s(ut->s, 10, buf_a), michael@0: ")\n", "", ""); michael@0: } else if (ut->p != NULL && ut->r != NULL) { michael@0: _malloc_message( michael@0: umax2s(getpid(), 10, buf_a), michael@0: " x USER 0x", michael@0: umax2s((uintptr_t)ut->r, 16, buf_b), michael@0: " = realloc(0x"); michael@0: _malloc_message( michael@0: umax2s((uintptr_t)ut->p, 16, buf_a), michael@0: ", ", michael@0: umax2s(ut->s, 10, buf_b), michael@0: ")\n"); michael@0: } else { michael@0: _malloc_message( michael@0: umax2s(getpid(), 10, buf_a), michael@0: " x USER free(0x", michael@0: umax2s((uintptr_t)ut->p, 16, buf_b), michael@0: ")\n"); michael@0: } michael@0: michael@0: return (0); michael@0: } michael@0: #endif michael@0: michael@0: static inline const char * michael@0: _getprogname(void) michael@0: { michael@0: michael@0: return (""); michael@0: } michael@0: michael@0: #ifdef MALLOC_STATS michael@0: /* michael@0: * Print to stderr in such a way as to (hopefully) avoid memory allocation. michael@0: */ michael@0: static void michael@0: malloc_printf(const char *format, ...) michael@0: { michael@0: char buf[4096]; michael@0: va_list ap; michael@0: michael@0: va_start(ap, format); michael@0: vsnprintf(buf, sizeof(buf), format, ap); michael@0: va_end(ap); michael@0: _malloc_message(buf, "", "", ""); michael@0: } michael@0: #endif michael@0: michael@0: /******************************************************************************/ michael@0: michael@0: static inline void michael@0: pages_decommit(void *addr, size_t size) michael@0: { michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: VirtualFree(addr, size, MEM_DECOMMIT); michael@0: #else michael@0: if (mmap(addr, size, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, michael@0: 0) == MAP_FAILED) michael@0: abort(); michael@0: #endif michael@0: } michael@0: michael@0: static inline void michael@0: pages_commit(void *addr, size_t size) michael@0: { michael@0: michael@0: # ifdef MOZ_MEMORY_WINDOWS michael@0: if (!VirtualAlloc(addr, size, MEM_COMMIT, PAGE_READWRITE)) michael@0: abort(); michael@0: # else michael@0: if (mmap(addr, size, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | michael@0: MAP_ANON, -1, 0) == MAP_FAILED) michael@0: abort(); michael@0: # endif michael@0: } michael@0: michael@0: static bool michael@0: base_pages_alloc_mmap(size_t minsize) michael@0: { michael@0: bool ret; michael@0: size_t csize; michael@0: #if defined(MALLOC_DECOMMIT) || defined(MALLOC_STATS) michael@0: size_t pminsize; michael@0: #endif michael@0: int pfd; michael@0: michael@0: assert(minsize != 0); michael@0: csize = CHUNK_CEILING(minsize); michael@0: #ifdef MALLOC_PAGEFILE michael@0: if (opt_pagefile) { michael@0: pfd = pagefile_init(csize); michael@0: if (pfd == -1) michael@0: return (true); michael@0: } else michael@0: #endif michael@0: pfd = -1; michael@0: base_pages = pages_map(NULL, csize, pfd); michael@0: if (base_pages == NULL) { michael@0: ret = true; michael@0: goto RETURN; michael@0: } michael@0: base_next_addr = base_pages; michael@0: base_past_addr = (void *)((uintptr_t)base_pages + csize); michael@0: #if defined(MALLOC_DECOMMIT) || defined(MALLOC_STATS) michael@0: /* michael@0: * Leave enough pages for minsize committed, since otherwise they would michael@0: * have to be immediately recommitted. michael@0: */ michael@0: pminsize = PAGE_CEILING(minsize); michael@0: base_next_decommitted = (void *)((uintptr_t)base_pages + pminsize); michael@0: # if defined(MALLOC_DECOMMIT) michael@0: if (pminsize < csize) michael@0: pages_decommit(base_next_decommitted, csize - pminsize); michael@0: # endif michael@0: # ifdef MALLOC_STATS michael@0: base_mapped += csize; michael@0: base_committed += pminsize; michael@0: # endif michael@0: #endif michael@0: michael@0: ret = false; michael@0: RETURN: michael@0: #ifdef MALLOC_PAGEFILE michael@0: if (pfd != -1) michael@0: pagefile_close(pfd); michael@0: #endif michael@0: return (false); michael@0: } michael@0: michael@0: static bool michael@0: base_pages_alloc(size_t minsize) michael@0: { michael@0: michael@0: if (base_pages_alloc_mmap(minsize) == false) michael@0: return (false); michael@0: michael@0: return (true); michael@0: } michael@0: michael@0: static void * michael@0: base_alloc(size_t size) michael@0: { michael@0: void *ret; michael@0: size_t csize; michael@0: michael@0: /* Round size up to nearest multiple of the cacheline size. */ michael@0: csize = CACHELINE_CEILING(size); michael@0: michael@0: malloc_mutex_lock(&base_mtx); michael@0: /* Make sure there's enough space for the allocation. */ michael@0: if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) { michael@0: if (base_pages_alloc(csize)) { michael@0: malloc_mutex_unlock(&base_mtx); michael@0: return (NULL); michael@0: } michael@0: } michael@0: /* Allocate. */ michael@0: ret = base_next_addr; michael@0: base_next_addr = (void *)((uintptr_t)base_next_addr + csize); michael@0: #if defined(MALLOC_DECOMMIT) || defined(MALLOC_STATS) michael@0: /* Make sure enough pages are committed for the new allocation. */ michael@0: if ((uintptr_t)base_next_addr > (uintptr_t)base_next_decommitted) { michael@0: void *pbase_next_addr = michael@0: (void *)(PAGE_CEILING((uintptr_t)base_next_addr)); michael@0: michael@0: # ifdef MALLOC_DECOMMIT michael@0: pages_commit(base_next_decommitted, (uintptr_t)pbase_next_addr - michael@0: (uintptr_t)base_next_decommitted); michael@0: # endif michael@0: base_next_decommitted = pbase_next_addr; michael@0: # ifdef MALLOC_STATS michael@0: base_committed += (uintptr_t)pbase_next_addr - michael@0: (uintptr_t)base_next_decommitted; michael@0: # endif michael@0: } michael@0: #endif michael@0: malloc_mutex_unlock(&base_mtx); michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, false); michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static void * michael@0: base_calloc(size_t number, size_t size) michael@0: { michael@0: void *ret; michael@0: michael@0: ret = base_alloc(number * size); michael@0: #ifdef MALLOC_VALGRIND michael@0: if (ret != NULL) { michael@0: VALGRIND_FREELIKE_BLOCK(ret, 0); michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, true); michael@0: } michael@0: #endif michael@0: memset(ret, 0, number * size); michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static extent_node_t * michael@0: base_node_alloc(void) michael@0: { michael@0: extent_node_t *ret; michael@0: michael@0: malloc_mutex_lock(&base_mtx); michael@0: if (base_nodes != NULL) { michael@0: ret = base_nodes; michael@0: base_nodes = *(extent_node_t **)ret; michael@0: VALGRIND_FREELIKE_BLOCK(ret, 0); michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, sizeof(extent_node_t), 0, false); michael@0: malloc_mutex_unlock(&base_mtx); michael@0: } else { michael@0: malloc_mutex_unlock(&base_mtx); michael@0: ret = (extent_node_t *)base_alloc(sizeof(extent_node_t)); michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static void michael@0: base_node_dealloc(extent_node_t *node) michael@0: { michael@0: michael@0: malloc_mutex_lock(&base_mtx); michael@0: VALGRIND_FREELIKE_BLOCK(node, 0); michael@0: VALGRIND_MALLOCLIKE_BLOCK(node, sizeof(extent_node_t *), 0, false); michael@0: *(extent_node_t **)node = base_nodes; michael@0: base_nodes = node; michael@0: malloc_mutex_unlock(&base_mtx); michael@0: } michael@0: michael@0: /******************************************************************************/ michael@0: michael@0: #ifdef MALLOC_STATS michael@0: static void michael@0: stats_print(arena_t *arena) michael@0: { michael@0: unsigned i, gap_start; michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: malloc_printf("dirty: %Iu page%s dirty, %I64u sweep%s," michael@0: " %I64u madvise%s, %I64u page%s purged\n", michael@0: arena->ndirty, arena->ndirty == 1 ? "" : "s", michael@0: arena->stats.npurge, arena->stats.npurge == 1 ? "" : "s", michael@0: arena->stats.nmadvise, arena->stats.nmadvise == 1 ? "" : "s", michael@0: arena->stats.purged, arena->stats.purged == 1 ? "" : "s"); michael@0: # ifdef MALLOC_DECOMMIT michael@0: malloc_printf("decommit: %I64u decommit%s, %I64u commit%s," michael@0: " %I64u page%s decommitted\n", michael@0: arena->stats.ndecommit, (arena->stats.ndecommit == 1) ? "" : "s", michael@0: arena->stats.ncommit, (arena->stats.ncommit == 1) ? "" : "s", michael@0: arena->stats.decommitted, michael@0: (arena->stats.decommitted == 1) ? "" : "s"); michael@0: # endif michael@0: michael@0: malloc_printf(" allocated nmalloc ndalloc\n"); michael@0: malloc_printf("small: %12Iu %12I64u %12I64u\n", michael@0: arena->stats.allocated_small, arena->stats.nmalloc_small, michael@0: arena->stats.ndalloc_small); michael@0: malloc_printf("large: %12Iu %12I64u %12I64u\n", michael@0: arena->stats.allocated_large, arena->stats.nmalloc_large, michael@0: arena->stats.ndalloc_large); michael@0: malloc_printf("total: %12Iu %12I64u %12I64u\n", michael@0: arena->stats.allocated_small + arena->stats.allocated_large, michael@0: arena->stats.nmalloc_small + arena->stats.nmalloc_large, michael@0: arena->stats.ndalloc_small + arena->stats.ndalloc_large); michael@0: malloc_printf("mapped: %12Iu\n", arena->stats.mapped); michael@0: #else michael@0: malloc_printf("dirty: %zu page%s dirty, %llu sweep%s," michael@0: " %llu madvise%s, %llu page%s purged\n", michael@0: arena->ndirty, arena->ndirty == 1 ? "" : "s", michael@0: arena->stats.npurge, arena->stats.npurge == 1 ? "" : "s", michael@0: arena->stats.nmadvise, arena->stats.nmadvise == 1 ? "" : "s", michael@0: arena->stats.purged, arena->stats.purged == 1 ? "" : "s"); michael@0: # ifdef MALLOC_DECOMMIT michael@0: malloc_printf("decommit: %llu decommit%s, %llu commit%s," michael@0: " %llu page%s decommitted\n", michael@0: arena->stats.ndecommit, (arena->stats.ndecommit == 1) ? "" : "s", michael@0: arena->stats.ncommit, (arena->stats.ncommit == 1) ? "" : "s", michael@0: arena->stats.decommitted, michael@0: (arena->stats.decommitted == 1) ? "" : "s"); michael@0: # endif michael@0: michael@0: malloc_printf(" allocated nmalloc ndalloc\n"); michael@0: malloc_printf("small: %12zu %12llu %12llu\n", michael@0: arena->stats.allocated_small, arena->stats.nmalloc_small, michael@0: arena->stats.ndalloc_small); michael@0: malloc_printf("large: %12zu %12llu %12llu\n", michael@0: arena->stats.allocated_large, arena->stats.nmalloc_large, michael@0: arena->stats.ndalloc_large); michael@0: malloc_printf("total: %12zu %12llu %12llu\n", michael@0: arena->stats.allocated_small + arena->stats.allocated_large, michael@0: arena->stats.nmalloc_small + arena->stats.nmalloc_large, michael@0: arena->stats.ndalloc_small + arena->stats.ndalloc_large); michael@0: malloc_printf("mapped: %12zu\n", arena->stats.mapped); michael@0: #endif michael@0: malloc_printf("bins: bin size regs pgs requests newruns" michael@0: " reruns maxruns curruns\n"); michael@0: for (i = 0, gap_start = UINT_MAX; i < ntbins + nqbins + nsbins; i++) { michael@0: if (arena->bins[i].stats.nrequests == 0) { michael@0: if (gap_start == UINT_MAX) michael@0: gap_start = i; michael@0: } else { michael@0: if (gap_start != UINT_MAX) { michael@0: if (i > gap_start + 1) { michael@0: /* Gap of more than one size class. */ michael@0: malloc_printf("[%u..%u]\n", michael@0: gap_start, i - 1); michael@0: } else { michael@0: /* Gap of one size class. */ michael@0: malloc_printf("[%u]\n", gap_start); michael@0: } michael@0: gap_start = UINT_MAX; michael@0: } michael@0: malloc_printf( michael@0: #if defined(MOZ_MEMORY_WINDOWS) michael@0: "%13u %1s %4u %4u %3u %9I64u %9I64u" michael@0: " %9I64u %7u %7u\n", michael@0: #else michael@0: "%13u %1s %4u %4u %3u %9llu %9llu" michael@0: " %9llu %7lu %7lu\n", michael@0: #endif michael@0: i, michael@0: i < ntbins ? "T" : i < ntbins + nqbins ? "Q" : "S", michael@0: arena->bins[i].reg_size, michael@0: arena->bins[i].nregs, michael@0: arena->bins[i].run_size >> pagesize_2pow, michael@0: arena->bins[i].stats.nrequests, michael@0: arena->bins[i].stats.nruns, michael@0: arena->bins[i].stats.reruns, michael@0: arena->bins[i].stats.highruns, michael@0: arena->bins[i].stats.curruns); michael@0: } michael@0: } michael@0: if (gap_start != UINT_MAX) { michael@0: if (i > gap_start + 1) { michael@0: /* Gap of more than one size class. */ michael@0: malloc_printf("[%u..%u]\n", gap_start, i - 1); michael@0: } else { michael@0: /* Gap of one size class. */ michael@0: malloc_printf("[%u]\n", gap_start); michael@0: } michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: /* michael@0: * End Utility functions/macros. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin extent tree code. michael@0: */ michael@0: michael@0: static inline int michael@0: extent_szad_comp(extent_node_t *a, extent_node_t *b) michael@0: { michael@0: int ret; michael@0: size_t a_size = a->size; michael@0: size_t b_size = b->size; michael@0: michael@0: ret = (a_size > b_size) - (a_size < b_size); michael@0: if (ret == 0) { michael@0: uintptr_t a_addr = (uintptr_t)a->addr; michael@0: uintptr_t b_addr = (uintptr_t)b->addr; michael@0: michael@0: ret = (a_addr > b_addr) - (a_addr < b_addr); michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: /* Wrap red-black tree macros in functions. */ michael@0: rb_wrap(static, extent_tree_szad_, extent_tree_t, extent_node_t, michael@0: link_szad, extent_szad_comp) michael@0: michael@0: static inline int michael@0: extent_ad_comp(extent_node_t *a, extent_node_t *b) michael@0: { michael@0: uintptr_t a_addr = (uintptr_t)a->addr; michael@0: uintptr_t b_addr = (uintptr_t)b->addr; michael@0: michael@0: return ((a_addr > b_addr) - (a_addr < b_addr)); michael@0: } michael@0: michael@0: /* Wrap red-black tree macros in functions. */ michael@0: rb_wrap(static, extent_tree_ad_, extent_tree_t, extent_node_t, link_ad, michael@0: extent_ad_comp) michael@0: michael@0: /* michael@0: * End extent tree code. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin chunk management functions. michael@0: */ michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: michael@0: static void * michael@0: pages_map(void *addr, size_t size, int pfd) michael@0: { michael@0: void *ret = NULL; michael@0: ret = VirtualAlloc(addr, size, MEM_COMMIT | MEM_RESERVE, michael@0: PAGE_READWRITE); michael@0: return (ret); michael@0: } michael@0: michael@0: static void michael@0: pages_unmap(void *addr, size_t size) michael@0: { michael@0: if (VirtualFree(addr, 0, MEM_RELEASE) == 0) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in VirtualFree()\n", "", ""); michael@0: if (opt_abort) michael@0: abort(); michael@0: } michael@0: } michael@0: #else michael@0: #ifdef JEMALLOC_USES_MAP_ALIGN michael@0: static void * michael@0: pages_map_align(size_t size, int pfd, size_t alignment) michael@0: { michael@0: void *ret; michael@0: michael@0: /* michael@0: * We don't use MAP_FIXED here, because it can cause the *replacement* michael@0: * of existing mappings, and we only want to create new mappings. michael@0: */ michael@0: #ifdef MALLOC_PAGEFILE michael@0: if (pfd != -1) { michael@0: ret = mmap((void *)alignment, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | michael@0: MAP_NOSYNC | MAP_ALIGN, pfd, 0); michael@0: } else michael@0: #endif michael@0: { michael@0: ret = mmap((void *)alignment, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | michael@0: MAP_NOSYNC | MAP_ALIGN | MAP_ANON, -1, 0); michael@0: } michael@0: assert(ret != NULL); michael@0: michael@0: if (ret == MAP_FAILED) michael@0: ret = NULL; michael@0: return (ret); michael@0: } michael@0: #endif michael@0: michael@0: static void * michael@0: pages_map(void *addr, size_t size, int pfd) michael@0: { michael@0: void *ret; michael@0: #if defined(__ia64__) michael@0: /* michael@0: * The JS engine assumes that all allocated pointers have their high 17 bits clear, michael@0: * which ia64's mmap doesn't support directly. However, we can emulate it by passing michael@0: * mmap an "addr" parameter with those bits clear. The mmap will return that address, michael@0: * or the nearest available memory above that address, providing a near-guarantee michael@0: * that those bits are clear. If they are not, we return NULL below to indicate michael@0: * out-of-memory. michael@0: * michael@0: * The addr is chosen as 0x0000070000000000, which still allows about 120TB of virtual michael@0: * address space. michael@0: * michael@0: * See Bug 589735 for more information. michael@0: */ michael@0: bool check_placement = true; michael@0: if (addr == NULL) { michael@0: addr = (void*)0x0000070000000000; michael@0: check_placement = false; michael@0: } michael@0: #endif michael@0: michael@0: /* michael@0: * We don't use MAP_FIXED here, because it can cause the *replacement* michael@0: * of existing mappings, and we only want to create new mappings. michael@0: */ michael@0: #ifdef MALLOC_PAGEFILE michael@0: if (pfd != -1) { michael@0: ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | michael@0: MAP_NOSYNC, pfd, 0); michael@0: } else michael@0: #endif michael@0: { michael@0: ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | michael@0: MAP_ANON, -1, 0); michael@0: } michael@0: assert(ret != NULL); michael@0: michael@0: if (ret == MAP_FAILED) { michael@0: ret = NULL; michael@0: } michael@0: #if defined(__ia64__) michael@0: /* michael@0: * If the allocated memory doesn't have its upper 17 bits clear, consider it michael@0: * as out of memory. michael@0: */ michael@0: else if ((long long)ret & 0xffff800000000000) { michael@0: munmap(ret, size); michael@0: ret = NULL; michael@0: } michael@0: /* If the caller requested a specific memory location, verify that's what mmap returned. */ michael@0: else if (check_placement && ret != addr) { michael@0: #else michael@0: else if (addr != NULL && ret != addr) { michael@0: #endif michael@0: /* michael@0: * We succeeded in mapping memory, but not in the right place. michael@0: */ michael@0: if (munmap(ret, size) == -1) { michael@0: char buf[STRERROR_BUF]; michael@0: michael@0: strerror_r(errno, buf, sizeof(buf)); michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in munmap(): ", buf, "\n"); michael@0: if (opt_abort) michael@0: abort(); michael@0: } michael@0: ret = NULL; michael@0: } michael@0: michael@0: #if defined(__ia64__) michael@0: assert(ret == NULL || (!check_placement && ret != NULL) michael@0: || (check_placement && ret == addr)); michael@0: #else michael@0: assert(ret == NULL || (addr == NULL && ret != addr) michael@0: || (addr != NULL && ret == addr)); michael@0: #endif michael@0: return (ret); michael@0: } michael@0: michael@0: static void michael@0: pages_unmap(void *addr, size_t size) michael@0: { michael@0: michael@0: if (munmap(addr, size) == -1) { michael@0: char buf[STRERROR_BUF]; michael@0: michael@0: strerror_r(errno, buf, sizeof(buf)); michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in munmap(): ", buf, "\n"); michael@0: if (opt_abort) michael@0: abort(); michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: #ifdef MOZ_MEMORY_DARWIN michael@0: #define VM_COPY_MIN (pagesize << 5) michael@0: static inline void michael@0: pages_copy(void *dest, const void *src, size_t n) michael@0: { michael@0: michael@0: assert((void *)((uintptr_t)dest & ~pagesize_mask) == dest); michael@0: assert(n >= VM_COPY_MIN); michael@0: assert((void *)((uintptr_t)src & ~pagesize_mask) == src); michael@0: michael@0: vm_copy(mach_task_self(), (vm_address_t)src, (vm_size_t)n, michael@0: (vm_address_t)dest); michael@0: } michael@0: #endif michael@0: michael@0: #ifdef MALLOC_VALIDATE michael@0: static inline malloc_rtree_t * michael@0: malloc_rtree_new(unsigned bits) michael@0: { michael@0: malloc_rtree_t *ret; michael@0: unsigned bits_per_level, height, i; michael@0: michael@0: bits_per_level = ffs(pow2_ceil((MALLOC_RTREE_NODESIZE / michael@0: sizeof(void *)))) - 1; michael@0: height = bits / bits_per_level; michael@0: if (height * bits_per_level != bits) michael@0: height++; michael@0: RELEASE_ASSERT(height * bits_per_level >= bits); michael@0: michael@0: ret = (malloc_rtree_t*)base_calloc(1, sizeof(malloc_rtree_t) + michael@0: (sizeof(unsigned) * (height - 1))); michael@0: if (ret == NULL) michael@0: return (NULL); michael@0: michael@0: malloc_spin_init(&ret->lock); michael@0: ret->height = height; michael@0: if (bits_per_level * height > bits) michael@0: ret->level2bits[0] = bits % bits_per_level; michael@0: else michael@0: ret->level2bits[0] = bits_per_level; michael@0: for (i = 1; i < height; i++) michael@0: ret->level2bits[i] = bits_per_level; michael@0: michael@0: ret->root = (void**)base_calloc(1, sizeof(void *) << ret->level2bits[0]); michael@0: if (ret->root == NULL) { michael@0: /* michael@0: * We leak the rtree here, since there's no generic base michael@0: * deallocation. michael@0: */ michael@0: return (NULL); michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: #define MALLOC_RTREE_GET_GENERATE(f) \ michael@0: /* The least significant bits of the key are ignored. */ \ michael@0: static inline void * \ michael@0: f(malloc_rtree_t *rtree, uintptr_t key) \ michael@0: { \ michael@0: void *ret; \ michael@0: uintptr_t subkey; \ michael@0: unsigned i, lshift, height, bits; \ michael@0: void **node, **child; \ michael@0: \ michael@0: MALLOC_RTREE_LOCK(&rtree->lock); \ michael@0: for (i = lshift = 0, height = rtree->height, node = rtree->root;\ michael@0: i < height - 1; \ michael@0: i++, lshift += bits, node = child) { \ michael@0: bits = rtree->level2bits[i]; \ michael@0: subkey = (key << lshift) >> ((SIZEOF_PTR << 3) - bits); \ michael@0: child = (void**)node[subkey]; \ michael@0: if (child == NULL) { \ michael@0: MALLOC_RTREE_UNLOCK(&rtree->lock); \ michael@0: return (NULL); \ michael@0: } \ michael@0: } \ michael@0: \ michael@0: /* \ michael@0: * node is a leaf, so it contains values rather than node \ michael@0: * pointers. \ michael@0: */ \ michael@0: bits = rtree->level2bits[i]; \ michael@0: subkey = (key << lshift) >> ((SIZEOF_PTR << 3) - bits); \ michael@0: ret = node[subkey]; \ michael@0: MALLOC_RTREE_UNLOCK(&rtree->lock); \ michael@0: \ michael@0: MALLOC_RTREE_GET_VALIDATE \ michael@0: return (ret); \ michael@0: } michael@0: michael@0: #ifdef MALLOC_DEBUG michael@0: # define MALLOC_RTREE_LOCK(l) malloc_spin_lock(l) michael@0: # define MALLOC_RTREE_UNLOCK(l) malloc_spin_unlock(l) michael@0: # define MALLOC_RTREE_GET_VALIDATE michael@0: MALLOC_RTREE_GET_GENERATE(malloc_rtree_get_locked) michael@0: # undef MALLOC_RTREE_LOCK michael@0: # undef MALLOC_RTREE_UNLOCK michael@0: # undef MALLOC_RTREE_GET_VALIDATE michael@0: #endif michael@0: michael@0: #define MALLOC_RTREE_LOCK(l) michael@0: #define MALLOC_RTREE_UNLOCK(l) michael@0: #ifdef MALLOC_DEBUG michael@0: /* michael@0: * Suppose that it were possible for a jemalloc-allocated chunk to be michael@0: * munmap()ped, followed by a different allocator in another thread re-using michael@0: * overlapping virtual memory, all without invalidating the cached rtree michael@0: * value. The result would be a false positive (the rtree would claim that michael@0: * jemalloc owns memory that it had actually discarded). I don't think this michael@0: * scenario is possible, but the following assertion is a prudent sanity michael@0: * check. michael@0: */ michael@0: # define MALLOC_RTREE_GET_VALIDATE \ michael@0: assert(malloc_rtree_get_locked(rtree, key) == ret); michael@0: #else michael@0: # define MALLOC_RTREE_GET_VALIDATE michael@0: #endif michael@0: MALLOC_RTREE_GET_GENERATE(malloc_rtree_get) michael@0: #undef MALLOC_RTREE_LOCK michael@0: #undef MALLOC_RTREE_UNLOCK michael@0: #undef MALLOC_RTREE_GET_VALIDATE michael@0: michael@0: static inline bool michael@0: malloc_rtree_set(malloc_rtree_t *rtree, uintptr_t key, void *val) michael@0: { michael@0: uintptr_t subkey; michael@0: unsigned i, lshift, height, bits; michael@0: void **node, **child; michael@0: michael@0: malloc_spin_lock(&rtree->lock); michael@0: for (i = lshift = 0, height = rtree->height, node = rtree->root; michael@0: i < height - 1; michael@0: i++, lshift += bits, node = child) { michael@0: bits = rtree->level2bits[i]; michael@0: subkey = (key << lshift) >> ((SIZEOF_PTR << 3) - bits); michael@0: child = (void**)node[subkey]; michael@0: if (child == NULL) { michael@0: child = (void**)base_calloc(1, sizeof(void *) << michael@0: rtree->level2bits[i+1]); michael@0: if (child == NULL) { michael@0: malloc_spin_unlock(&rtree->lock); michael@0: return (true); michael@0: } michael@0: node[subkey] = child; michael@0: } michael@0: } michael@0: michael@0: /* node is a leaf, so it contains values rather than node pointers. */ michael@0: bits = rtree->level2bits[i]; michael@0: subkey = (key << lshift) >> ((SIZEOF_PTR << 3) - bits); michael@0: node[subkey] = val; michael@0: malloc_spin_unlock(&rtree->lock); michael@0: michael@0: return (false); michael@0: } michael@0: #endif michael@0: michael@0: #if defined(MOZ_MEMORY_WINDOWS) || defined(JEMALLOC_USES_MAP_ALIGN) || defined(MALLOC_PAGEFILE) michael@0: michael@0: /* Allocate an aligned chunk while maintaining a 1:1 correspondence between michael@0: * mmap and unmap calls. This is important on Windows, but not elsewhere. */ michael@0: static void * michael@0: chunk_alloc_mmap(size_t size, bool pagefile) michael@0: { michael@0: void *ret; michael@0: #ifndef JEMALLOC_USES_MAP_ALIGN michael@0: size_t offset; michael@0: #endif michael@0: int pfd; michael@0: michael@0: #ifdef MALLOC_PAGEFILE michael@0: if (opt_pagefile && pagefile) { michael@0: pfd = pagefile_init(size); michael@0: if (pfd == -1) michael@0: return (NULL); michael@0: } else michael@0: #endif michael@0: pfd = -1; michael@0: michael@0: #ifdef JEMALLOC_USES_MAP_ALIGN michael@0: ret = pages_map_align(size, pfd, chunksize); michael@0: #else michael@0: ret = pages_map(NULL, size, pfd); michael@0: if (ret == NULL) michael@0: goto RETURN; michael@0: michael@0: offset = CHUNK_ADDR2OFFSET(ret); michael@0: if (offset != 0) { michael@0: /* Deallocate, then try to allocate at (ret + size - offset). */ michael@0: pages_unmap(ret, size); michael@0: ret = pages_map((void *)((uintptr_t)ret + size - offset), size, michael@0: pfd); michael@0: while (ret == NULL) { michael@0: /* michael@0: * Over-allocate in order to map a memory region that michael@0: * is definitely large enough. michael@0: */ michael@0: ret = pages_map(NULL, size + chunksize, -1); michael@0: if (ret == NULL) michael@0: goto RETURN; michael@0: /* michael@0: * Deallocate, then allocate the correct size, within michael@0: * the over-sized mapping. michael@0: */ michael@0: offset = CHUNK_ADDR2OFFSET(ret); michael@0: pages_unmap(ret, size + chunksize); michael@0: if (offset == 0) michael@0: ret = pages_map(ret, size, pfd); michael@0: else { michael@0: ret = pages_map((void *)((uintptr_t)ret + michael@0: chunksize - offset), size, pfd); michael@0: } michael@0: /* michael@0: * Failure here indicates a race with another thread, so michael@0: * try again. michael@0: */ michael@0: } michael@0: } michael@0: RETURN: michael@0: #endif michael@0: #ifdef MALLOC_PAGEFILE michael@0: if (pfd != -1) michael@0: pagefile_close(pfd); michael@0: #endif michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: #else /* ! (defined(MOZ_MEMORY_WINDOWS) || defined(JEMALLOC_USES_MAP_ALIGN) || defined(MALLOC_PAGEFILE)) */ michael@0: michael@0: /* pages_trim, chunk_alloc_mmap_slow and chunk_alloc_mmap were cherry-picked michael@0: * from upstream jemalloc 3.4.1 to fix Mozilla bug 956501. */ michael@0: michael@0: /* Return the offset between a and the nearest aligned address at or below a. */ michael@0: #define ALIGNMENT_ADDR2OFFSET(a, alignment) \ michael@0: ((size_t)((uintptr_t)(a) & (alignment - 1))) michael@0: michael@0: /* Return the smallest alignment multiple that is >= s. */ michael@0: #define ALIGNMENT_CEILING(s, alignment) \ michael@0: (((s) + (alignment - 1)) & (-(alignment))) michael@0: michael@0: static void * michael@0: pages_trim(void *addr, size_t alloc_size, size_t leadsize, size_t size) michael@0: { michael@0: size_t trailsize; michael@0: void *ret = (void *)((uintptr_t)addr + leadsize); michael@0: michael@0: assert(alloc_size >= leadsize + size); michael@0: trailsize = alloc_size - leadsize - size; michael@0: michael@0: if (leadsize != 0) michael@0: pages_unmap(addr, leadsize); michael@0: if (trailsize != 0) michael@0: pages_unmap((void *)((uintptr_t)ret + size), trailsize); michael@0: return (ret); michael@0: } michael@0: michael@0: static void * michael@0: chunk_alloc_mmap_slow(size_t size, size_t alignment) michael@0: { michael@0: void *ret, *pages; michael@0: size_t alloc_size, leadsize; michael@0: michael@0: alloc_size = size + alignment - pagesize; michael@0: /* Beware size_t wrap-around. */ michael@0: if (alloc_size < size) michael@0: return (NULL); michael@0: do { michael@0: pages = pages_map(NULL, alloc_size, -1); michael@0: if (pages == NULL) michael@0: return (NULL); michael@0: leadsize = ALIGNMENT_CEILING((uintptr_t)pages, alignment) - michael@0: (uintptr_t)pages; michael@0: ret = pages_trim(pages, alloc_size, leadsize, size); michael@0: } while (ret == NULL); michael@0: michael@0: assert(ret != NULL); michael@0: return (ret); michael@0: } michael@0: michael@0: static void * michael@0: chunk_alloc_mmap(size_t size, bool pagefile) michael@0: { michael@0: void *ret; michael@0: size_t offset; michael@0: michael@0: /* michael@0: * Ideally, there would be a way to specify alignment to mmap() (like michael@0: * NetBSD has), but in the absence of such a feature, we have to work michael@0: * hard to efficiently create aligned mappings. The reliable, but michael@0: * slow method is to create a mapping that is over-sized, then trim the michael@0: * excess. However, that always results in one or two calls to michael@0: * pages_unmap(). michael@0: * michael@0: * Optimistically try mapping precisely the right amount before falling michael@0: * back to the slow method, with the expectation that the optimistic michael@0: * approach works most of the time. michael@0: */ michael@0: michael@0: ret = pages_map(NULL, size, -1); michael@0: if (ret == NULL) michael@0: return (NULL); michael@0: offset = ALIGNMENT_ADDR2OFFSET(ret, chunksize); michael@0: if (offset != 0) { michael@0: pages_unmap(ret, size); michael@0: return (chunk_alloc_mmap_slow(size, chunksize)); michael@0: } michael@0: michael@0: assert(ret != NULL); michael@0: return (ret); michael@0: } michael@0: michael@0: #endif /* defined(MOZ_MEMORY_WINDOWS) || defined(JEMALLOC_USES_MAP_ALIGN) || defined(MALLOC_PAGEFILE) */ michael@0: michael@0: #ifdef MALLOC_PAGEFILE michael@0: static int michael@0: pagefile_init(size_t size) michael@0: { michael@0: int ret; michael@0: size_t i; michael@0: char pagefile_path[PATH_MAX]; michael@0: char zbuf[MALLOC_PAGEFILE_WRITE_SIZE]; michael@0: michael@0: /* michael@0: * Create a temporary file, then immediately unlink it so that it will michael@0: * not persist. michael@0: */ michael@0: strcpy(pagefile_path, pagefile_templ); michael@0: ret = mkstemp(pagefile_path); michael@0: if (ret == -1) michael@0: return (ret); michael@0: if (unlink(pagefile_path)) { michael@0: char buf[STRERROR_BUF]; michael@0: michael@0: strerror_r(errno, buf, sizeof(buf)); michael@0: _malloc_message(_getprogname(), ": (malloc) Error in unlink(\"", michael@0: pagefile_path, "\"):"); michael@0: _malloc_message(buf, "\n", "", ""); michael@0: if (opt_abort) michael@0: abort(); michael@0: } michael@0: michael@0: /* michael@0: * Write sequential zeroes to the file in order to assure that disk michael@0: * space is committed, with minimal fragmentation. It would be michael@0: * sufficient to write one zero per disk block, but that potentially michael@0: * results in more system calls, for no real gain. michael@0: */ michael@0: memset(zbuf, 0, sizeof(zbuf)); michael@0: for (i = 0; i < size; i += sizeof(zbuf)) { michael@0: if (write(ret, zbuf, sizeof(zbuf)) != sizeof(zbuf)) { michael@0: if (errno != ENOSPC) { michael@0: char buf[STRERROR_BUF]; michael@0: michael@0: strerror_r(errno, buf, sizeof(buf)); michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in write(): ", buf, "\n"); michael@0: if (opt_abort) michael@0: abort(); michael@0: } michael@0: pagefile_close(ret); michael@0: return (-1); michael@0: } michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static void michael@0: pagefile_close(int pfd) michael@0: { michael@0: michael@0: if (close(pfd)) { michael@0: char buf[STRERROR_BUF]; michael@0: michael@0: strerror_r(errno, buf, sizeof(buf)); michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in close(): ", buf, "\n"); michael@0: if (opt_abort) michael@0: abort(); michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: static void * michael@0: chunk_alloc(size_t size, bool zero, bool pagefile) michael@0: { michael@0: void *ret; michael@0: michael@0: assert(size != 0); michael@0: assert((size & chunksize_mask) == 0); michael@0: michael@0: ret = chunk_alloc_mmap(size, pagefile); michael@0: if (ret != NULL) { michael@0: goto RETURN; michael@0: } michael@0: michael@0: /* All strategies for allocation failed. */ michael@0: ret = NULL; michael@0: RETURN: michael@0: michael@0: #ifdef MALLOC_VALIDATE michael@0: if (ret != NULL) { michael@0: if (malloc_rtree_set(chunk_rtree, (uintptr_t)ret, ret)) { michael@0: chunk_dealloc(ret, size); michael@0: return (NULL); michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: assert(CHUNK_ADDR2BASE(ret) == ret); michael@0: return (ret); michael@0: } michael@0: michael@0: static void michael@0: chunk_dealloc_mmap(void *chunk, size_t size) michael@0: { michael@0: michael@0: pages_unmap(chunk, size); michael@0: } michael@0: michael@0: static void michael@0: chunk_dealloc(void *chunk, size_t size) michael@0: { michael@0: michael@0: assert(chunk != NULL); michael@0: assert(CHUNK_ADDR2BASE(chunk) == chunk); michael@0: assert(size != 0); michael@0: assert((size & chunksize_mask) == 0); michael@0: michael@0: #ifdef MALLOC_VALIDATE michael@0: malloc_rtree_set(chunk_rtree, (uintptr_t)chunk, NULL); michael@0: #endif michael@0: michael@0: chunk_dealloc_mmap(chunk, size); michael@0: } michael@0: michael@0: /* michael@0: * End chunk management functions. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin arena. michael@0: */ michael@0: michael@0: /* michael@0: * Choose an arena based on a per-thread value (fast-path code, calls slow-path michael@0: * code if necessary). michael@0: */ michael@0: static inline arena_t * michael@0: choose_arena(void) michael@0: { michael@0: arena_t *ret; michael@0: michael@0: /* michael@0: * We can only use TLS if this is a PIC library, since for the static michael@0: * library version, libc's malloc is used by TLS allocation, which michael@0: * introduces a bootstrapping issue. michael@0: */ michael@0: #ifndef NO_TLS michael@0: if (isthreaded == false) { michael@0: /* Avoid the overhead of TLS for single-threaded operation. */ michael@0: return (arenas[0]); michael@0: } michael@0: michael@0: # ifdef MOZ_MEMORY_WINDOWS michael@0: ret = (arena_t*)TlsGetValue(tlsIndex); michael@0: # else michael@0: ret = arenas_map; michael@0: # endif michael@0: michael@0: if (ret == NULL) { michael@0: ret = choose_arena_hard(); michael@0: RELEASE_ASSERT(ret != NULL); michael@0: } michael@0: #else michael@0: if (isthreaded && narenas > 1) { michael@0: unsigned long ind; michael@0: michael@0: /* michael@0: * Hash _pthread_self() to one of the arenas. There is a prime michael@0: * number of arenas, so this has a reasonable chance of michael@0: * working. Even so, the hashing can be easily thwarted by michael@0: * inconvenient _pthread_self() values. Without specific michael@0: * knowledge of how _pthread_self() calculates values, we can't michael@0: * easily do much better than this. michael@0: */ michael@0: ind = (unsigned long) _pthread_self() % narenas; michael@0: michael@0: /* michael@0: * Optimistially assume that arenas[ind] has been initialized. michael@0: * At worst, we find out that some other thread has already michael@0: * done so, after acquiring the lock in preparation. Note that michael@0: * this lazy locking also has the effect of lazily forcing michael@0: * cache coherency; without the lock acquisition, there's no michael@0: * guarantee that modification of arenas[ind] by another thread michael@0: * would be seen on this CPU for an arbitrary amount of time. michael@0: * michael@0: * In general, this approach to modifying a synchronized value michael@0: * isn't a good idea, but in this case we only ever modify the michael@0: * value once, so things work out well. michael@0: */ michael@0: ret = arenas[ind]; michael@0: if (ret == NULL) { michael@0: /* michael@0: * Avoid races with another thread that may have already michael@0: * initialized arenas[ind]. michael@0: */ michael@0: malloc_spin_lock(&arenas_lock); michael@0: if (arenas[ind] == NULL) michael@0: ret = arenas_extend((unsigned)ind); michael@0: else michael@0: ret = arenas[ind]; michael@0: malloc_spin_unlock(&arenas_lock); michael@0: } michael@0: } else michael@0: ret = arenas[0]; michael@0: #endif michael@0: michael@0: RELEASE_ASSERT(ret != NULL); michael@0: return (ret); michael@0: } michael@0: michael@0: #ifndef NO_TLS michael@0: /* michael@0: * Choose an arena based on a per-thread value (slow-path code only, called michael@0: * only by choose_arena()). michael@0: */ michael@0: static arena_t * michael@0: choose_arena_hard(void) michael@0: { michael@0: arena_t *ret; michael@0: michael@0: assert(isthreaded); michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: /* Seed the PRNG used for arena load balancing. */ michael@0: SPRN(balance, (uint32_t)(uintptr_t)(_pthread_self())); michael@0: #endif michael@0: michael@0: if (narenas > 1) { michael@0: #ifdef MALLOC_BALANCE michael@0: unsigned ind; michael@0: michael@0: ind = PRN(balance, narenas_2pow); michael@0: if ((ret = arenas[ind]) == NULL) { michael@0: malloc_spin_lock(&arenas_lock); michael@0: if ((ret = arenas[ind]) == NULL) michael@0: ret = arenas_extend(ind); michael@0: malloc_spin_unlock(&arenas_lock); michael@0: } michael@0: #else michael@0: malloc_spin_lock(&arenas_lock); michael@0: if ((ret = arenas[next_arena]) == NULL) michael@0: ret = arenas_extend(next_arena); michael@0: next_arena = (next_arena + 1) % narenas; michael@0: malloc_spin_unlock(&arenas_lock); michael@0: #endif michael@0: } else michael@0: ret = arenas[0]; michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: TlsSetValue(tlsIndex, ret); michael@0: #else michael@0: arenas_map = ret; michael@0: #endif michael@0: michael@0: return (ret); michael@0: } michael@0: #endif michael@0: michael@0: static inline int michael@0: arena_chunk_comp(arena_chunk_t *a, arena_chunk_t *b) michael@0: { michael@0: uintptr_t a_chunk = (uintptr_t)a; michael@0: uintptr_t b_chunk = (uintptr_t)b; michael@0: michael@0: assert(a != NULL); michael@0: assert(b != NULL); michael@0: michael@0: return ((a_chunk > b_chunk) - (a_chunk < b_chunk)); michael@0: } michael@0: michael@0: /* Wrap red-black tree macros in functions. */ michael@0: rb_wrap(static, arena_chunk_tree_dirty_, arena_chunk_tree_t, michael@0: arena_chunk_t, link_dirty, arena_chunk_comp) michael@0: michael@0: static inline int michael@0: arena_run_comp(arena_chunk_map_t *a, arena_chunk_map_t *b) michael@0: { michael@0: uintptr_t a_mapelm = (uintptr_t)a; michael@0: uintptr_t b_mapelm = (uintptr_t)b; michael@0: michael@0: assert(a != NULL); michael@0: assert(b != NULL); michael@0: michael@0: return ((a_mapelm > b_mapelm) - (a_mapelm < b_mapelm)); michael@0: } michael@0: michael@0: /* Wrap red-black tree macros in functions. */ michael@0: rb_wrap(static, arena_run_tree_, arena_run_tree_t, arena_chunk_map_t, link, michael@0: arena_run_comp) michael@0: michael@0: static inline int michael@0: arena_avail_comp(arena_chunk_map_t *a, arena_chunk_map_t *b) michael@0: { michael@0: int ret; michael@0: size_t a_size = a->bits & ~pagesize_mask; michael@0: size_t b_size = b->bits & ~pagesize_mask; michael@0: michael@0: ret = (a_size > b_size) - (a_size < b_size); michael@0: if (ret == 0) { michael@0: uintptr_t a_mapelm, b_mapelm; michael@0: michael@0: if ((a->bits & CHUNK_MAP_KEY) == 0) michael@0: a_mapelm = (uintptr_t)a; michael@0: else { michael@0: /* michael@0: * Treat keys as though they are lower than anything michael@0: * else. michael@0: */ michael@0: a_mapelm = 0; michael@0: } michael@0: b_mapelm = (uintptr_t)b; michael@0: michael@0: ret = (a_mapelm > b_mapelm) - (a_mapelm < b_mapelm); michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: /* Wrap red-black tree macros in functions. */ michael@0: rb_wrap(static, arena_avail_tree_, arena_avail_tree_t, arena_chunk_map_t, link, michael@0: arena_avail_comp) michael@0: michael@0: static inline void * michael@0: arena_run_reg_alloc(arena_run_t *run, arena_bin_t *bin) michael@0: { michael@0: void *ret; michael@0: unsigned i, mask, bit, regind; michael@0: michael@0: assert(run->magic == ARENA_RUN_MAGIC); michael@0: assert(run->regs_minelm < bin->regs_mask_nelms); michael@0: michael@0: /* michael@0: * Move the first check outside the loop, so that run->regs_minelm can michael@0: * be updated unconditionally, without the possibility of updating it michael@0: * multiple times. michael@0: */ michael@0: i = run->regs_minelm; michael@0: mask = run->regs_mask[i]; michael@0: if (mask != 0) { michael@0: /* Usable allocation found. */ michael@0: bit = ffs((int)mask) - 1; michael@0: michael@0: regind = ((i << (SIZEOF_INT_2POW + 3)) + bit); michael@0: assert(regind < bin->nregs); michael@0: ret = (void *)(((uintptr_t)run) + bin->reg0_offset michael@0: + (bin->reg_size * regind)); michael@0: michael@0: /* Clear bit. */ michael@0: mask ^= (1U << bit); michael@0: run->regs_mask[i] = mask; michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: for (i++; i < bin->regs_mask_nelms; i++) { michael@0: mask = run->regs_mask[i]; michael@0: if (mask != 0) { michael@0: /* Usable allocation found. */ michael@0: bit = ffs((int)mask) - 1; michael@0: michael@0: regind = ((i << (SIZEOF_INT_2POW + 3)) + bit); michael@0: assert(regind < bin->nregs); michael@0: ret = (void *)(((uintptr_t)run) + bin->reg0_offset michael@0: + (bin->reg_size * regind)); michael@0: michael@0: /* Clear bit. */ michael@0: mask ^= (1U << bit); michael@0: run->regs_mask[i] = mask; michael@0: michael@0: /* michael@0: * Make a note that nothing before this element michael@0: * contains a free region. michael@0: */ michael@0: run->regs_minelm = i; /* Low payoff: + (mask == 0); */ michael@0: michael@0: return (ret); michael@0: } michael@0: } michael@0: /* Not reached. */ michael@0: RELEASE_ASSERT(0); michael@0: return (NULL); michael@0: } michael@0: michael@0: static inline void michael@0: arena_run_reg_dalloc(arena_run_t *run, arena_bin_t *bin, void *ptr, size_t size) michael@0: { michael@0: /* michael@0: * To divide by a number D that is not a power of two we multiply michael@0: * by (2^21 / D) and then right shift by 21 positions. michael@0: * michael@0: * X / D michael@0: * michael@0: * becomes michael@0: * michael@0: * (X * size_invs[(D >> QUANTUM_2POW_MIN) - 3]) >> SIZE_INV_SHIFT michael@0: */ michael@0: #define SIZE_INV_SHIFT 21 michael@0: #define SIZE_INV(s) (((1U << SIZE_INV_SHIFT) / (s << QUANTUM_2POW_MIN)) + 1) michael@0: static const unsigned size_invs[] = { michael@0: SIZE_INV(3), michael@0: SIZE_INV(4), SIZE_INV(5), SIZE_INV(6), SIZE_INV(7), michael@0: SIZE_INV(8), SIZE_INV(9), SIZE_INV(10), SIZE_INV(11), michael@0: SIZE_INV(12),SIZE_INV(13), SIZE_INV(14), SIZE_INV(15), michael@0: SIZE_INV(16),SIZE_INV(17), SIZE_INV(18), SIZE_INV(19), michael@0: SIZE_INV(20),SIZE_INV(21), SIZE_INV(22), SIZE_INV(23), michael@0: SIZE_INV(24),SIZE_INV(25), SIZE_INV(26), SIZE_INV(27), michael@0: SIZE_INV(28),SIZE_INV(29), SIZE_INV(30), SIZE_INV(31) michael@0: #if (QUANTUM_2POW_MIN < 4) michael@0: , michael@0: SIZE_INV(32), SIZE_INV(33), SIZE_INV(34), SIZE_INV(35), michael@0: SIZE_INV(36), SIZE_INV(37), SIZE_INV(38), SIZE_INV(39), michael@0: SIZE_INV(40), SIZE_INV(41), SIZE_INV(42), SIZE_INV(43), michael@0: SIZE_INV(44), SIZE_INV(45), SIZE_INV(46), SIZE_INV(47), michael@0: SIZE_INV(48), SIZE_INV(49), SIZE_INV(50), SIZE_INV(51), michael@0: SIZE_INV(52), SIZE_INV(53), SIZE_INV(54), SIZE_INV(55), michael@0: SIZE_INV(56), SIZE_INV(57), SIZE_INV(58), SIZE_INV(59), michael@0: SIZE_INV(60), SIZE_INV(61), SIZE_INV(62), SIZE_INV(63) michael@0: #endif michael@0: }; michael@0: unsigned diff, regind, elm, bit; michael@0: michael@0: assert(run->magic == ARENA_RUN_MAGIC); michael@0: assert(((sizeof(size_invs)) / sizeof(unsigned)) + 3 michael@0: >= (SMALL_MAX_DEFAULT >> QUANTUM_2POW_MIN)); michael@0: michael@0: /* michael@0: * Avoid doing division with a variable divisor if possible. Using michael@0: * actual division here can reduce allocator throughput by over 20%! michael@0: */ michael@0: diff = (unsigned)((uintptr_t)ptr - (uintptr_t)run - bin->reg0_offset); michael@0: if ((size & (size - 1)) == 0) { michael@0: /* michael@0: * log2_table allows fast division of a power of two in the michael@0: * [1..128] range. michael@0: * michael@0: * (x / divisor) becomes (x >> log2_table[divisor - 1]). michael@0: */ michael@0: static const unsigned char log2_table[] = { michael@0: 0, 1, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, michael@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, michael@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, michael@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, michael@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, michael@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, michael@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, michael@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7 michael@0: }; michael@0: michael@0: if (size <= 128) michael@0: regind = (diff >> log2_table[size - 1]); michael@0: else if (size <= 32768) michael@0: regind = diff >> (8 + log2_table[(size >> 8) - 1]); michael@0: else { michael@0: /* michael@0: * The run size is too large for us to use the lookup michael@0: * table. Use real division. michael@0: */ michael@0: regind = diff / size; michael@0: } michael@0: } else if (size <= ((sizeof(size_invs) / sizeof(unsigned)) michael@0: << QUANTUM_2POW_MIN) + 2) { michael@0: regind = size_invs[(size >> QUANTUM_2POW_MIN) - 3] * diff; michael@0: regind >>= SIZE_INV_SHIFT; michael@0: } else { michael@0: /* michael@0: * size_invs isn't large enough to handle this size class, so michael@0: * calculate regind using actual division. This only happens michael@0: * if the user increases small_max via the 'S' runtime michael@0: * configuration option. michael@0: */ michael@0: regind = diff / size; michael@0: }; michael@0: RELEASE_ASSERT(diff == regind * size); michael@0: RELEASE_ASSERT(regind < bin->nregs); michael@0: michael@0: elm = regind >> (SIZEOF_INT_2POW + 3); michael@0: if (elm < run->regs_minelm) michael@0: run->regs_minelm = elm; michael@0: bit = regind - (elm << (SIZEOF_INT_2POW + 3)); michael@0: RELEASE_ASSERT((run->regs_mask[elm] & (1U << bit)) == 0); michael@0: run->regs_mask[elm] |= (1U << bit); michael@0: #undef SIZE_INV michael@0: #undef SIZE_INV_SHIFT michael@0: } michael@0: michael@0: static void michael@0: arena_run_split(arena_t *arena, arena_run_t *run, size_t size, bool large, michael@0: bool zero) michael@0: { michael@0: arena_chunk_t *chunk; michael@0: size_t old_ndirty, run_ind, total_pages, need_pages, rem_pages, i; michael@0: michael@0: chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run); michael@0: old_ndirty = chunk->ndirty; michael@0: run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk) michael@0: >> pagesize_2pow); michael@0: total_pages = (chunk->map[run_ind].bits & ~pagesize_mask) >> michael@0: pagesize_2pow; michael@0: need_pages = (size >> pagesize_2pow); michael@0: assert(need_pages > 0); michael@0: assert(need_pages <= total_pages); michael@0: rem_pages = total_pages - need_pages; michael@0: michael@0: arena_avail_tree_remove(&arena->runs_avail, &chunk->map[run_ind]); michael@0: michael@0: /* Keep track of trailing unused pages for later use. */ michael@0: if (rem_pages > 0) { michael@0: chunk->map[run_ind+need_pages].bits = (rem_pages << michael@0: pagesize_2pow) | (chunk->map[run_ind+need_pages].bits & michael@0: pagesize_mask); michael@0: chunk->map[run_ind+total_pages-1].bits = (rem_pages << michael@0: pagesize_2pow) | (chunk->map[run_ind+total_pages-1].bits & michael@0: pagesize_mask); michael@0: arena_avail_tree_insert(&arena->runs_avail, michael@0: &chunk->map[run_ind+need_pages]); michael@0: } michael@0: michael@0: for (i = 0; i < need_pages; i++) { michael@0: #if defined(MALLOC_DECOMMIT) || defined(MALLOC_STATS) || defined(MALLOC_DOUBLE_PURGE) michael@0: /* michael@0: * Commit decommitted pages if necessary. If a decommitted michael@0: * page is encountered, commit all needed adjacent decommitted michael@0: * pages in one operation, in order to reduce system call michael@0: * overhead. michael@0: */ michael@0: if (chunk->map[run_ind + i].bits & CHUNK_MAP_MADVISED_OR_DECOMMITTED) { michael@0: size_t j; michael@0: michael@0: /* michael@0: * Advance i+j to just past the index of the last page michael@0: * to commit. Clear CHUNK_MAP_DECOMMITTED and michael@0: * CHUNK_MAP_MADVISED along the way. michael@0: */ michael@0: for (j = 0; i + j < need_pages && (chunk->map[run_ind + michael@0: i + j].bits & CHUNK_MAP_MADVISED_OR_DECOMMITTED); j++) { michael@0: /* DECOMMITTED and MADVISED are mutually exclusive. */ michael@0: assert(!(chunk->map[run_ind + i + j].bits & CHUNK_MAP_DECOMMITTED && michael@0: chunk->map[run_ind + i + j].bits & CHUNK_MAP_MADVISED)); michael@0: michael@0: chunk->map[run_ind + i + j].bits &= michael@0: ~CHUNK_MAP_MADVISED_OR_DECOMMITTED; michael@0: } michael@0: michael@0: # ifdef MALLOC_DECOMMIT michael@0: pages_commit((void *)((uintptr_t)chunk + ((run_ind + i) michael@0: << pagesize_2pow)), (j << pagesize_2pow)); michael@0: # ifdef MALLOC_STATS michael@0: arena->stats.ncommit++; michael@0: # endif michael@0: # endif michael@0: michael@0: # ifdef MALLOC_STATS michael@0: arena->stats.committed += j; michael@0: # endif michael@0: michael@0: # ifndef MALLOC_DECOMMIT michael@0: } michael@0: # else michael@0: } else /* No need to zero since commit zeros. */ michael@0: # endif michael@0: michael@0: #endif michael@0: michael@0: /* Zero if necessary. */ michael@0: if (zero) { michael@0: if ((chunk->map[run_ind + i].bits & CHUNK_MAP_ZEROED) michael@0: == 0) { michael@0: VALGRIND_MALLOCLIKE_BLOCK((void *)((uintptr_t) michael@0: chunk + ((run_ind + i) << pagesize_2pow)), michael@0: pagesize, 0, false); michael@0: memset((void *)((uintptr_t)chunk + ((run_ind michael@0: + i) << pagesize_2pow)), 0, pagesize); michael@0: VALGRIND_FREELIKE_BLOCK((void *)((uintptr_t) michael@0: chunk + ((run_ind + i) << pagesize_2pow)), michael@0: 0); michael@0: /* CHUNK_MAP_ZEROED is cleared below. */ michael@0: } michael@0: } michael@0: michael@0: /* Update dirty page accounting. */ michael@0: if (chunk->map[run_ind + i].bits & CHUNK_MAP_DIRTY) { michael@0: chunk->ndirty--; michael@0: arena->ndirty--; michael@0: /* CHUNK_MAP_DIRTY is cleared below. */ michael@0: } michael@0: michael@0: /* Initialize the chunk map. */ michael@0: if (large) { michael@0: chunk->map[run_ind + i].bits = CHUNK_MAP_LARGE michael@0: | CHUNK_MAP_ALLOCATED; michael@0: } else { michael@0: chunk->map[run_ind + i].bits = (size_t)run michael@0: | CHUNK_MAP_ALLOCATED; michael@0: } michael@0: } michael@0: michael@0: /* michael@0: * Set the run size only in the first element for large runs. This is michael@0: * primarily a debugging aid, since the lack of size info for trailing michael@0: * pages only matters if the application tries to operate on an michael@0: * interior pointer. michael@0: */ michael@0: if (large) michael@0: chunk->map[run_ind].bits |= size; michael@0: michael@0: if (chunk->ndirty == 0 && old_ndirty > 0) michael@0: arena_chunk_tree_dirty_remove(&arena->chunks_dirty, chunk); michael@0: } michael@0: michael@0: static void michael@0: arena_chunk_init(arena_t *arena, arena_chunk_t *chunk) michael@0: { michael@0: arena_run_t *run; michael@0: size_t i; michael@0: michael@0: VALGRIND_MALLOCLIKE_BLOCK(chunk, (arena_chunk_header_npages << michael@0: pagesize_2pow), 0, false); michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.mapped += chunksize; michael@0: #endif michael@0: michael@0: chunk->arena = arena; michael@0: michael@0: /* michael@0: * Claim that no pages are in use, since the header is merely overhead. michael@0: */ michael@0: chunk->ndirty = 0; michael@0: michael@0: /* Initialize the map to contain one maximal free untouched run. */ michael@0: run = (arena_run_t *)((uintptr_t)chunk + (arena_chunk_header_npages << michael@0: pagesize_2pow)); michael@0: for (i = 0; i < arena_chunk_header_npages; i++) michael@0: chunk->map[i].bits = 0; michael@0: chunk->map[i].bits = arena_maxclass | CHUNK_MAP_DECOMMITTED | CHUNK_MAP_ZEROED; michael@0: for (i++; i < chunk_npages-1; i++) { michael@0: chunk->map[i].bits = CHUNK_MAP_DECOMMITTED | CHUNK_MAP_ZEROED; michael@0: } michael@0: chunk->map[chunk_npages-1].bits = arena_maxclass | CHUNK_MAP_DECOMMITTED | CHUNK_MAP_ZEROED; michael@0: michael@0: #ifdef MALLOC_DECOMMIT michael@0: /* michael@0: * Start out decommitted, in order to force a closer correspondence michael@0: * between dirty pages and committed untouched pages. michael@0: */ michael@0: pages_decommit(run, arena_maxclass); michael@0: # ifdef MALLOC_STATS michael@0: arena->stats.ndecommit++; michael@0: arena->stats.decommitted += (chunk_npages - arena_chunk_header_npages); michael@0: # endif michael@0: #endif michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.committed += arena_chunk_header_npages; michael@0: #endif michael@0: michael@0: /* Insert the run into the runs_avail tree. */ michael@0: arena_avail_tree_insert(&arena->runs_avail, michael@0: &chunk->map[arena_chunk_header_npages]); michael@0: michael@0: #ifdef MALLOC_DOUBLE_PURGE michael@0: LinkedList_Init(&chunk->chunks_madvised_elem); michael@0: #endif michael@0: } michael@0: michael@0: static void michael@0: arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk) michael@0: { michael@0: michael@0: if (arena->spare != NULL) { michael@0: if (arena->spare->ndirty > 0) { michael@0: arena_chunk_tree_dirty_remove( michael@0: &chunk->arena->chunks_dirty, arena->spare); michael@0: arena->ndirty -= arena->spare->ndirty; michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.committed -= arena->spare->ndirty; michael@0: #endif michael@0: } michael@0: michael@0: #ifdef MALLOC_DOUBLE_PURGE michael@0: /* This is safe to do even if arena->spare is not in the list. */ michael@0: LinkedList_Remove(&arena->spare->chunks_madvised_elem); michael@0: #endif michael@0: michael@0: VALGRIND_FREELIKE_BLOCK(arena->spare, 0); michael@0: chunk_dealloc((void *)arena->spare, chunksize); michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.mapped -= chunksize; michael@0: arena->stats.committed -= arena_chunk_header_npages; michael@0: #endif michael@0: } michael@0: michael@0: /* michael@0: * Remove run from runs_avail, so that the arena does not use it. michael@0: * Dirty page flushing only uses the chunks_dirty tree, so leaving this michael@0: * chunk in the chunks_* trees is sufficient for that purpose. michael@0: */ michael@0: arena_avail_tree_remove(&arena->runs_avail, michael@0: &chunk->map[arena_chunk_header_npages]); michael@0: michael@0: arena->spare = chunk; michael@0: } michael@0: michael@0: static arena_run_t * michael@0: arena_run_alloc(arena_t *arena, arena_bin_t *bin, size_t size, bool large, michael@0: bool zero) michael@0: { michael@0: arena_run_t *run; michael@0: arena_chunk_map_t *mapelm, key; michael@0: michael@0: assert(size <= arena_maxclass); michael@0: assert((size & pagesize_mask) == 0); michael@0: michael@0: /* Search the arena's chunks for the lowest best fit. */ michael@0: key.bits = size | CHUNK_MAP_KEY; michael@0: mapelm = arena_avail_tree_nsearch(&arena->runs_avail, &key); michael@0: if (mapelm != NULL) { michael@0: arena_chunk_t *chunk = michael@0: (arena_chunk_t*)CHUNK_ADDR2BASE(mapelm); michael@0: size_t pageind = ((uintptr_t)mapelm - michael@0: (uintptr_t)chunk->map) / michael@0: sizeof(arena_chunk_map_t); michael@0: michael@0: run = (arena_run_t *)((uintptr_t)chunk + (pageind michael@0: << pagesize_2pow)); michael@0: arena_run_split(arena, run, size, large, zero); michael@0: return (run); michael@0: } michael@0: michael@0: if (arena->spare != NULL) { michael@0: /* Use the spare. */ michael@0: arena_chunk_t *chunk = arena->spare; michael@0: arena->spare = NULL; michael@0: run = (arena_run_t *)((uintptr_t)chunk + michael@0: (arena_chunk_header_npages << pagesize_2pow)); michael@0: /* Insert the run into the runs_avail tree. */ michael@0: arena_avail_tree_insert(&arena->runs_avail, michael@0: &chunk->map[arena_chunk_header_npages]); michael@0: arena_run_split(arena, run, size, large, zero); michael@0: return (run); michael@0: } michael@0: michael@0: /* michael@0: * No usable runs. Create a new chunk from which to allocate michael@0: * the run. michael@0: */ michael@0: { michael@0: arena_chunk_t *chunk = (arena_chunk_t *) michael@0: chunk_alloc(chunksize, true, true); michael@0: if (chunk == NULL) michael@0: return (NULL); michael@0: michael@0: arena_chunk_init(arena, chunk); michael@0: run = (arena_run_t *)((uintptr_t)chunk + michael@0: (arena_chunk_header_npages << pagesize_2pow)); michael@0: } michael@0: /* Update page map. */ michael@0: arena_run_split(arena, run, size, large, zero); michael@0: return (run); michael@0: } michael@0: michael@0: static void michael@0: arena_purge(arena_t *arena, bool all) michael@0: { michael@0: arena_chunk_t *chunk; michael@0: size_t i, npages; michael@0: /* If all is set purge all dirty pages. */ michael@0: size_t dirty_max = all ? 1 : opt_dirty_max; michael@0: #ifdef MALLOC_DEBUG michael@0: size_t ndirty = 0; michael@0: rb_foreach_begin(arena_chunk_t, link_dirty, &arena->chunks_dirty, michael@0: chunk) { michael@0: ndirty += chunk->ndirty; michael@0: } rb_foreach_end(arena_chunk_t, link_dirty, &arena->chunks_dirty, chunk) michael@0: assert(ndirty == arena->ndirty); michael@0: #endif michael@0: RELEASE_ASSERT(all || (arena->ndirty > opt_dirty_max)); michael@0: michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.npurge++; michael@0: #endif michael@0: michael@0: /* michael@0: * Iterate downward through chunks until enough dirty memory has been michael@0: * purged. Terminate as soon as possible in order to minimize the michael@0: * number of system calls, even if a chunk has only been partially michael@0: * purged. michael@0: */ michael@0: while (arena->ndirty > (dirty_max >> 1)) { michael@0: #ifdef MALLOC_DOUBLE_PURGE michael@0: bool madvised = false; michael@0: #endif michael@0: chunk = arena_chunk_tree_dirty_last(&arena->chunks_dirty); michael@0: RELEASE_ASSERT(chunk != NULL); michael@0: michael@0: for (i = chunk_npages - 1; chunk->ndirty > 0; i--) { michael@0: RELEASE_ASSERT(i >= arena_chunk_header_npages); michael@0: michael@0: if (chunk->map[i].bits & CHUNK_MAP_DIRTY) { michael@0: #ifdef MALLOC_DECOMMIT michael@0: const size_t free_operation = CHUNK_MAP_DECOMMITTED; michael@0: #else michael@0: const size_t free_operation = CHUNK_MAP_MADVISED; michael@0: #endif michael@0: assert((chunk->map[i].bits & michael@0: CHUNK_MAP_MADVISED_OR_DECOMMITTED) == 0); michael@0: chunk->map[i].bits ^= free_operation | CHUNK_MAP_DIRTY; michael@0: /* Find adjacent dirty run(s). */ michael@0: for (npages = 1; michael@0: i > arena_chunk_header_npages && michael@0: (chunk->map[i - 1].bits & CHUNK_MAP_DIRTY); michael@0: npages++) { michael@0: i--; michael@0: assert((chunk->map[i].bits & michael@0: CHUNK_MAP_MADVISED_OR_DECOMMITTED) == 0); michael@0: chunk->map[i].bits ^= free_operation | CHUNK_MAP_DIRTY; michael@0: } michael@0: chunk->ndirty -= npages; michael@0: arena->ndirty -= npages; michael@0: michael@0: #ifdef MALLOC_DECOMMIT michael@0: pages_decommit((void *)((uintptr_t) michael@0: chunk + (i << pagesize_2pow)), michael@0: (npages << pagesize_2pow)); michael@0: # ifdef MALLOC_STATS michael@0: arena->stats.ndecommit++; michael@0: arena->stats.decommitted += npages; michael@0: # endif michael@0: #endif michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.committed -= npages; michael@0: #endif michael@0: michael@0: #ifndef MALLOC_DECOMMIT michael@0: madvise((void *)((uintptr_t)chunk + (i << michael@0: pagesize_2pow)), (npages << pagesize_2pow), michael@0: MADV_FREE); michael@0: # ifdef MALLOC_DOUBLE_PURGE michael@0: madvised = true; michael@0: # endif michael@0: #endif michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.nmadvise++; michael@0: arena->stats.purged += npages; michael@0: #endif michael@0: if (arena->ndirty <= (dirty_max >> 1)) michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (chunk->ndirty == 0) { michael@0: arena_chunk_tree_dirty_remove(&arena->chunks_dirty, michael@0: chunk); michael@0: } michael@0: #ifdef MALLOC_DOUBLE_PURGE michael@0: if (madvised) { michael@0: /* The chunk might already be in the list, but this michael@0: * makes sure it's at the front. */ michael@0: LinkedList_Remove(&chunk->chunks_madvised_elem); michael@0: LinkedList_InsertHead(&arena->chunks_madvised, &chunk->chunks_madvised_elem); michael@0: } michael@0: #endif michael@0: } michael@0: } michael@0: michael@0: static void michael@0: arena_run_dalloc(arena_t *arena, arena_run_t *run, bool dirty) michael@0: { michael@0: arena_chunk_t *chunk; michael@0: size_t size, run_ind, run_pages; michael@0: michael@0: chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run); michael@0: run_ind = (size_t)(((uintptr_t)run - (uintptr_t)chunk) michael@0: >> pagesize_2pow); michael@0: RELEASE_ASSERT(run_ind >= arena_chunk_header_npages); michael@0: RELEASE_ASSERT(run_ind < chunk_npages); michael@0: if ((chunk->map[run_ind].bits & CHUNK_MAP_LARGE) != 0) michael@0: size = chunk->map[run_ind].bits & ~pagesize_mask; michael@0: else michael@0: size = run->bin->run_size; michael@0: run_pages = (size >> pagesize_2pow); michael@0: michael@0: /* Mark pages as unallocated in the chunk map. */ michael@0: if (dirty) { michael@0: size_t i; michael@0: michael@0: for (i = 0; i < run_pages; i++) { michael@0: RELEASE_ASSERT((chunk->map[run_ind + i].bits & CHUNK_MAP_DIRTY) michael@0: == 0); michael@0: chunk->map[run_ind + i].bits = CHUNK_MAP_DIRTY; michael@0: } michael@0: michael@0: if (chunk->ndirty == 0) { michael@0: arena_chunk_tree_dirty_insert(&arena->chunks_dirty, michael@0: chunk); michael@0: } michael@0: chunk->ndirty += run_pages; michael@0: arena->ndirty += run_pages; michael@0: } else { michael@0: size_t i; michael@0: michael@0: for (i = 0; i < run_pages; i++) { michael@0: chunk->map[run_ind + i].bits &= ~(CHUNK_MAP_LARGE | michael@0: CHUNK_MAP_ALLOCATED); michael@0: } michael@0: } michael@0: chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & michael@0: pagesize_mask); michael@0: chunk->map[run_ind+run_pages-1].bits = size | michael@0: (chunk->map[run_ind+run_pages-1].bits & pagesize_mask); michael@0: michael@0: /* Try to coalesce forward. */ michael@0: if (run_ind + run_pages < chunk_npages && michael@0: (chunk->map[run_ind+run_pages].bits & CHUNK_MAP_ALLOCATED) == 0) { michael@0: size_t nrun_size = chunk->map[run_ind+run_pages].bits & michael@0: ~pagesize_mask; michael@0: michael@0: /* michael@0: * Remove successor from runs_avail; the coalesced run is michael@0: * inserted later. michael@0: */ michael@0: arena_avail_tree_remove(&arena->runs_avail, michael@0: &chunk->map[run_ind+run_pages]); michael@0: michael@0: size += nrun_size; michael@0: run_pages = size >> pagesize_2pow; michael@0: michael@0: RELEASE_ASSERT((chunk->map[run_ind+run_pages-1].bits & ~pagesize_mask) michael@0: == nrun_size); michael@0: chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & michael@0: pagesize_mask); michael@0: chunk->map[run_ind+run_pages-1].bits = size | michael@0: (chunk->map[run_ind+run_pages-1].bits & pagesize_mask); michael@0: } michael@0: michael@0: /* Try to coalesce backward. */ michael@0: if (run_ind > arena_chunk_header_npages && (chunk->map[run_ind-1].bits & michael@0: CHUNK_MAP_ALLOCATED) == 0) { michael@0: size_t prun_size = chunk->map[run_ind-1].bits & ~pagesize_mask; michael@0: michael@0: run_ind -= prun_size >> pagesize_2pow; michael@0: michael@0: /* michael@0: * Remove predecessor from runs_avail; the coalesced run is michael@0: * inserted later. michael@0: */ michael@0: arena_avail_tree_remove(&arena->runs_avail, michael@0: &chunk->map[run_ind]); michael@0: michael@0: size += prun_size; michael@0: run_pages = size >> pagesize_2pow; michael@0: michael@0: RELEASE_ASSERT((chunk->map[run_ind].bits & ~pagesize_mask) == michael@0: prun_size); michael@0: chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & michael@0: pagesize_mask); michael@0: chunk->map[run_ind+run_pages-1].bits = size | michael@0: (chunk->map[run_ind+run_pages-1].bits & pagesize_mask); michael@0: } michael@0: michael@0: /* Insert into runs_avail, now that coalescing is complete. */ michael@0: arena_avail_tree_insert(&arena->runs_avail, &chunk->map[run_ind]); michael@0: michael@0: /* Deallocate chunk if it is now completely unused. */ michael@0: if ((chunk->map[arena_chunk_header_npages].bits & (~pagesize_mask | michael@0: CHUNK_MAP_ALLOCATED)) == arena_maxclass) michael@0: arena_chunk_dealloc(arena, chunk); michael@0: michael@0: /* Enforce opt_dirty_max. */ michael@0: if (arena->ndirty > opt_dirty_max) michael@0: arena_purge(arena, false); michael@0: } michael@0: michael@0: static void michael@0: arena_run_trim_head(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run, michael@0: size_t oldsize, size_t newsize) michael@0: { michael@0: size_t pageind = ((uintptr_t)run - (uintptr_t)chunk) >> pagesize_2pow; michael@0: size_t head_npages = (oldsize - newsize) >> pagesize_2pow; michael@0: michael@0: assert(oldsize > newsize); michael@0: michael@0: /* michael@0: * Update the chunk map so that arena_run_dalloc() can treat the michael@0: * leading run as separately allocated. michael@0: */ michael@0: chunk->map[pageind].bits = (oldsize - newsize) | CHUNK_MAP_LARGE | michael@0: CHUNK_MAP_ALLOCATED; michael@0: chunk->map[pageind+head_npages].bits = newsize | CHUNK_MAP_LARGE | michael@0: CHUNK_MAP_ALLOCATED; michael@0: michael@0: arena_run_dalloc(arena, run, false); michael@0: } michael@0: michael@0: static void michael@0: arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run, michael@0: size_t oldsize, size_t newsize, bool dirty) michael@0: { michael@0: size_t pageind = ((uintptr_t)run - (uintptr_t)chunk) >> pagesize_2pow; michael@0: size_t npages = newsize >> pagesize_2pow; michael@0: michael@0: assert(oldsize > newsize); michael@0: michael@0: /* michael@0: * Update the chunk map so that arena_run_dalloc() can treat the michael@0: * trailing run as separately allocated. michael@0: */ michael@0: chunk->map[pageind].bits = newsize | CHUNK_MAP_LARGE | michael@0: CHUNK_MAP_ALLOCATED; michael@0: chunk->map[pageind+npages].bits = (oldsize - newsize) | CHUNK_MAP_LARGE michael@0: | CHUNK_MAP_ALLOCATED; michael@0: michael@0: arena_run_dalloc(arena, (arena_run_t *)((uintptr_t)run + newsize), michael@0: dirty); michael@0: } michael@0: michael@0: static arena_run_t * michael@0: arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin) michael@0: { michael@0: arena_chunk_map_t *mapelm; michael@0: arena_run_t *run; michael@0: unsigned i, remainder; michael@0: michael@0: /* Look for a usable run. */ michael@0: mapelm = arena_run_tree_first(&bin->runs); michael@0: if (mapelm != NULL) { michael@0: /* run is guaranteed to have available space. */ michael@0: arena_run_tree_remove(&bin->runs, mapelm); michael@0: run = (arena_run_t *)(mapelm->bits & ~pagesize_mask); michael@0: #ifdef MALLOC_STATS michael@0: bin->stats.reruns++; michael@0: #endif michael@0: return (run); michael@0: } michael@0: /* No existing runs have any space available. */ michael@0: michael@0: /* Allocate a new run. */ michael@0: run = arena_run_alloc(arena, bin, bin->run_size, false, false); michael@0: if (run == NULL) michael@0: return (NULL); michael@0: /* michael@0: * Don't initialize if a race in arena_run_alloc() allowed an existing michael@0: * run to become usable. michael@0: */ michael@0: if (run == bin->runcur) michael@0: return (run); michael@0: michael@0: VALGRIND_MALLOCLIKE_BLOCK(run, sizeof(arena_run_t) + (sizeof(unsigned) * michael@0: (bin->regs_mask_nelms - 1)), 0, false); michael@0: michael@0: /* Initialize run internals. */ michael@0: run->bin = bin; michael@0: michael@0: for (i = 0; i < bin->regs_mask_nelms - 1; i++) michael@0: run->regs_mask[i] = UINT_MAX; michael@0: remainder = bin->nregs & ((1U << (SIZEOF_INT_2POW + 3)) - 1); michael@0: if (remainder == 0) michael@0: run->regs_mask[i] = UINT_MAX; michael@0: else { michael@0: /* The last element has spare bits that need to be unset. */ michael@0: run->regs_mask[i] = (UINT_MAX >> ((1U << (SIZEOF_INT_2POW + 3)) michael@0: - remainder)); michael@0: } michael@0: michael@0: run->regs_minelm = 0; michael@0: michael@0: run->nfree = bin->nregs; michael@0: #if defined(MALLOC_DEBUG) || defined(MOZ_JEMALLOC_HARD_ASSERTS) michael@0: run->magic = ARENA_RUN_MAGIC; michael@0: #endif michael@0: michael@0: #ifdef MALLOC_STATS michael@0: bin->stats.nruns++; michael@0: bin->stats.curruns++; michael@0: if (bin->stats.curruns > bin->stats.highruns) michael@0: bin->stats.highruns = bin->stats.curruns; michael@0: #endif michael@0: return (run); michael@0: } michael@0: michael@0: /* bin->runcur must have space available before this function is called. */ michael@0: static inline void * michael@0: arena_bin_malloc_easy(arena_t *arena, arena_bin_t *bin, arena_run_t *run) michael@0: { michael@0: void *ret; michael@0: michael@0: RELEASE_ASSERT(run->magic == ARENA_RUN_MAGIC); michael@0: RELEASE_ASSERT(run->nfree > 0); michael@0: michael@0: ret = arena_run_reg_alloc(run, bin); michael@0: RELEASE_ASSERT(ret != NULL); michael@0: run->nfree--; michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: /* Re-fill bin->runcur, then call arena_bin_malloc_easy(). */ michael@0: static void * michael@0: arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin) michael@0: { michael@0: michael@0: bin->runcur = arena_bin_nonfull_run_get(arena, bin); michael@0: if (bin->runcur == NULL) michael@0: return (NULL); michael@0: RELEASE_ASSERT(bin->runcur->magic == ARENA_RUN_MAGIC); michael@0: RELEASE_ASSERT(bin->runcur->nfree > 0); michael@0: michael@0: return (arena_bin_malloc_easy(arena, bin, bin->runcur)); michael@0: } michael@0: michael@0: /* michael@0: * Calculate bin->run_size such that it meets the following constraints: michael@0: * michael@0: * *) bin->run_size >= min_run_size michael@0: * *) bin->run_size <= arena_maxclass michael@0: * *) bin->run_size <= RUN_MAX_SMALL michael@0: * *) run header overhead <= RUN_MAX_OVRHD (or header overhead relaxed). michael@0: * michael@0: * bin->nregs, bin->regs_mask_nelms, and bin->reg0_offset are michael@0: * also calculated here, since these settings are all interdependent. michael@0: */ michael@0: static size_t michael@0: arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size) michael@0: { michael@0: size_t try_run_size, good_run_size; michael@0: unsigned good_nregs, good_mask_nelms, good_reg0_offset; michael@0: unsigned try_nregs, try_mask_nelms, try_reg0_offset; michael@0: michael@0: assert(min_run_size >= pagesize); michael@0: assert(min_run_size <= arena_maxclass); michael@0: assert(min_run_size <= RUN_MAX_SMALL); michael@0: michael@0: /* michael@0: * Calculate known-valid settings before entering the run_size michael@0: * expansion loop, so that the first part of the loop always copies michael@0: * valid settings. michael@0: * michael@0: * The do..while loop iteratively reduces the number of regions until michael@0: * the run header and the regions no longer overlap. A closed formula michael@0: * would be quite messy, since there is an interdependency between the michael@0: * header's mask length and the number of regions. michael@0: */ michael@0: try_run_size = min_run_size; michael@0: try_nregs = ((try_run_size - sizeof(arena_run_t)) / bin->reg_size) michael@0: + 1; /* Counter-act try_nregs-- in loop. */ michael@0: do { michael@0: try_nregs--; michael@0: try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) + michael@0: ((try_nregs & ((1U << (SIZEOF_INT_2POW + 3)) - 1)) ? 1 : 0); michael@0: try_reg0_offset = try_run_size - (try_nregs * bin->reg_size); michael@0: } while (sizeof(arena_run_t) + (sizeof(unsigned) * (try_mask_nelms - 1)) michael@0: > try_reg0_offset); michael@0: michael@0: /* run_size expansion loop. */ michael@0: do { michael@0: /* michael@0: * Copy valid settings before trying more aggressive settings. michael@0: */ michael@0: good_run_size = try_run_size; michael@0: good_nregs = try_nregs; michael@0: good_mask_nelms = try_mask_nelms; michael@0: good_reg0_offset = try_reg0_offset; michael@0: michael@0: /* Try more aggressive settings. */ michael@0: try_run_size += pagesize; michael@0: try_nregs = ((try_run_size - sizeof(arena_run_t)) / michael@0: bin->reg_size) + 1; /* Counter-act try_nregs-- in loop. */ michael@0: do { michael@0: try_nregs--; michael@0: try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) + michael@0: ((try_nregs & ((1U << (SIZEOF_INT_2POW + 3)) - 1)) ? michael@0: 1 : 0); michael@0: try_reg0_offset = try_run_size - (try_nregs * michael@0: bin->reg_size); michael@0: } while (sizeof(arena_run_t) + (sizeof(unsigned) * michael@0: (try_mask_nelms - 1)) > try_reg0_offset); michael@0: } while (try_run_size <= arena_maxclass && try_run_size <= RUN_MAX_SMALL michael@0: && RUN_MAX_OVRHD * (bin->reg_size << 3) > RUN_MAX_OVRHD_RELAX michael@0: && (try_reg0_offset << RUN_BFP) > RUN_MAX_OVRHD * try_run_size); michael@0: michael@0: assert(sizeof(arena_run_t) + (sizeof(unsigned) * (good_mask_nelms - 1)) michael@0: <= good_reg0_offset); michael@0: assert((good_mask_nelms << (SIZEOF_INT_2POW + 3)) >= good_nregs); michael@0: michael@0: /* Copy final settings. */ michael@0: bin->run_size = good_run_size; michael@0: bin->nregs = good_nregs; michael@0: bin->regs_mask_nelms = good_mask_nelms; michael@0: bin->reg0_offset = good_reg0_offset; michael@0: michael@0: return (good_run_size); michael@0: } michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: static inline void michael@0: arena_lock_balance(arena_t *arena) michael@0: { michael@0: unsigned contention; michael@0: michael@0: contention = malloc_spin_lock(&arena->lock); michael@0: if (narenas > 1) { michael@0: /* michael@0: * Calculate the exponentially averaged contention for this michael@0: * arena. Due to integer math always rounding down, this value michael@0: * decays somewhat faster then normal. michael@0: */ michael@0: arena->contention = (((uint64_t)arena->contention michael@0: * (uint64_t)((1U << BALANCE_ALPHA_INV_2POW)-1)) michael@0: + (uint64_t)contention) >> BALANCE_ALPHA_INV_2POW; michael@0: if (arena->contention >= opt_balance_threshold) michael@0: arena_lock_balance_hard(arena); michael@0: } michael@0: } michael@0: michael@0: static void michael@0: arena_lock_balance_hard(arena_t *arena) michael@0: { michael@0: uint32_t ind; michael@0: michael@0: arena->contention = 0; michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.nbalance++; michael@0: #endif michael@0: ind = PRN(balance, narenas_2pow); michael@0: if (arenas[ind] != NULL) { michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: TlsSetValue(tlsIndex, arenas[ind]); michael@0: #else michael@0: arenas_map = arenas[ind]; michael@0: #endif michael@0: } else { michael@0: malloc_spin_lock(&arenas_lock); michael@0: if (arenas[ind] != NULL) { michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: TlsSetValue(tlsIndex, arenas[ind]); michael@0: #else michael@0: arenas_map = arenas[ind]; michael@0: #endif michael@0: } else { michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: TlsSetValue(tlsIndex, arenas_extend(ind)); michael@0: #else michael@0: arenas_map = arenas_extend(ind); michael@0: #endif michael@0: } michael@0: malloc_spin_unlock(&arenas_lock); michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: static inline void * michael@0: arena_malloc_small(arena_t *arena, size_t size, bool zero) michael@0: { michael@0: void *ret; michael@0: arena_bin_t *bin; michael@0: arena_run_t *run; michael@0: michael@0: if (size < small_min) { michael@0: /* Tiny. */ michael@0: size = pow2_ceil(size); michael@0: bin = &arena->bins[ffs((int)(size >> (TINY_MIN_2POW + michael@0: 1)))]; michael@0: #if (!defined(NDEBUG) || defined(MALLOC_STATS)) michael@0: /* michael@0: * Bin calculation is always correct, but we may need michael@0: * to fix size for the purposes of assertions and/or michael@0: * stats accuracy. michael@0: */ michael@0: if (size < (1U << TINY_MIN_2POW)) michael@0: size = (1U << TINY_MIN_2POW); michael@0: #endif michael@0: } else if (size <= small_max) { michael@0: /* Quantum-spaced. */ michael@0: size = QUANTUM_CEILING(size); michael@0: bin = &arena->bins[ntbins + (size >> opt_quantum_2pow) michael@0: - 1]; michael@0: } else { michael@0: /* Sub-page. */ michael@0: size = pow2_ceil(size); michael@0: bin = &arena->bins[ntbins + nqbins michael@0: + (ffs((int)(size >> opt_small_max_2pow)) - 2)]; michael@0: } michael@0: RELEASE_ASSERT(size == bin->reg_size); michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: arena_lock_balance(arena); michael@0: #else michael@0: malloc_spin_lock(&arena->lock); michael@0: #endif michael@0: if ((run = bin->runcur) != NULL && run->nfree > 0) michael@0: ret = arena_bin_malloc_easy(arena, bin, run); michael@0: else michael@0: ret = arena_bin_malloc_hard(arena, bin); michael@0: michael@0: if (ret == NULL) { michael@0: malloc_spin_unlock(&arena->lock); michael@0: return (NULL); michael@0: } michael@0: michael@0: #ifdef MALLOC_STATS michael@0: bin->stats.nrequests++; michael@0: arena->stats.nmalloc_small++; michael@0: arena->stats.allocated_small += size; michael@0: #endif michael@0: malloc_spin_unlock(&arena->lock); michael@0: michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, zero); michael@0: if (zero == false) { michael@0: #ifdef MALLOC_FILL michael@0: if (opt_junk) michael@0: memset(ret, 0xa5, size); michael@0: else if (opt_zero) michael@0: memset(ret, 0, size); michael@0: #endif michael@0: } else michael@0: memset(ret, 0, size); michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static void * michael@0: arena_malloc_large(arena_t *arena, size_t size, bool zero) michael@0: { michael@0: void *ret; michael@0: michael@0: /* Large allocation. */ michael@0: size = PAGE_CEILING(size); michael@0: #ifdef MALLOC_BALANCE michael@0: arena_lock_balance(arena); michael@0: #else michael@0: malloc_spin_lock(&arena->lock); michael@0: #endif michael@0: ret = (void *)arena_run_alloc(arena, NULL, size, true, zero); michael@0: if (ret == NULL) { michael@0: malloc_spin_unlock(&arena->lock); michael@0: return (NULL); michael@0: } michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.nmalloc_large++; michael@0: arena->stats.allocated_large += size; michael@0: #endif michael@0: malloc_spin_unlock(&arena->lock); michael@0: michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, zero); michael@0: if (zero == false) { michael@0: #ifdef MALLOC_FILL michael@0: if (opt_junk) michael@0: memset(ret, 0xa5, size); michael@0: else if (opt_zero) michael@0: memset(ret, 0, size); michael@0: #endif michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static inline void * michael@0: arena_malloc(arena_t *arena, size_t size, bool zero) michael@0: { michael@0: michael@0: assert(arena != NULL); michael@0: RELEASE_ASSERT(arena->magic == ARENA_MAGIC); michael@0: assert(size != 0); michael@0: assert(QUANTUM_CEILING(size) <= arena_maxclass); michael@0: michael@0: if (size <= bin_maxclass) { michael@0: return (arena_malloc_small(arena, size, zero)); michael@0: } else michael@0: return (arena_malloc_large(arena, size, zero)); michael@0: } michael@0: michael@0: static inline void * michael@0: imalloc(size_t size) michael@0: { michael@0: michael@0: assert(size != 0); michael@0: michael@0: if (size <= arena_maxclass) michael@0: return (arena_malloc(choose_arena(), size, false)); michael@0: else michael@0: return (huge_malloc(size, false)); michael@0: } michael@0: michael@0: static inline void * michael@0: icalloc(size_t size) michael@0: { michael@0: michael@0: if (size <= arena_maxclass) michael@0: return (arena_malloc(choose_arena(), size, true)); michael@0: else michael@0: return (huge_malloc(size, true)); michael@0: } michael@0: michael@0: /* Only handles large allocations that require more than page alignment. */ michael@0: static void * michael@0: arena_palloc(arena_t *arena, size_t alignment, size_t size, size_t alloc_size) michael@0: { michael@0: void *ret; michael@0: size_t offset; michael@0: arena_chunk_t *chunk; michael@0: michael@0: assert((size & pagesize_mask) == 0); michael@0: assert((alignment & pagesize_mask) == 0); michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: arena_lock_balance(arena); michael@0: #else michael@0: malloc_spin_lock(&arena->lock); michael@0: #endif michael@0: ret = (void *)arena_run_alloc(arena, NULL, alloc_size, true, false); michael@0: if (ret == NULL) { michael@0: malloc_spin_unlock(&arena->lock); michael@0: return (NULL); michael@0: } michael@0: michael@0: chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret); michael@0: michael@0: offset = (uintptr_t)ret & (alignment - 1); michael@0: assert((offset & pagesize_mask) == 0); michael@0: assert(offset < alloc_size); michael@0: if (offset == 0) michael@0: arena_run_trim_tail(arena, chunk, (arena_run_t*)ret, alloc_size, size, false); michael@0: else { michael@0: size_t leadsize, trailsize; michael@0: michael@0: leadsize = alignment - offset; michael@0: if (leadsize > 0) { michael@0: arena_run_trim_head(arena, chunk, (arena_run_t*)ret, alloc_size, michael@0: alloc_size - leadsize); michael@0: ret = (void *)((uintptr_t)ret + leadsize); michael@0: } michael@0: michael@0: trailsize = alloc_size - leadsize - size; michael@0: if (trailsize != 0) { michael@0: /* Trim trailing space. */ michael@0: assert(trailsize < alloc_size); michael@0: arena_run_trim_tail(arena, chunk, (arena_run_t*)ret, size + trailsize, michael@0: size, false); michael@0: } michael@0: } michael@0: michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.nmalloc_large++; michael@0: arena->stats.allocated_large += size; michael@0: #endif michael@0: malloc_spin_unlock(&arena->lock); michael@0: michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, false); michael@0: #ifdef MALLOC_FILL michael@0: if (opt_junk) michael@0: memset(ret, 0xa5, size); michael@0: else if (opt_zero) michael@0: memset(ret, 0, size); michael@0: #endif michael@0: return (ret); michael@0: } michael@0: michael@0: static inline void * michael@0: ipalloc(size_t alignment, size_t size) michael@0: { michael@0: void *ret; michael@0: size_t ceil_size; michael@0: michael@0: /* michael@0: * Round size up to the nearest multiple of alignment. michael@0: * michael@0: * This done, we can take advantage of the fact that for each small michael@0: * size class, every object is aligned at the smallest power of two michael@0: * that is non-zero in the base two representation of the size. For michael@0: * example: michael@0: * michael@0: * Size | Base 2 | Minimum alignment michael@0: * -----+----------+------------------ michael@0: * 96 | 1100000 | 32 michael@0: * 144 | 10100000 | 32 michael@0: * 192 | 11000000 | 64 michael@0: * michael@0: * Depending on runtime settings, it is possible that arena_malloc() michael@0: * will further round up to a power of two, but that never causes michael@0: * correctness issues. michael@0: */ michael@0: ceil_size = (size + (alignment - 1)) & (-alignment); michael@0: /* michael@0: * (ceil_size < size) protects against the combination of maximal michael@0: * alignment and size greater than maximal alignment. michael@0: */ michael@0: if (ceil_size < size) { michael@0: /* size_t overflow. */ michael@0: return (NULL); michael@0: } michael@0: michael@0: if (ceil_size <= pagesize || (alignment <= pagesize michael@0: && ceil_size <= arena_maxclass)) michael@0: ret = arena_malloc(choose_arena(), ceil_size, false); michael@0: else { michael@0: size_t run_size; michael@0: michael@0: /* michael@0: * We can't achieve sub-page alignment, so round up alignment michael@0: * permanently; it makes later calculations simpler. michael@0: */ michael@0: alignment = PAGE_CEILING(alignment); michael@0: ceil_size = PAGE_CEILING(size); michael@0: /* michael@0: * (ceil_size < size) protects against very large sizes within michael@0: * pagesize of SIZE_T_MAX. michael@0: * michael@0: * (ceil_size + alignment < ceil_size) protects against the michael@0: * combination of maximal alignment and ceil_size large enough michael@0: * to cause overflow. This is similar to the first overflow michael@0: * check above, but it needs to be repeated due to the new michael@0: * ceil_size value, which may now be *equal* to maximal michael@0: * alignment, whereas before we only detected overflow if the michael@0: * original size was *greater* than maximal alignment. michael@0: */ michael@0: if (ceil_size < size || ceil_size + alignment < ceil_size) { michael@0: /* size_t overflow. */ michael@0: return (NULL); michael@0: } michael@0: michael@0: /* michael@0: * Calculate the size of the over-size run that arena_palloc() michael@0: * would need to allocate in order to guarantee the alignment. michael@0: */ michael@0: if (ceil_size >= alignment) michael@0: run_size = ceil_size + alignment - pagesize; michael@0: else { michael@0: /* michael@0: * It is possible that (alignment << 1) will cause michael@0: * overflow, but it doesn't matter because we also michael@0: * subtract pagesize, which in the case of overflow michael@0: * leaves us with a very large run_size. That causes michael@0: * the first conditional below to fail, which means michael@0: * that the bogus run_size value never gets used for michael@0: * anything important. michael@0: */ michael@0: run_size = (alignment << 1) - pagesize; michael@0: } michael@0: michael@0: if (run_size <= arena_maxclass) { michael@0: ret = arena_palloc(choose_arena(), alignment, ceil_size, michael@0: run_size); michael@0: } else if (alignment <= chunksize) michael@0: ret = huge_malloc(ceil_size, false); michael@0: else michael@0: ret = huge_palloc(alignment, ceil_size); michael@0: } michael@0: michael@0: assert(((uintptr_t)ret & (alignment - 1)) == 0); michael@0: return (ret); michael@0: } michael@0: michael@0: /* Return the size of the allocation pointed to by ptr. */ michael@0: static size_t michael@0: arena_salloc(const void *ptr) michael@0: { michael@0: size_t ret; michael@0: arena_chunk_t *chunk; michael@0: size_t pageind, mapbits; michael@0: michael@0: assert(ptr != NULL); michael@0: assert(CHUNK_ADDR2BASE(ptr) != ptr); michael@0: michael@0: chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); michael@0: pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> pagesize_2pow); michael@0: mapbits = chunk->map[pageind].bits; michael@0: RELEASE_ASSERT((mapbits & CHUNK_MAP_ALLOCATED) != 0); michael@0: if ((mapbits & CHUNK_MAP_LARGE) == 0) { michael@0: arena_run_t *run = (arena_run_t *)(mapbits & ~pagesize_mask); michael@0: RELEASE_ASSERT(run->magic == ARENA_RUN_MAGIC); michael@0: ret = run->bin->reg_size; michael@0: } else { michael@0: ret = mapbits & ~pagesize_mask; michael@0: RELEASE_ASSERT(ret != 0); michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: #if (defined(MALLOC_VALIDATE) || defined(MOZ_MEMORY_DARWIN)) michael@0: /* michael@0: * Validate ptr before assuming that it points to an allocation. Currently, michael@0: * the following validation is performed: michael@0: * michael@0: * + Check that ptr is not NULL. michael@0: * michael@0: * + Check that ptr lies within a mapped chunk. michael@0: */ michael@0: static inline size_t michael@0: isalloc_validate(const void *ptr) michael@0: { michael@0: arena_chunk_t *chunk; michael@0: michael@0: chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); michael@0: if (chunk == NULL) michael@0: return (0); michael@0: michael@0: if (malloc_rtree_get(chunk_rtree, (uintptr_t)chunk) == NULL) michael@0: return (0); michael@0: michael@0: if (chunk != ptr) { michael@0: RELEASE_ASSERT(chunk->arena->magic == ARENA_MAGIC); michael@0: return (arena_salloc(ptr)); michael@0: } else { michael@0: size_t ret; michael@0: extent_node_t *node; michael@0: extent_node_t key; michael@0: michael@0: /* Chunk. */ michael@0: key.addr = (void *)chunk; michael@0: malloc_mutex_lock(&huge_mtx); michael@0: node = extent_tree_ad_search(&huge, &key); michael@0: if (node != NULL) michael@0: ret = node->size; michael@0: else michael@0: ret = 0; michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: return (ret); michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: static inline size_t michael@0: isalloc(const void *ptr) michael@0: { michael@0: size_t ret; michael@0: arena_chunk_t *chunk; michael@0: michael@0: assert(ptr != NULL); michael@0: michael@0: chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); michael@0: if (chunk != ptr) { michael@0: /* Region. */ michael@0: assert(chunk->arena->magic == ARENA_MAGIC); michael@0: michael@0: ret = arena_salloc(ptr); michael@0: } else { michael@0: extent_node_t *node, key; michael@0: michael@0: /* Chunk (huge allocation). */ michael@0: michael@0: malloc_mutex_lock(&huge_mtx); michael@0: michael@0: /* Extract from tree of huge allocations. */ michael@0: key.addr = __DECONST(void *, ptr); michael@0: node = extent_tree_ad_search(&huge, &key); michael@0: RELEASE_ASSERT(node != NULL); michael@0: michael@0: ret = node->size; michael@0: michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static inline void michael@0: arena_dalloc_small(arena_t *arena, arena_chunk_t *chunk, void *ptr, michael@0: arena_chunk_map_t *mapelm) michael@0: { michael@0: arena_run_t *run; michael@0: arena_bin_t *bin; michael@0: size_t size; michael@0: michael@0: run = (arena_run_t *)(mapelm->bits & ~pagesize_mask); michael@0: RELEASE_ASSERT(run->magic == ARENA_RUN_MAGIC); michael@0: bin = run->bin; michael@0: size = bin->reg_size; michael@0: michael@0: #ifdef MALLOC_FILL michael@0: if (opt_poison) michael@0: memset(ptr, 0x5a, size); michael@0: #endif michael@0: michael@0: arena_run_reg_dalloc(run, bin, ptr, size); michael@0: run->nfree++; michael@0: michael@0: if (run->nfree == bin->nregs) { michael@0: /* Deallocate run. */ michael@0: if (run == bin->runcur) michael@0: bin->runcur = NULL; michael@0: else if (bin->nregs != 1) { michael@0: size_t run_pageind = (((uintptr_t)run - michael@0: (uintptr_t)chunk)) >> pagesize_2pow; michael@0: arena_chunk_map_t *run_mapelm = michael@0: &chunk->map[run_pageind]; michael@0: /* michael@0: * This block's conditional is necessary because if the michael@0: * run only contains one region, then it never gets michael@0: * inserted into the non-full runs tree. michael@0: */ michael@0: RELEASE_ASSERT(arena_run_tree_search(&bin->runs, run_mapelm) == michael@0: run_mapelm); michael@0: arena_run_tree_remove(&bin->runs, run_mapelm); michael@0: } michael@0: #if defined(MALLOC_DEBUG) || defined(MOZ_JEMALLOC_HARD_ASSERTS) michael@0: run->magic = 0; michael@0: #endif michael@0: VALGRIND_FREELIKE_BLOCK(run, 0); michael@0: arena_run_dalloc(arena, run, true); michael@0: #ifdef MALLOC_STATS michael@0: bin->stats.curruns--; michael@0: #endif michael@0: } else if (run->nfree == 1 && run != bin->runcur) { michael@0: /* michael@0: * Make sure that bin->runcur always refers to the lowest michael@0: * non-full run, if one exists. michael@0: */ michael@0: if (bin->runcur == NULL) michael@0: bin->runcur = run; michael@0: else if ((uintptr_t)run < (uintptr_t)bin->runcur) { michael@0: /* Switch runcur. */ michael@0: if (bin->runcur->nfree > 0) { michael@0: arena_chunk_t *runcur_chunk = michael@0: (arena_chunk_t*)CHUNK_ADDR2BASE(bin->runcur); michael@0: size_t runcur_pageind = michael@0: (((uintptr_t)bin->runcur - michael@0: (uintptr_t)runcur_chunk)) >> pagesize_2pow; michael@0: arena_chunk_map_t *runcur_mapelm = michael@0: &runcur_chunk->map[runcur_pageind]; michael@0: michael@0: /* Insert runcur. */ michael@0: RELEASE_ASSERT(arena_run_tree_search(&bin->runs, michael@0: runcur_mapelm) == NULL); michael@0: arena_run_tree_insert(&bin->runs, michael@0: runcur_mapelm); michael@0: } michael@0: bin->runcur = run; michael@0: } else { michael@0: size_t run_pageind = (((uintptr_t)run - michael@0: (uintptr_t)chunk)) >> pagesize_2pow; michael@0: arena_chunk_map_t *run_mapelm = michael@0: &chunk->map[run_pageind]; michael@0: michael@0: RELEASE_ASSERT(arena_run_tree_search(&bin->runs, run_mapelm) == michael@0: NULL); michael@0: arena_run_tree_insert(&bin->runs, run_mapelm); michael@0: } michael@0: } michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.allocated_small -= size; michael@0: arena->stats.ndalloc_small++; michael@0: #endif michael@0: } michael@0: michael@0: static void michael@0: arena_dalloc_large(arena_t *arena, arena_chunk_t *chunk, void *ptr) michael@0: { michael@0: /* Large allocation. */ michael@0: malloc_spin_lock(&arena->lock); michael@0: michael@0: #ifdef MALLOC_FILL michael@0: #ifndef MALLOC_STATS michael@0: if (opt_poison) michael@0: #endif michael@0: #endif michael@0: { michael@0: size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> michael@0: pagesize_2pow; michael@0: size_t size = chunk->map[pageind].bits & ~pagesize_mask; michael@0: michael@0: #ifdef MALLOC_FILL michael@0: #ifdef MALLOC_STATS michael@0: if (opt_poison) michael@0: #endif michael@0: memset(ptr, 0x5a, size); michael@0: #endif michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.allocated_large -= size; michael@0: #endif michael@0: } michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.ndalloc_large++; michael@0: #endif michael@0: michael@0: arena_run_dalloc(arena, (arena_run_t *)ptr, true); michael@0: malloc_spin_unlock(&arena->lock); michael@0: } michael@0: michael@0: static inline void michael@0: arena_dalloc(void *ptr, size_t offset) michael@0: { michael@0: arena_chunk_t *chunk; michael@0: arena_t *arena; michael@0: size_t pageind; michael@0: arena_chunk_map_t *mapelm; michael@0: michael@0: assert(ptr != NULL); michael@0: assert(offset != 0); michael@0: assert(CHUNK_ADDR2OFFSET(ptr) == offset); michael@0: michael@0: chunk = (arena_chunk_t *) ((uintptr_t)ptr - offset); michael@0: arena = chunk->arena; michael@0: assert(arena != NULL); michael@0: RELEASE_ASSERT(arena->magic == ARENA_MAGIC); michael@0: michael@0: pageind = offset >> pagesize_2pow; michael@0: mapelm = &chunk->map[pageind]; michael@0: RELEASE_ASSERT((mapelm->bits & CHUNK_MAP_ALLOCATED) != 0); michael@0: if ((mapelm->bits & CHUNK_MAP_LARGE) == 0) { michael@0: /* Small allocation. */ michael@0: malloc_spin_lock(&arena->lock); michael@0: arena_dalloc_small(arena, chunk, ptr, mapelm); michael@0: malloc_spin_unlock(&arena->lock); michael@0: } else michael@0: arena_dalloc_large(arena, chunk, ptr); michael@0: VALGRIND_FREELIKE_BLOCK(ptr, 0); michael@0: } michael@0: michael@0: static inline void michael@0: idalloc(void *ptr) michael@0: { michael@0: size_t offset; michael@0: michael@0: assert(ptr != NULL); michael@0: michael@0: offset = CHUNK_ADDR2OFFSET(ptr); michael@0: if (offset != 0) michael@0: arena_dalloc(ptr, offset); michael@0: else michael@0: huge_dalloc(ptr); michael@0: } michael@0: michael@0: static void michael@0: arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk, void *ptr, michael@0: size_t size, size_t oldsize) michael@0: { michael@0: michael@0: assert(size < oldsize); michael@0: michael@0: /* michael@0: * Shrink the run, and make trailing pages available for other michael@0: * allocations. michael@0: */ michael@0: #ifdef MALLOC_BALANCE michael@0: arena_lock_balance(arena); michael@0: #else michael@0: malloc_spin_lock(&arena->lock); michael@0: #endif michael@0: arena_run_trim_tail(arena, chunk, (arena_run_t *)ptr, oldsize, size, michael@0: true); michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.allocated_large -= oldsize - size; michael@0: #endif michael@0: malloc_spin_unlock(&arena->lock); michael@0: } michael@0: michael@0: static bool michael@0: arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk, void *ptr, michael@0: size_t size, size_t oldsize) michael@0: { michael@0: size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> pagesize_2pow; michael@0: size_t npages = oldsize >> pagesize_2pow; michael@0: michael@0: RELEASE_ASSERT(oldsize == (chunk->map[pageind].bits & ~pagesize_mask)); michael@0: michael@0: /* Try to extend the run. */ michael@0: assert(size > oldsize); michael@0: #ifdef MALLOC_BALANCE michael@0: arena_lock_balance(arena); michael@0: #else michael@0: malloc_spin_lock(&arena->lock); michael@0: #endif michael@0: if (pageind + npages < chunk_npages && (chunk->map[pageind+npages].bits michael@0: & CHUNK_MAP_ALLOCATED) == 0 && (chunk->map[pageind+npages].bits & michael@0: ~pagesize_mask) >= size - oldsize) { michael@0: /* michael@0: * The next run is available and sufficiently large. Split the michael@0: * following run, then merge the first part with the existing michael@0: * allocation. michael@0: */ michael@0: arena_run_split(arena, (arena_run_t *)((uintptr_t)chunk + michael@0: ((pageind+npages) << pagesize_2pow)), size - oldsize, true, michael@0: false); michael@0: michael@0: chunk->map[pageind].bits = size | CHUNK_MAP_LARGE | michael@0: CHUNK_MAP_ALLOCATED; michael@0: chunk->map[pageind+npages].bits = CHUNK_MAP_LARGE | michael@0: CHUNK_MAP_ALLOCATED; michael@0: michael@0: #ifdef MALLOC_STATS michael@0: arena->stats.allocated_large += size - oldsize; michael@0: #endif michael@0: malloc_spin_unlock(&arena->lock); michael@0: return (false); michael@0: } michael@0: malloc_spin_unlock(&arena->lock); michael@0: michael@0: return (true); michael@0: } michael@0: michael@0: /* michael@0: * Try to resize a large allocation, in order to avoid copying. This will michael@0: * always fail if growing an object, and the following run is already in use. michael@0: */ michael@0: static bool michael@0: arena_ralloc_large(void *ptr, size_t size, size_t oldsize) michael@0: { michael@0: size_t psize; michael@0: michael@0: psize = PAGE_CEILING(size); michael@0: if (psize == oldsize) { michael@0: /* Same size class. */ michael@0: #ifdef MALLOC_FILL michael@0: if (opt_poison && size < oldsize) { michael@0: memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - michael@0: size); michael@0: } michael@0: #endif michael@0: return (false); michael@0: } else { michael@0: arena_chunk_t *chunk; michael@0: arena_t *arena; michael@0: michael@0: chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); michael@0: arena = chunk->arena; michael@0: RELEASE_ASSERT(arena->magic == ARENA_MAGIC); michael@0: michael@0: if (psize < oldsize) { michael@0: #ifdef MALLOC_FILL michael@0: /* Fill before shrinking in order avoid a race. */ michael@0: if (opt_poison) { michael@0: memset((void *)((uintptr_t)ptr + size), 0x5a, michael@0: oldsize - size); michael@0: } michael@0: #endif michael@0: arena_ralloc_large_shrink(arena, chunk, ptr, psize, michael@0: oldsize); michael@0: return (false); michael@0: } else { michael@0: bool ret = arena_ralloc_large_grow(arena, chunk, ptr, michael@0: psize, oldsize); michael@0: #ifdef MALLOC_FILL michael@0: if (ret == false && opt_zero) { michael@0: memset((void *)((uintptr_t)ptr + oldsize), 0, michael@0: size - oldsize); michael@0: } michael@0: #endif michael@0: return (ret); michael@0: } michael@0: } michael@0: } michael@0: michael@0: static void * michael@0: arena_ralloc(void *ptr, size_t size, size_t oldsize) michael@0: { michael@0: void *ret; michael@0: size_t copysize; michael@0: michael@0: /* Try to avoid moving the allocation. */ michael@0: if (size < small_min) { michael@0: if (oldsize < small_min && michael@0: ffs((int)(pow2_ceil(size) >> (TINY_MIN_2POW + 1))) michael@0: == ffs((int)(pow2_ceil(oldsize) >> (TINY_MIN_2POW + 1)))) michael@0: goto IN_PLACE; /* Same size class. */ michael@0: } else if (size <= small_max) { michael@0: if (oldsize >= small_min && oldsize <= small_max && michael@0: (QUANTUM_CEILING(size) >> opt_quantum_2pow) michael@0: == (QUANTUM_CEILING(oldsize) >> opt_quantum_2pow)) michael@0: goto IN_PLACE; /* Same size class. */ michael@0: } else if (size <= bin_maxclass) { michael@0: if (oldsize > small_max && oldsize <= bin_maxclass && michael@0: pow2_ceil(size) == pow2_ceil(oldsize)) michael@0: goto IN_PLACE; /* Same size class. */ michael@0: } else if (oldsize > bin_maxclass && oldsize <= arena_maxclass) { michael@0: assert(size > bin_maxclass); michael@0: if (arena_ralloc_large(ptr, size, oldsize) == false) michael@0: return (ptr); michael@0: } michael@0: michael@0: /* michael@0: * If we get here, then size and oldsize are different enough that we michael@0: * need to move the object. In that case, fall back to allocating new michael@0: * space and copying. michael@0: */ michael@0: ret = arena_malloc(choose_arena(), size, false); michael@0: if (ret == NULL) michael@0: return (NULL); michael@0: michael@0: /* Junk/zero-filling were already done by arena_malloc(). */ michael@0: copysize = (size < oldsize) ? size : oldsize; michael@0: #ifdef VM_COPY_MIN michael@0: if (copysize >= VM_COPY_MIN) michael@0: pages_copy(ret, ptr, copysize); michael@0: else michael@0: #endif michael@0: memcpy(ret, ptr, copysize); michael@0: idalloc(ptr); michael@0: return (ret); michael@0: IN_PLACE: michael@0: #ifdef MALLOC_FILL michael@0: if (opt_poison && size < oldsize) michael@0: memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - size); michael@0: else if (opt_zero && size > oldsize) michael@0: memset((void *)((uintptr_t)ptr + oldsize), 0, size - oldsize); michael@0: #endif michael@0: return (ptr); michael@0: } michael@0: michael@0: static inline void * michael@0: iralloc(void *ptr, size_t size) michael@0: { michael@0: size_t oldsize; michael@0: michael@0: assert(ptr != NULL); michael@0: assert(size != 0); michael@0: michael@0: oldsize = isalloc(ptr); michael@0: michael@0: #ifndef MALLOC_VALGRIND michael@0: if (size <= arena_maxclass) michael@0: return (arena_ralloc(ptr, size, oldsize)); michael@0: else michael@0: return (huge_ralloc(ptr, size, oldsize)); michael@0: #else michael@0: /* michael@0: * Valgrind does not provide a public interface for modifying an michael@0: * existing allocation, so use malloc/memcpy/free instead. michael@0: */ michael@0: { michael@0: void *ret = imalloc(size); michael@0: if (ret != NULL) { michael@0: if (oldsize < size) michael@0: memcpy(ret, ptr, oldsize); michael@0: else michael@0: memcpy(ret, ptr, size); michael@0: idalloc(ptr); michael@0: } michael@0: return (ret); michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: static bool michael@0: arena_new(arena_t *arena) michael@0: { michael@0: unsigned i; michael@0: arena_bin_t *bin; michael@0: size_t pow2_size, prev_run_size; michael@0: michael@0: if (malloc_spin_init(&arena->lock)) michael@0: return (true); michael@0: michael@0: #ifdef MALLOC_STATS michael@0: memset(&arena->stats, 0, sizeof(arena_stats_t)); michael@0: #endif michael@0: michael@0: /* Initialize chunks. */ michael@0: arena_chunk_tree_dirty_new(&arena->chunks_dirty); michael@0: #ifdef MALLOC_DOUBLE_PURGE michael@0: LinkedList_Init(&arena->chunks_madvised); michael@0: #endif michael@0: arena->spare = NULL; michael@0: michael@0: arena->ndirty = 0; michael@0: michael@0: arena_avail_tree_new(&arena->runs_avail); michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: arena->contention = 0; michael@0: #endif michael@0: michael@0: /* Initialize bins. */ michael@0: prev_run_size = pagesize; michael@0: michael@0: /* (2^n)-spaced tiny bins. */ michael@0: for (i = 0; i < ntbins; i++) { michael@0: bin = &arena->bins[i]; michael@0: bin->runcur = NULL; michael@0: arena_run_tree_new(&bin->runs); michael@0: michael@0: bin->reg_size = (1U << (TINY_MIN_2POW + i)); michael@0: michael@0: prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); michael@0: michael@0: #ifdef MALLOC_STATS michael@0: memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); michael@0: #endif michael@0: } michael@0: michael@0: /* Quantum-spaced bins. */ michael@0: for (; i < ntbins + nqbins; i++) { michael@0: bin = &arena->bins[i]; michael@0: bin->runcur = NULL; michael@0: arena_run_tree_new(&bin->runs); michael@0: michael@0: bin->reg_size = quantum * (i - ntbins + 1); michael@0: michael@0: pow2_size = pow2_ceil(quantum * (i - ntbins + 1)); michael@0: prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); michael@0: michael@0: #ifdef MALLOC_STATS michael@0: memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); michael@0: #endif michael@0: } michael@0: michael@0: /* (2^n)-spaced sub-page bins. */ michael@0: for (; i < ntbins + nqbins + nsbins; i++) { michael@0: bin = &arena->bins[i]; michael@0: bin->runcur = NULL; michael@0: arena_run_tree_new(&bin->runs); michael@0: michael@0: bin->reg_size = (small_max << (i - (ntbins + nqbins) + 1)); michael@0: michael@0: prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); michael@0: michael@0: #ifdef MALLOC_STATS michael@0: memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); michael@0: #endif michael@0: } michael@0: michael@0: #if defined(MALLOC_DEBUG) || defined(MOZ_JEMALLOC_HARD_ASSERTS) michael@0: arena->magic = ARENA_MAGIC; michael@0: #endif michael@0: michael@0: return (false); michael@0: } michael@0: michael@0: /* Create a new arena and insert it into the arenas array at index ind. */ michael@0: static arena_t * michael@0: arenas_extend(unsigned ind) michael@0: { michael@0: arena_t *ret; michael@0: michael@0: /* Allocate enough space for trailing bins. */ michael@0: ret = (arena_t *)base_alloc(sizeof(arena_t) michael@0: + (sizeof(arena_bin_t) * (ntbins + nqbins + nsbins - 1))); michael@0: if (ret != NULL && arena_new(ret) == false) { michael@0: arenas[ind] = ret; michael@0: return (ret); michael@0: } michael@0: /* Only reached if there is an OOM error. */ michael@0: michael@0: /* michael@0: * OOM here is quite inconvenient to propagate, since dealing with it michael@0: * would require a check for failure in the fast path. Instead, punt michael@0: * by using arenas[0]. In practice, this is an extremely unlikely michael@0: * failure. michael@0: */ michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error initializing arena\n", "", ""); michael@0: if (opt_abort) michael@0: abort(); michael@0: michael@0: return (arenas[0]); michael@0: } michael@0: michael@0: /* michael@0: * End arena. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin general internal functions. michael@0: */ michael@0: michael@0: static void * michael@0: huge_malloc(size_t size, bool zero) michael@0: { michael@0: void *ret; michael@0: size_t csize; michael@0: size_t psize; michael@0: extent_node_t *node; michael@0: michael@0: /* Allocate one or more contiguous chunks for this request. */ michael@0: michael@0: csize = CHUNK_CEILING(size); michael@0: if (csize == 0) { michael@0: /* size is large enough to cause size_t wrap-around. */ michael@0: return (NULL); michael@0: } michael@0: michael@0: /* Allocate an extent node with which to track the chunk. */ michael@0: node = base_node_alloc(); michael@0: if (node == NULL) michael@0: return (NULL); michael@0: michael@0: ret = chunk_alloc(csize, zero, true); michael@0: if (ret == NULL) { michael@0: base_node_dealloc(node); michael@0: return (NULL); michael@0: } michael@0: michael@0: /* Insert node into huge. */ michael@0: node->addr = ret; michael@0: psize = PAGE_CEILING(size); michael@0: node->size = psize; michael@0: michael@0: malloc_mutex_lock(&huge_mtx); michael@0: extent_tree_ad_insert(&huge, node); michael@0: #ifdef MALLOC_STATS michael@0: huge_nmalloc++; michael@0: michael@0: /* Although we allocated space for csize bytes, we indicate that we've michael@0: * allocated only psize bytes. michael@0: * michael@0: * If DECOMMIT is defined, this is a reasonable thing to do, since michael@0: * we'll explicitly decommit the bytes in excess of psize. michael@0: * michael@0: * If DECOMMIT is not defined, then we're relying on the OS to be lazy michael@0: * about how it allocates physical pages to mappings. If we never michael@0: * touch the pages in excess of psize, the OS won't allocate a physical michael@0: * page, and we won't use more than psize bytes of physical memory. michael@0: * michael@0: * A correct program will only touch memory in excess of how much it michael@0: * requested if it first calls malloc_usable_size and finds out how michael@0: * much space it has to play with. But because we set node->size = michael@0: * psize above, malloc_usable_size will return psize, not csize, and michael@0: * the program will (hopefully) never touch bytes in excess of psize. michael@0: * Thus those bytes won't take up space in physical memory, and we can michael@0: * reasonably claim we never "allocated" them in the first place. */ michael@0: huge_allocated += psize; michael@0: huge_mapped += csize; michael@0: #endif michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: michael@0: #ifdef MALLOC_DECOMMIT michael@0: if (csize - psize > 0) michael@0: pages_decommit((void *)((uintptr_t)ret + psize), csize - psize); michael@0: #endif michael@0: michael@0: #ifdef MALLOC_DECOMMIT michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, psize, 0, zero); michael@0: #else michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, csize, 0, zero); michael@0: #endif michael@0: michael@0: #ifdef MALLOC_FILL michael@0: if (zero == false) { michael@0: if (opt_junk) michael@0: # ifdef MALLOC_DECOMMIT michael@0: memset(ret, 0xa5, psize); michael@0: # else michael@0: memset(ret, 0xa5, csize); michael@0: # endif michael@0: else if (opt_zero) michael@0: # ifdef MALLOC_DECOMMIT michael@0: memset(ret, 0, psize); michael@0: # else michael@0: memset(ret, 0, csize); michael@0: # endif michael@0: } michael@0: #endif michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: /* Only handles large allocations that require more than chunk alignment. */ michael@0: static void * michael@0: huge_palloc(size_t alignment, size_t size) michael@0: { michael@0: void *ret; michael@0: size_t alloc_size, chunk_size, offset; michael@0: size_t psize; michael@0: extent_node_t *node; michael@0: int pfd; michael@0: michael@0: /* michael@0: * This allocation requires alignment that is even larger than chunk michael@0: * alignment. This means that huge_malloc() isn't good enough. michael@0: * michael@0: * Allocate almost twice as many chunks as are demanded by the size or michael@0: * alignment, in order to assure the alignment can be achieved, then michael@0: * unmap leading and trailing chunks. michael@0: */ michael@0: assert(alignment >= chunksize); michael@0: michael@0: chunk_size = CHUNK_CEILING(size); michael@0: michael@0: if (size >= alignment) michael@0: alloc_size = chunk_size + alignment - chunksize; michael@0: else michael@0: alloc_size = (alignment << 1) - chunksize; michael@0: michael@0: /* Allocate an extent node with which to track the chunk. */ michael@0: node = base_node_alloc(); michael@0: if (node == NULL) michael@0: return (NULL); michael@0: michael@0: /* michael@0: * Windows requires that there be a 1:1 mapping between VM michael@0: * allocation/deallocation operations. Therefore, take care here to michael@0: * acquire the final result via one mapping operation. michael@0: * michael@0: * The MALLOC_PAGEFILE code also benefits from this mapping algorithm, michael@0: * since it reduces the number of page files. michael@0: */ michael@0: #ifdef MALLOC_PAGEFILE michael@0: if (opt_pagefile) { michael@0: pfd = pagefile_init(size); michael@0: if (pfd == -1) michael@0: return (NULL); michael@0: } else michael@0: #endif michael@0: pfd = -1; michael@0: #ifdef JEMALLOC_USES_MAP_ALIGN michael@0: ret = pages_map_align(chunk_size, pfd, alignment); michael@0: #else michael@0: do { michael@0: void *over; michael@0: michael@0: over = chunk_alloc(alloc_size, false, false); michael@0: if (over == NULL) { michael@0: base_node_dealloc(node); michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: michael@0: offset = (uintptr_t)over & (alignment - 1); michael@0: assert((offset & chunksize_mask) == 0); michael@0: assert(offset < alloc_size); michael@0: ret = (void *)((uintptr_t)over + offset); michael@0: chunk_dealloc(over, alloc_size); michael@0: ret = pages_map(ret, chunk_size, pfd); michael@0: /* michael@0: * Failure here indicates a race with another thread, so try michael@0: * again. michael@0: */ michael@0: } while (ret == NULL); michael@0: #endif michael@0: /* Insert node into huge. */ michael@0: node->addr = ret; michael@0: psize = PAGE_CEILING(size); michael@0: node->size = psize; michael@0: michael@0: malloc_mutex_lock(&huge_mtx); michael@0: extent_tree_ad_insert(&huge, node); michael@0: #ifdef MALLOC_STATS michael@0: huge_nmalloc++; michael@0: /* See note in huge_alloc() for why huge_allocated += psize is correct michael@0: * here even when DECOMMIT is not defined. */ michael@0: huge_allocated += psize; michael@0: huge_mapped += chunk_size; michael@0: #endif michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: michael@0: #ifdef MALLOC_DECOMMIT michael@0: if (chunk_size - psize > 0) { michael@0: pages_decommit((void *)((uintptr_t)ret + psize), michael@0: chunk_size - psize); michael@0: } michael@0: #endif michael@0: michael@0: #ifdef MALLOC_DECOMMIT michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, psize, 0, false); michael@0: #else michael@0: VALGRIND_MALLOCLIKE_BLOCK(ret, chunk_size, 0, false); michael@0: #endif michael@0: michael@0: #ifdef MALLOC_FILL michael@0: if (opt_junk) michael@0: # ifdef MALLOC_DECOMMIT michael@0: memset(ret, 0xa5, psize); michael@0: # else michael@0: memset(ret, 0xa5, chunk_size); michael@0: # endif michael@0: else if (opt_zero) michael@0: # ifdef MALLOC_DECOMMIT michael@0: memset(ret, 0, psize); michael@0: # else michael@0: memset(ret, 0, chunk_size); michael@0: # endif michael@0: #endif michael@0: michael@0: RETURN: michael@0: #ifdef MALLOC_PAGEFILE michael@0: if (pfd != -1) michael@0: pagefile_close(pfd); michael@0: #endif michael@0: return (ret); michael@0: } michael@0: michael@0: static void * michael@0: huge_ralloc(void *ptr, size_t size, size_t oldsize) michael@0: { michael@0: void *ret; michael@0: size_t copysize; michael@0: michael@0: /* Avoid moving the allocation if the size class would not change. */ michael@0: michael@0: if (oldsize > arena_maxclass && michael@0: CHUNK_CEILING(size) == CHUNK_CEILING(oldsize)) { michael@0: size_t psize = PAGE_CEILING(size); michael@0: #ifdef MALLOC_FILL michael@0: if (opt_poison && size < oldsize) { michael@0: memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize michael@0: - size); michael@0: } michael@0: #endif michael@0: #ifdef MALLOC_DECOMMIT michael@0: if (psize < oldsize) { michael@0: extent_node_t *node, key; michael@0: michael@0: pages_decommit((void *)((uintptr_t)ptr + psize), michael@0: oldsize - psize); michael@0: michael@0: /* Update recorded size. */ michael@0: malloc_mutex_lock(&huge_mtx); michael@0: key.addr = __DECONST(void *, ptr); michael@0: node = extent_tree_ad_search(&huge, &key); michael@0: assert(node != NULL); michael@0: assert(node->size == oldsize); michael@0: # ifdef MALLOC_STATS michael@0: huge_allocated -= oldsize - psize; michael@0: /* No need to change huge_mapped, because we didn't michael@0: * (un)map anything. */ michael@0: # endif michael@0: node->size = psize; michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: } else if (psize > oldsize) { michael@0: pages_commit((void *)((uintptr_t)ptr + oldsize), michael@0: psize - oldsize); michael@0: } michael@0: #endif michael@0: michael@0: /* Although we don't have to commit or decommit anything if michael@0: * DECOMMIT is not defined and the size class didn't change, we michael@0: * do need to update the recorded size if the size increased, michael@0: * so malloc_usable_size doesn't return a value smaller than michael@0: * what was requested via realloc(). */ michael@0: michael@0: if (psize > oldsize) { michael@0: /* Update recorded size. */ michael@0: extent_node_t *node, key; michael@0: malloc_mutex_lock(&huge_mtx); michael@0: key.addr = __DECONST(void *, ptr); michael@0: node = extent_tree_ad_search(&huge, &key); michael@0: assert(node != NULL); michael@0: assert(node->size == oldsize); michael@0: # ifdef MALLOC_STATS michael@0: huge_allocated += psize - oldsize; michael@0: /* No need to change huge_mapped, because we didn't michael@0: * (un)map anything. */ michael@0: # endif michael@0: node->size = psize; michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: } michael@0: michael@0: #ifdef MALLOC_FILL michael@0: if (opt_zero && size > oldsize) { michael@0: memset((void *)((uintptr_t)ptr + oldsize), 0, size michael@0: - oldsize); michael@0: } michael@0: #endif michael@0: return (ptr); michael@0: } michael@0: michael@0: /* michael@0: * If we get here, then size and oldsize are different enough that we michael@0: * need to use a different size class. In that case, fall back to michael@0: * allocating new space and copying. michael@0: */ michael@0: ret = huge_malloc(size, false); michael@0: if (ret == NULL) michael@0: return (NULL); michael@0: michael@0: copysize = (size < oldsize) ? size : oldsize; michael@0: #ifdef VM_COPY_MIN michael@0: if (copysize >= VM_COPY_MIN) michael@0: pages_copy(ret, ptr, copysize); michael@0: else michael@0: #endif michael@0: memcpy(ret, ptr, copysize); michael@0: idalloc(ptr); michael@0: return (ret); michael@0: } michael@0: michael@0: static void michael@0: huge_dalloc(void *ptr) michael@0: { michael@0: extent_node_t *node, key; michael@0: michael@0: malloc_mutex_lock(&huge_mtx); michael@0: michael@0: /* Extract from tree of huge allocations. */ michael@0: key.addr = ptr; michael@0: node = extent_tree_ad_search(&huge, &key); michael@0: assert(node != NULL); michael@0: assert(node->addr == ptr); michael@0: extent_tree_ad_remove(&huge, node); michael@0: michael@0: #ifdef MALLOC_STATS michael@0: huge_ndalloc++; michael@0: huge_allocated -= node->size; michael@0: huge_mapped -= CHUNK_CEILING(node->size); michael@0: #endif michael@0: michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: michael@0: /* Unmap chunk. */ michael@0: #ifdef MALLOC_FILL michael@0: if (opt_junk) michael@0: memset(node->addr, 0x5a, node->size); michael@0: #endif michael@0: chunk_dealloc(node->addr, CHUNK_CEILING(node->size)); michael@0: VALGRIND_FREELIKE_BLOCK(node->addr, 0); michael@0: michael@0: base_node_dealloc(node); michael@0: } michael@0: michael@0: #ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE michael@0: #ifdef MOZ_MEMORY_BSD michael@0: static inline unsigned michael@0: malloc_ncpus(void) michael@0: { michael@0: unsigned ret; michael@0: int mib[2]; michael@0: size_t len; michael@0: michael@0: mib[0] = CTL_HW; michael@0: mib[1] = HW_NCPU; michael@0: len = sizeof(ret); michael@0: if (sysctl(mib, 2, &ret, &len, (void *) 0, 0) == -1) { michael@0: /* Error. */ michael@0: return (1); michael@0: } michael@0: michael@0: return (ret); michael@0: } michael@0: #elif (defined(MOZ_MEMORY_LINUX)) michael@0: #include michael@0: michael@0: static inline unsigned michael@0: malloc_ncpus(void) michael@0: { michael@0: unsigned ret; michael@0: int fd, nread, column; michael@0: char buf[1024]; michael@0: static const char matchstr[] = "processor\t:"; michael@0: int i; michael@0: michael@0: /* michael@0: * sysconf(3) would be the preferred method for determining the number michael@0: * of CPUs, but it uses malloc internally, which causes untennable michael@0: * recursion during malloc initialization. michael@0: */ michael@0: fd = open("/proc/cpuinfo", O_RDONLY); michael@0: if (fd == -1) michael@0: return (1); /* Error. */ michael@0: /* michael@0: * Count the number of occurrences of matchstr at the beginnings of michael@0: * lines. This treats hyperthreaded CPUs as multiple processors. michael@0: */ michael@0: column = 0; michael@0: ret = 0; michael@0: while (true) { michael@0: nread = read(fd, &buf, sizeof(buf)); michael@0: if (nread <= 0) michael@0: break; /* EOF or error. */ michael@0: for (i = 0;i < nread;i++) { michael@0: char c = buf[i]; michael@0: if (c == '\n') michael@0: column = 0; michael@0: else if (column != -1) { michael@0: if (c == matchstr[column]) { michael@0: column++; michael@0: if (column == sizeof(matchstr) - 1) { michael@0: column = -1; michael@0: ret++; michael@0: } michael@0: } else michael@0: column = -1; michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (ret == 0) michael@0: ret = 1; /* Something went wrong in the parser. */ michael@0: close(fd); michael@0: michael@0: return (ret); michael@0: } michael@0: #elif (defined(MOZ_MEMORY_DARWIN)) michael@0: #include michael@0: #include michael@0: michael@0: static inline unsigned michael@0: malloc_ncpus(void) michael@0: { michael@0: kern_return_t error; michael@0: natural_t n; michael@0: processor_info_array_t pinfo; michael@0: mach_msg_type_number_t pinfocnt; michael@0: michael@0: error = host_processor_info(mach_host_self(), PROCESSOR_BASIC_INFO, michael@0: &n, &pinfo, &pinfocnt); michael@0: if (error != KERN_SUCCESS) michael@0: return (1); /* Error. */ michael@0: else michael@0: return (n); michael@0: } michael@0: #elif (defined(MOZ_MEMORY_SOLARIS)) michael@0: michael@0: static inline unsigned michael@0: malloc_ncpus(void) michael@0: { michael@0: return sysconf(_SC_NPROCESSORS_ONLN); michael@0: } michael@0: #else michael@0: static inline unsigned michael@0: malloc_ncpus(void) michael@0: { michael@0: michael@0: /* michael@0: * We lack a way to determine the number of CPUs on this platform, so michael@0: * assume 1 CPU. michael@0: */ michael@0: return (1); michael@0: } michael@0: #endif michael@0: #endif michael@0: michael@0: static void michael@0: malloc_print_stats(void) michael@0: { michael@0: michael@0: if (opt_print_stats) { michael@0: char s[UMAX2S_BUFSIZE]; michael@0: _malloc_message("___ Begin malloc statistics ___\n", "", "", michael@0: ""); michael@0: _malloc_message("Assertions ", michael@0: #ifdef NDEBUG michael@0: "disabled", michael@0: #else michael@0: "enabled", michael@0: #endif michael@0: "\n", ""); michael@0: _malloc_message("Boolean MALLOC_OPTIONS: ", michael@0: opt_abort ? "A" : "a", "", ""); michael@0: #ifdef MALLOC_FILL michael@0: _malloc_message(opt_poison ? "C" : "c", "", "", ""); michael@0: _malloc_message(opt_junk ? "J" : "j", "", "", ""); michael@0: #endif michael@0: #ifdef MALLOC_PAGEFILE michael@0: _malloc_message(opt_pagefile ? "o" : "O", "", "", ""); michael@0: #endif michael@0: _malloc_message("P", "", "", ""); michael@0: #ifdef MALLOC_UTRACE michael@0: _malloc_message(opt_utrace ? "U" : "u", "", "", ""); michael@0: #endif michael@0: #ifdef MALLOC_SYSV michael@0: _malloc_message(opt_sysv ? "V" : "v", "", "", ""); michael@0: #endif michael@0: #ifdef MALLOC_XMALLOC michael@0: _malloc_message(opt_xmalloc ? "X" : "x", "", "", ""); michael@0: #endif michael@0: #ifdef MALLOC_FILL michael@0: _malloc_message(opt_zero ? "Z" : "z", "", "", ""); michael@0: #endif michael@0: _malloc_message("\n", "", "", ""); michael@0: michael@0: #ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE michael@0: _malloc_message("CPUs: ", umax2s(ncpus, 10, s), "\n", ""); michael@0: #endif michael@0: _malloc_message("Max arenas: ", umax2s(narenas, 10, s), "\n", michael@0: ""); michael@0: #ifdef MALLOC_BALANCE michael@0: _malloc_message("Arena balance threshold: ", michael@0: umax2s(opt_balance_threshold, 10, s), "\n", ""); michael@0: #endif michael@0: _malloc_message("Pointer size: ", umax2s(sizeof(void *), 10, s), michael@0: "\n", ""); michael@0: _malloc_message("Quantum size: ", umax2s(quantum, 10, s), "\n", michael@0: ""); michael@0: _malloc_message("Max small size: ", umax2s(small_max, 10, s), michael@0: "\n", ""); michael@0: _malloc_message("Max dirty pages per arena: ", michael@0: umax2s(opt_dirty_max, 10, s), "\n", ""); michael@0: michael@0: _malloc_message("Chunk size: ", umax2s(chunksize, 10, s), "", michael@0: ""); michael@0: _malloc_message(" (2^", umax2s(opt_chunk_2pow, 10, s), ")\n", michael@0: ""); michael@0: michael@0: #ifdef MALLOC_STATS michael@0: { michael@0: size_t allocated, mapped = 0; michael@0: #ifdef MALLOC_BALANCE michael@0: uint64_t nbalance = 0; michael@0: #endif michael@0: unsigned i; michael@0: arena_t *arena; michael@0: michael@0: /* Calculate and print allocated/mapped stats. */ michael@0: michael@0: /* arenas. */ michael@0: for (i = 0, allocated = 0; i < narenas; i++) { michael@0: if (arenas[i] != NULL) { michael@0: malloc_spin_lock(&arenas[i]->lock); michael@0: allocated += michael@0: arenas[i]->stats.allocated_small; michael@0: allocated += michael@0: arenas[i]->stats.allocated_large; michael@0: mapped += arenas[i]->stats.mapped; michael@0: #ifdef MALLOC_BALANCE michael@0: nbalance += arenas[i]->stats.nbalance; michael@0: #endif michael@0: malloc_spin_unlock(&arenas[i]->lock); michael@0: } michael@0: } michael@0: michael@0: /* huge/base. */ michael@0: malloc_mutex_lock(&huge_mtx); michael@0: allocated += huge_allocated; michael@0: mapped += huge_mapped; michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: michael@0: malloc_mutex_lock(&base_mtx); michael@0: mapped += base_mapped; michael@0: malloc_mutex_unlock(&base_mtx); michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: malloc_printf("Allocated: %lu, mapped: %lu\n", michael@0: allocated, mapped); michael@0: #else michael@0: malloc_printf("Allocated: %zu, mapped: %zu\n", michael@0: allocated, mapped); michael@0: #endif michael@0: michael@0: #ifdef MALLOC_BALANCE michael@0: malloc_printf("Arena balance reassignments: %llu\n", michael@0: nbalance); michael@0: #endif michael@0: michael@0: /* Print chunk stats. */ michael@0: malloc_printf( michael@0: "huge: nmalloc ndalloc allocated\n"); michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: malloc_printf(" %12llu %12llu %12lu\n", michael@0: huge_nmalloc, huge_ndalloc, huge_allocated); michael@0: #else michael@0: malloc_printf(" %12llu %12llu %12zu\n", michael@0: huge_nmalloc, huge_ndalloc, huge_allocated); michael@0: #endif michael@0: /* Print stats for each arena. */ michael@0: for (i = 0; i < narenas; i++) { michael@0: arena = arenas[i]; michael@0: if (arena != NULL) { michael@0: malloc_printf( michael@0: "\narenas[%u]:\n", i); michael@0: malloc_spin_lock(&arena->lock); michael@0: stats_print(arena); michael@0: malloc_spin_unlock(&arena->lock); michael@0: } michael@0: } michael@0: } michael@0: #endif /* #ifdef MALLOC_STATS */ michael@0: _malloc_message("--- End malloc statistics ---\n", "", "", ""); michael@0: } michael@0: } michael@0: michael@0: /* michael@0: * FreeBSD's pthreads implementation calls malloc(3), so the malloc michael@0: * implementation has to take pains to avoid infinite recursion during michael@0: * initialization. michael@0: */ michael@0: #if (defined(MOZ_MEMORY_WINDOWS) || defined(MOZ_MEMORY_DARWIN)) michael@0: #define malloc_init() false michael@0: #else michael@0: static inline bool michael@0: malloc_init(void) michael@0: { michael@0: michael@0: if (malloc_initialized == false) michael@0: return (malloc_init_hard()); michael@0: michael@0: return (false); michael@0: } michael@0: #endif michael@0: michael@0: #if !defined(MOZ_MEMORY_WINDOWS) michael@0: static michael@0: #endif michael@0: bool michael@0: malloc_init_hard(void) michael@0: { michael@0: unsigned i; michael@0: char buf[PATH_MAX + 1]; michael@0: const char *opts; michael@0: long result; michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: int linklen; michael@0: #endif michael@0: #ifdef MOZ_MEMORY_DARWIN michael@0: malloc_zone_t* default_zone; michael@0: #endif michael@0: michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: malloc_mutex_lock(&init_lock); michael@0: #endif michael@0: michael@0: if (malloc_initialized) { michael@0: /* michael@0: * Another thread initialized the allocator before this one michael@0: * acquired init_lock. michael@0: */ michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: malloc_mutex_unlock(&init_lock); michael@0: #endif michael@0: return (false); michael@0: } michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: /* get a thread local storage index */ michael@0: tlsIndex = TlsAlloc(); michael@0: #endif michael@0: michael@0: /* Get page size and number of CPUs */ michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: { michael@0: SYSTEM_INFO info; michael@0: michael@0: GetSystemInfo(&info); michael@0: result = info.dwPageSize; michael@0: michael@0: #ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE michael@0: ncpus = info.dwNumberOfProcessors; michael@0: #endif michael@0: } michael@0: #else michael@0: #ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE michael@0: ncpus = malloc_ncpus(); michael@0: #endif michael@0: michael@0: result = sysconf(_SC_PAGESIZE); michael@0: assert(result != -1); michael@0: #endif michael@0: michael@0: /* We assume that the page size is a power of 2. */ michael@0: assert(((result - 1) & result) == 0); michael@0: #ifdef MALLOC_STATIC_SIZES michael@0: if (pagesize % (size_t) result) { michael@0: _malloc_message(_getprogname(), michael@0: "Compile-time page size does not divide the runtime one.\n", michael@0: "", ""); michael@0: abort(); michael@0: } michael@0: #else michael@0: pagesize = (size_t) result; michael@0: pagesize_mask = (size_t) result - 1; michael@0: pagesize_2pow = ffs((int)result) - 1; michael@0: #endif michael@0: michael@0: #ifdef MALLOC_PAGEFILE michael@0: /* michael@0: * Determine where to create page files. It is insufficient to michael@0: * unconditionally use P_tmpdir (typically "/tmp"), since for some michael@0: * operating systems /tmp is a separate filesystem that is rather small. michael@0: * Therefore prefer, in order, the following locations: michael@0: * michael@0: * 1) MALLOC_TMPDIR michael@0: * 2) TMPDIR michael@0: * 3) P_tmpdir michael@0: */ michael@0: { michael@0: char *s; michael@0: size_t slen; michael@0: static const char suffix[] = "/jemalloc.XXXXXX"; michael@0: michael@0: if ((s = getenv("MALLOC_TMPDIR")) == NULL && (s = michael@0: getenv("TMPDIR")) == NULL) michael@0: s = P_tmpdir; michael@0: slen = strlen(s); michael@0: if (slen + sizeof(suffix) > sizeof(pagefile_templ)) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Page file path too long\n", michael@0: "", ""); michael@0: abort(); michael@0: } michael@0: memcpy(pagefile_templ, s, slen); michael@0: memcpy(&pagefile_templ[slen], suffix, sizeof(suffix)); michael@0: } michael@0: #endif michael@0: michael@0: for (i = 0; i < 3; i++) { michael@0: unsigned j; michael@0: michael@0: /* Get runtime configuration. */ michael@0: switch (i) { michael@0: case 0: michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: if ((linklen = readlink("/etc/malloc.conf", buf, michael@0: sizeof(buf) - 1)) != -1) { michael@0: /* michael@0: * Use the contents of the "/etc/malloc.conf" michael@0: * symbolic link's name. michael@0: */ michael@0: buf[linklen] = '\0'; michael@0: opts = buf; michael@0: } else michael@0: #endif michael@0: { michael@0: /* No configuration specified. */ michael@0: buf[0] = '\0'; michael@0: opts = buf; michael@0: } michael@0: break; michael@0: case 1: michael@0: if (issetugid() == 0 && (opts = michael@0: getenv("MALLOC_OPTIONS")) != NULL) { michael@0: /* michael@0: * Do nothing; opts is already initialized to michael@0: * the value of the MALLOC_OPTIONS environment michael@0: * variable. michael@0: */ michael@0: } else { michael@0: /* No configuration specified. */ michael@0: buf[0] = '\0'; michael@0: opts = buf; michael@0: } michael@0: break; michael@0: case 2: michael@0: if (_malloc_options != NULL) { michael@0: /* michael@0: * Use options that were compiled into the michael@0: * program. michael@0: */ michael@0: opts = _malloc_options; michael@0: } else { michael@0: /* No configuration specified. */ michael@0: buf[0] = '\0'; michael@0: opts = buf; michael@0: } michael@0: break; michael@0: default: michael@0: /* NOTREACHED */ michael@0: buf[0] = '\0'; michael@0: opts = buf; michael@0: assert(false); michael@0: } michael@0: michael@0: for (j = 0; opts[j] != '\0'; j++) { michael@0: unsigned k, nreps; michael@0: bool nseen; michael@0: michael@0: /* Parse repetition count, if any. */ michael@0: for (nreps = 0, nseen = false;; j++, nseen = true) { michael@0: switch (opts[j]) { michael@0: case '0': case '1': case '2': case '3': michael@0: case '4': case '5': case '6': case '7': michael@0: case '8': case '9': michael@0: nreps *= 10; michael@0: nreps += opts[j] - '0'; michael@0: break; michael@0: default: michael@0: goto MALLOC_OUT; michael@0: } michael@0: } michael@0: MALLOC_OUT: michael@0: if (nseen == false) michael@0: nreps = 1; michael@0: michael@0: for (k = 0; k < nreps; k++) { michael@0: switch (opts[j]) { michael@0: case 'a': michael@0: opt_abort = false; michael@0: break; michael@0: case 'A': michael@0: opt_abort = true; michael@0: break; michael@0: case 'b': michael@0: #ifdef MALLOC_BALANCE michael@0: opt_balance_threshold >>= 1; michael@0: #endif michael@0: break; michael@0: case 'B': michael@0: #ifdef MALLOC_BALANCE michael@0: if (opt_balance_threshold == 0) michael@0: opt_balance_threshold = 1; michael@0: else if ((opt_balance_threshold << 1) michael@0: > opt_balance_threshold) michael@0: opt_balance_threshold <<= 1; michael@0: #endif michael@0: break; michael@0: #ifdef MALLOC_FILL michael@0: #ifndef MALLOC_PRODUCTION michael@0: case 'c': michael@0: opt_poison = false; michael@0: break; michael@0: case 'C': michael@0: opt_poison = true; michael@0: break; michael@0: #endif michael@0: #endif michael@0: case 'f': michael@0: opt_dirty_max >>= 1; michael@0: break; michael@0: case 'F': michael@0: if (opt_dirty_max == 0) michael@0: opt_dirty_max = 1; michael@0: else if ((opt_dirty_max << 1) != 0) michael@0: opt_dirty_max <<= 1; michael@0: break; michael@0: #ifdef MALLOC_FILL michael@0: #ifndef MALLOC_PRODUCTION michael@0: case 'j': michael@0: opt_junk = false; michael@0: break; michael@0: case 'J': michael@0: opt_junk = true; michael@0: break; michael@0: #endif michael@0: #endif michael@0: #ifndef MALLOC_STATIC_SIZES michael@0: case 'k': michael@0: /* michael@0: * Chunks always require at least one michael@0: * header page, so chunks can never be michael@0: * smaller than two pages. michael@0: */ michael@0: if (opt_chunk_2pow > pagesize_2pow + 1) michael@0: opt_chunk_2pow--; michael@0: break; michael@0: case 'K': michael@0: if (opt_chunk_2pow + 1 < michael@0: (sizeof(size_t) << 3)) michael@0: opt_chunk_2pow++; michael@0: break; michael@0: #endif michael@0: case 'n': michael@0: opt_narenas_lshift--; michael@0: break; michael@0: case 'N': michael@0: opt_narenas_lshift++; michael@0: break; michael@0: #ifdef MALLOC_PAGEFILE michael@0: case 'o': michael@0: /* Do not over-commit. */ michael@0: opt_pagefile = true; michael@0: break; michael@0: case 'O': michael@0: /* Allow over-commit. */ michael@0: opt_pagefile = false; michael@0: break; michael@0: #endif michael@0: case 'p': michael@0: opt_print_stats = false; michael@0: break; michael@0: case 'P': michael@0: opt_print_stats = true; michael@0: break; michael@0: #ifndef MALLOC_STATIC_SIZES michael@0: case 'q': michael@0: if (opt_quantum_2pow > QUANTUM_2POW_MIN) michael@0: opt_quantum_2pow--; michael@0: break; michael@0: case 'Q': michael@0: if (opt_quantum_2pow < pagesize_2pow - michael@0: 1) michael@0: opt_quantum_2pow++; michael@0: break; michael@0: case 's': michael@0: if (opt_small_max_2pow > michael@0: QUANTUM_2POW_MIN) michael@0: opt_small_max_2pow--; michael@0: break; michael@0: case 'S': michael@0: if (opt_small_max_2pow < pagesize_2pow michael@0: - 1) michael@0: opt_small_max_2pow++; michael@0: break; michael@0: #endif michael@0: #ifdef MALLOC_UTRACE michael@0: case 'u': michael@0: opt_utrace = false; michael@0: break; michael@0: case 'U': michael@0: opt_utrace = true; michael@0: break; michael@0: #endif michael@0: #ifdef MALLOC_SYSV michael@0: case 'v': michael@0: opt_sysv = false; michael@0: break; michael@0: case 'V': michael@0: opt_sysv = true; michael@0: break; michael@0: #endif michael@0: #ifdef MALLOC_XMALLOC michael@0: case 'x': michael@0: opt_xmalloc = false; michael@0: break; michael@0: case 'X': michael@0: opt_xmalloc = true; michael@0: break; michael@0: #endif michael@0: #ifdef MALLOC_FILL michael@0: #ifndef MALLOC_PRODUCTION michael@0: case 'z': michael@0: opt_zero = false; michael@0: break; michael@0: case 'Z': michael@0: opt_zero = true; michael@0: break; michael@0: #endif michael@0: #endif michael@0: default: { michael@0: char cbuf[2]; michael@0: michael@0: cbuf[0] = opts[j]; michael@0: cbuf[1] = '\0'; michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Unsupported character " michael@0: "in malloc options: '", cbuf, michael@0: "'\n"); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* Take care to call atexit() only once. */ michael@0: if (opt_print_stats) { michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: /* Print statistics at exit. */ michael@0: atexit(malloc_print_stats); michael@0: #endif michael@0: } michael@0: michael@0: #if !defined(MOZ_MEMORY_WINDOWS) && !defined(MOZ_MEMORY_DARWIN) michael@0: /* Prevent potential deadlock on malloc locks after fork. */ michael@0: pthread_atfork(_malloc_prefork, _malloc_postfork, _malloc_postfork); michael@0: #endif michael@0: michael@0: #ifndef MALLOC_STATIC_SIZES michael@0: /* Set variables according to the value of opt_small_max_2pow. */ michael@0: if (opt_small_max_2pow < opt_quantum_2pow) michael@0: opt_small_max_2pow = opt_quantum_2pow; michael@0: small_max = (1U << opt_small_max_2pow); michael@0: michael@0: /* Set bin-related variables. */ michael@0: bin_maxclass = (pagesize >> 1); michael@0: assert(opt_quantum_2pow >= TINY_MIN_2POW); michael@0: ntbins = opt_quantum_2pow - TINY_MIN_2POW; michael@0: assert(ntbins <= opt_quantum_2pow); michael@0: nqbins = (small_max >> opt_quantum_2pow); michael@0: nsbins = pagesize_2pow - opt_small_max_2pow - 1; michael@0: michael@0: /* Set variables according to the value of opt_quantum_2pow. */ michael@0: quantum = (1U << opt_quantum_2pow); michael@0: quantum_mask = quantum - 1; michael@0: if (ntbins > 0) michael@0: small_min = (quantum >> 1) + 1; michael@0: else michael@0: small_min = 1; michael@0: assert(small_min <= quantum); michael@0: michael@0: /* Set variables according to the value of opt_chunk_2pow. */ michael@0: chunksize = (1LU << opt_chunk_2pow); michael@0: chunksize_mask = chunksize - 1; michael@0: chunk_npages = (chunksize >> pagesize_2pow); michael@0: michael@0: arena_chunk_header_npages = calculate_arena_header_pages(); michael@0: arena_maxclass = calculate_arena_maxclass(); michael@0: #endif michael@0: michael@0: #ifdef JEMALLOC_USES_MAP_ALIGN michael@0: /* michael@0: * When using MAP_ALIGN, the alignment parameter must be a power of two michael@0: * multiple of the system pagesize, or mmap will fail. michael@0: */ michael@0: assert((chunksize % pagesize) == 0); michael@0: assert((1 << (ffs(chunksize / pagesize) - 1)) == (chunksize/pagesize)); michael@0: #endif michael@0: michael@0: UTRACE(0, 0, 0); michael@0: michael@0: /* Various sanity checks that regard configuration. */ michael@0: assert(quantum >= sizeof(void *)); michael@0: assert(quantum <= pagesize); michael@0: assert(chunksize >= pagesize); michael@0: assert(quantum * 4 <= chunksize); michael@0: michael@0: /* Initialize chunks data. */ michael@0: malloc_mutex_init(&huge_mtx); michael@0: extent_tree_ad_new(&huge); michael@0: #ifdef MALLOC_STATS michael@0: huge_nmalloc = 0; michael@0: huge_ndalloc = 0; michael@0: huge_allocated = 0; michael@0: huge_mapped = 0; michael@0: #endif michael@0: michael@0: /* Initialize base allocation data structures. */ michael@0: #ifdef MALLOC_STATS michael@0: base_mapped = 0; michael@0: base_committed = 0; michael@0: #endif michael@0: base_nodes = NULL; michael@0: malloc_mutex_init(&base_mtx); michael@0: michael@0: #ifdef MOZ_MEMORY_NARENAS_DEFAULT_ONE michael@0: narenas = 1; michael@0: #else michael@0: if (ncpus > 1) { michael@0: /* michael@0: * For SMP systems, create four times as many arenas as there michael@0: * are CPUs by default. michael@0: */ michael@0: opt_narenas_lshift += 2; michael@0: } michael@0: michael@0: /* Determine how many arenas to use. */ michael@0: narenas = ncpus; michael@0: #endif michael@0: if (opt_narenas_lshift > 0) { michael@0: if ((narenas << opt_narenas_lshift) > narenas) michael@0: narenas <<= opt_narenas_lshift; michael@0: /* michael@0: * Make sure not to exceed the limits of what base_alloc() can michael@0: * handle. michael@0: */ michael@0: if (narenas * sizeof(arena_t *) > chunksize) michael@0: narenas = chunksize / sizeof(arena_t *); michael@0: } else if (opt_narenas_lshift < 0) { michael@0: if ((narenas >> -opt_narenas_lshift) < narenas) michael@0: narenas >>= -opt_narenas_lshift; michael@0: /* Make sure there is at least one arena. */ michael@0: if (narenas == 0) michael@0: narenas = 1; michael@0: } michael@0: #ifdef MALLOC_BALANCE michael@0: assert(narenas != 0); michael@0: for (narenas_2pow = 0; michael@0: (narenas >> (narenas_2pow + 1)) != 0; michael@0: narenas_2pow++); michael@0: #endif michael@0: michael@0: #ifdef NO_TLS michael@0: if (narenas > 1) { michael@0: static const unsigned primes[] = {1, 3, 5, 7, 11, 13, 17, 19, michael@0: 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, michael@0: 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, michael@0: 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, michael@0: 223, 227, 229, 233, 239, 241, 251, 257, 263}; michael@0: unsigned nprimes, parenas; michael@0: michael@0: /* michael@0: * Pick a prime number of hash arenas that is more than narenas michael@0: * so that direct hashing of pthread_self() pointers tends to michael@0: * spread allocations evenly among the arenas. michael@0: */ michael@0: assert((narenas & 1) == 0); /* narenas must be even. */ michael@0: nprimes = (sizeof(primes) >> SIZEOF_INT_2POW); michael@0: parenas = primes[nprimes - 1]; /* In case not enough primes. */ michael@0: for (i = 1; i < nprimes; i++) { michael@0: if (primes[i] > narenas) { michael@0: parenas = primes[i]; michael@0: break; michael@0: } michael@0: } michael@0: narenas = parenas; michael@0: } michael@0: #endif michael@0: michael@0: #ifndef NO_TLS michael@0: # ifndef MALLOC_BALANCE michael@0: next_arena = 0; michael@0: # endif michael@0: #endif michael@0: michael@0: /* Allocate and initialize arenas. */ michael@0: arenas = (arena_t **)base_alloc(sizeof(arena_t *) * narenas); michael@0: if (arenas == NULL) { michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: malloc_mutex_unlock(&init_lock); michael@0: #endif michael@0: return (true); michael@0: } michael@0: /* michael@0: * Zero the array. In practice, this should always be pre-zeroed, michael@0: * since it was just mmap()ed, but let's be sure. michael@0: */ michael@0: memset(arenas, 0, sizeof(arena_t *) * narenas); michael@0: michael@0: /* michael@0: * Initialize one arena here. The rest are lazily created in michael@0: * choose_arena_hard(). michael@0: */ michael@0: arenas_extend(0); michael@0: if (arenas[0] == NULL) { michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: malloc_mutex_unlock(&init_lock); michael@0: #endif michael@0: return (true); michael@0: } michael@0: #ifndef NO_TLS michael@0: /* michael@0: * Assign the initial arena to the initial thread, in order to avoid michael@0: * spurious creation of an extra arena if the application switches to michael@0: * threaded mode. michael@0: */ michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: TlsSetValue(tlsIndex, arenas[0]); michael@0: #else michael@0: arenas_map = arenas[0]; michael@0: #endif michael@0: #endif michael@0: michael@0: /* michael@0: * Seed here for the initial thread, since choose_arena_hard() is only michael@0: * called for other threads. The seed value doesn't really matter. michael@0: */ michael@0: #ifdef MALLOC_BALANCE michael@0: SPRN(balance, 42); michael@0: #endif michael@0: michael@0: malloc_spin_init(&arenas_lock); michael@0: michael@0: #ifdef MALLOC_VALIDATE michael@0: chunk_rtree = malloc_rtree_new((SIZEOF_PTR << 3) - opt_chunk_2pow); michael@0: if (chunk_rtree == NULL) michael@0: return (true); michael@0: #endif michael@0: michael@0: malloc_initialized = true; michael@0: michael@0: #if defined(NEEDS_PTHREAD_MMAP_UNALIGNED_TSD) michael@0: if (pthread_key_create(&mmap_unaligned_tsd, NULL) != 0) { michael@0: malloc_printf(": Error in pthread_key_create()\n"); michael@0: } michael@0: #endif michael@0: michael@0: #if defined(MOZ_MEMORY_DARWIN) && !defined(MOZ_REPLACE_MALLOC) michael@0: /* michael@0: * Overwrite the default memory allocator to use jemalloc everywhere. michael@0: */ michael@0: default_zone = malloc_default_zone(); michael@0: michael@0: /* michael@0: * We only use jemalloc with MacOS 10.6 and 10.7. jemalloc is disabled michael@0: * on 32-bit builds (10.5 and 32-bit 10.6) due to bug 702250, an michael@0: * apparent MacOS bug. In fact, this code isn't even compiled on michael@0: * 32-bit builds. michael@0: * michael@0: * We'll have to update our code to work with newer versions, because michael@0: * the malloc zone layout is likely to change. michael@0: */ michael@0: michael@0: osx_use_jemalloc = (default_zone->version == SNOW_LEOPARD_MALLOC_ZONE_T_VERSION || michael@0: default_zone->version == LION_MALLOC_ZONE_T_VERSION); michael@0: michael@0: /* Allow us dynamically turn off jemalloc for testing. */ michael@0: if (getenv("NO_MAC_JEMALLOC")) { michael@0: osx_use_jemalloc = false; michael@0: #ifdef __i386__ michael@0: malloc_printf("Warning: NO_MAC_JEMALLOC has no effect on " michael@0: "i386 machines (such as this one).\n"); michael@0: #endif michael@0: } michael@0: michael@0: if (osx_use_jemalloc) { michael@0: /* michael@0: * Convert the default szone to an "overlay zone" that is capable michael@0: * of deallocating szone-allocated objects, but allocating new michael@0: * objects from jemalloc. michael@0: */ michael@0: size_t size = zone_version_size(default_zone->version); michael@0: szone2ozone(default_zone, size); michael@0: } michael@0: else { michael@0: szone = default_zone; michael@0: } michael@0: #endif michael@0: michael@0: #ifndef MOZ_MEMORY_WINDOWS michael@0: malloc_mutex_unlock(&init_lock); michael@0: #endif michael@0: return (false); michael@0: } michael@0: michael@0: /* XXX Why not just expose malloc_print_stats()? */ michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: void michael@0: malloc_shutdown() michael@0: { michael@0: michael@0: malloc_print_stats(); michael@0: } michael@0: #endif michael@0: michael@0: /* michael@0: * End general internal functions. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin malloc(3)-compatible functions. michael@0: */ michael@0: michael@0: /* michael@0: * Even though we compile with MOZ_MEMORY, we may have to dynamically decide michael@0: * not to use jemalloc, as discussed above. However, we call jemalloc michael@0: * functions directly from mozalloc. Since it's pretty dangerous to mix the michael@0: * allocators, we need to call the OSX allocators from the functions below, michael@0: * when osx_use_jemalloc is not (dynamically) set. michael@0: * michael@0: * Note that we assume jemalloc is enabled on i386. This is safe because the michael@0: * only i386 versions of MacOS are 10.5 and 10.6, which we support. We have to michael@0: * do this because madvise isn't in the malloc zone struct for 10.5. michael@0: * michael@0: * This means that NO_MAC_JEMALLOC doesn't work on i386. michael@0: */ michael@0: #if defined(MOZ_MEMORY_DARWIN) && !defined(__i386__) && !defined(MOZ_REPLACE_MALLOC) michael@0: #define DARWIN_ONLY(A) if (!osx_use_jemalloc) { A; } michael@0: #else michael@0: #define DARWIN_ONLY(A) michael@0: #endif michael@0: michael@0: MOZ_MEMORY_API void * michael@0: malloc_impl(size_t size) michael@0: { michael@0: void *ret; michael@0: michael@0: DARWIN_ONLY(return (szone->malloc)(szone, size)); michael@0: michael@0: if (malloc_init()) { michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: michael@0: if (size == 0) { michael@0: #ifdef MALLOC_SYSV michael@0: if (opt_sysv == false) michael@0: #endif michael@0: size = 1; michael@0: #ifdef MALLOC_SYSV michael@0: else { michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: ret = imalloc(size); michael@0: michael@0: RETURN: michael@0: if (ret == NULL) { michael@0: #ifdef MALLOC_XMALLOC michael@0: if (opt_xmalloc) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in malloc(): out of memory\n", "", michael@0: ""); michael@0: abort(); michael@0: } michael@0: #endif michael@0: errno = ENOMEM; michael@0: } michael@0: michael@0: UTRACE(0, size, ret); michael@0: return (ret); michael@0: } michael@0: michael@0: /* michael@0: * In ELF systems the default visibility allows symbols to be preempted at michael@0: * runtime. This in turn prevents the uses of memalign in this file from being michael@0: * optimized. What we do in here is define two aliasing symbols (they point to michael@0: * the same code): memalign and memalign_internal. The internal version has michael@0: * hidden visibility and is used in every reference from this file. michael@0: * michael@0: * For more information on this technique, see section 2.2.7 (Avoid Using michael@0: * Exported Symbols) in http://www.akkadia.org/drepper/dsohowto.pdf. michael@0: */ michael@0: michael@0: #ifndef MOZ_REPLACE_MALLOC michael@0: #if defined(__GNUC__) && !defined(MOZ_MEMORY_DARWIN) michael@0: #define MOZ_MEMORY_ELF michael@0: #endif michael@0: michael@0: #ifdef MOZ_MEMORY_SOLARIS michael@0: # ifdef __SUNPRO_C michael@0: void * michael@0: memalign_impl(size_t alignment, size_t size); michael@0: #pragma no_inline(memalign_impl) michael@0: # elif (defined(__GNUC__)) michael@0: __attribute__((noinline)) michael@0: # endif michael@0: #else michael@0: #if (defined(MOZ_MEMORY_ELF)) michael@0: __attribute__((visibility ("hidden"))) michael@0: #endif michael@0: #endif michael@0: #endif /* MOZ_REPLACE_MALLOC */ michael@0: michael@0: #ifdef MOZ_MEMORY_ELF michael@0: #define MEMALIGN memalign_internal michael@0: #else michael@0: #define MEMALIGN memalign_impl michael@0: #endif michael@0: michael@0: #ifndef MOZ_MEMORY_ELF michael@0: MOZ_MEMORY_API michael@0: #endif michael@0: void * michael@0: MEMALIGN(size_t alignment, size_t size) michael@0: { michael@0: void *ret; michael@0: michael@0: DARWIN_ONLY(return (szone->memalign)(szone, alignment, size)); michael@0: michael@0: assert(((alignment - 1) & alignment) == 0); michael@0: michael@0: if (malloc_init()) { michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: michael@0: if (size == 0) { michael@0: #ifdef MALLOC_SYSV michael@0: if (opt_sysv == false) michael@0: #endif michael@0: size = 1; michael@0: #ifdef MALLOC_SYSV michael@0: else { michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: alignment = alignment < sizeof(void*) ? sizeof(void*) : alignment; michael@0: ret = ipalloc(alignment, size); michael@0: michael@0: RETURN: michael@0: #ifdef MALLOC_XMALLOC michael@0: if (opt_xmalloc && ret == NULL) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in memalign(): out of memory\n", "", ""); michael@0: abort(); michael@0: } michael@0: #endif michael@0: UTRACE(0, size, ret); michael@0: return (ret); michael@0: } michael@0: michael@0: #ifdef MOZ_MEMORY_ELF michael@0: extern void * michael@0: memalign_impl(size_t alignment, size_t size) __attribute__((alias ("memalign_internal"), visibility ("default"))); michael@0: #endif michael@0: michael@0: MOZ_MEMORY_API int michael@0: posix_memalign_impl(void **memptr, size_t alignment, size_t size) michael@0: { michael@0: void *result; michael@0: michael@0: /* Make sure that alignment is a large enough power of 2. */ michael@0: if (((alignment - 1) & alignment) != 0 || alignment < sizeof(void *)) { michael@0: #ifdef MALLOC_XMALLOC michael@0: if (opt_xmalloc) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in posix_memalign(): " michael@0: "invalid alignment\n", "", ""); michael@0: abort(); michael@0: } michael@0: #endif michael@0: return (EINVAL); michael@0: } michael@0: michael@0: /* The 0-->1 size promotion is done in the memalign() call below */ michael@0: michael@0: result = MEMALIGN(alignment, size); michael@0: michael@0: if (result == NULL) michael@0: return (ENOMEM); michael@0: michael@0: *memptr = result; michael@0: return (0); michael@0: } michael@0: michael@0: MOZ_MEMORY_API void * michael@0: aligned_alloc_impl(size_t alignment, size_t size) michael@0: { michael@0: if (size % alignment) { michael@0: #ifdef MALLOC_XMALLOC michael@0: if (opt_xmalloc) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in aligned_alloc(): " michael@0: "size is not multiple of alignment\n", "", ""); michael@0: abort(); michael@0: } michael@0: #endif michael@0: return (NULL); michael@0: } michael@0: return MEMALIGN(alignment, size); michael@0: } michael@0: michael@0: MOZ_MEMORY_API void * michael@0: valloc_impl(size_t size) michael@0: { michael@0: return (MEMALIGN(pagesize, size)); michael@0: } michael@0: michael@0: MOZ_MEMORY_API void * michael@0: calloc_impl(size_t num, size_t size) michael@0: { michael@0: void *ret; michael@0: size_t num_size; michael@0: michael@0: DARWIN_ONLY(return (szone->calloc)(szone, num, size)); michael@0: michael@0: if (malloc_init()) { michael@0: num_size = 0; michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: michael@0: num_size = num * size; michael@0: if (num_size == 0) { michael@0: #ifdef MALLOC_SYSV michael@0: if ((opt_sysv == false) && ((num == 0) || (size == 0))) michael@0: #endif michael@0: num_size = 1; michael@0: #ifdef MALLOC_SYSV michael@0: else { michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: #endif michael@0: /* michael@0: * Try to avoid division here. We know that it isn't possible to michael@0: * overflow during multiplication if neither operand uses any of the michael@0: * most significant half of the bits in a size_t. michael@0: */ michael@0: } else if (((num | size) & (SIZE_T_MAX << (sizeof(size_t) << 2))) michael@0: && (num_size / size != num)) { michael@0: /* size_t overflow. */ michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: michael@0: ret = icalloc(num_size); michael@0: michael@0: RETURN: michael@0: if (ret == NULL) { michael@0: #ifdef MALLOC_XMALLOC michael@0: if (opt_xmalloc) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in calloc(): out of memory\n", "", michael@0: ""); michael@0: abort(); michael@0: } michael@0: #endif michael@0: errno = ENOMEM; michael@0: } michael@0: michael@0: UTRACE(0, num_size, ret); michael@0: return (ret); michael@0: } michael@0: michael@0: MOZ_MEMORY_API void * michael@0: realloc_impl(void *ptr, size_t size) michael@0: { michael@0: void *ret; michael@0: michael@0: DARWIN_ONLY(return (szone->realloc)(szone, ptr, size)); michael@0: michael@0: if (size == 0) { michael@0: #ifdef MALLOC_SYSV michael@0: if (opt_sysv == false) michael@0: #endif michael@0: size = 1; michael@0: #ifdef MALLOC_SYSV michael@0: else { michael@0: if (ptr != NULL) michael@0: idalloc(ptr); michael@0: ret = NULL; michael@0: goto RETURN; michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: if (ptr != NULL) { michael@0: assert(malloc_initialized); michael@0: michael@0: ret = iralloc(ptr, size); michael@0: michael@0: if (ret == NULL) { michael@0: #ifdef MALLOC_XMALLOC michael@0: if (opt_xmalloc) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in realloc(): out of " michael@0: "memory\n", "", ""); michael@0: abort(); michael@0: } michael@0: #endif michael@0: errno = ENOMEM; michael@0: } michael@0: } else { michael@0: if (malloc_init()) michael@0: ret = NULL; michael@0: else michael@0: ret = imalloc(size); michael@0: michael@0: if (ret == NULL) { michael@0: #ifdef MALLOC_XMALLOC michael@0: if (opt_xmalloc) { michael@0: _malloc_message(_getprogname(), michael@0: ": (malloc) Error in realloc(): out of " michael@0: "memory\n", "", ""); michael@0: abort(); michael@0: } michael@0: #endif michael@0: errno = ENOMEM; michael@0: } michael@0: } michael@0: michael@0: #ifdef MALLOC_SYSV michael@0: RETURN: michael@0: #endif michael@0: UTRACE(ptr, size, ret); michael@0: return (ret); michael@0: } michael@0: michael@0: MOZ_MEMORY_API void michael@0: free_impl(void *ptr) michael@0: { michael@0: size_t offset; michael@0: michael@0: DARWIN_ONLY((szone->free)(szone, ptr); return); michael@0: michael@0: UTRACE(ptr, 0, 0); michael@0: michael@0: /* michael@0: * A version of idalloc that checks for NULL pointer but only for michael@0: * huge allocations assuming that CHUNK_ADDR2OFFSET(NULL) == 0. michael@0: */ michael@0: assert(CHUNK_ADDR2OFFSET(NULL) == 0); michael@0: offset = CHUNK_ADDR2OFFSET(ptr); michael@0: if (offset != 0) michael@0: arena_dalloc(ptr, offset); michael@0: else if (ptr != NULL) michael@0: huge_dalloc(ptr); michael@0: } michael@0: michael@0: /* michael@0: * End malloc(3)-compatible functions. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin non-standard functions. michael@0: */ michael@0: michael@0: /* This was added by Mozilla for use by SQLite. */ michael@0: #if defined(MOZ_MEMORY_DARWIN) && !defined(MOZ_REPLACE_MALLOC) michael@0: static michael@0: #else michael@0: MOZ_MEMORY_API michael@0: #endif michael@0: size_t michael@0: malloc_good_size_impl(size_t size) michael@0: { michael@0: /* michael@0: * This duplicates the logic in imalloc(), arena_malloc() and michael@0: * arena_malloc_small(). michael@0: */ michael@0: if (size < small_min) { michael@0: /* Small (tiny). */ michael@0: size = pow2_ceil(size); michael@0: /* michael@0: * We omit the #ifdefs from arena_malloc_small() -- michael@0: * it can be inaccurate with its size in some cases, but this michael@0: * function must be accurate. michael@0: */ michael@0: if (size < (1U << TINY_MIN_2POW)) michael@0: size = (1U << TINY_MIN_2POW); michael@0: } else if (size <= small_max) { michael@0: /* Small (quantum-spaced). */ michael@0: size = QUANTUM_CEILING(size); michael@0: } else if (size <= bin_maxclass) { michael@0: /* Small (sub-page). */ michael@0: size = pow2_ceil(size); michael@0: } else if (size <= arena_maxclass) { michael@0: /* Large. */ michael@0: size = PAGE_CEILING(size); michael@0: } else { michael@0: /* michael@0: * Huge. We use PAGE_CEILING to get psize, instead of using michael@0: * CHUNK_CEILING to get csize. This ensures that this michael@0: * malloc_usable_size(malloc(n)) always matches michael@0: * malloc_good_size(n). michael@0: */ michael@0: size = PAGE_CEILING(size); michael@0: } michael@0: return size; michael@0: } michael@0: michael@0: michael@0: #if defined(MOZ_MEMORY_ANDROID) && (ANDROID_VERSION < 19) michael@0: MOZ_MEMORY_API size_t michael@0: malloc_usable_size_impl(void *ptr) michael@0: #else michael@0: MOZ_MEMORY_API size_t michael@0: malloc_usable_size_impl(const void *ptr) michael@0: #endif michael@0: { michael@0: DARWIN_ONLY(return (szone->size)(szone, ptr)); michael@0: michael@0: #ifdef MALLOC_VALIDATE michael@0: return (isalloc_validate(ptr)); michael@0: #else michael@0: assert(ptr != NULL); michael@0: michael@0: return (isalloc(ptr)); michael@0: #endif michael@0: } michael@0: michael@0: MOZ_JEMALLOC_API void michael@0: jemalloc_stats_impl(jemalloc_stats_t *stats) michael@0: { michael@0: size_t i; michael@0: michael@0: assert(stats != NULL); michael@0: michael@0: /* michael@0: * Gather runtime settings. michael@0: */ michael@0: stats->opt_abort = opt_abort; michael@0: stats->opt_junk = michael@0: #ifdef MALLOC_FILL michael@0: opt_junk ? true : michael@0: #endif michael@0: false; michael@0: stats->opt_poison = michael@0: #ifdef MALLOC_FILL michael@0: opt_poison ? true : michael@0: #endif michael@0: false; michael@0: stats->opt_utrace = michael@0: #ifdef MALLOC_UTRACE michael@0: opt_utrace ? true : michael@0: #endif michael@0: false; michael@0: stats->opt_sysv = michael@0: #ifdef MALLOC_SYSV michael@0: opt_sysv ? true : michael@0: #endif michael@0: false; michael@0: stats->opt_xmalloc = michael@0: #ifdef MALLOC_XMALLOC michael@0: opt_xmalloc ? true : michael@0: #endif michael@0: false; michael@0: stats->opt_zero = michael@0: #ifdef MALLOC_FILL michael@0: opt_zero ? true : michael@0: #endif michael@0: false; michael@0: stats->narenas = narenas; michael@0: stats->balance_threshold = michael@0: #ifdef MALLOC_BALANCE michael@0: opt_balance_threshold michael@0: #else michael@0: SIZE_T_MAX michael@0: #endif michael@0: ; michael@0: stats->quantum = quantum; michael@0: stats->small_max = small_max; michael@0: stats->large_max = arena_maxclass; michael@0: stats->chunksize = chunksize; michael@0: stats->dirty_max = opt_dirty_max; michael@0: michael@0: /* michael@0: * Gather current memory usage statistics. michael@0: */ michael@0: stats->mapped = 0; michael@0: stats->allocated = 0; michael@0: stats->waste = 0; michael@0: stats->page_cache = 0; michael@0: stats->bookkeeping = 0; michael@0: michael@0: /* Get huge mapped/allocated. */ michael@0: malloc_mutex_lock(&huge_mtx); michael@0: stats->mapped += huge_mapped; michael@0: stats->allocated += huge_allocated; michael@0: assert(huge_mapped >= huge_allocated); michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: michael@0: /* Get base mapped/allocated. */ michael@0: malloc_mutex_lock(&base_mtx); michael@0: stats->mapped += base_mapped; michael@0: stats->bookkeeping += base_committed; michael@0: assert(base_mapped >= base_committed); michael@0: malloc_mutex_unlock(&base_mtx); michael@0: michael@0: /* Iterate over arenas. */ michael@0: for (i = 0; i < narenas; i++) { michael@0: arena_t *arena = arenas[i]; michael@0: size_t arena_mapped, arena_allocated, arena_committed, arena_dirty; michael@0: michael@0: if (arena == NULL) { michael@0: continue; michael@0: } michael@0: michael@0: malloc_spin_lock(&arena->lock); michael@0: michael@0: arena_mapped = arena->stats.mapped; michael@0: michael@0: /* "committed" counts dirty and allocated memory. */ michael@0: arena_committed = arena->stats.committed << pagesize_2pow; michael@0: michael@0: arena_allocated = arena->stats.allocated_small + michael@0: arena->stats.allocated_large; michael@0: michael@0: arena_dirty = arena->ndirty << pagesize_2pow; michael@0: michael@0: malloc_spin_unlock(&arena->lock); michael@0: michael@0: assert(arena_mapped >= arena_committed); michael@0: assert(arena_committed >= arena_allocated + arena_dirty); michael@0: michael@0: /* "waste" is committed memory that is neither dirty nor michael@0: * allocated. */ michael@0: stats->mapped += arena_mapped; michael@0: stats->allocated += arena_allocated; michael@0: stats->page_cache += arena_dirty; michael@0: stats->waste += arena_committed - arena_allocated - arena_dirty; michael@0: } michael@0: michael@0: assert(stats->mapped >= stats->allocated + stats->waste + michael@0: stats->page_cache + stats->bookkeeping); michael@0: } michael@0: michael@0: #ifdef MALLOC_DOUBLE_PURGE michael@0: michael@0: /* Explicitly remove all of this chunk's MADV_FREE'd pages from memory. */ michael@0: static void michael@0: hard_purge_chunk(arena_chunk_t *chunk) michael@0: { michael@0: /* See similar logic in arena_purge(). */ michael@0: michael@0: size_t i; michael@0: for (i = arena_chunk_header_npages; i < chunk_npages; i++) { michael@0: /* Find all adjacent pages with CHUNK_MAP_MADVISED set. */ michael@0: size_t npages; michael@0: for (npages = 0; michael@0: chunk->map[i + npages].bits & CHUNK_MAP_MADVISED && i + npages < chunk_npages; michael@0: npages++) { michael@0: /* Turn off the chunk's MADV_FREED bit and turn on its michael@0: * DECOMMITTED bit. */ michael@0: RELEASE_ASSERT(!(chunk->map[i + npages].bits & CHUNK_MAP_DECOMMITTED)); michael@0: chunk->map[i + npages].bits ^= CHUNK_MAP_MADVISED_OR_DECOMMITTED; michael@0: } michael@0: michael@0: /* We could use mincore to find out which pages are actually michael@0: * present, but it's not clear that's better. */ michael@0: if (npages > 0) { michael@0: pages_decommit(((char*)chunk) + (i << pagesize_2pow), npages << pagesize_2pow); michael@0: pages_commit(((char*)chunk) + (i << pagesize_2pow), npages << pagesize_2pow); michael@0: } michael@0: i += npages; michael@0: } michael@0: } michael@0: michael@0: /* Explicitly remove all of this arena's MADV_FREE'd pages from memory. */ michael@0: static void michael@0: hard_purge_arena(arena_t *arena) michael@0: { michael@0: malloc_spin_lock(&arena->lock); michael@0: michael@0: while (!LinkedList_IsEmpty(&arena->chunks_madvised)) { michael@0: LinkedList* next = arena->chunks_madvised.next; michael@0: arena_chunk_t *chunk = michael@0: LinkedList_Get(arena->chunks_madvised.next, michael@0: arena_chunk_t, chunks_madvised_elem); michael@0: hard_purge_chunk(chunk); michael@0: LinkedList_Remove(&chunk->chunks_madvised_elem); michael@0: } michael@0: michael@0: malloc_spin_unlock(&arena->lock); michael@0: } michael@0: michael@0: MOZ_JEMALLOC_API void michael@0: jemalloc_purge_freed_pages_impl() michael@0: { michael@0: size_t i; michael@0: for (i = 0; i < narenas; i++) { michael@0: arena_t *arena = arenas[i]; michael@0: if (arena != NULL) michael@0: hard_purge_arena(arena); michael@0: } michael@0: } michael@0: michael@0: #else /* !defined MALLOC_DOUBLE_PURGE */ michael@0: michael@0: MOZ_JEMALLOC_API void michael@0: jemalloc_purge_freed_pages_impl() michael@0: { michael@0: /* Do nothing. */ michael@0: } michael@0: michael@0: #endif /* defined MALLOC_DOUBLE_PURGE */ michael@0: michael@0: michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: void* michael@0: _recalloc(void *ptr, size_t count, size_t size) michael@0: { michael@0: size_t oldsize = (ptr != NULL) ? isalloc(ptr) : 0; michael@0: size_t newsize = count * size; michael@0: michael@0: /* michael@0: * In order for all trailing bytes to be zeroed, the caller needs to michael@0: * use calloc(), followed by recalloc(). However, the current calloc() michael@0: * implementation only zeros the bytes requested, so if recalloc() is michael@0: * to work 100% correctly, calloc() will need to change to zero michael@0: * trailing bytes. michael@0: */ michael@0: michael@0: ptr = realloc(ptr, newsize); michael@0: if (ptr != NULL && oldsize < newsize) { michael@0: memset((void *)((uintptr_t)ptr + oldsize), 0, newsize - michael@0: oldsize); michael@0: } michael@0: michael@0: return ptr; michael@0: } michael@0: michael@0: /* michael@0: * This impl of _expand doesn't ever actually expand or shrink blocks: it michael@0: * simply replies that you may continue using a shrunk block. michael@0: */ michael@0: void* michael@0: _expand(void *ptr, size_t newsize) michael@0: { michael@0: if (isalloc(ptr) >= newsize) michael@0: return ptr; michael@0: michael@0: return NULL; michael@0: } michael@0: michael@0: size_t michael@0: _msize(const void *ptr) michael@0: { michael@0: michael@0: return malloc_usable_size_impl(ptr); michael@0: } michael@0: #endif michael@0: michael@0: MOZ_JEMALLOC_API void michael@0: jemalloc_free_dirty_pages_impl(void) michael@0: { michael@0: size_t i; michael@0: for (i = 0; i < narenas; i++) { michael@0: arena_t *arena = arenas[i]; michael@0: michael@0: if (arena != NULL) { michael@0: malloc_spin_lock(&arena->lock); michael@0: arena_purge(arena, true); michael@0: malloc_spin_unlock(&arena->lock); michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* michael@0: * End non-standard functions. michael@0: */ michael@0: /******************************************************************************/ michael@0: /* michael@0: * Begin library-private functions, used by threading libraries for protection michael@0: * of malloc during fork(). These functions are only called if the program is michael@0: * running in threaded mode, so there is no need to check whether the program michael@0: * is threaded here. michael@0: */ michael@0: michael@0: static void michael@0: _malloc_prefork(void) michael@0: { michael@0: unsigned i; michael@0: michael@0: /* Acquire all mutexes in a safe order. */ michael@0: michael@0: malloc_spin_lock(&arenas_lock); michael@0: for (i = 0; i < narenas; i++) { michael@0: if (arenas[i] != NULL) michael@0: malloc_spin_lock(&arenas[i]->lock); michael@0: } michael@0: michael@0: malloc_mutex_lock(&base_mtx); michael@0: michael@0: malloc_mutex_lock(&huge_mtx); michael@0: } michael@0: michael@0: static void michael@0: _malloc_postfork(void) michael@0: { michael@0: unsigned i; michael@0: michael@0: /* Release all mutexes, now that fork() has completed. */ michael@0: michael@0: malloc_mutex_unlock(&huge_mtx); michael@0: michael@0: malloc_mutex_unlock(&base_mtx); michael@0: michael@0: for (i = 0; i < narenas; i++) { michael@0: if (arenas[i] != NULL) michael@0: malloc_spin_unlock(&arenas[i]->lock); michael@0: } michael@0: malloc_spin_unlock(&arenas_lock); michael@0: } michael@0: michael@0: /* michael@0: * End library-private functions. michael@0: */ michael@0: /******************************************************************************/ michael@0: michael@0: #ifdef HAVE_DLOPEN michael@0: # include michael@0: #endif michael@0: michael@0: #if defined(MOZ_MEMORY_DARWIN) michael@0: michael@0: #if !defined(MOZ_REPLACE_MALLOC) michael@0: static void * michael@0: zone_malloc(malloc_zone_t *zone, size_t size) michael@0: { michael@0: michael@0: return (malloc_impl(size)); michael@0: } michael@0: michael@0: static void * michael@0: zone_calloc(malloc_zone_t *zone, size_t num, size_t size) michael@0: { michael@0: michael@0: return (calloc_impl(num, size)); michael@0: } michael@0: michael@0: static void * michael@0: zone_valloc(malloc_zone_t *zone, size_t size) michael@0: { michael@0: void *ret = NULL; /* Assignment avoids useless compiler warning. */ michael@0: michael@0: posix_memalign_impl(&ret, pagesize, size); michael@0: michael@0: return (ret); michael@0: } michael@0: michael@0: static void * michael@0: zone_memalign(malloc_zone_t *zone, size_t alignment, size_t size) michael@0: { michael@0: return (memalign_impl(alignment, size)); michael@0: } michael@0: michael@0: static void * michael@0: zone_destroy(malloc_zone_t *zone) michael@0: { michael@0: michael@0: /* This function should never be called. */ michael@0: assert(false); michael@0: return (NULL); michael@0: } michael@0: michael@0: static size_t michael@0: zone_good_size(malloc_zone_t *zone, size_t size) michael@0: { michael@0: return malloc_good_size_impl(size); michael@0: } michael@0: michael@0: static size_t michael@0: ozone_size(malloc_zone_t *zone, void *ptr) michael@0: { michael@0: size_t ret = isalloc_validate(ptr); michael@0: if (ret == 0) michael@0: ret = szone->size(zone, ptr); michael@0: michael@0: return ret; michael@0: } michael@0: michael@0: static void michael@0: ozone_free(malloc_zone_t *zone, void *ptr) michael@0: { michael@0: if (isalloc_validate(ptr) != 0) michael@0: free_impl(ptr); michael@0: else { michael@0: size_t size = szone->size(zone, ptr); michael@0: if (size != 0) michael@0: (szone->free)(zone, ptr); michael@0: /* Otherwise we leak. */ michael@0: } michael@0: } michael@0: michael@0: static void * michael@0: ozone_realloc(malloc_zone_t *zone, void *ptr, size_t size) michael@0: { michael@0: size_t oldsize; michael@0: if (ptr == NULL) michael@0: return (malloc_impl(size)); michael@0: michael@0: oldsize = isalloc_validate(ptr); michael@0: if (oldsize != 0) michael@0: return (realloc_impl(ptr, size)); michael@0: else { michael@0: oldsize = szone->size(zone, ptr); michael@0: if (oldsize == 0) michael@0: return (malloc_impl(size)); michael@0: else { michael@0: void *ret = malloc_impl(size); michael@0: if (ret != NULL) { michael@0: memcpy(ret, ptr, (oldsize < size) ? oldsize : michael@0: size); michael@0: (szone->free)(zone, ptr); michael@0: } michael@0: return (ret); michael@0: } michael@0: } michael@0: } michael@0: michael@0: static unsigned michael@0: ozone_batch_malloc(malloc_zone_t *zone, size_t size, void **results, michael@0: unsigned num_requested) michael@0: { michael@0: /* Don't bother implementing this interface, since it isn't required. */ michael@0: return 0; michael@0: } michael@0: michael@0: static void michael@0: ozone_batch_free(malloc_zone_t *zone, void **to_be_freed, unsigned num) michael@0: { michael@0: unsigned i; michael@0: michael@0: for (i = 0; i < num; i++) michael@0: ozone_free(zone, to_be_freed[i]); michael@0: } michael@0: michael@0: static void michael@0: ozone_free_definite_size(malloc_zone_t *zone, void *ptr, size_t size) michael@0: { michael@0: if (isalloc_validate(ptr) != 0) { michael@0: assert(isalloc_validate(ptr) == size); michael@0: free_impl(ptr); michael@0: } else { michael@0: assert(size == szone->size(zone, ptr)); michael@0: l_szone.m16(zone, ptr, size); michael@0: } michael@0: } michael@0: michael@0: static void michael@0: ozone_force_lock(malloc_zone_t *zone) michael@0: { michael@0: _malloc_prefork(); michael@0: szone->introspect->force_lock(zone); michael@0: } michael@0: michael@0: static void michael@0: ozone_force_unlock(malloc_zone_t *zone) michael@0: { michael@0: szone->introspect->force_unlock(zone); michael@0: _malloc_postfork(); michael@0: } michael@0: michael@0: static size_t michael@0: zone_version_size(int version) michael@0: { michael@0: switch (version) michael@0: { michael@0: case SNOW_LEOPARD_MALLOC_ZONE_T_VERSION: michael@0: return sizeof(snow_leopard_malloc_zone); michael@0: case LEOPARD_MALLOC_ZONE_T_VERSION: michael@0: return sizeof(leopard_malloc_zone); michael@0: default: michael@0: case LION_MALLOC_ZONE_T_VERSION: michael@0: return sizeof(lion_malloc_zone); michael@0: } michael@0: } michael@0: michael@0: /* michael@0: * Overlay the default scalable zone (szone) such that existing allocations are michael@0: * drained, and further allocations come from jemalloc. This is necessary michael@0: * because Core Foundation directly accesses and uses the szone before the michael@0: * jemalloc library is even loaded. michael@0: */ michael@0: static void michael@0: szone2ozone(malloc_zone_t *default_zone, size_t size) michael@0: { michael@0: lion_malloc_zone *l_zone; michael@0: assert(malloc_initialized); michael@0: michael@0: /* michael@0: * Stash a copy of the original szone so that we can call its michael@0: * functions as needed. Note that internally, the szone stores its michael@0: * bookkeeping data structures immediately following the malloc_zone_t michael@0: * header, so when calling szone functions, we need to pass a pointer to michael@0: * the original zone structure. michael@0: */ michael@0: memcpy(szone, default_zone, size); michael@0: michael@0: /* OSX 10.7 allocates the default zone in protected memory. */ michael@0: if (default_zone->version >= LION_MALLOC_ZONE_T_VERSION) { michael@0: void* start_of_page = (void*)((size_t)(default_zone) & ~pagesize_mask); michael@0: mprotect (start_of_page, size, PROT_READ | PROT_WRITE); michael@0: } michael@0: michael@0: default_zone->size = (void *)ozone_size; michael@0: default_zone->malloc = (void *)zone_malloc; michael@0: default_zone->calloc = (void *)zone_calloc; michael@0: default_zone->valloc = (void *)zone_valloc; michael@0: default_zone->free = (void *)ozone_free; michael@0: default_zone->realloc = (void *)ozone_realloc; michael@0: default_zone->destroy = (void *)zone_destroy; michael@0: default_zone->batch_malloc = NULL; michael@0: default_zone->batch_free = ozone_batch_free; michael@0: default_zone->introspect = ozone_introspect; michael@0: michael@0: /* Don't modify default_zone->zone_name; Mac libc may rely on the name michael@0: * being unchanged. See Mozilla bug 694896. */ michael@0: michael@0: ozone_introspect->enumerator = NULL; michael@0: ozone_introspect->good_size = (void *)zone_good_size; michael@0: ozone_introspect->check = NULL; michael@0: ozone_introspect->print = NULL; michael@0: ozone_introspect->log = NULL; michael@0: ozone_introspect->force_lock = (void *)ozone_force_lock; michael@0: ozone_introspect->force_unlock = (void *)ozone_force_unlock; michael@0: ozone_introspect->statistics = NULL; michael@0: michael@0: /* Platform-dependent structs */ michael@0: l_zone = (lion_malloc_zone*)(default_zone); michael@0: michael@0: if (default_zone->version >= SNOW_LEOPARD_MALLOC_ZONE_T_VERSION) { michael@0: l_zone->m15 = (void (*)())zone_memalign; michael@0: l_zone->m16 = (void (*)())ozone_free_definite_size; michael@0: l_ozone_introspect.m9 = NULL; michael@0: } michael@0: michael@0: if (default_zone->version >= LION_MALLOC_ZONE_T_VERSION) { michael@0: l_zone->m17 = NULL; michael@0: l_ozone_introspect.m10 = NULL; michael@0: l_ozone_introspect.m11 = NULL; michael@0: l_ozone_introspect.m12 = NULL; michael@0: l_ozone_introspect.m13 = NULL; michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: __attribute__((constructor)) michael@0: void michael@0: jemalloc_darwin_init(void) michael@0: { michael@0: if (malloc_init_hard()) michael@0: abort(); michael@0: } michael@0: michael@0: #endif michael@0: michael@0: /* michael@0: * is_malloc(malloc_impl) is some macro magic to detect if malloc_impl is michael@0: * defined as "malloc" in mozmemory_wrap.h michael@0: */ michael@0: #define malloc_is_malloc 1 michael@0: #define is_malloc_(a) malloc_is_ ## a michael@0: #define is_malloc(a) is_malloc_(a) michael@0: michael@0: #if !defined(MOZ_MEMORY_DARWIN) && (is_malloc(malloc_impl) == 1) michael@0: # if defined(__GLIBC__) && !defined(__UCLIBC__) michael@0: /* michael@0: * glibc provides the RTLD_DEEPBIND flag for dlopen which can make it possible michael@0: * to inconsistently reference libc's malloc(3)-compatible functions michael@0: * (bug 493541). michael@0: * michael@0: * These definitions interpose hooks in glibc. The functions are actually michael@0: * passed an extra argument for the caller return address, which will be michael@0: * ignored. michael@0: */ michael@0: MOZ_MEMORY_API void (*__free_hook)(void *ptr) = free_impl; michael@0: MOZ_MEMORY_API void *(*__malloc_hook)(size_t size) = malloc_impl; michael@0: MOZ_MEMORY_API void *(*__realloc_hook)(void *ptr, size_t size) = realloc_impl; michael@0: MOZ_MEMORY_API void *(*__memalign_hook)(size_t alignment, size_t size) = MEMALIGN; michael@0: michael@0: # elif defined(RTLD_DEEPBIND) michael@0: /* michael@0: * XXX On systems that support RTLD_GROUP or DF_1_GROUP, do their michael@0: * implementations permit similar inconsistencies? Should STV_SINGLETON michael@0: * visibility be used for interposition where available? michael@0: */ michael@0: # error "Interposing malloc is unsafe on this system without libc malloc hooks." michael@0: # endif michael@0: #endif michael@0: michael@0: #ifdef MOZ_MEMORY_WINDOWS michael@0: /* michael@0: * In the new style jemalloc integration jemalloc is built as a separate michael@0: * shared library. Since we're no longer hooking into the CRT binary, michael@0: * we need to initialize the heap at the first opportunity we get. michael@0: * DLL_PROCESS_ATTACH in DllMain is that opportunity. michael@0: */ michael@0: BOOL APIENTRY DllMain(HINSTANCE hModule, michael@0: DWORD reason, michael@0: LPVOID lpReserved) michael@0: { michael@0: switch (reason) { michael@0: case DLL_PROCESS_ATTACH: michael@0: /* Don't force the system to page DllMain back in every time michael@0: * we create/destroy a thread */ michael@0: DisableThreadLibraryCalls(hModule); michael@0: /* Initialize the heap */ michael@0: malloc_init_hard(); michael@0: break; michael@0: michael@0: case DLL_PROCESS_DETACH: michael@0: break; michael@0: michael@0: } michael@0: michael@0: return TRUE; michael@0: } michael@0: #endif