diff --git a/src/malloc/rpmalloc/glue.h b/src/malloc/rpmalloc/glue.h index befa6903..d49bda10 100644 --- a/src/malloc/rpmalloc/glue.h +++ b/src/malloc/rpmalloc/glue.h @@ -1,12 +1,7 @@ #include "rpmalloc.h" -#if (defined(__GNUC__) && __GNUC__ >= 9) - #pragma GCC diagnostic ignored "-Wattributes" // or we get warnings that nodiscard is ignored on a forward - #define hidden_alias(fun) __attribute__((alias(#fun), used, visibility("hidden"), copy(fun))); - #define public_alias(fun) __attribute__((alias(#fun), used, visibility("default"), copy(fun))); -#else - #define hidden_alias(fun) __attribute__((alias(#fun), used, visibility("hidden"))); - #define public_alias(fun) __attribute__((alias(#fun), used, visibility("default"), copy(fun))); -#endif + +#define hidden_alias(fun) __attribute__((alias(#fun), used, visibility("hidden"))); +#define public_alias(fun) __attribute__((alias(#fun), used, visibility("default"), copy(fun))); void* __libc_malloc_impl(size_t) hidden_alias(rpmalloc) void* __libc_realloc(void*, size_t) hidden_alias(rprealloc) @@ -18,8 +13,8 @@ hidden void __malloc_atfork(int who) {} hidden void __malloc_donate(char *start, char *end) {} hidden void __malloc_process_init() { - rpmalloc_set_main_thread(); - if (rpmalloc_initialize() < 0) { + global_main_thread_id = get_thread_id(); + if (rpmalloc_initialize(0) < 0) { abort(); } } @@ -27,7 +22,7 @@ hidden void __malloc_thread_init() { rpmalloc_thread_initialize(); } hidden void __malloc_thread_finalize() { - rpmalloc_thread_finalize(1); + rpmalloc_thread_finalize(); } #include "pthread_impl.h" @@ -42,6 +37,10 @@ static inline uintptr_t get_thread_id(void) { } static void set_thread_heap(heap_t* heap) { - __pthread_self()->theap = (void *)heap; - if (heap) heap->owner_thread = get_thread_id(); + if (heap && (heap->id != 0)) { + rpmalloc_assert(heap->id != 0, "Default heap being used"); + heap->owner_thread = get_thread_id(); + } + + __pthread_self()->theap = (void*)heap; } diff --git a/src/malloc/rpmalloc/rpmalloc.c b/src/malloc/rpmalloc/rpmalloc.c index 50583567..26514ad2 100644 --- a/src/malloc/rpmalloc/rpmalloc.c +++ b/src/malloc/rpmalloc/rpmalloc.c @@ -1,21 +1,32 @@ -/* rpmalloc.c - Memory allocator - Public Domain - 2016-2020 Mattias Jansson +/* rpmalloc.c - Memory allocator - 2016-2020 Mattias Jansson * - * This library provides a cross-platform lock free thread caching malloc implementation in C11. - * The latest source code is always available at + * SPDX-FileCopyrightText: 2016-2020 Mattias Jansson + * SPDX-License-Identifier: Unlicense OR MIT + * + * This library provides a cross-platform lock free thread caching malloc + * implementation in C11. The latest source code is always available at * * https://github.com/mjansson/rpmalloc * - * This library is put in the public domain; you can redistribute it and/or modify it without any restrictions. + * This library is put in the public domain; you can redistribute it and/or + * modify it without any restrictions. Or, if you choose, you can use it under + * the MIT license. * */ #include "rpmalloc.h" -//////////// -/// -/// Build time configurable limits -/// -////// +#include +#include + +#include +#include +#include +#include + +#if !defined(__has_builtin) +#define __has_builtin(b) 0 +#endif #if defined(__clang__) #pragma clang diagnostic ignored "-Wunused-macros" @@ -23,331 +34,445 @@ #if __has_warning("-Wreserved-identifier") #pragma clang diagnostic ignored "-Wreserved-identifier" #endif +#if __has_warning("-Wstatic-in-inline") +#pragma clang diagnostic ignored "-Wstatic-in-inline" +#endif +#if __has_warning("-Wunsafe-buffer-usage") +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" +#endif +#if __has_warning("-Wimplicit-void-ptr-cast") +#pragma clang diagnostic ignored "-Wimplicit-void-ptr-cast" +#endif +#if __has_warning("-Wallocator-wrappers") +#pragma clang diagnostic ignored "-Wallocator-wrappers" +#endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-macros" #pragma GCC diagnostic ignored "-Wunused-function" #endif -#ifndef HEAP_ARRAY_SIZE -//! Size of heap hashmap -#define HEAP_ARRAY_SIZE 47 -#endif -#ifndef ENABLE_THREAD_CACHE -//! Enable per-thread cache -#define ENABLE_THREAD_CACHE 1 -#endif -#ifndef ENABLE_GLOBAL_CACHE -//! Enable global cache shared between all threads, requires thread cache -#define ENABLE_GLOBAL_CACHE 1 -#endif -#ifndef ENABLE_VALIDATE_ARGS -//! Enable validation of args to public entry points -#define ENABLE_VALIDATE_ARGS 0 -#endif -#ifndef ENABLE_STATISTICS -//! Enable statistics collection -#define ENABLE_STATISTICS 0 -#endif -#ifndef ENABLE_ASSERTS -//! Enable asserts -#define ENABLE_ASSERTS 0 -#endif -#ifndef ENABLE_OVERRIDE -//! Override standard library malloc/free and new/delete entry points -#define ENABLE_OVERRIDE 0 -#endif -#ifndef ENABLE_PRELOAD -//! Support preloading -#define ENABLE_PRELOAD 0 -#endif -#ifndef DISABLE_UNMAP -//! Disable unmapping memory pages (also enables unlimited cache) -#define DISABLE_UNMAP 0 -#endif -#ifndef ENABLE_UNLIMITED_CACHE -//! Enable unlimited global cache (no unmapping until finalization) -#define ENABLE_UNLIMITED_CACHE 0 -#endif -#ifndef ENABLE_ADAPTIVE_THREAD_CACHE -//! Enable adaptive thread cache size based on use heuristics -#define ENABLE_ADAPTIVE_THREAD_CACHE 0 -#endif -#ifndef DEFAULT_SPAN_MAP_COUNT -//! Default number of spans to map in call to map more virtual memory (default values yield 4MiB here) -#define DEFAULT_SPAN_MAP_COUNT 64 -#endif -#ifndef GLOBAL_CACHE_MULTIPLIER -//! Multiplier for global cache -#define GLOBAL_CACHE_MULTIPLIER 8 -#endif - -#if DISABLE_UNMAP && !ENABLE_GLOBAL_CACHE -#error Must use global cache if unmap is disabled -#endif - -#if DISABLE_UNMAP -#undef ENABLE_UNLIMITED_CACHE -#define ENABLE_UNLIMITED_CACHE 1 -#endif - -#if !ENABLE_GLOBAL_CACHE -#undef ENABLE_UNLIMITED_CACHE -#define ENABLE_UNLIMITED_CACHE 0 -#endif - -#if !ENABLE_THREAD_CACHE -#undef ENABLE_ADAPTIVE_THREAD_CACHE -#define ENABLE_ADAPTIVE_THREAD_CACHE 0 -#endif - #if defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) -# define PLATFORM_WINDOWS 1 -# define PLATFORM_POSIX 0 +#define PLATFORM_WINDOWS 1 +#define PLATFORM_POSIX 0 #else -# define PLATFORM_WINDOWS 0 -# define PLATFORM_POSIX 1 +#define PLATFORM_WINDOWS 0 +#define PLATFORM_POSIX 1 #endif -/// Platform and arch specifics -#if defined(_MSC_VER) && !defined(__clang__) -# pragma warning (disable: 5105) -# ifndef FORCEINLINE -# define FORCEINLINE inline __forceinline -# endif -# define _Static_assert static_assert +#if defined(_MSC_VER) +#define NOINLINE __declspec(noinline) #else -# ifndef FORCEINLINE -# define FORCEINLINE inline __attribute__((__always_inline__)) -# endif +#define NOINLINE __attribute__((noinline)) #endif + #if PLATFORM_WINDOWS -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include -# if ENABLE_VALIDATE_ARGS -# include -# endif -#else -# include -# include -# include -# include -# if defined(__APPLE__) -# include -# if !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR -# include -# include -# endif -# include -# endif -# if defined(__HAIKU__) || defined(__TINYC__) -# include -# endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN #endif - -#include -#include -#include - -#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK) +#include #include static DWORD fls_key; +//! VirtualAlloc2 (Windows 10+), resolved dynamically; null on older systems +typedef PVOID(WINAPI* virtualalloc2_fn)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); +static virtualalloc2_fn os_virtualalloc2; #endif - #if PLATFORM_POSIX -# include -# include -# ifdef __FreeBSD__ -# include -# define MAP_HUGETLB MAP_ALIGNED_SUPER -# ifndef PROT_MAX -# define PROT_MAX(f) 0 -# endif -# else -# define PROT_MAX(f) 0 -# endif -# ifdef __sun -extern int madvise(caddr_t, size_t, int); -# endif -# ifndef MAP_UNINITIALIZED -# define MAP_UNINITIALIZED 0 -# endif +#include +#include +#include +#include +#include +static pthread_key_t pthread_key; +#ifdef __FreeBSD__ +#include +#define MAP_HUGETLB MAP_ALIGNED_SUPER +#ifndef PROT_MAX +#define PROT_MAX(f) 0 #endif -#include - -#if ENABLE_ASSERTS -# undef NDEBUG -# if defined(_MSC_VER) && !defined(_DEBUG) -# define _DEBUG -# endif -# include -#define RPMALLOC_TOSTRING_M(x) #x -#define RPMALLOC_TOSTRING(x) RPMALLOC_TOSTRING_M(x) -#define rpmalloc_assert(truth, message) \ - do { \ - if (!(truth)) { \ - if (_memory_config.error_callback) { \ - _memory_config.error_callback( \ - message " (" RPMALLOC_TOSTRING(truth) ") at " __FILE__ ":" RPMALLOC_TOSTRING(__LINE__)); \ - } else { \ - assert((truth) && message); \ - } \ - } \ - } while (0) #else -# define rpmalloc_assert(truth, message) do {} while(0) +#define PROT_MAX(f) 0 +#endif +#ifdef __sun +extern int +madvise(caddr_t, size_t, int); +#endif +#ifndef MAP_UNINITIALIZED +#define MAP_UNINITIALIZED 0 #endif -#if ENABLE_STATISTICS -# include #endif -////// -/// -/// Atomic access abstraction (since MSVC does not do C11 yet) -/// -////// - -#if defined(_MSC_VER) && !defined(__clang__) - -typedef volatile long atomic32_t; -typedef volatile long long atomic64_t; -typedef volatile void* atomicptr_t; - -static FORCEINLINE int32_t atomic_load32(atomic32_t* src) { return *src; } -static FORCEINLINE void atomic_store32(atomic32_t* dst, int32_t val) { *dst = val; } -static FORCEINLINE int32_t atomic_incr32(atomic32_t* val) { return (int32_t)InterlockedIncrement(val); } -static FORCEINLINE int32_t atomic_decr32(atomic32_t* val) { return (int32_t)InterlockedDecrement(val); } -static FORCEINLINE int32_t atomic_add32(atomic32_t* val, int32_t add) { return (int32_t)InterlockedExchangeAdd(val, add) + add; } -static FORCEINLINE int atomic_cas32_acquire(atomic32_t* dst, int32_t val, int32_t ref) { return (InterlockedCompareExchange(dst, val, ref) == ref) ? 1 : 0; } -static FORCEINLINE void atomic_store32_release(atomic32_t* dst, int32_t val) { *dst = val; } -static FORCEINLINE int64_t atomic_load64(atomic64_t* src) { return *src; } -static FORCEINLINE int64_t atomic_add64(atomic64_t* val, int64_t add) { return (int64_t)InterlockedExchangeAdd64(val, add) + add; } -static FORCEINLINE void* atomic_load_ptr(atomicptr_t* src) { return (void*)*src; } -static FORCEINLINE void atomic_store_ptr(atomicptr_t* dst, void* val) { *dst = val; } -static FORCEINLINE void atomic_store_ptr_release(atomicptr_t* dst, void* val) { *dst = val; } -static FORCEINLINE void* atomic_exchange_ptr_acquire(atomicptr_t* dst, void* val) { return (void*)InterlockedExchangePointer((void* volatile*)dst, val); } -static FORCEINLINE int atomic_cas_ptr(atomicptr_t* dst, void* val, void* ref) { return (InterlockedCompareExchangePointer((void* volatile*)dst, val, ref) == ref) ? 1 : 0; } - -#define EXPECTED(x) (x) -#define UNEXPECTED(x) (x) +#if defined(__linux__) || defined(__ANDROID__) +#include +#if !defined(PR_SET_VMA) +#define PR_SET_VMA 0x53564d41 +#define PR_SET_VMA_ANON_NAME 0 +#endif +#endif +#if defined(__APPLE__) +#include +#if !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR +#include +#include +#endif +#include +#endif +#if defined(__HAIKU__) || defined(__TINYC__) +#include +#endif +#include +#if (INTPTR_MAX > INT32_MAX) +#define ARCH_64BIT 1 +#define ARCH_32BIT 0 #else - -#include - -typedef volatile _Atomic(int32_t) atomic32_t; -typedef volatile _Atomic(int64_t) atomic64_t; -typedef volatile _Atomic(void*) atomicptr_t; - -static FORCEINLINE int32_t atomic_load32(atomic32_t* src) { return atomic_load_explicit(src, memory_order_relaxed); } -static FORCEINLINE void atomic_store32(atomic32_t* dst, int32_t val) { atomic_store_explicit(dst, val, memory_order_relaxed); } -static FORCEINLINE int32_t atomic_incr32(atomic32_t* val) { return atomic_fetch_add_explicit(val, 1, memory_order_relaxed) + 1; } -static FORCEINLINE int32_t atomic_decr32(atomic32_t* val) { return atomic_fetch_add_explicit(val, -1, memory_order_relaxed) - 1; } -static FORCEINLINE int32_t atomic_add32(atomic32_t* val, int32_t add) { return atomic_fetch_add_explicit(val, add, memory_order_relaxed) + add; } -static FORCEINLINE int atomic_cas32_acquire(atomic32_t* dst, int32_t val, int32_t ref) { return atomic_compare_exchange_weak_explicit(dst, &ref, val, memory_order_acquire, memory_order_relaxed); } -static FORCEINLINE void atomic_store32_release(atomic32_t* dst, int32_t val) { atomic_store_explicit(dst, val, memory_order_release); } -static FORCEINLINE int64_t atomic_load64(atomic64_t* val) { return atomic_load_explicit(val, memory_order_relaxed); } -static FORCEINLINE int64_t atomic_add64(atomic64_t* val, int64_t add) { return atomic_fetch_add_explicit(val, add, memory_order_relaxed) + add; } -static FORCEINLINE void* atomic_load_ptr(atomicptr_t* src) { return atomic_load_explicit(src, memory_order_relaxed); } -static FORCEINLINE void atomic_store_ptr(atomicptr_t* dst, void* val) { atomic_store_explicit(dst, val, memory_order_relaxed); } -static FORCEINLINE void atomic_store_ptr_release(atomicptr_t* dst, void* val) { atomic_store_explicit(dst, val, memory_order_release); } -static FORCEINLINE void* atomic_exchange_ptr_acquire(atomicptr_t* dst, void* val) { return atomic_exchange_explicit(dst, val, memory_order_acquire); } -static FORCEINLINE int atomic_cas_ptr(atomicptr_t* dst, void* val, void* ref) { return atomic_compare_exchange_weak_explicit(dst, &ref, val, memory_order_relaxed, memory_order_relaxed); } - -#define EXPECTED(x) __builtin_expect((x), 1) -#define UNEXPECTED(x) __builtin_expect((x), 0) - -#endif - -//////////// -/// -/// Statistics related functions (evaluate to nothing when statistics not enabled) -/// -////// - -#if ENABLE_STATISTICS -# define _rpmalloc_stat_inc(counter) atomic_incr32(counter) -# define _rpmalloc_stat_dec(counter) atomic_decr32(counter) -# define _rpmalloc_stat_add(counter, value) atomic_add32(counter, (int32_t)(value)) -# define _rpmalloc_stat_add64(counter, value) atomic_add64(counter, (int64_t)(value)) -# define _rpmalloc_stat_add_peak(counter, value, peak) do { int32_t _cur_count = atomic_add32(counter, (int32_t)(value)); if (_cur_count > (peak)) peak = _cur_count; } while (0) -# define _rpmalloc_stat_sub(counter, value) atomic_add32(counter, -(int32_t)(value)) -# define _rpmalloc_stat_inc_alloc(heap, class_idx) do { \ - int32_t alloc_current = atomic_incr32(&heap->size_class_use[class_idx].alloc_current); \ - if (alloc_current > heap->size_class_use[class_idx].alloc_peak) \ - heap->size_class_use[class_idx].alloc_peak = alloc_current; \ - atomic_incr32(&heap->size_class_use[class_idx].alloc_total); \ -} while(0) -# define _rpmalloc_stat_inc_free(heap, class_idx) do { \ - atomic_decr32(&heap->size_class_use[class_idx].alloc_current); \ - atomic_incr32(&heap->size_class_use[class_idx].free_total); \ -} while(0) -#else -# define _rpmalloc_stat_inc(counter) do {} while(0) -# define _rpmalloc_stat_dec(counter) do {} while(0) -# define _rpmalloc_stat_add(counter, value) do {} while(0) -# define _rpmalloc_stat_add64(counter, value) do {} while(0) -# define _rpmalloc_stat_add_peak(counter, value, peak) do {} while (0) -# define _rpmalloc_stat_sub(counter, value) do {} while(0) -# define _rpmalloc_stat_inc_alloc(heap, class_idx) do {} while(0) -# define _rpmalloc_stat_inc_free(heap, class_idx) do {} while(0) -#endif - - -/// -/// Preconfigured limits and sizes -/// - -//! Granularity of a small allocation block (must be power of two) -#define SMALL_GRANULARITY 16 -//! Small granularity shift count -#define SMALL_GRANULARITY_SHIFT 4 -//! Number of small block size classes -#define SMALL_CLASS_COUNT 65 -//! Maximum size of a small block -#define SMALL_SIZE_LIMIT (SMALL_GRANULARITY * (SMALL_CLASS_COUNT - 1)) -//! Granularity of a medium allocation block -#define MEDIUM_GRANULARITY 512 -//! Medium granularity shift count -#define MEDIUM_GRANULARITY_SHIFT 9 -//! Number of medium block size classes -#define MEDIUM_CLASS_COUNT 61 -//! Total number of small + medium size classes -#define SIZE_CLASS_COUNT (SMALL_CLASS_COUNT + MEDIUM_CLASS_COUNT) -//! Number of large block size classes -#define LARGE_CLASS_COUNT 63 -//! Maximum size of a medium block -#define MEDIUM_SIZE_LIMIT (SMALL_SIZE_LIMIT + (MEDIUM_GRANULARITY * MEDIUM_CLASS_COUNT)) -//! Maximum size of a large block -#define LARGE_SIZE_LIMIT ((LARGE_CLASS_COUNT * _memory_span_size) - SPAN_HEADER_SIZE) -//! Size of a span header (must be a multiple of SMALL_GRANULARITY and a power of two) -#define SPAN_HEADER_SIZE 128 -//! Number of spans in thread cache -#define MAX_THREAD_SPAN_CACHE 400 -//! Number of spans to transfer between thread and global cache -#define THREAD_SPAN_CACHE_TRANSFER 64 -//! Number of spans in thread cache for large spans (must be greater than LARGE_CLASS_COUNT / 2) -#define MAX_THREAD_SPAN_LARGE_CACHE 100 -//! Number of spans to transfer between thread and global cache for large spans -#define THREAD_SPAN_LARGE_CACHE_TRANSFER 6 - -_Static_assert((SMALL_GRANULARITY & (SMALL_GRANULARITY - 1)) == 0, "Small granularity must be power of two"); -_Static_assert((SPAN_HEADER_SIZE & (SPAN_HEADER_SIZE - 1)) == 0, "Span header size must be power of two"); - -#if ENABLE_VALIDATE_ARGS -//! Maximum allocation size to avoid integer overflow -#undef MAX_ALLOC_SIZE -#define MAX_ALLOC_SIZE (((size_t)-1) - _memory_span_size) +#define ARCH_64BIT 0 +#define ARCH_32BIT 1 #endif #define pointer_offset(ptr, ofs) (void*)((char*)(ptr) + (ptrdiff_t)(ofs)) #define pointer_diff(first, second) (ptrdiff_t)((const char*)(first) - (const char*)(second)) -#define INVALID_POINTER ((void*)((uintptr_t)-1)) +//////////// +/// +/// Build time configurable limits +/// +////// -#define SIZE_CLASS_LARGE SIZE_CLASS_COUNT -#define SIZE_CLASS_HUGE ((uint32_t)-1) +#ifndef ENABLE_VALIDATE_ARGS +//! Enable validation of args to public entry points +#define ENABLE_VALIDATE_ARGS 0 +#endif +#ifndef ENABLE_ASSERTS +//! Enable asserts +#define ENABLE_ASSERTS 0 +#endif +#ifndef ENABLE_UNMAP +//! Enable unmapping memory pages +#define ENABLE_UNMAP 1 +#endif +#ifndef ENABLE_DECOMMIT +//! Enable decommitting memory pages +#define ENABLE_DECOMMIT 1 +#endif +#ifndef ENABLE_DYNAMIC_LINK +//! Enable building as dynamic library +#define ENABLE_DYNAMIC_LINK 0 +#endif +#ifndef ENABLE_OVERRIDE +//! Enable standard library malloc/free/new/delete overrides. When enabled, rpmalloc becomes the +// backing store for the entire process, including the C runtime's own allocations (for example +// per-thread TLS allocated by the loader). Two finalize-time features are therefore adjusted: +// the unmap_on_finalize config option is ignored (see rpmalloc_initialize), since returning all +// mappings to the OS while the process keeps running would unmap memory the runtime still holds; +// and ENABLE_LEAK_DETECTION defaults off, since the runtime's still-live allocations are +// indistinguishable from application leaks at finalize. +#define ENABLE_OVERRIDE 1 +#endif +#ifndef ENABLE_STATISTICS +//! Enable statistics +#define ENABLE_STATISTICS 0 +#endif +#ifndef ENABLE_LEAK_DETECTION +//! Enable detection of allocations still outstanding at rpmalloc_finalize. Requires ENABLE_STATISTICS +// for the allocation counters, and follows it by default - except under ENABLE_OVERRIDE, where it +// defaults off: the override makes rpmalloc the backing store for the C runtime's own allocations +// (for example per-thread TLS allocated by the loader), which are still live at finalize and +// indistinguishable from application leaks, so the check would always report false positives. +#if ENABLE_OVERRIDE +#define ENABLE_LEAK_DETECTION 0 +#else +#define ENABLE_LEAK_DETECTION ENABLE_STATISTICS +#endif +#endif +#if ENABLE_LEAK_DETECTION && !ENABLE_STATISTICS +#error ENABLE_LEAK_DETECTION requires ENABLE_STATISTICS +#endif + +//////////// +/// +/// Built in size configurations +/// +////// + +#define PAGE_HEADER_SIZE 128 +#define SPAN_HEADER_SIZE PAGE_HEADER_SIZE + +//! Alignment of each heap control structure within a shared mapping. Keeps adjacent +// heaps on separate cache lines so cross-thread writes to one heap (thread_free) do +// not falsely share with a neighbour heap owned by another thread. Sized for a 128 byte +// cache line (Apple Silicon, x86 destructive interference) to cover 64 byte lines too. +#define HEAP_ALIGNMENT 128 + +#define SMALL_GRANULARITY 16 + +#define SMALL_BLOCK_SIZE_LIMIT (4 * 1024) +#define MEDIUM_SMALL_BLOCK_SIZE_LIMIT (32 * 1024) +#define MEDIUM_LARGE_BLOCK_SIZE_LIMIT (256 * 1024) +#define LARGE_BLOCK_SIZE_LIMIT (2 * 1024 * 1024) + +#define SMALL_SIZE_CLASS_COUNT 73 +#define MEDIUM_SMALL_SIZE_CLASS_COUNT 12 +#define MEDIUM_LARGE_SIZE_CLASS_COUNT 12 +#define LARGE_SIZE_CLASS_COUNT 12 +#define SIZE_CLASS_COUNT \ + (SMALL_SIZE_CLASS_COUNT + MEDIUM_SMALL_SIZE_CLASS_COUNT + MEDIUM_LARGE_SIZE_CLASS_COUNT + LARGE_SIZE_CLASS_COUNT) + +#define SMALL_PAGE_SIZE_SHIFT 16 +#define SMALL_PAGE_SIZE (1 << SMALL_PAGE_SIZE_SHIFT) +#define SMALL_PAGE_MASK (~((uintptr_t)SMALL_PAGE_SIZE - 1)) +#define MEDIUM_SMALL_PAGE_SIZE_SHIFT 20 +#define MEDIUM_SMALL_PAGE_SIZE (1 << MEDIUM_SMALL_PAGE_SIZE_SHIFT) +#define MEDIUM_SMALL_PAGE_MASK (~((uintptr_t)MEDIUM_SMALL_PAGE_SIZE - 1)) +#define MEDIUM_LARGE_PAGE_SIZE_SHIFT 22 +#define MEDIUM_LARGE_PAGE_SIZE (1 << MEDIUM_LARGE_PAGE_SIZE_SHIFT) +#define MEDIUM_LARGE_PAGE_MASK (~((uintptr_t)MEDIUM_LARGE_PAGE_SIZE - 1)) +#define LARGE_PAGE_SIZE_SHIFT 24 +#define LARGE_PAGE_SIZE (1 << LARGE_PAGE_SIZE_SHIFT) +#define LARGE_PAGE_MASK (~((uintptr_t)LARGE_PAGE_SIZE - 1)) + +#define SPAN_SIZE (256 * 1024 * 1024) +#define SPAN_MASK (~((uintptr_t)(SPAN_SIZE - 1))) + +#if ENABLE_VALIDATE_ARGS +//! Maximum allocation size to avoid integer overflow +#undef MAX_ALLOC_SIZE +#define MAX_ALLOC_SIZE (((size_t)-1) - SPAN_SIZE) +#endif + +//////////// +/// +/// Utility macros +/// +////// + +#if ENABLE_ASSERTS +#undef NDEBUG +#if defined(_MSC_VER) && !defined(_DEBUG) +#define _DEBUG +#endif +#include +#define RPMALLOC_TOSTRING_M(x) #x +#define RPMALLOC_TOSTRING(x) RPMALLOC_TOSTRING_M(x) +#define rpmalloc_assert(truth, message) \ + do { \ + if (!(truth)) { \ + assert((truth) && message); \ + } \ + } while (0) +#else +#define rpmalloc_assert(truth, message) \ + do { \ + } while (0) +#endif + +#if defined(_MSC_VER) +#define rpmalloc_assume(cond) __assume(cond) +#elif defined(__clang__) && __has_builtin(__builtin_assume) +#define rpmalloc_assume(cond) __builtin_assume(cond) +#elif defined(__GNUC__) +#define rpmalloc_assume(cond) \ + do { \ + if (!__builtin_expect(cond, 0)) \ + __builtin_unreachable(); \ + } while (0) +#else +#define rpmalloc_assume(cond) 0 +#endif + +//////////// +/// +/// Statistics +/// +////// + +#if ENABLE_STATISTICS + +typedef struct rpmalloc_statistics_t { + atomic_size_t page_mapped; + atomic_size_t page_mapped_peak; + atomic_size_t page_commit; + atomic_size_t page_decommit; + atomic_size_t page_active; + atomic_size_t page_active_peak; + atomic_size_t huge_alloc; + atomic_size_t huge_alloc_peak; + atomic_size_t heap_count; +} rpmalloc_statistics_t; + +static rpmalloc_statistics_t global_statistics; + +//! Subtract from a statistics counter, clamping at zero. Counters are in units of the +//! configured page size and heaps with committed pages are retained across finalize and +//! initialize cycles where the page size can change, so strict accounting is not possible. +static void +statistics_sub_saturating(atomic_size_t* counter, size_t value) { + size_t current = atomic_load_explicit(counter, memory_order_relaxed); + size_t next; + do { + next = (current > value) ? (current - value) : 0; + } while ( + !atomic_compare_exchange_weak_explicit(counter, ¤t, next, memory_order_relaxed, memory_order_relaxed)); +} + +//! Per size class allocation counters, updated only by the owning thread (cross-thread frees are +// deferred and accounted when the owner processes them), so plain integers suffice +typedef struct heap_size_use_t { + int32_t alloc_current; + int32_t alloc_peak; + int32_t alloc_total; + int32_t free_total; +} heap_size_use_t; + +//! A successful allocation of the given size class on the owning heap +#define _rpmalloc_stat_inc_alloc(heap, class_idx) \ + do { \ + heap_size_use_t* _su = (heap)->size_use + (class_idx); \ + if (++_su->alloc_current > _su->alloc_peak) \ + _su->alloc_peak = _su->alloc_current; \ + ++_su->alloc_total; \ + } while (0) +//! Account for a number of freed blocks of the given size class on the owning heap +#define _rpmalloc_stat_add_free(heap, class_idx, count) \ + do { \ + heap_size_use_t* _su = (heap)->size_use + (class_idx); \ + _su->alloc_current -= (int32_t)(count); \ + _su->free_total += (int32_t)(count); \ + } while (0) +//! A raw memory map call for a span of the given page type on the owning heap +#define _rpmalloc_stat_inc_span_map(heap, page_type) \ + do { \ + ++(heap)->span_map_calls[page_type]; \ + } while (0) + +#else + +#define _rpmalloc_stat_inc_alloc(heap, class_idx) \ + do { \ + } while (0) +#define _rpmalloc_stat_add_free(heap, class_idx, count) \ + do { \ + } while (0) +#define _rpmalloc_stat_inc_span_map(heap, page_type) \ + do { \ + } while (0) + +#endif + +//////////// +/// +/// Low level abstractions +/// +////// + +static inline size_t +rpmalloc_clz(uintptr_t x) { +#if ARCH_64BIT +#if defined(_MSC_VER) && !defined(__clang__) +#if defined(_M_ARM64) + return (size_t)_CountLeadingZeros64(x); // __lzcnt64 is x86-only +#else + return (size_t)__lzcnt64(x); +#endif +#else + return (size_t)__builtin_clzll(x); +#endif +#else +#if defined(_MSC_VER) && !defined(__clang__) +#if defined(_M_ARM64) || defined(_M_ARM) + return (size_t)_CountLeadingZeros((unsigned long)x); // __lzcnt32 is x86-only +#else + return (size_t)__lzcnt32(x); +#endif +#else + return (size_t)__builtin_clzl(x); +#endif +#endif +} + +//! Yield the rest of this thread's scheduling quantum so another runnable thread (e.g. a lock +//! holder that has been preempted) can run. This is a real scheduler yield, unlike the per-arch +//! CPU pause/yield hint used by wait_spin below. +static inline void +thread_yield(void) { +#if PLATFORM_WINDOWS + SwitchToThread(); +#else + sched_yield(); +#endif +} + +#ifndef WAIT_SPIN_YIELD_THRESHOLD +//! Number of cheap CPU-pause spins before wait_spin escalates to a real OS scheduler yield. +#define WAIT_SPIN_YIELD_THRESHOLD 100 +#endif + +static inline void +wait_spin(uint32_t* spin_count) { + if (++(*spin_count) >= WAIT_SPIN_YIELD_THRESHOLD) { + thread_yield(); + return; + } +#if defined(_MSC_VER) +#if defined(_M_ARM64) + __yield(); +#else + _mm_pause(); +#endif +#elif (defined(__x86_64__) || defined(__i386__)) && !defined(_M_ARM64EC) + __asm__ volatile("pause" ::: "memory"); +#elif defined(__aarch64__) || (defined(__arm__) && __ARM_ARCH >= 7) || defined(_M_ARM64EC) + __asm__ volatile("yield" ::: "memory"); +#elif defined(__powerpc__) || defined(__powerpc64__) + // No idea if ever been compiled in such archs but ... as precaution + __asm__ volatile("or 27,27,27"); +#elif defined(__sparc__) + __asm__ volatile("rd %ccr, %g0 \n\trd %ccr, %g0 \n\trd %ccr, %g0"); +#else + struct timespec ts = {0}; + nanosleep(&ts, 0); +#endif +} + +#if defined(__GNUC__) || defined(__clang__) + +#define EXPECTED(x) __builtin_expect((x), 1) +#define UNEXPECTED(x) __builtin_expect((x), 0) + +#else + +#define EXPECTED(x) x +#define UNEXPECTED(x) x + +#endif + +#if defined(__GNUC__) || defined(__clang__) +#ifdef __has_builtin +#if __has_builtin(__builtin_memcpy_inline) +#define memcpy_const(x, y, s) __builtin_memcpy_inline(x, y, s) +#else +#define memcpy_const(x, y, s) \ + do { \ + _Static_assert(__builtin_choose_expr(__builtin_constant_p(s), 1, 0), "len must be a constant integer"); \ + memcpy(x, y, s); \ + } while (0) +#endif + +#if __has_builtin(__builtin_memset_inline) +#define memset_const(x, y, s) __builtin_memset_inline(x, y, s) +#else +#define memset_const(x, y, s) \ + do { \ + _Static_assert(__builtin_choose_expr(__builtin_constant_p(s), 1, 0), "len must be a constant integer"); \ + memset(x, y, s); \ + } while (0) +#endif +#endif +#endif + +#ifndef memcpy_const +#define memcpy_const(x, y, s) memcpy(x, y, s) +#define memset_const(x, y, s) memset(x, y, s) +#endif //////////// /// @@ -359,327 +484,247 @@ _Static_assert((SPAN_HEADER_SIZE & (SPAN_HEADER_SIZE - 1)) == 0, "Span header si typedef struct heap_t heap_t; //! Span of memory pages typedef struct span_t span_t; -//! Span list -typedef struct span_list_t span_list_t; -//! Span active data -typedef struct span_active_t span_active_t; -//! Size class definition +//! Memory page +typedef struct page_t page_t; +//! Memory block +typedef struct block_t block_t; +//! Size class for a memory block typedef struct size_class_t size_class_t; -//! Global cache -typedef struct global_cache_t global_cache_t; -//! Flag indicating span is the first (master) span of a split superspan -#define SPAN_FLAG_MASTER 1U -//! Flag indicating span is a secondary (sub) span of a split superspan -#define SPAN_FLAG_SUBSPAN 2U -//! Flag indicating span has blocks with increased alignment -#define SPAN_FLAG_ALIGNED_BLOCKS 4U -//! Flag indicating an unmapped master span -#define SPAN_FLAG_UNMAPPED_MASTER 8U +//! Memory page type +typedef enum page_type_t { + PAGE_SMALL, // 64KiB + PAGE_MEDIUM_SMALL, // 1MiB + PAGE_MEDIUM_LARGE, // 4MiB + PAGE_LARGE, // 16MiB + PAGE_HUGE +} page_type_t; -#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS -struct span_use_t { - //! Current number of spans used (actually used, not in cache) - atomic32_t current; - //! High water mark of spans used - atomic32_t high; -#if ENABLE_STATISTICS - //! Number of spans in deferred list - atomic32_t spans_deferred; - //! Number of spans transitioned to global cache - atomic32_t spans_to_global; - //! Number of spans transitioned from global cache - atomic32_t spans_from_global; - //! Number of spans transitioned to thread cache - atomic32_t spans_to_cache; - //! Number of spans transitioned from thread cache - atomic32_t spans_from_cache; - //! Number of spans transitioned to reserved state - atomic32_t spans_to_reserved; - //! Number of spans transitioned from reserved state - atomic32_t spans_from_reserved; - //! Number of raw memory map calls - atomic32_t spans_map_calls; -#endif -}; -typedef struct span_use_t span_use_t; -#endif - -#if ENABLE_STATISTICS -struct size_class_use_t { - //! Current number of allocations - atomic32_t alloc_current; - //! Peak number of allocations - int32_t alloc_peak; - //! Total number of allocations - atomic32_t alloc_total; - //! Total number of frees - atomic32_t free_total; - //! Number of spans in use - atomic32_t spans_current; - //! Number of spans transitioned to cache - int32_t spans_peak; - //! Number of spans transitioned to cache - atomic32_t spans_to_cache; - //! Number of spans transitioned from cache - atomic32_t spans_from_cache; - //! Number of spans transitioned from reserved state - atomic32_t spans_from_reserved; - //! Number of spans mapped - atomic32_t spans_map_calls; - int32_t unused; -}; -typedef struct size_class_use_t size_class_use_t; -#endif - -// A span can either represent a single span of memory pages with size declared by span_map_count configuration variable, -// or a set of spans in a continuous region, a super span. Any reference to the term "span" usually refers to both a single -// span or a super span. A super span can further be divided into multiple spans (or this, super spans), where the first -// (super)span is the master and subsequent (super)spans are subspans. The master span keeps track of how many subspans -// that are still alive and mapped in virtual memory, and once all subspans and master have been unmapped the entire -// superspan region is released and unmapped (on Windows for example, the entire superspan range has to be released -// in the same call to release the virtual memory range, but individual subranges can be decommitted individually -// to reduce physical memory use). -struct span_t { - //! Free list - void* free_list; - //! Total block count of size class - uint32_t block_count; - //! Size class - uint32_t size_class; - //! Index of last block initialized in free list - uint32_t free_list_limit; - //! Number of used blocks remaining when in partial state - uint32_t used_count; - //! Deferred free list - atomicptr_t free_list_deferred; - //! Size of deferred free list, or list of spans when part of a cache list - uint32_t list_size; - //! Size of a block - uint32_t block_size; - //! Flags and counters - uint32_t flags; - //! Number of spans - uint32_t span_count; - //! Total span counter for master spans - uint32_t total_spans; - //! Offset from master span for subspans - uint32_t offset_from_master; - //! Remaining span counter, for master spans - atomic32_t remaining_spans; - //! Alignment offset - uint32_t align_offset; - //! Owning heap - heap_t* heap; - //! Next span - span_t* next; - //! Previous span - span_t* prev; -}; -_Static_assert(sizeof(span_t) <= SPAN_HEADER_SIZE, "span size mismatch"); - -struct span_cache_t { - size_t count; - span_t* span[MAX_THREAD_SPAN_CACHE]; -}; -typedef struct span_cache_t span_cache_t; - -struct span_large_cache_t { - size_t count; - span_t* span[MAX_THREAD_SPAN_LARGE_CACHE]; -}; -typedef struct span_large_cache_t span_large_cache_t; - -struct heap_size_class_t { - //! Free list of active span - void* free_list; - //! Double linked list of partially used spans with free blocks. - // Previous span pointer in head points to tail span of list. - span_t* partial_span; - //! Early level cache of fully free spans - span_t* cache; -}; -typedef struct heap_size_class_t heap_size_class_t; - -// Control structure for a heap, either a thread heap or a first class heap if enabled -struct heap_t { - //! Owning thread ID - uintptr_t owner_thread; - //! Free lists for each size class - heap_size_class_t size_class[SIZE_CLASS_COUNT]; -#if ENABLE_THREAD_CACHE - //! Arrays of fully freed spans, single span - span_cache_t span_cache; -#endif - //! List of deferred free spans (single linked list) - atomicptr_t span_free_deferred; - //! Number of full spans - size_t full_span_count; - //! Mapped but unused spans - span_t* span_reserve; - //! Master span for mapped but unused spans - span_t* span_reserve_master; - //! Number of mapped but unused spans - uint32_t spans_reserved; - //! Child count - atomic32_t child_count; - //! Next heap in id list - heap_t* next_heap; - //! Next heap in orphan list - heap_t* next_orphan; - //! Heap ID - int32_t id; - //! Finalization state flag - int finalize; - //! Master heap owning the memory pages - heap_t* master_heap; -#if ENABLE_THREAD_CACHE - //! Arrays of fully freed spans, large spans with > 1 span count - span_large_cache_t span_large_cache[LARGE_CLASS_COUNT - 1]; -#endif -#if RPMALLOC_FIRST_CLASS_HEAPS - //! Double linked list of fully utilized spans with free blocks for each size class. - // Previous span pointer in head points to tail span of list. - span_t* full_span[SIZE_CLASS_COUNT]; - //! Double linked list of large and huge spans allocated by this heap - span_t* large_huge_span; -#endif -#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS - //! Current and high water mark of spans used per span count - span_use_t span_use[LARGE_CLASS_COUNT]; -#endif -#if ENABLE_STATISTICS - //! Allocation stats per size class - size_class_use_t size_class_use[SIZE_CLASS_COUNT + 1]; - //! Number of bytes transitioned thread -> global - atomic64_t thread_to_global; - //! Number of bytes transitioned global -> thread - atomic64_t global_to_thread; -#endif -}; - -// Size class for defining a block size bucket +//! Block size class struct size_class_t { //! Size of blocks in this class uint32_t block_size; //! Number of blocks in each chunk - uint16_t block_count; - //! Class index this class is merged with - uint16_t class_idx; + uint32_t block_count; }; -_Static_assert(sizeof(size_class_t) == 8, "Size class size mismatch"); -struct global_cache_t { - //! Cache lock - atomic32_t lock; - //! Cache count - uint32_t count; -#if ENABLE_STATISTICS - //! Insert count - size_t insert_count; - //! Extract count - size_t extract_count; -#endif - //! Cached spans - span_t* span[GLOBAL_CACHE_MULTIPLIER * MAX_THREAD_SPAN_CACHE]; - //! Unlimited cache overflow - span_t* overflow; +//! A memory block +struct block_t { + //! Next block in list + block_t* next; }; +//! A page contains blocks of a given size +struct page_t { + //! Size class of blocks + uint32_t size_class; + //! Block size + uint32_t block_size; + //! Block count + uint32_t block_count; + //! Block initialized count + uint32_t block_initialized; + //! Block used count + uint32_t block_used; + //! Page type + page_type_t page_type; + //! Flag set if part of heap full list + uint32_t is_full : 1; + //! Flag set if part of heap free list + uint32_t is_free : 1; + //! Flag set if blocks are zero initialied + uint32_t is_zero : 1; + //! Flag set if memory pages have been decommitted + uint32_t is_decommitted : 1; + //! Flag set if containing aligned blocks. + // Note: has_aligned_block and is_full are read on the cross-thread free path while the + // owner thread writes this packed flag word. The owner is the sole writer and the word is + // naturally aligned (hardware-atomic access), and the read flags are monotonic/tolerant, + // so the read/write race is benign. ThreadSanitizer still reports it; see + // test/tsan-suppressions.txt. + uint32_t has_aligned_block : 1; + //! Fast combination flag for either huge, fully allocated or has aligned blocks + uint32_t generic_free : 1; + //! Set if the span maps reserve-only (pages commit on demand, may be decommitted), + // captured at map time so it survives a config change across a finalize/initialize + uint32_t commit_on_demand : 1; + //! log2 of the committed prefix (the page size at the span's map time) + uint32_t commit_prefix_shift : 6; + //! Local free list count + uint32_t local_free_count; + //! Local free list + block_t* local_free; + //! Owning heap + heap_t* heap; + //! Next page in list + page_t* next; + //! Previous page in list + page_t* prev; + //! Multithreaded free list, block index is in low 32 bit, list count is high 32 bit + atomic_ullong thread_free; +}; + +//! A span contains pages of a given type +struct span_t { + //! Page header + page_t page; + //! Owning heap (do not deduplicate into page.heap - that field is the + //! owner of page 0 as a memory page and changes if the page is adopted + //! by another heap, while the span owner must remain stable) + heap_t* heap; + //! Page address mask + uintptr_t page_address_mask; + //! Number of pages initialized + uint32_t page_initialized; + //! Number of pages in use + uint32_t page_count; + //! Number of bytes per page + uint32_t page_size; + //! Page type + page_type_t page_type; + //! Offset to start of mapped memory region + uint32_t offset; + //! Mapped size + uint64_t mapped_size; + //! Next span in list + span_t* next; +}; + +// Control structure for a heap, either a thread heap or a first class heap if enabled +struct heap_t { + //! Owning thread ID + uintptr_t owner_thread; + //! Heap local free list for small size classes + block_t* local_free[SIZE_CLASS_COUNT]; + //! Available non-full pages for each size class + page_t* page_available[SIZE_CLASS_COUNT]; + //! Free pages for each page type + page_t* page_free[4]; + //! Free but still committed page count for each page tyoe + uint32_t page_free_commit_count[4]; + //! Multithreaded free list + atomic_uintptr_t thread_free[4]; + //! Available partially initialized spans for each page type + span_t* span_partial[4]; + //! Spans in full use for each page type + span_t* span_used[5]; + //! Next heap in queue + heap_t* next; + //! Previous heap in queue + heap_t* prev; + //! Heap ID + uint32_t id; + //! Finalization state flag + uint32_t finalize; + //! Memory map region offset + uint32_t offset; + //! Memory map size + size_t mapped_size; +#if RPMALLOC_HEAP_STATISTICS + struct rpmalloc_heap_statistics_t stats; +#endif +#if ENABLE_STATISTICS + //! Per size class allocation counters (current span_use count is computed live on demand) + heap_size_use_t size_use[SIZE_CLASS_COUNT]; + //! Per page type raw span map call counters + uint32_t span_map_calls[5]; +#endif +}; + +_Static_assert(sizeof(page_t) <= PAGE_HEADER_SIZE, "Invalid page header size"); +_Static_assert(sizeof(span_t) <= SPAN_HEADER_SIZE, "Invalid span header size"); +_Static_assert(sizeof(heap_t) <= 4096, "Invalid heap size"); + //////////// /// /// Global data /// ////// -//! Default span size (64KiB) -#define _memory_default_span_size (64 * 1024) -#define _memory_default_span_size_shift 16 -#define _memory_default_span_mask (~((uintptr_t)(_memory_span_size - 1))) - -//! Initialized flag -static int _rpmalloc_initialized; -//! Main thread ID -static uintptr_t _rpmalloc_main_thread_id; -//! Configuration -static rpmalloc_config_t _memory_config; -//! Memory page size -static size_t _memory_page_size; -//! Shift to divide by page size -static size_t _memory_page_size_shift; -//! Granularity at which memory pages are mapped by OS -static size_t _memory_map_granularity; -#if RPMALLOC_CONFIGURABLE -//! Size of a span of memory pages -static size_t _memory_span_size; -//! Shift to divide by span size -static size_t _memory_span_size_shift; -//! Mask to get to start of a memory span -static uintptr_t _memory_span_mask; -#else -//! Hardwired span size -#define _memory_span_size _memory_default_span_size -#define _memory_span_size_shift _memory_default_span_size_shift -#define _memory_span_mask _memory_default_span_mask -#endif -//! Number of spans to map in each map call -static size_t _memory_span_map_count; -//! Number of spans to keep reserved in each heap -static size_t _memory_heap_reserve_count; -//! Global size classes -static size_class_t _memory_size_class[SIZE_CLASS_COUNT]; -//! Run-time size limit of medium blocks -static size_t _memory_medium_size_limit; +//! Fallback heap +static RPMALLOC_CACHE_ALIGNED heap_t global_heap_fallback; +//! Default heap +static heap_t* global_heap_default = &global_heap_fallback; +//! Released heaps available for reuse. These have been used and may hold caches, so they are +// only handed to ordinary thread heaps, never to first-class heaps (which require pristine state) +static heap_t* global_heap_queue; +//! Pristine, never-used heaps carved from a shared block but not yet handed out. Safe for any +// request including first-class, which needs a heap with no prior allocations +static heap_t* global_heap_pristine; +//! In use heaps +static heap_t* global_heap_used; +//! Set while a thread is mapping and carving a new shared heap block, so concurrent thread +// starts wait for the carved heaps to reach a pool instead of each mapping their own block. +// A user memory interface callback must not allocate through rpmalloc on the creating thread: +// a nested heap creation would wait on this flag set by the same thread and deadlock +static int global_heap_creating; +//! Lock for heap queue +static atomic_uintptr_t global_heap_lock; //! Heap ID counter -static atomic32_t _memory_heap_id; -//! Huge page support -static int _memory_huge_pages; -#if ENABLE_GLOBAL_CACHE -//! Global span cache -static global_cache_t _memory_span_cache[LARGE_CLASS_COUNT]; -#endif -//! Global reserved spans -static span_t* _memory_global_reserve; -//! Global reserved count -static size_t _memory_global_reserve_count; -//! Global reserved master -static span_t* _memory_global_reserve_master; -//! All heaps -static heap_t* _memory_heaps[HEAP_ARRAY_SIZE]; -//! Used to restrict access to mapping memory for huge pages -static atomic32_t _memory_global_lock; -//! Orphaned heaps -static heap_t* _memory_orphan_heaps; -#if RPMALLOC_FIRST_CLASS_HEAPS -//! Orphaned heaps (first class heaps) -static heap_t* _memory_first_class_orphan_heaps; -#endif -#if ENABLE_STATISTICS -//! Allocations counter -static atomic64_t _allocation_counter; -//! Deallocations counter -static atomic64_t _deallocation_counter; -//! Active heap count -static atomic32_t _memory_active_heaps; -//! Number of currently mapped memory pages -static atomic32_t _mapped_pages; -//! Peak number of concurrently mapped memory pages -static int32_t _mapped_pages_peak; -//! Number of mapped master spans -static atomic32_t _master_spans; -//! Number of unmapped dangling master spans -static atomic32_t _unmapped_master_spans; -//! Running counter of total number of mapped memory pages since start -static atomic32_t _mapped_total; -//! Running counter of total number of unmapped memory pages since start -static atomic32_t _unmapped_total; -//! Number of currently mapped memory pages in OS calls -static atomic32_t _mapped_pages_os; -//! Number of currently allocated pages in huge allocations -static atomic32_t _huge_pages_current; -//! Peak number of currently allocated pages in huge allocations -static int32_t _huge_pages_peak; -#endif +static atomic_uint global_heap_id = 1; +//! Global initialization state. rpmalloc_initialize can be called concurrently from multiple +//! threads (the first allocation on any thread may trigger it), so it is driven as an atomic +//! state machine: exactly one thread performs the global setup while the others wait for it to +//! complete before allocating - they must never observe, or allocate against, a partially +//! written global_config. Release/acquire ordering on the DONE transition publishes all of the +//! global_config writes to threads that observe completion. +#define RPMALLOC_INIT_UNINIT 0 +#define RPMALLOC_INIT_RUNNING 1 +#define RPMALLOC_INIT_DONE 2 +static atomic_int global_rpmalloc_init_state; +//! Memory interface +static rpmalloc_interface_t* global_memory_interface; +//! Default memory interface +static rpmalloc_interface_t global_memory_interface_default; +//! Current configuration +static rpmalloc_config_t global_config = {0}; +//! Main thread ID +static uintptr_t global_main_thread_id; + +//! Size classes +#define SCLASS(n) \ + { (n * SMALL_GRANULARITY), (SMALL_PAGE_SIZE - PAGE_HEADER_SIZE) / (n * SMALL_GRANULARITY) } +#define MSCLASS(n) \ + { (n * SMALL_GRANULARITY), (MEDIUM_SMALL_PAGE_SIZE - PAGE_HEADER_SIZE) / (n * SMALL_GRANULARITY) } +#define MLCLASS(n) \ + { (n * SMALL_GRANULARITY), (MEDIUM_LARGE_PAGE_SIZE - PAGE_HEADER_SIZE) / (n * SMALL_GRANULARITY) } +#define LCLASS(n) \ + { (n * SMALL_GRANULARITY), (LARGE_PAGE_SIZE - PAGE_HEADER_SIZE) / (n * SMALL_GRANULARITY) } +static const size_class_t global_size_class[SIZE_CLASS_COUNT] = { + SCLASS(1), SCLASS(1), SCLASS(2), SCLASS(3), SCLASS(4), SCLASS(5), SCLASS(6), + SCLASS(7), SCLASS(8), SCLASS(9), SCLASS(10), SCLASS(11), SCLASS(12), SCLASS(13), + SCLASS(14), SCLASS(15), SCLASS(16), SCLASS(17), SCLASS(18), SCLASS(19), SCLASS(20), + SCLASS(21), SCLASS(22), SCLASS(23), SCLASS(24), SCLASS(25), SCLASS(26), SCLASS(27), + SCLASS(28), SCLASS(29), SCLASS(30), SCLASS(31), SCLASS(32), SCLASS(33), SCLASS(34), + SCLASS(35), SCLASS(36), SCLASS(37), SCLASS(38), SCLASS(39), SCLASS(40), SCLASS(41), + SCLASS(42), SCLASS(43), SCLASS(44), SCLASS(45), SCLASS(46), SCLASS(47), SCLASS(48), + SCLASS(49), SCLASS(50), SCLASS(51), SCLASS(52), SCLASS(53), SCLASS(54), SCLASS(55), + SCLASS(56), SCLASS(57), SCLASS(58), SCLASS(59), SCLASS(60), SCLASS(61), SCLASS(62), + SCLASS(63), SCLASS(64), SCLASS(80), SCLASS(96), SCLASS(112), SCLASS(128), SCLASS(160), + SCLASS(192), SCLASS(224), SCLASS(256), MSCLASS(320), MSCLASS(384), MSCLASS(448), MSCLASS(512), + MSCLASS(640), MSCLASS(768), MSCLASS(896), MSCLASS(1024), MSCLASS(1280), MSCLASS(1536), MSCLASS(1792), + MSCLASS(2048), MLCLASS(2560), MLCLASS(3072), MLCLASS(3584), MLCLASS(4096), MLCLASS(5120), MLCLASS(6144), + MLCLASS(7168), MLCLASS(8192), MLCLASS(10240), MLCLASS(12288), MLCLASS(14336), MLCLASS(16384), LCLASS(20480), + LCLASS(24576), LCLASS(28672), LCLASS(32768), LCLASS(40960), LCLASS(49152), LCLASS(57344), LCLASS(65536), + LCLASS(81920), LCLASS(98304), LCLASS(114688), LCLASS(131072)}; + +//! Threshold number of pages for when free pages are decommitted +static uint32_t global_page_free_overflow[5] = {16, 8, 4, 2, 0}; + +//! Number of pages to retain when free page threshold overflows +static uint32_t global_page_free_retain[5] = {4, 2, 1, 1, 0}; + +//! OS huge page support +static int os_huge_pages; +//! OS transparent huge page support (advise mappings to be huge page backed without +//! requiring a preallocated huge page pool, currently Linux/Android only) +static int os_thp; +//! Shift for the huge page size (log2 of huge page size when huge pages are enabled) +static size_t os_huge_page_shift; +//! OS memory map granularity +static size_t os_map_granularity; +//! OS memory page size +static size_t os_page_size; //////////// /// @@ -687,1468 +732,1571 @@ static int32_t _huge_pages_peak; /// ////// -//! Get thread heap -static inline heap_t* get_thread_heap_raw(void); +static heap_t* +heap_allocate(int first_class); + +static void +heap_page_free_decommit(heap_t* heap, uint32_t page_type, uint32_t page_retain_count); + +static inline heap_t* +get_thread_heap_raw(void); + +static inline uintptr_t +get_thread_id(void); + +static void +set_thread_heap(heap_t* heap); + +static heap_t* +get_thread_heap_allocate(void) { + heap_t* heap = heap_allocate(0); + set_thread_heap(heap); + return heap; +} //! Get the current thread heap static inline heap_t* get_thread_heap(void) { - heap_t* heap = get_thread_heap_raw(); -#if ENABLE_PRELOAD - if (EXPECTED(heap != 0)) - return heap; - rpmalloc_initialize(); return get_thread_heap_raw(); +} + +//! Get the size class from given size in bytes for tiny blocks (below 16 times the minimum granularity) +static inline uint32_t +get_size_class_tiny(size_t size) { + return (((uint32_t)size + (SMALL_GRANULARITY - 1)) / SMALL_GRANULARITY); +} + +//! Get the size class from given size in bytes +static inline uint32_t +get_size_class(size_t size) { + uintptr_t minblock_count = (size + (SMALL_GRANULARITY - 1)) / SMALL_GRANULARITY; + // For sizes up to 64 times the minimum granularity (i.e 1024 bytes) the size class is equal to number of such + // blocks + if (size <= (SMALL_GRANULARITY * 64)) { + rpmalloc_assert(global_size_class[minblock_count].block_size >= size, "Size class misconfiguration"); + return (uint32_t)(minblock_count ? minblock_count : 1); + } + --minblock_count; + // Calculate position of most significant bit, since minblock_count now guaranteed to be > 64 this position is + // guaranteed to be >= 6 +#if ARCH_64BIT + const uint32_t most_significant_bit = (uint32_t)(63 - (int)rpmalloc_clz(minblock_count)); #else - return heap; + const uint32_t most_significant_bit = (uint32_t)(31 - (int)rpmalloc_clz(minblock_count)); #endif + // Class sizes are of the bit format [..]000xxx000[..] where we already have the position of the most significant + // bit, now calculate the subclass from the remaining two bits + const uint32_t subclass_bits = (minblock_count >> (most_significant_bit - 2)) & 0x03; + const uint32_t class_idx = (uint32_t)((most_significant_bit << 2) + subclass_bits) + 41; + rpmalloc_assert((class_idx >= SIZE_CLASS_COUNT) || (global_size_class[class_idx].block_size >= size), + "Size class misconfiguration"); + rpmalloc_assert((class_idx >= SIZE_CLASS_COUNT) || (global_size_class[class_idx - 1].block_size < size), + "Size class misconfiguration"); + return class_idx; } -//! Fast thread ID -static inline uintptr_t get_thread_id(void); - -//! Set the current thread heap -static void set_thread_heap(heap_t* heap); - -//! Set main thread ID -static void -rpmalloc_set_main_thread(void) { - _rpmalloc_main_thread_id = get_thread_id(); +static inline page_type_t +get_page_type(uint32_t size_class) { + if (size_class < SMALL_SIZE_CLASS_COUNT) + return PAGE_SMALL; + else if (size_class < (SMALL_SIZE_CLASS_COUNT + MEDIUM_SMALL_SIZE_CLASS_COUNT)) + return PAGE_MEDIUM_SMALL; + else if (size_class < (SMALL_SIZE_CLASS_COUNT + MEDIUM_SMALL_SIZE_CLASS_COUNT + MEDIUM_LARGE_SIZE_CLASS_COUNT)) + return PAGE_MEDIUM_LARGE; + else if (size_class < SIZE_CLASS_COUNT) + return PAGE_LARGE; + return PAGE_HUGE; } -static void -_rpmalloc_spin(void) { -#if defined(_MSC_VER) - _mm_pause(); -#elif defined(__x86_64__) || defined(__i386__) - __asm__ volatile("pause" ::: "memory"); -#elif defined(__aarch64__) || (defined(__arm__) && __ARM_ARCH >= 7) - __asm__ volatile("yield" ::: "memory"); -#elif defined(__powerpc__) || defined(__powerpc64__) - // No idea if ever been compiled in such archs but ... as precaution - __asm__ volatile("or 27,27,27"); -#elif defined(__sparc__) - __asm__ volatile("rd %ccr, %g0 \n\trd %ccr, %g0 \n\trd %ccr, %g0"); -#else - struct timespec ts = {0}; - nanosleep(&ts, 0); -#endif +static inline size_t +get_page_aligned_size(size_t size) { + size_t unalign = size % global_config.page_size; + if (unalign) + size += global_config.page_size - unalign; + return size; } -#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK) -static void NTAPI -_rpmalloc_thread_destructor(void* value) { -#if ENABLE_OVERRIDE - // If this is called on main thread it means rpmalloc_finalize - // has not been called and shutdown is forced (through _exit) or unclean - if (get_thread_id() == _rpmalloc_main_thread_id) - return; -#endif - if (value) - rpmalloc_thread_finalize(1); -} -#endif - - //////////// /// -/// Low level memory map/unmap +/// OS entry points /// ////// -//! Map more virtual memory -// size is number of bytes to map -// offset receives the offset in bytes from start of mapped region -// returns address to start of mapped region to use -static void* -_rpmalloc_mmap(size_t size, size_t* offset) { - rpmalloc_assert(!(size % _memory_page_size), "Invalid mmap size"); - rpmalloc_assert(size >= _memory_page_size, "Invalid mmap size"); - void* address = _memory_config.memory_map(size, offset); - if (EXPECTED(address != 0)) { - _rpmalloc_stat_add_peak(&_mapped_pages, (size >> _memory_page_size_shift), _mapped_pages_peak); - _rpmalloc_stat_add(&_mapped_total, (size >> _memory_page_size_shift)); - } - return address; -} - -//! Unmap virtual memory -// address is the memory address to unmap, as returned from _memory_map -// size is the number of bytes to unmap, which might be less than full region for a partial unmap -// offset is the offset in bytes to the actual mapped region, as set by _memory_map -// release is set to 0 for partial unmap, or size of entire range for a full unmap static void -_rpmalloc_unmap(void* address, size_t size, size_t offset, size_t release) { - rpmalloc_assert(!release || (release >= size), "Invalid unmap size"); - rpmalloc_assert(!release || (release >= _memory_page_size), "Invalid unmap size"); - if (release) { - rpmalloc_assert(!(release % _memory_page_size), "Invalid unmap size"); - _rpmalloc_stat_sub(&_mapped_pages, (release >> _memory_page_size_shift)); - _rpmalloc_stat_add(&_unmapped_total, (release >> _memory_page_size_shift)); - } - _memory_config.memory_unmap(address, size, offset, release); +os_set_page_name(void* address, size_t size) { +#if defined(__linux__) || defined(__ANDROID__) + const char* name = os_huge_pages ? global_config.huge_page_name : global_config.page_name; + if ((address == MAP_FAILED) || !name) + return; + // If the kernel does not support CONFIG_ANON_VMA_NAME or if the call fails + // (e.g. invalid name) it is a no-op basically. + (void)prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, (uintptr_t)address, size, (uintptr_t)name); +#else + (void)sizeof(size); + (void)sizeof(address); +#endif } -//! Default implementation to map new pages to virtual memory static void* -_rpmalloc_mmap_os(size_t size, size_t* offset) { - //Either size is a heap (a single page) or a (multiple) span - we only need to align spans, and only if larger than map granularity - size_t padding = ((size >= _memory_span_size) && (_memory_span_size > _memory_map_granularity)) ? _memory_span_size : 0; - rpmalloc_assert(size >= _memory_page_size, "Invalid mmap size"); +os_mmap(size_t size, size_t alignment, size_t* offset, size_t* mapped_size) { + size_t map_size = size + alignment; #if PLATFORM_WINDOWS - //Ok to MEM_COMMIT - according to MSDN, "actual physical pages are not allocated unless/until the virtual addresses are actually accessed" - void* ptr = VirtualAlloc(0, size + padding, (_memory_huge_pages ? MEM_LARGE_PAGES : 0) | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!ptr) { - if (_memory_config.map_fail_callback) { - if (_memory_config.map_fail_callback(size + padding)) - return _rpmalloc_mmap_os(size, offset); - } else { - rpmalloc_assert(ptr, "Failed to map virtual memory block"); - } - return 0; + // Ok to MEM_COMMIT - according to MSDN, "actual physical pages are not allocated unless/until the virtual addresses + // are actually accessed". But if we enable decommit it's better to not immediately commit and instead commit per + // page to avoid saturating the OS commit limit +#if ENABLE_DECOMMIT + DWORD do_commit = 0; + if (global_config.disable_decommit) + do_commit = MEM_COMMIT; +#else + DWORD do_commit = MEM_COMMIT; +#endif + const DWORD base_flags = MEM_RESERVE | do_commit; + const DWORD large_flag = (os_huge_pages ? MEM_LARGE_PAGES : 0); + void* ptr = 0; + if (alignment && os_virtualalloc2) { + // Map an aligned region directly so no alignment padding is retained per mapping + MEM_ADDRESS_REQUIREMENTS reqs; + memset(&reqs, 0, sizeof(reqs)); + reqs.Alignment = alignment; + MEM_EXTENDED_PARAMETER param; + memset(¶m, 0, sizeof(param)); + param.Type = MemExtendedParameterAddressRequirements; + param.Pointer = &reqs; + map_size = size; + ptr = os_virtualalloc2(0, 0, map_size, large_flag | base_flags, PAGE_READWRITE, ¶m, 1); + if (!ptr && large_flag) + ptr = os_virtualalloc2(0, 0, map_size, base_flags, PAGE_READWRITE, ¶m, 1); + } else { + // Pre Windows 10: over-allocate and offset for alignment below + ptr = VirtualAlloc(0, map_size, large_flag | base_flags, PAGE_READWRITE); + if (!ptr && large_flag) + ptr = VirtualAlloc(0, map_size, base_flags, PAGE_READWRITE); } #else int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_UNINITIALIZED; -# if defined(__APPLE__) && !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR +#if defined(__APPLE__) && !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR int fd = (int)VM_MAKE_TAG(240U); - if (_memory_huge_pages) + if (os_huge_pages) fd |= VM_FLAGS_SUPERPAGE_SIZE_2MB; - void* ptr = mmap(0, size + padding, PROT_READ | PROT_WRITE, flags, fd, 0); -# elif defined(MAP_HUGETLB) - void* ptr = mmap(0, size + padding, PROT_READ | PROT_WRITE | PROT_MAX(PROT_READ | PROT_WRITE), (_memory_huge_pages ? MAP_HUGETLB : 0) | flags, -1, 0); -# if defined(MADV_HUGEPAGE) + void* ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, flags, fd, 0); + if (((ptr == MAP_FAILED) || !ptr) && os_huge_pages) { + // Superpage allocations can fail due to physical memory fragmentation, + // fall back to regular pages + ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, flags, (int)VM_MAKE_TAG(240U), 0); + } +#elif defined(MAP_HUGETLB) + int huge_flags = 0; + if (os_huge_pages) { + huge_flags = MAP_HUGETLB; +#if defined(MAP_HUGE_SHIFT) + // Explicitly request the detected huge page size, the system default huge + // page size can be a different (unusable) size like 1GiB + if (os_huge_page_shift) + huge_flags |= (int)(os_huge_page_shift << MAP_HUGE_SHIFT); +#endif + } + void* ptr = + mmap(0, map_size, PROT_READ | PROT_WRITE | PROT_MAX(PROT_READ | PROT_WRITE), huge_flags | flags, -1, 0); +#if defined(MADV_HUGEPAGE) // In some configurations, huge pages allocations might fail thus // we fallback to normal allocations and promote the region as transparent huge page - if ((ptr == MAP_FAILED || !ptr) && _memory_huge_pages) { - ptr = mmap(0, size + padding, PROT_READ | PROT_WRITE, flags, -1, 0); - if (ptr && ptr != MAP_FAILED) { - int prm = madvise(ptr, size + padding, MADV_HUGEPAGE); - (void)prm; - rpmalloc_assert((prm == 0), "Failed to promote the page to THP"); + if ((ptr == MAP_FAILED || !ptr) && os_huge_pages) { + ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, flags, -1, 0); + if (ptr && (ptr != MAP_FAILED)) { + // Best-effort promotion to transparent huge pages; ignore failures (for + // example when THP is disabled system-wide, where madvise returns EINVAL). + // The mapping is still valid, just backed by normal pages. + (void)madvise(ptr, map_size, MADV_HUGEPAGE); } + } else if (os_thp && ptr && (ptr != MAP_FAILED)) { + // Transparent huge page mode, advise the kernel to back this mapping with + // huge pages without requiring a preallocated huge page pool + (void)madvise(ptr, map_size, MADV_HUGEPAGE); } -# endif -# elif defined(MAP_ALIGNED) +#endif + os_set_page_name(ptr, map_size); +#elif defined(MAP_ALIGNED) const size_t align = (sizeof(size_t) * 8) - (size_t)(__builtin_clzl(size - 1)); - void* ptr = mmap(0, size + padding, PROT_READ | PROT_WRITE, (_memory_huge_pages ? MAP_ALIGNED(align) : 0) | flags, -1, 0); -# elif defined(MAP_ALIGN) - caddr_t base = (_memory_huge_pages ? (caddr_t)(4 << 20) : 0); - void* ptr = mmap(base, size + padding, PROT_READ | PROT_WRITE, (_memory_huge_pages ? MAP_ALIGN : 0) | flags, -1, 0); -# else - void* ptr = mmap(0, size + padding, PROT_READ | PROT_WRITE, flags, -1, 0); -# endif - if ((ptr == MAP_FAILED) || !ptr) { - if (_memory_config.map_fail_callback) { - if (_memory_config.map_fail_callback(size + padding)) - return _rpmalloc_mmap_os(size, offset); - } else if (errno != ENOMEM) { - rpmalloc_assert((ptr != MAP_FAILED) && ptr, "Failed to map virtual memory block"); + void* ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, (os_huge_pages ? MAP_ALIGNED(align) : 0) | flags, -1, 0); +#elif defined(MAP_ALIGN) + caddr_t base = (os_huge_pages ? (caddr_t)(4 << 20) : 0); + void* ptr = mmap(base, map_size, PROT_READ | PROT_WRITE, (os_huge_pages ? MAP_ALIGN : 0) | flags, -1, 0); +#else + void* ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, flags, -1, 0); +#endif + if (ptr == MAP_FAILED) + ptr = 0; +#endif + if (!ptr) { + if (global_memory_interface->map_fail_callback) { + if (global_memory_interface->map_fail_callback(map_size)) + return os_mmap(size, alignment, offset, mapped_size); + } else { + rpmalloc_assert(ptr != 0, "Failed to map more virtual memory"); } return 0; } + if (alignment) { + size_t padding = ((uintptr_t)ptr & (uintptr_t)(alignment - 1)); + if (padding) + padding = alignment - padding; + rpmalloc_assert(padding <= alignment, "Internal failure in padding"); + rpmalloc_assert(!(padding % 8), "Internal failure in padding"); +#if !PLATFORM_WINDOWS + // Unmap the alignment padding head and tail to avoid holding on to unusable + // address space (and huge page reservations when using huge pages). Both the + // mmap result and the alignment are multiples of the mapping page size, so + // head and tail stay page aligned (huge page aligned for huge page mappings) + if (padding) + munmap(ptr, padding); + ptr = pointer_offset(ptr, padding); + if (alignment - padding) + munmap(pointer_offset(ptr, size), alignment - padding); + *offset = 0; + map_size = size; +#else + ptr = pointer_offset(ptr, padding); + *offset = padding; #endif - _rpmalloc_stat_add(&_mapped_pages_os, (int32_t)((size + padding) >> _memory_page_size_shift)); - if (padding) { - size_t final_padding = padding - ((uintptr_t)ptr & ~_memory_span_mask); - rpmalloc_assert(final_padding <= _memory_span_size, "Internal failure in padding"); - rpmalloc_assert(final_padding <= padding, "Internal failure in padding"); - rpmalloc_assert(!(final_padding % 8), "Internal failure in padding"); - ptr = pointer_offset(ptr, final_padding); - *offset = final_padding >> 3; } - rpmalloc_assert((size < _memory_span_size) || !((uintptr_t)ptr & ~_memory_span_mask), "Internal failure in padding"); + *mapped_size = map_size; +#if ENABLE_STATISTICS + size_t page_count = map_size / global_config.page_size; + size_t page_mapped_current = + atomic_fetch_add_explicit(&global_statistics.page_mapped, page_count, memory_order_relaxed) + page_count; + size_t page_mapped_peak = atomic_load_explicit(&global_statistics.page_mapped_peak, memory_order_relaxed); + while (page_mapped_current > page_mapped_peak) { + if (atomic_compare_exchange_weak_explicit(&global_statistics.page_mapped_peak, &page_mapped_peak, + page_mapped_current, memory_order_relaxed, memory_order_relaxed)) + break; + } +#endif return ptr; } -//! Default implementation to unmap pages from virtual memory -static void -_rpmalloc_unmap_os(void* address, size_t size, size_t offset, size_t release) { - rpmalloc_assert(release || (offset == 0), "Invalid unmap size"); - rpmalloc_assert(!release || (release >= _memory_page_size), "Invalid unmap size"); - rpmalloc_assert(size >= _memory_page_size, "Invalid unmap size"); - if (release && offset) { - offset <<= 3; - address = pointer_offset(address, -(int32_t)offset); - if ((release >= _memory_span_size) && (_memory_span_size > _memory_map_granularity)) { - //Padding is always one span size - release += _memory_span_size; - } - } -#if !DISABLE_UNMAP +//! Whether newly mapped regions are reserve-only (pages committed on demand). Mirrors the +// commit choice os_mmap makes; the single definition spans/heaps capture at map time. +static inline int +os_commit_on_demand(void) { +#if ENABLE_DECOMMIT + return global_config.disable_decommit ? 0 : 1; +#else + return 0; +#endif +} + +static int +os_mcommit(void* address, size_t size) { +#if ENABLE_DECOMMIT + // Gated by callers on the per-span commit_on_demand flag; spans committed in full at + // map time (incl. huge/large pages, which cannot be partially committed) never reach here #if PLATFORM_WINDOWS - if (!VirtualFree(address, release ? 0 : size, release ? MEM_RELEASE : MEM_DECOMMIT)) { + if (!VirtualAlloc(address, size, MEM_COMMIT, PAGE_READWRITE)) { + if (global_memory_interface->map_fail_callback && global_memory_interface->map_fail_callback(size)) + return os_mcommit(address, size); + rpmalloc_assert(0, "Failed to commit virtual memory block"); + return 1; + } +#else + /* + if (mprotect(address, size, PROT_READ | PROT_WRITE)) { + rpmalloc_assert(0, "Failed to commit virtual memory block"); + } + */ +#endif +#if ENABLE_STATISTICS + size_t page_count = size / global_config.page_size; + atomic_fetch_add_explicit(&global_statistics.page_commit, page_count, memory_order_relaxed); + size_t page_active_current = + atomic_fetch_add_explicit(&global_statistics.page_active, page_count, memory_order_relaxed) + page_count; + size_t page_active_peak = atomic_load_explicit(&global_statistics.page_active_peak, memory_order_relaxed); + while (page_active_current > page_active_peak) { + if (atomic_compare_exchange_weak_explicit(&global_statistics.page_active_peak, &page_active_peak, + page_active_current, memory_order_relaxed, memory_order_relaxed)) + break; + } +#endif +#endif + (void)sizeof(address); + (void)sizeof(size); + return 0; +} + +static int +os_mdecommit(void* address, size_t size) { +#if ENABLE_DECOMMIT + // Unlike os_mcommit, honor the live flag so the Linux fallback below can stop all + // further decommits by setting disable_decommit mid-run + if (global_config.disable_decommit) + return 1; +#if PLATFORM_WINDOWS + if (!VirtualFree(address, size, MEM_DECOMMIT)) { + rpmalloc_assert(0, "Failed to decommit virtual memory block"); + return 1; + } +#else + /* + if (mprotect(address, size, PROT_NONE)) { + rpmalloc_assert(0, "Failed to decommit virtual memory block"); + } + */ +#if defined(MADV_DONTNEED) + if (madvise(address, size, MADV_DONTNEED)) { +#elif defined(MADV_FREE_REUSABLE) + int ret; + while ((ret = madvise(address, size, MADV_FREE_REUSABLE)) == -1 && (errno == EAGAIN)) + errno = 0; + if ((ret == -1) && (errno != 0)) { +#elif defined(MADV_PAGEOUT) + if (madvise(address, size, MADV_PAGEOUT)) { +#elif defined(MADV_FREE) + if (madvise(address, size, MADV_FREE)) { +#else + if (posix_madvise(address, size, POSIX_MADV_DONTNEED)) { +#endif +#if defined(__linux__) + if (os_huge_pages) { + // MADV_DONTNEED on huge page mappings requires Linux 5.18 or later, keep + // pages committed and stop further decommit attempts + global_config.disable_decommit = 1; + return 1; + } +#endif + rpmalloc_assert(0, "Failed to decommit virtual memory block"); + return 1; + } +#endif +#if ENABLE_STATISTICS + size_t page_count = size / global_config.page_size; + atomic_fetch_add_explicit(&global_statistics.page_decommit, page_count, memory_order_relaxed); + statistics_sub_saturating(&global_statistics.page_active, page_count); +#endif +#else + (void)sizeof(address); + (void)sizeof(size); +#endif + return 0; +} + +static void +os_munmap(void* address, size_t offset, size_t mapped_size) { + (void)sizeof(mapped_size); + address = pointer_offset(address, -(int32_t)offset); +#if ENABLE_UNMAP +#if PLATFORM_WINDOWS + if (!VirtualFree(address, 0, MEM_RELEASE)) { rpmalloc_assert(0, "Failed to unmap virtual memory block"); } #else - if (release) { - if (munmap(address, release)) { - rpmalloc_assert(0, "Failed to unmap virtual memory block"); - } - } else { -#if defined(MADV_FREE_REUSABLE) - int ret; - while ((ret = madvise(address, size, MADV_FREE_REUSABLE)) == -1 && (errno == EAGAIN)) - errno = 0; - if ((ret == -1) && (errno != 0)) { -#elif defined(MADV_DONTNEED) - if (madvise(address, size, MADV_DONTNEED)) { -#elif defined(MADV_PAGEOUT) - if (madvise(address, size, MADV_PAGEOUT)) { -#elif defined(MADV_FREE) - if (madvise(address, size, MADV_FREE)) { -#else - if (posix_madvise(address, size, POSIX_MADV_DONTNEED)) { + if (munmap(address, mapped_size)) + rpmalloc_assert(0, "Failed to unmap virtual memory block"); #endif - rpmalloc_assert(0, "Failed to madvise virtual memory block as free"); - } - } +#if ENABLE_STATISTICS + size_t page_count = mapped_size / global_config.page_size; + statistics_sub_saturating(&global_statistics.page_mapped, page_count); + statistics_sub_saturating(&global_statistics.page_active, page_count); #endif #endif - if (release) - _rpmalloc_stat_sub(&_mapped_pages_os, release >> _memory_page_size_shift); } -static void -_rpmalloc_span_mark_as_subspan_unless_master(span_t* master, span_t* subspan, size_t span_count); +//////////// +/// +/// Page interface +/// +////// -//! Use global reserved spans to fulfill a memory map request (reserve size must be checked by caller) -static span_t* -_rpmalloc_global_get_reserved_spans(size_t span_count) { - span_t* span = _memory_global_reserve; - _rpmalloc_span_mark_as_subspan_unless_master(_memory_global_reserve_master, span, span_count); - _memory_global_reserve_count -= span_count; - if (_memory_global_reserve_count) - _memory_global_reserve = (span_t*)pointer_offset(span, span_count << _memory_span_size_shift); +static inline span_t* +page_get_span(page_t* page) { + return (span_t*)((uintptr_t)page & SPAN_MASK); +} + +static inline size_t +page_get_size(page_t* page) { + if (page->page_type == PAGE_SMALL) + return SMALL_PAGE_SIZE; + else if (page->page_type == PAGE_MEDIUM_SMALL) + return MEDIUM_SMALL_PAGE_SIZE; + else if (page->page_type == PAGE_MEDIUM_LARGE) + return MEDIUM_LARGE_PAGE_SIZE; + else if (page->page_type == PAGE_LARGE) + return LARGE_PAGE_SIZE; else - _memory_global_reserve = 0; - return span; + return page_get_span(page)->page_size; } -//! Store the given spans as global reserve (must only be called from within new heap allocation, not thread safe) -static void -_rpmalloc_global_set_reserved_spans(span_t* master, span_t* reserve, size_t reserve_span_count) { - _memory_global_reserve_master = master; - _memory_global_reserve_count = reserve_span_count; - _memory_global_reserve = reserve; +static inline int +page_is_thread_heap(page_t* page) { +#if RPMALLOC_FIRST_CLASS_HEAPS + return (!page->heap->owner_thread || (page->heap->owner_thread == get_thread_id())); +#else + return (page->heap->owner_thread == get_thread_id()); +#endif } - -//////////// -/// -/// Span linked list management -/// -////// - -//! Add a span to double linked list at the head -static void -_rpmalloc_span_double_link_list_add(span_t** head, span_t* span) { - if (*head) - (*head)->prev = span; - span->next = *head; - *head = span; +static inline block_t* +page_block_start(page_t* page) { + return pointer_offset(page, PAGE_HEADER_SIZE); } -//! Pop head span from double linked list -static void -_rpmalloc_span_double_link_list_pop_head(span_t** head, span_t* span) { - rpmalloc_assert(*head == span, "Linked list corrupted"); - span = *head; - *head = span->next; +static inline block_t* +page_block(page_t* page, uint32_t block_index) { + return pointer_offset(page, PAGE_HEADER_SIZE + (page->block_size * block_index)); } -//! Remove a span from double linked list -static void -_rpmalloc_span_double_link_list_remove(span_t** head, span_t* span) { - rpmalloc_assert(*head, "Linked list corrupted"); - if (*head == span) { - *head = span->next; - } else { - span_t* next_span = span->next; - span_t* prev_span = span->prev; - prev_span->next = next_span; - if (EXPECTED(next_span != 0)) - next_span->prev = prev_span; - } +static inline uint32_t +page_block_index(page_t* page, block_t* block) { + block_t* block_first = page_block_start(page); + return (uint32_t)pointer_diff(block, block_first) / page->block_size; } - -//////////// -/// -/// Span control -/// -////// - -static void -_rpmalloc_heap_cache_insert(heap_t* heap, span_t* span); - -static void -_rpmalloc_heap_finalize(heap_t* heap); - -static void -_rpmalloc_heap_set_reserved_spans(heap_t* heap, span_t* master, span_t* reserve, size_t reserve_span_count); - -//! Declare the span to be a subspan and store distance from master span and span count -static void -_rpmalloc_span_mark_as_subspan_unless_master(span_t* master, span_t* subspan, size_t span_count) { - rpmalloc_assert((subspan != master) || (subspan->flags & SPAN_FLAG_MASTER), "Span master pointer and/or flag mismatch"); - if (subspan != master) { - subspan->flags = SPAN_FLAG_SUBSPAN; - subspan->offset_from_master = (uint32_t)((uintptr_t)pointer_diff(subspan, master) >> _memory_span_size_shift); - subspan->align_offset = 0; - } - subspan->span_count = (uint32_t)span_count; +static inline uint32_t +page_block_from_thread_free_list(page_t* page, uint64_t token, block_t** block) { + uint32_t block_index = (uint32_t)(token & 0xFFFFFFFFULL); + uint32_t list_count = (uint32_t)((token >> 32ULL) & 0xFFFFFFFFULL); + *block = list_count ? page_block(page, block_index) : 0; + return list_count; } -//! Use reserved spans to fulfill a memory map request (reserve size must be checked by caller) -static span_t* -_rpmalloc_span_map_from_reserve(heap_t* heap, size_t span_count) { - //Update the heap span reserve - span_t* span = heap->span_reserve; - heap->span_reserve = (span_t*)pointer_offset(span, span_count * _memory_span_size); - heap->spans_reserved -= (uint32_t)span_count; - - _rpmalloc_span_mark_as_subspan_unless_master(heap->span_reserve_master, span, span_count); - if (span_count <= LARGE_CLASS_COUNT) - _rpmalloc_stat_inc(&heap->span_use[span_count - 1].spans_from_reserved); - - return span; +static inline uint64_t +page_block_to_thread_free_list(page_t* page, uint32_t block_index, uint32_t list_count) { + (void)sizeof(page); + return ((uint64_t)list_count << 32ULL) | (uint64_t)block_index; } -//! Get the aligned number of spans to map in based on wanted count, configured mapping granularity and the page size -static size_t -_rpmalloc_span_align_count(size_t span_count) { - size_t request_count = (span_count > _memory_span_map_count) ? span_count : _memory_span_map_count; - if ((_memory_page_size > _memory_span_size) && ((request_count * _memory_span_size) % _memory_page_size)) - request_count += _memory_span_map_count - (request_count % _memory_span_map_count); - return request_count; +static inline block_t* +page_block_realign(page_t* page, block_t* block) { + void* blocks_start = page_block_start(page); + uint32_t block_offset = (uint32_t)pointer_diff(block, blocks_start); + return pointer_offset(block, -(int32_t)(block_offset % page->block_size)); } -//! Setup a newly mapped span -static void -_rpmalloc_span_initialize(span_t* span, size_t total_span_count, size_t span_count, size_t align_offset) { - span->total_spans = (uint32_t)total_span_count; - span->span_count = (uint32_t)span_count; - span->align_offset = (uint32_t)align_offset; - span->flags = SPAN_FLAG_MASTER; - atomic_store32(&span->remaining_spans, (int32_t)total_span_count); +static block_t* +page_get_local_free_block(page_t* page) { + block_t* block = page->local_free; + page->local_free = block->next; + --page->local_free_count; + ++page->block_used; + return block; } -static void -_rpmalloc_span_unmap(span_t* span); +static inline void +page_decommit_memory_pages(page_t* page) { + if (page->is_decommitted) + return; + // Only reserve-only spans support decommit + if (!page->commit_on_demand) + return; + // Keep the prefix (holding the page header) committed and decommit the rest. The prefix + // is the span's fixed map-time page size, so commit and decommit always use the same one. + size_t commit_prefix = (size_t)1 << page->commit_prefix_shift; + size_t page_size = page_get_size(page); + if (page_size <= commit_prefix) + return; + void* extra_page = pointer_offset(page, commit_prefix); + size_t extra_page_size = page_size - commit_prefix; + if (global_memory_interface->memory_decommit(extra_page, extra_page_size) != 0) + return; +#if RPMALLOC_HEAP_STATISTICS && ENABLE_DECOMMIT + if (page->heap) + page->heap->stats.committed_size -= extra_page_size; +#endif + page->is_decommitted = 1; +} -//! Map an aligned set of spans, taking configured mapping granularity and the page size into account -static span_t* -_rpmalloc_span_map_aligned_count(heap_t* heap, size_t span_count) { - //If we already have some, but not enough, reserved spans, release those to heap cache and map a new - //full set of spans. Otherwise we would waste memory if page size > span size (huge pages) - size_t aligned_span_count = _rpmalloc_span_align_count(span_count); - size_t align_offset = 0; - span_t* span = (span_t*)_rpmalloc_mmap(aligned_span_count * _memory_span_size, &align_offset); - if (!span) +static inline int +page_commit_memory_pages(page_t* page) { + if (!page->is_decommitted) return 0; - _rpmalloc_span_initialize(span, aligned_span_count, span_count, align_offset); - _rpmalloc_stat_inc(&_master_spans); - if (span_count <= LARGE_CLASS_COUNT) - _rpmalloc_stat_inc(&heap->span_use[span_count - 1].spans_map_calls); - if (aligned_span_count > span_count) { - span_t* reserved_spans = (span_t*)pointer_offset(span, span_count * _memory_span_size); - size_t reserved_count = aligned_span_count - span_count; - if (heap->spans_reserved) { - _rpmalloc_span_mark_as_subspan_unless_master(heap->span_reserve_master, heap->span_reserve, heap->spans_reserved); - _rpmalloc_heap_cache_insert(heap, heap->span_reserve); - } - if (reserved_count > _memory_heap_reserve_count) { - // If huge pages or eager spam map count, the global reserve spin lock is held by caller, _rpmalloc_span_map - rpmalloc_assert(atomic_load32(&_memory_global_lock) == 1, "Global spin lock not held as expected"); - size_t remain_count = reserved_count - _memory_heap_reserve_count; - reserved_count = _memory_heap_reserve_count; - span_t* remain_span = (span_t*)pointer_offset(reserved_spans, reserved_count * _memory_span_size); - if (_memory_global_reserve) { - _rpmalloc_span_mark_as_subspan_unless_master(_memory_global_reserve_master, _memory_global_reserve, _memory_global_reserve_count); - _rpmalloc_span_unmap(_memory_global_reserve); - } - _rpmalloc_global_set_reserved_spans(span, remain_span, remain_count); - } - _rpmalloc_heap_set_reserved_spans(heap, span, reserved_spans, reserved_count); - } - return span; -} - -//! Map in memory pages for the given number of spans (or use previously reserved pages) -static span_t* -_rpmalloc_span_map(heap_t* heap, size_t span_count) { - if (span_count <= heap->spans_reserved) - return _rpmalloc_span_map_from_reserve(heap, span_count); - span_t* span = 0; - int use_global_reserve = (_memory_page_size > _memory_span_size) || (_memory_span_map_count > _memory_heap_reserve_count); - if (use_global_reserve) { - // If huge pages, make sure only one thread maps more memory to avoid bloat - while (!atomic_cas32_acquire(&_memory_global_lock, 1, 0)) - _rpmalloc_spin(); - if (_memory_global_reserve_count >= span_count) { - size_t reserve_count = (!heap->spans_reserved ? _memory_heap_reserve_count : span_count); - if (_memory_global_reserve_count < reserve_count) - reserve_count = _memory_global_reserve_count; - span = _rpmalloc_global_get_reserved_spans(reserve_count); - if (span) { - if (reserve_count > span_count) { - span_t* reserved_span = (span_t*)pointer_offset(span, span_count << _memory_span_size_shift); - _rpmalloc_heap_set_reserved_spans(heap, _memory_global_reserve_master, reserved_span, reserve_count - span_count); - } - // Already marked as subspan in _rpmalloc_global_get_reserved_spans - span->span_count = (uint32_t)span_count; - } - } - } - if (!span) - span = _rpmalloc_span_map_aligned_count(heap, span_count); - if (use_global_reserve) - atomic_store32_release(&_memory_global_lock, 0); - return span; -} - -//! Unmap memory pages for the given number of spans (or mark as unused if no partial unmappings) -static void -_rpmalloc_span_unmap(span_t* span) { - rpmalloc_assert((span->flags & SPAN_FLAG_MASTER) || (span->flags & SPAN_FLAG_SUBSPAN), "Span flag corrupted"); - rpmalloc_assert(!(span->flags & SPAN_FLAG_MASTER) || !(span->flags & SPAN_FLAG_SUBSPAN), "Span flag corrupted"); - - int is_master = !!(span->flags & SPAN_FLAG_MASTER); - span_t* master = is_master ? span : ((span_t*)pointer_offset(span, -(intptr_t)((uintptr_t)span->offset_from_master * _memory_span_size))); - rpmalloc_assert(is_master || (span->flags & SPAN_FLAG_SUBSPAN), "Span flag corrupted"); - rpmalloc_assert(master->flags & SPAN_FLAG_MASTER, "Span flag corrupted"); - - size_t span_count = span->span_count; - if (!is_master) { - //Directly unmap subspans (unless huge pages, in which case we defer and unmap entire page range with master) - rpmalloc_assert(span->align_offset == 0, "Span align offset corrupted"); - if (_memory_span_size >= _memory_page_size) - _rpmalloc_unmap(span, span_count * _memory_span_size, 0, 0); - } else { - //Special double flag to denote an unmapped master - //It must be kept in memory since span header must be used - span->flags |= SPAN_FLAG_MASTER | SPAN_FLAG_SUBSPAN | SPAN_FLAG_UNMAPPED_MASTER; - _rpmalloc_stat_add(&_unmapped_master_spans, 1); - } - - if (atomic_add32(&master->remaining_spans, -(int32_t)span_count) <= 0) { - //Everything unmapped, unmap the master span with release flag to unmap the entire range of the super span - rpmalloc_assert(!!(master->flags & SPAN_FLAG_MASTER) && !!(master->flags & SPAN_FLAG_SUBSPAN), "Span flag corrupted"); - size_t unmap_count = master->span_count; - if (_memory_span_size < _memory_page_size) - unmap_count = master->total_spans; - _rpmalloc_stat_sub(&_master_spans, 1); - _rpmalloc_stat_sub(&_unmapped_master_spans, 1); - _rpmalloc_unmap(master, unmap_count * _memory_span_size, master->align_offset, (size_t)master->total_spans * _memory_span_size); - } -} - -//! Move the span (used for small or medium allocations) to the heap thread cache -static void -_rpmalloc_span_release_to_cache(heap_t* heap, span_t* span) { - rpmalloc_assert(heap == span->heap, "Span heap pointer corrupted"); - rpmalloc_assert(span->size_class < SIZE_CLASS_COUNT, "Invalid span size class"); - rpmalloc_assert(span->span_count == 1, "Invalid span count"); -#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS - atomic_decr32(&heap->span_use[0].current); -#endif - _rpmalloc_stat_dec(&heap->size_class_use[span->size_class].spans_current); - if (!heap->finalize) { - _rpmalloc_stat_inc(&heap->span_use[0].spans_to_cache); - _rpmalloc_stat_inc(&heap->size_class_use[span->size_class].spans_to_cache); - if (heap->size_class[span->size_class].cache) - _rpmalloc_heap_cache_insert(heap, heap->size_class[span->size_class].cache); - heap->size_class[span->size_class].cache = span; - } else { - _rpmalloc_span_unmap(span); - } -} - -//! Initialize a (partial) free list up to next system memory page, while reserving the first block -//! as allocated, returning number of blocks in list -static uint32_t -free_list_partial_init(void** list, void** first_block, void* page_start, void* block_start, uint32_t block_count, uint32_t block_size) { - rpmalloc_assert(block_count, "Internal failure"); - *first_block = block_start; - if (block_count > 1) { - void* free_block = pointer_offset(block_start, block_size); - void* block_end = pointer_offset(block_start, (size_t)block_size * block_count); - //If block size is less than half a memory page, bound init to next memory page boundary - if (block_size < (_memory_page_size >> 1)) { - void* page_end = pointer_offset(page_start, _memory_page_size); - if (page_end < block_end) - block_end = page_end; - } - *list = free_block; - block_count = 2; - void* next_block = pointer_offset(free_block, block_size); - while (next_block < block_end) { - *((void**)free_block) = next_block; - free_block = next_block; - ++block_count; - next_block = pointer_offset(next_block, block_size); - } - *((void**)free_block) = 0; - } else { - *list = 0; - } - return block_count; -} - -//! Initialize an unused span (from cache or mapped) to be new active span, putting the initial free list in heap class free list -static void* -_rpmalloc_span_initialize_new(heap_t* heap, heap_size_class_t* heap_size_class, span_t* span, uint32_t class_idx) { - rpmalloc_assert(span->span_count == 1, "Internal failure"); - size_class_t* size_class = _memory_size_class + class_idx; - span->size_class = class_idx; - span->heap = heap; - span->flags &= ~SPAN_FLAG_ALIGNED_BLOCKS; - span->block_size = size_class->block_size; - span->block_count = size_class->block_count; - span->free_list = 0; - span->list_size = 0; - atomic_store_ptr_release(&span->free_list_deferred, 0); - - //Setup free list. Only initialize one system page worth of free blocks in list - void* block; - span->free_list_limit = free_list_partial_init(&heap_size_class->free_list, &block, - span, pointer_offset(span, SPAN_HEADER_SIZE), size_class->block_count, size_class->block_size); - //Link span as partial if there remains blocks to be initialized as free list, or full if fully initialized - if (span->free_list_limit < span->block_count) { - _rpmalloc_span_double_link_list_add(&heap_size_class->partial_span, span); - span->used_count = span->free_list_limit; - } else { -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_add(&heap->full_span[class_idx], span); -#endif - ++heap->full_span_count; - span->used_count = span->block_count; - } - return block; -} - -static void -_rpmalloc_span_extract_free_list_deferred(span_t* span) { - // We need acquire semantics on the CAS operation since we are interested in the list size - // Refer to _rpmalloc_deallocate_defer_small_or_medium for further comments on this dependency - do { - span->free_list = atomic_exchange_ptr_acquire(&span->free_list_deferred, INVALID_POINTER); - } while (span->free_list == INVALID_POINTER); - span->used_count -= span->list_size; - span->list_size = 0; - atomic_store_ptr_release(&span->free_list_deferred, 0); -} - -static int -_rpmalloc_span_is_fully_utilized(span_t* span) { - rpmalloc_assert(span->free_list_limit <= span->block_count, "Span free list corrupted"); - return !span->free_list && (span->free_list_limit >= span->block_count); -} - -static int -_rpmalloc_span_finalize(heap_t* heap, size_t iclass, span_t* span, span_t** list_head) { - void* free_list = heap->size_class[iclass].free_list; - span_t* class_span = (span_t*)((uintptr_t)free_list & _memory_span_mask); - if (span == class_span) { - // Adopt the heap class free list back into the span free list - void* block = span->free_list; - void* last_block = 0; - while (block) { - last_block = block; - block = *((void**)block); - } - uint32_t free_count = 0; - block = free_list; - while (block) { - ++free_count; - block = *((void**)block); - } - if (last_block) { - *((void**)last_block) = free_list; - } else { - span->free_list = free_list; - } - heap->size_class[iclass].free_list = 0; - span->used_count -= free_count; - } - //If this assert triggers you have memory leaks - rpmalloc_assert(span->list_size == span->used_count, "Memory leak detected"); - if (span->list_size == span->used_count) { - _rpmalloc_stat_dec(&heap->span_use[0].current); - _rpmalloc_stat_dec(&heap->size_class_use[iclass].spans_current); - // This function only used for spans in double linked lists - if (list_head) - _rpmalloc_span_double_link_list_remove(list_head, span); - _rpmalloc_span_unmap(span); + size_t commit_prefix = (size_t)1 << page->commit_prefix_shift; + void* extra_page = pointer_offset(page, commit_prefix); + size_t extra_page_size = page_get_size(page) - commit_prefix; + if (global_memory_interface->memory_commit(extra_page, extra_page_size) != 0) return 1; - } - return 0; -} - - -//////////// -/// -/// Global cache -/// -////// - -#if ENABLE_GLOBAL_CACHE - -//! Finalize a global cache -static void -_rpmalloc_global_cache_finalize(global_cache_t* cache) { - while (!atomic_cas32_acquire(&cache->lock, 1, 0)) - _rpmalloc_spin(); - - for (size_t ispan = 0; ispan < cache->count; ++ispan) - _rpmalloc_span_unmap(cache->span[ispan]); - cache->count = 0; - - while (cache->overflow) { - span_t* span = cache->overflow; - cache->overflow = span->next; - _rpmalloc_span_unmap(span); - } - - atomic_store32_release(&cache->lock, 0); -} - -static void -_rpmalloc_global_cache_insert_spans(span_t** span, size_t span_count, size_t count) { - const size_t cache_limit = (span_count == 1) ? - GLOBAL_CACHE_MULTIPLIER * MAX_THREAD_SPAN_CACHE : - GLOBAL_CACHE_MULTIPLIER * (MAX_THREAD_SPAN_LARGE_CACHE - (span_count >> 1)); - - global_cache_t* cache = &_memory_span_cache[span_count - 1]; - - size_t insert_count = count; - while (!atomic_cas32_acquire(&cache->lock, 1, 0)) - _rpmalloc_spin(); - -#if ENABLE_STATISTICS - cache->insert_count += count; + page->is_decommitted = 0; +#if ENABLE_DECOMMIT +#if RPMALLOC_HEAP_STATISTICS + if (page->heap) + page->heap->stats.committed_size += extra_page_size; #endif - if ((cache->count + insert_count) > cache_limit) - insert_count = cache_limit - cache->count; - - memcpy(cache->span + cache->count, span, sizeof(span_t*) * insert_count); - cache->count += (uint32_t)insert_count; - -#if ENABLE_UNLIMITED_CACHE - while (insert_count < count) { -#else - // Enable unlimited cache if huge pages, or we will leak since it is unlikely that an entire huge page - // will be unmapped, and we're unable to partially decommit a huge page - while ((_memory_page_size > _memory_span_size) && (insert_count < count)) { -#endif - span_t* current_span = span[insert_count++]; - current_span->next = cache->overflow; - cache->overflow = current_span; - } - atomic_store32_release(&cache->lock, 0); - - span_t* keep = 0; - for (size_t ispan = insert_count; ispan < count; ++ispan) { - span_t* current_span = span[ispan]; - // Keep master spans that has remaining subspans to avoid dangling them - if ((current_span->flags & SPAN_FLAG_MASTER) && - (atomic_load32(¤t_span->remaining_spans) > (int32_t)current_span->span_count)) { - current_span->next = keep; - keep = current_span; - } else { - _rpmalloc_span_unmap(current_span); - } - } - - if (keep) { - while (!atomic_cas32_acquire(&cache->lock, 1, 0)) - _rpmalloc_spin(); - - size_t islot = 0; - while (keep) { - for (; islot < cache->count; ++islot) { - span_t* current_span = cache->span[islot]; - if (!(current_span->flags & SPAN_FLAG_MASTER) || ((current_span->flags & SPAN_FLAG_MASTER) && - (atomic_load32(¤t_span->remaining_spans) <= (int32_t)current_span->span_count))) { - _rpmalloc_span_unmap(current_span); - cache->span[islot] = keep; - break; - } - } - if (islot == cache->count) - break; - keep = keep->next; - } - - if (keep) { - span_t* tail = keep; - while (tail->next) - tail = tail->next; - tail->next = cache->overflow; - cache->overflow = keep; - } - - atomic_store32_release(&cache->lock, 0); - } -} - -static size_t -_rpmalloc_global_cache_extract_spans(span_t** span, size_t span_count, size_t count) { - global_cache_t* cache = &_memory_span_cache[span_count - 1]; - - size_t extract_count = 0; - while (!atomic_cas32_acquire(&cache->lock, 1, 0)) - _rpmalloc_spin(); - -#if ENABLE_STATISTICS - cache->extract_count += count; -#endif - size_t want = count - extract_count; - if (want > cache->count) - want = cache->count; - - memcpy(span + extract_count, cache->span + (cache->count - want), sizeof(span_t*) * want); - cache->count -= (uint32_t)want; - extract_count += want; - - while ((extract_count < count) && cache->overflow) { - span_t* current_span = cache->overflow; - span[extract_count++] = current_span; - cache->overflow = current_span->next; - } - -#if ENABLE_ASSERTS - for (size_t ispan = 0; ispan < extract_count; ++ispan) { - assert(span[ispan]->span_count == span_count); - } -#endif - - atomic_store32_release(&cache->lock, 0); - - return extract_count; -} - -#endif - -//////////// -/// -/// Heap control -/// -////// - -static void _rpmalloc_deallocate_huge(span_t*); - -//! Store the given spans as reserve in the given heap -static void -_rpmalloc_heap_set_reserved_spans(heap_t* heap, span_t* master, span_t* reserve, size_t reserve_span_count) { - heap->span_reserve_master = master; - heap->span_reserve = reserve; - heap->spans_reserved = (uint32_t)reserve_span_count; -} - -//! Adopt the deferred span cache list, optionally extracting the first single span for immediate re-use -static void -_rpmalloc_heap_cache_adopt_deferred(heap_t* heap, span_t** single_span) { - span_t* span = (span_t*)((void*)atomic_exchange_ptr_acquire(&heap->span_free_deferred, 0)); - while (span) { - span_t* next_span = (span_t*)span->free_list; - rpmalloc_assert(span->heap == heap, "Span heap pointer corrupted"); - if (EXPECTED(span->size_class < SIZE_CLASS_COUNT)) { - rpmalloc_assert(heap->full_span_count, "Heap span counter corrupted"); - --heap->full_span_count; - _rpmalloc_stat_dec(&heap->span_use[0].spans_deferred); -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_remove(&heap->full_span[span->size_class], span); -#endif - _rpmalloc_stat_dec(&heap->span_use[0].current); - _rpmalloc_stat_dec(&heap->size_class_use[span->size_class].spans_current); - if (single_span && !*single_span) - *single_span = span; - else - _rpmalloc_heap_cache_insert(heap, span); - } else { - if (span->size_class == SIZE_CLASS_HUGE) { - _rpmalloc_deallocate_huge(span); - } else { - rpmalloc_assert(span->size_class == SIZE_CLASS_LARGE, "Span size class invalid"); - rpmalloc_assert(heap->full_span_count, "Heap span counter corrupted"); - --heap->full_span_count; -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_remove(&heap->large_huge_span, span); -#endif - uint32_t idx = span->span_count - 1; - _rpmalloc_stat_dec(&heap->span_use[idx].spans_deferred); - _rpmalloc_stat_dec(&heap->span_use[idx].current); - if (!idx && single_span && !*single_span) - *single_span = span; - else - _rpmalloc_heap_cache_insert(heap, span); - } - } - span = next_span; - } -} - -static void -_rpmalloc_heap_unmap(heap_t* heap) { - if (!heap->master_heap) { - if ((heap->finalize > 1) && !atomic_load32(&heap->child_count)) { - span_t* span = (span_t*)((uintptr_t)heap & _memory_span_mask); - _rpmalloc_span_unmap(span); - } - } else { - if (atomic_decr32(&heap->master_heap->child_count) == 0) { - _rpmalloc_heap_unmap(heap->master_heap); - } - } -} - -static void -_rpmalloc_heap_global_finalize(heap_t* heap) { - if (heap->finalize++ > 1) { - --heap->finalize; - return; - } - - _rpmalloc_heap_finalize(heap); - -#if ENABLE_THREAD_CACHE - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - span_cache_t* span_cache; - if (!iclass) - span_cache = &heap->span_cache; - else - span_cache = (span_cache_t*)(heap->span_large_cache + (iclass - 1)); - for (size_t ispan = 0; ispan < span_cache->count; ++ispan) - _rpmalloc_span_unmap(span_cache->span[ispan]); - span_cache->count = 0; - } -#endif - - if (heap->full_span_count) { - --heap->finalize; - return; - } - - for (size_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { - if (heap->size_class[iclass].free_list || heap->size_class[iclass].partial_span) { - --heap->finalize; - return; - } - } - //Heap is now completely free, unmap and remove from heap list - size_t list_idx = (size_t)heap->id % HEAP_ARRAY_SIZE; - heap_t* list_heap = _memory_heaps[list_idx]; - if (list_heap == heap) { - _memory_heaps[list_idx] = heap->next_heap; - } else { - while (list_heap->next_heap != heap) - list_heap = list_heap->next_heap; - list_heap->next_heap = heap->next_heap; - } - - _rpmalloc_heap_unmap(heap); -} - -//! Insert a single span into thread heap cache, releasing to global cache if overflow -static void -_rpmalloc_heap_cache_insert(heap_t* heap, span_t* span) { - if (UNEXPECTED(heap->finalize != 0)) { - _rpmalloc_span_unmap(span); - _rpmalloc_heap_global_finalize(heap); - return; - } -#if ENABLE_THREAD_CACHE - size_t span_count = span->span_count; - _rpmalloc_stat_inc(&heap->span_use[span_count - 1].spans_to_cache); - if (span_count == 1) { - span_cache_t* span_cache = &heap->span_cache; - span_cache->span[span_cache->count++] = span; - if (span_cache->count == MAX_THREAD_SPAN_CACHE) { - const size_t remain_count = MAX_THREAD_SPAN_CACHE - THREAD_SPAN_CACHE_TRANSFER; -#if ENABLE_GLOBAL_CACHE - _rpmalloc_stat_add64(&heap->thread_to_global, THREAD_SPAN_CACHE_TRANSFER * _memory_span_size); - _rpmalloc_stat_add(&heap->span_use[span_count - 1].spans_to_global, THREAD_SPAN_CACHE_TRANSFER); - _rpmalloc_global_cache_insert_spans(span_cache->span + remain_count, span_count, THREAD_SPAN_CACHE_TRANSFER); -#else - for (size_t ispan = 0; ispan < THREAD_SPAN_CACHE_TRANSFER; ++ispan) - _rpmalloc_span_unmap(span_cache->span[remain_count + ispan]); -#endif - span_cache->count = remain_count; - } - } else { - size_t cache_idx = span_count - 2; - span_large_cache_t* span_cache = heap->span_large_cache + cache_idx; - span_cache->span[span_cache->count++] = span; - const size_t cache_limit = (MAX_THREAD_SPAN_LARGE_CACHE - (span_count >> 1)); - if (span_cache->count == cache_limit) { - const size_t transfer_limit = 2 + (cache_limit >> 2); - const size_t transfer_count = (THREAD_SPAN_LARGE_CACHE_TRANSFER <= transfer_limit ? THREAD_SPAN_LARGE_CACHE_TRANSFER : transfer_limit); - const size_t remain_count = cache_limit - transfer_count; -#if ENABLE_GLOBAL_CACHE - _rpmalloc_stat_add64(&heap->thread_to_global, transfer_count * span_count * _memory_span_size); - _rpmalloc_stat_add(&heap->span_use[span_count - 1].spans_to_global, transfer_count); - _rpmalloc_global_cache_insert_spans(span_cache->span + remain_count, span_count, transfer_count); -#else - for (size_t ispan = 0; ispan < transfer_count; ++ispan) - _rpmalloc_span_unmap(span_cache->span[remain_count + ispan]); -#endif - span_cache->count = remain_count; - } - } -#else - (void)sizeof(heap); - _rpmalloc_span_unmap(span); -#endif -} - -//! Extract the given number of spans from the different cache levels -static span_t* -_rpmalloc_heap_thread_cache_extract(heap_t* heap, size_t span_count) { - span_t* span = 0; -#if ENABLE_THREAD_CACHE - span_cache_t* span_cache; - if (span_count == 1) - span_cache = &heap->span_cache; - else - span_cache = (span_cache_t*)(heap->span_large_cache + (span_count - 2)); - if (span_cache->count) { - _rpmalloc_stat_inc(&heap->span_use[span_count - 1].spans_from_cache); - return span_cache->span[--span_cache->count]; - } -#endif - return span; -} - -static span_t* -_rpmalloc_heap_thread_cache_deferred_extract(heap_t* heap, size_t span_count) { - span_t* span = 0; - if (span_count == 1) { - _rpmalloc_heap_cache_adopt_deferred(heap, &span); - } else { - _rpmalloc_heap_cache_adopt_deferred(heap, 0); - span = _rpmalloc_heap_thread_cache_extract(heap, span_count); - } - return span; -} - -static span_t* -_rpmalloc_heap_reserved_extract(heap_t* heap, size_t span_count) { - if (heap->spans_reserved >= span_count) - return _rpmalloc_span_map(heap, span_count); - return 0; -} - -//! Extract a span from the global cache -static span_t* -_rpmalloc_heap_global_cache_extract(heap_t* heap, size_t span_count) { -#if ENABLE_GLOBAL_CACHE -#if ENABLE_THREAD_CACHE - span_cache_t* span_cache; - size_t wanted_count; - if (span_count == 1) { - span_cache = &heap->span_cache; - wanted_count = THREAD_SPAN_CACHE_TRANSFER; - } else { - span_cache = (span_cache_t*)(heap->span_large_cache + (span_count - 2)); - wanted_count = THREAD_SPAN_LARGE_CACHE_TRANSFER; - } - span_cache->count = _rpmalloc_global_cache_extract_spans(span_cache->span, span_count, wanted_count); - if (span_cache->count) { - _rpmalloc_stat_add64(&heap->global_to_thread, span_count * span_cache->count * _memory_span_size); - _rpmalloc_stat_add(&heap->span_use[span_count - 1].spans_from_global, span_cache->count); - return span_cache->span[--span_cache->count]; - } -#else - span_t* span = 0; - size_t count = _rpmalloc_global_cache_extract_spans(&span, span_count, 1); - if (count) { - _rpmalloc_stat_add64(&heap->global_to_thread, span_count * count * _memory_span_size); - _rpmalloc_stat_add(&heap->span_use[span_count - 1].spans_from_global, count); - return span; - } +#if !defined(__APPLE__) + // When page is recommitted, the blocks in the second memory page and forward + // will be zeroed out by OS - take advantage in zalloc/calloc calls and make sure + // blocks in first page is zeroed out + void* first_page = pointer_offset(page, PAGE_HEADER_SIZE); + memset(first_page, 0, commit_prefix - PAGE_HEADER_SIZE); + page->is_zero = 1; #endif #endif - (void)sizeof(heap); - (void)sizeof(span_count); return 0; } static void -_rpmalloc_inc_span_statistics(heap_t* heap, size_t span_count, uint32_t class_idx) { - (void)sizeof(heap); - (void)sizeof(span_count); - (void)sizeof(class_idx); -#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS - uint32_t idx = (uint32_t)span_count - 1; - uint32_t current_count = (uint32_t)atomic_incr32(&heap->span_use[idx].current); - if (current_count > (uint32_t)atomic_load32(&heap->span_use[idx].high)) - atomic_store32(&heap->span_use[idx].high, (int32_t)current_count); - _rpmalloc_stat_add_peak(&heap->size_class_use[class_idx].spans_current, 1, heap->size_class_use[class_idx].spans_peak); -#endif -} - -//! Get a span from one of the cache levels (thread cache, reserved, global cache) or fallback to mapping more memory -static span_t* -_rpmalloc_heap_extract_new_span(heap_t* heap, heap_size_class_t* heap_size_class, size_t span_count, uint32_t class_idx) { - span_t* span; -#if ENABLE_THREAD_CACHE - if (heap_size_class && heap_size_class->cache) { - span = heap_size_class->cache; - heap_size_class->cache = (heap->span_cache.count ? heap->span_cache.span[--heap->span_cache.count] : 0); - _rpmalloc_inc_span_statistics(heap, span_count, class_idx); - return span; +page_available_to_free(page_t* page) { + rpmalloc_assert(page->is_full == 0, "Page full flag internal failure"); + rpmalloc_assert(page->is_decommitted == 0, "Page decommitted flag internal failure"); + heap_t* heap = page->heap; + if (heap->page_available[page->size_class] == page) { + heap->page_available[page->size_class] = page->next; + } else { + page->prev->next = page->next; + if (page->next) + page->next->prev = page->prev; } -#endif - (void)sizeof(class_idx); - // Allow 50% overhead to increase cache hits - size_t base_span_count = span_count; - size_t limit_span_count = (span_count > 2) ? (span_count + (span_count >> 1)) : span_count; - if (limit_span_count > LARGE_CLASS_COUNT) - limit_span_count = LARGE_CLASS_COUNT; - do { - span = _rpmalloc_heap_thread_cache_extract(heap, span_count); - if (EXPECTED(span != 0)) { - _rpmalloc_stat_inc(&heap->size_class_use[class_idx].spans_from_cache); - _rpmalloc_inc_span_statistics(heap, span_count, class_idx); - return span; - } - span = _rpmalloc_heap_thread_cache_deferred_extract(heap, span_count); - if (EXPECTED(span != 0)) { - _rpmalloc_stat_inc(&heap->size_class_use[class_idx].spans_from_cache); - _rpmalloc_inc_span_statistics(heap, span_count, class_idx); - return span; - } - span = _rpmalloc_heap_reserved_extract(heap, span_count); - if (EXPECTED(span != 0)) { - _rpmalloc_stat_inc(&heap->size_class_use[class_idx].spans_from_reserved); - _rpmalloc_inc_span_statistics(heap, span_count, class_idx); - return span; - } - span = _rpmalloc_heap_global_cache_extract(heap, span_count); - if (EXPECTED(span != 0)) { - _rpmalloc_stat_inc(&heap->size_class_use[class_idx].spans_from_cache); - _rpmalloc_inc_span_statistics(heap, span_count, class_idx); - return span; - } - ++span_count; - } while (span_count <= limit_span_count); - //Final fallback, map in more virtual memory - span = _rpmalloc_span_map(heap, base_span_count); - _rpmalloc_inc_span_statistics(heap, base_span_count, class_idx); - _rpmalloc_stat_inc(&heap->size_class_use[class_idx].spans_map_calls); - return span; + page->is_free = 1; + page->is_zero = 0; + page->next = heap->page_free[page->page_type]; + heap->page_free[page->page_type] = page; + if (++heap->page_free_commit_count[page->page_type] >= global_page_free_overflow[page->page_type]) + heap_page_free_decommit(heap, page->page_type, global_page_free_retain[page->page_type]); } static void -_rpmalloc_heap_initialize(heap_t* heap) { - memset(heap, 0, sizeof(heap_t)); - //Get a new heap ID - heap->id = 1 + atomic_incr32(&_memory_heap_id); - - //Link in heap in heap ID map - size_t list_idx = (size_t)heap->id % HEAP_ARRAY_SIZE; - heap->next_heap = _memory_heaps[list_idx]; - _memory_heaps[list_idx] = heap; +page_full_to_available(page_t* page) { + rpmalloc_assert(page->is_full == 1, "Page full flag internal failure"); + rpmalloc_assert(page->is_decommitted == 0, "Page decommitted flag internal failure"); + heap_t* heap = page->heap; + page->next = heap->page_available[page->size_class]; + if (page->next) + page->next->prev = page; + heap->page_available[page->size_class] = page; + page->is_full = 0; + if (page->has_aligned_block == 0) + page->generic_free = 0; } static void -_rpmalloc_heap_orphan(heap_t* heap, int first_class) { - heap->owner_thread = (uintptr_t)-1; -#if RPMALLOC_FIRST_CLASS_HEAPS - heap_t** heap_list = (first_class ? &_memory_first_class_orphan_heaps : &_memory_orphan_heaps); -#else - (void)sizeof(first_class); - heap_t** heap_list = &_memory_orphan_heaps; -#endif - heap->next_orphan = *heap_list; - *heap_list = heap; -} - -//! Allocate a new heap from newly mapped memory pages -static heap_t* -_rpmalloc_heap_allocate_new(void) { - // Map in pages for a 16 heaps. If page size is greater than required size for this, map a page and - // use first part for heaps and remaining part for spans for allocations. Adds a lot of complexity, - // but saves a lot of memory on systems where page size > 64 spans (4MiB) - size_t heap_size = sizeof(heap_t); - size_t aligned_heap_size = 16 * ((heap_size + 15) / 16); - size_t request_heap_count = 16; - size_t heap_span_count = ((aligned_heap_size * request_heap_count) + sizeof(span_t) + _memory_span_size - 1) / _memory_span_size; - size_t block_size = _memory_span_size * heap_span_count; - size_t span_count = heap_span_count; - span_t* span = 0; - // If there are global reserved spans, use these first - if (_memory_global_reserve_count >= heap_span_count) { - span = _rpmalloc_global_get_reserved_spans(heap_span_count); - } - if (!span) { - if (_memory_page_size > block_size) { - span_count = _memory_page_size / _memory_span_size; - block_size = _memory_page_size; - // If using huge pages, make sure to grab enough heaps to avoid reallocating a huge page just to serve new heaps - size_t possible_heap_count = (block_size - sizeof(span_t)) / aligned_heap_size; - if (possible_heap_count >= (request_heap_count * 16)) - request_heap_count *= 16; - else if (possible_heap_count < request_heap_count) - request_heap_count = possible_heap_count; - heap_span_count = ((aligned_heap_size * request_heap_count) + sizeof(span_t) + _memory_span_size - 1) / _memory_span_size; - } - - size_t align_offset = 0; - span = (span_t*)_rpmalloc_mmap(block_size, &align_offset); - if (!span) - return 0; - - // Master span will contain the heaps - _rpmalloc_stat_inc(&_master_spans); - _rpmalloc_span_initialize(span, span_count, heap_span_count, align_offset); - } - - size_t remain_size = _memory_span_size - sizeof(span_t); - heap_t* heap = (heap_t*)pointer_offset(span, sizeof(span_t)); - _rpmalloc_heap_initialize(heap); - - // Put extra heaps as orphans - size_t num_heaps = remain_size / aligned_heap_size; - if (num_heaps < request_heap_count) - num_heaps = request_heap_count; - atomic_store32(&heap->child_count, (int32_t)num_heaps - 1); - heap_t* extra_heap = (heap_t*)pointer_offset(heap, aligned_heap_size); - while (num_heaps > 1) { - _rpmalloc_heap_initialize(extra_heap); - extra_heap->master_heap = heap; - _rpmalloc_heap_orphan(extra_heap, 1); - extra_heap = (heap_t*)pointer_offset(extra_heap, aligned_heap_size); - --num_heaps; - } - - if (span_count > heap_span_count) { - // Cap reserved spans - size_t remain_count = span_count - heap_span_count; - size_t reserve_count = (remain_count > _memory_heap_reserve_count ? _memory_heap_reserve_count : remain_count); - span_t* remain_span = (span_t*)pointer_offset(span, heap_span_count * _memory_span_size); - _rpmalloc_heap_set_reserved_spans(heap, span, remain_span, reserve_count); - - if (remain_count > reserve_count) { - // Set to global reserved spans - remain_span = (span_t*)pointer_offset(remain_span, reserve_count * _memory_span_size); - reserve_count = remain_count - reserve_count; - _rpmalloc_global_set_reserved_spans(span, remain_span, reserve_count); - } - } - - return heap; -} - -static heap_t* -_rpmalloc_heap_extract_orphan(heap_t** heap_list) { - heap_t* heap = *heap_list; - *heap_list = (heap ? heap->next_orphan : 0); - return heap; -} - -//! Allocate a new heap, potentially reusing a previously orphaned heap -static heap_t* -_rpmalloc_heap_allocate(int first_class) { - heap_t* heap = 0; - while (!atomic_cas32_acquire(&_memory_global_lock, 1, 0)) - _rpmalloc_spin(); - if (first_class == 0) - heap = _rpmalloc_heap_extract_orphan(&_memory_orphan_heaps); -#if RPMALLOC_FIRST_CLASS_HEAPS - if (!heap) - heap = _rpmalloc_heap_extract_orphan(&_memory_first_class_orphan_heaps); -#endif - if (!heap) - heap = _rpmalloc_heap_allocate_new(); - atomic_store32_release(&_memory_global_lock, 0); - _rpmalloc_heap_cache_adopt_deferred(heap, 0); - return heap; +page_full_to_free_on_new_heap(page_t* page, heap_t* heap) { + rpmalloc_assert(heap->id, "Page full to free on default heap"); + rpmalloc_assert(page->is_full == 1, "Page full flag internal failure"); + rpmalloc_assert(page->is_decommitted == 0, "Page decommitted flag internal failure"); + page->is_full = 0; + page->is_free = 1; + page->heap = heap; + atomic_store_explicit(&page->thread_free, 0, memory_order_release); + page->next = heap->page_free[page->page_type]; + heap->page_free[page->page_type] = page; + if (++heap->page_free_commit_count[page->page_type] >= global_page_free_overflow[page->page_type]) + heap_page_free_decommit(heap, page->page_type, global_page_free_retain[page->page_type]); } static void -_rpmalloc_heap_release(void* heapptr, int first_class, int release_cache) { - heap_t* heap = (heap_t*)heapptr; - if (!heap) +page_available_to_full(page_t* page) { + heap_t* heap = page->heap; + if (heap->page_available[page->size_class] == page) { + heap->page_available[page->size_class] = page->next; + } else { + page->prev->next = page->next; + if (page->next) + page->next->prev = page->prev; + } + page->is_full = 1; + page->is_zero = 0; + page->generic_free = 1; +} + +static inline void +page_put_local_free_block(page_t* page, block_t* block) { + block->next = page->local_free; + page->local_free = block; + ++page->local_free_count; + _rpmalloc_stat_add_free(page->heap, page->size_class, 1); + if (UNEXPECTED(--page->block_used == 0)) { + page_available_to_free(page); + } else if (UNEXPECTED(page->is_full != 0)) { + page_full_to_available(page); + } +} + +static NOINLINE void +page_adopt_thread_free_block_list(page_t* page) { + if (page->local_free) return; - //Release thread cache spans back to global cache - _rpmalloc_heap_cache_adopt_deferred(heap, 0); - if (release_cache || heap->finalize) { -#if ENABLE_THREAD_CACHE - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - span_cache_t* span_cache; - if (!iclass) - span_cache = &heap->span_cache; - else - span_cache = (span_cache_t*)(heap->span_large_cache + (iclass - 1)); - if (!span_cache->count) - continue; -#if ENABLE_GLOBAL_CACHE - if (heap->finalize) { - for (size_t ispan = 0; ispan < span_cache->count; ++ispan) - _rpmalloc_span_unmap(span_cache->span[ispan]); - } else { - _rpmalloc_stat_add64(&heap->thread_to_global, span_cache->count * (iclass + 1) * _memory_span_size); - _rpmalloc_stat_add(&heap->span_use[iclass].spans_to_global, span_cache->count); - _rpmalloc_global_cache_insert_spans(span_cache->span, iclass + 1, span_cache->count); - } -#else - for (size_t ispan = 0; ispan < span_cache->count; ++ispan) - _rpmalloc_span_unmap(span_cache->span[ispan]); -#endif - span_cache->count = 0; + unsigned long long thread_free = atomic_load_explicit(&page->thread_free, memory_order_relaxed); + if (thread_free != 0) { + // Other threads can only replace with another valid list head, this will never change to 0 in other threads + uint32_t spin = 0; + while (!atomic_compare_exchange_weak_explicit(&page->thread_free, &thread_free, 0, memory_order_acquire, + memory_order_relaxed)) + wait_spin(&spin); + page->local_free_count = page_block_from_thread_free_list(page, thread_free, &page->local_free); + rpmalloc_assert(page->local_free_count <= page->block_used, "Page thread free list count internal failure"); + page->block_used -= page->local_free_count; + _rpmalloc_stat_add_free(page->heap, page->size_class, page->local_free_count); + } +} + +static NOINLINE void +page_put_thread_free_block(page_t* page, block_t* block) { + atomic_thread_fence(memory_order_acquire); + if (page->is_full) { + // Page is full, put the block in the heap thread free list instead, otherwise + // the heap will not pick up the free blocks until a thread local free happens + heap_t* heap = page->heap; + uintptr_t prev_head = atomic_load_explicit(&heap->thread_free[page->page_type], memory_order_relaxed); + block->next = (void*)prev_head; + uint32_t spin = 0; + while (!atomic_compare_exchange_weak_explicit(&heap->thread_free[page->page_type], &prev_head, (uintptr_t)block, + memory_order_release, memory_order_relaxed)) { + block->next = (void*)prev_head; + wait_spin(&spin); + } + } else { + unsigned long long prev_thread_free = atomic_load_explicit(&page->thread_free, memory_order_relaxed); + uint32_t block_index = page_block_index(page, block); + rpmalloc_assert(page_block(page, block_index) == block, "Block pointer is not aligned to start of block"); + uint32_t list_size = page_block_from_thread_free_list(page, prev_thread_free, &block->next) + 1; + uint64_t thread_free = page_block_to_thread_free_list(page, block_index, list_size); + uint32_t spin = 0; + while (!atomic_compare_exchange_weak_explicit(&page->thread_free, &prev_thread_free, thread_free, + memory_order_release, memory_order_relaxed)) { + list_size = page_block_from_thread_free_list(page, prev_thread_free, &block->next) + 1; + thread_free = page_block_to_thread_free_list(page, block_index, list_size); + wait_spin(&spin); } -#endif } - - if (get_thread_heap_raw() == heap) - set_thread_heap(0); - -#if ENABLE_STATISTICS - atomic_decr32(&_memory_active_heaps); - rpmalloc_assert(atomic_load32(&_memory_active_heaps) >= 0, "Still active heaps during finalization"); -#endif - - // If we are forcibly terminating with _exit the state of the - // lock atomic is unknown and it's best to just go ahead and exit - if (get_thread_id() != _rpmalloc_main_thread_id) { - while (!atomic_cas32_acquire(&_memory_global_lock, 1, 0)) - _rpmalloc_spin(); - } - _rpmalloc_heap_orphan(heap, first_class); - atomic_store32_release(&_memory_global_lock, 0); } static void -_rpmalloc_heap_release_raw(void* heapptr, int release_cache) { - _rpmalloc_heap_release(heapptr, 0, release_cache); +page_push_local_free_to_heap(page_t* page) { + // Push the page free list as the fast track list of free blocks for heap + page->heap->local_free[page->size_class] = page->local_free; + page->block_used += page->local_free_count; + page->local_free = 0; + page->local_free_count = 0; } -static void -_rpmalloc_heap_release_raw_fc(void* heapptr) { - _rpmalloc_heap_release_raw(heapptr, 1); -} +static NOINLINE void* +page_initialize_blocks(page_t* page) { + rpmalloc_assert(page->block_initialized < page->block_count, "Block initialization internal failure"); + block_t* block = page_block(page, page->block_initialized); + ++page->block_initialized; + ++page->block_used; -static void -_rpmalloc_heap_finalize(heap_t* heap) { - if (heap->spans_reserved) { - span_t* span = _rpmalloc_span_map(heap, heap->spans_reserved); - _rpmalloc_span_unmap(span); - heap->spans_reserved = 0; - } - - _rpmalloc_heap_cache_adopt_deferred(heap, 0); - - for (size_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { - if (heap->size_class[iclass].cache) - _rpmalloc_span_unmap(heap->size_class[iclass].cache); - heap->size_class[iclass].cache = 0; - span_t* span = heap->size_class[iclass].partial_span; - while (span) { - span_t* next = span->next; - _rpmalloc_span_finalize(heap, iclass, span, &heap->size_class[iclass].partial_span); - span = next; + if ((page->page_type == PAGE_SMALL) && (page->block_size < (global_config.page_size >> 1))) { + // Link up until next memory page in free list + void* memory_page_start = (void*)((uintptr_t)block & ~(uintptr_t)(global_config.page_size - 1)); + void* memory_page_next = pointer_offset(memory_page_start, global_config.page_size); + block_t* free_block = pointer_offset(block, page->block_size); + block_t* first_block = free_block; + block_t* last_block = free_block; + uint32_t list_count = 0; + uint32_t max_list_count = page->block_count - page->block_initialized; + while (((void*)free_block < memory_page_next) && (list_count < max_list_count)) { + last_block = free_block; + free_block->next = pointer_offset(free_block, page->block_size); + free_block = free_block->next; + ++list_count; } - // If class still has a free list it must be a full span - if (heap->size_class[iclass].free_list) { - span_t* class_span = (span_t*)((uintptr_t)heap->size_class[iclass].free_list & _memory_span_mask); - span_t** list = 0; -#if RPMALLOC_FIRST_CLASS_HEAPS - list = &heap->full_span[iclass]; -#endif - --heap->full_span_count; - if (!_rpmalloc_span_finalize(heap, iclass, class_span, list)) { - if (list) - _rpmalloc_span_double_link_list_remove(list, class_span); - _rpmalloc_span_double_link_list_add(&heap->size_class[iclass].partial_span, class_span); - } + if (list_count) { + last_block->next = 0; + page->local_free = first_block; + page->block_initialized += list_count; + page->local_free_count = list_count; } } -#if ENABLE_THREAD_CACHE - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - span_cache_t* span_cache; - if (!iclass) - span_cache = &heap->span_cache; - else - span_cache = (span_cache_t*)(heap->span_large_cache + (iclass - 1)); - for (size_t ispan = 0; ispan < span_cache->count; ++ispan) - _rpmalloc_span_unmap(span_cache->span[ispan]); - span_cache->count = 0; - } -#endif - rpmalloc_assert(!atomic_load_ptr(&heap->span_free_deferred), "Heaps still active during finalization"); -} - - -//////////// -/// -/// Allocation entry points -/// -////// - -//! Pop first block from a free list -static void* -free_list_pop(void** list) { - void* block = *list; - *list = *((void**)block); return block; } -//! Allocate a small/medium sized memory block from the given heap -static void* -_rpmalloc_allocate_from_heap_fallback(heap_t* heap, heap_size_class_t* heap_size_class, uint32_t class_idx) { - span_t* span = heap_size_class->partial_span; - if (EXPECTED(span != 0)) { - rpmalloc_assert(span->block_count == _memory_size_class[span->size_class].block_count, "Span block count corrupted"); - rpmalloc_assert(!_rpmalloc_span_is_fully_utilized(span), "Internal failure"); - void* block; - if (span->free_list) { - //Span local free list is not empty, swap to size class free list - block = free_list_pop(&span->free_list); - heap_size_class->free_list = span->free_list; - span->free_list = 0; - } else { - //If the span did not fully initialize free list, link up another page worth of blocks - void* block_start = pointer_offset(span, SPAN_HEADER_SIZE + ((size_t)span->free_list_limit * span->block_size)); - span->free_list_limit += free_list_partial_init(&heap_size_class->free_list, &block, - (void*)((uintptr_t)block_start & ~(_memory_page_size - 1)), block_start, - span->block_count - span->free_list_limit, span->block_size); +static inline RPMALLOC_ALLOCATOR void* +page_allocate_block(page_t* page, unsigned int zero) { + unsigned int is_zero = 0; + block_t* block = (page->local_free != 0) ? page_get_local_free_block(page) : 0; + if (UNEXPECTED(block == 0)) { + if (atomic_load_explicit(&page->thread_free, memory_order_acquire) != 0) { + page_adopt_thread_free_block_list(page); + block = (page->local_free != 0) ? page_get_local_free_block(page) : 0; } - rpmalloc_assert(span->free_list_limit <= span->block_count, "Span block count corrupted"); - span->used_count = span->free_list_limit; + if (block == 0) { + block = page_initialize_blocks(page); + is_zero = page->is_zero; + } + } - //Swap in deferred free list if present - if (atomic_load_ptr(&span->free_list_deferred)) - _rpmalloc_span_extract_free_list_deferred(span); + rpmalloc_assert(page->block_used <= page->block_count, "Page block use counter out of sync"); + if (page->local_free && !page->heap->local_free[page->size_class]) + page_push_local_free_to_heap(page); - //If span is still not fully utilized keep it in partial list and early return block - if (!_rpmalloc_span_is_fully_utilized(span)) - return block; + // The page might be full when free list has been pushed to heap local free list, + // check if there is a thread free list to adopt + if (page->block_used == page->block_count) { + page_adopt_thread_free_block_list(page); + if (page->block_used == page->block_count) { + // Page is now fully utilized + rpmalloc_assert(!page->is_full, "Page block use counter out of sync with full flag"); + page_available_to_full(page); + } + } - //The span is fully utilized, unlink from partial list and add to fully utilized list - _rpmalloc_span_double_link_list_pop_head(&heap_size_class->partial_span, span); + if (zero) { + if (!is_zero) + memset(block, 0, page->block_size); + else + *(uintptr_t*)block = 0; + } + + return block; +} + +//////////// +/// +/// Span interface +/// +////// + +static inline int +span_is_thread_heap(span_t* span) { #if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_add(&heap->full_span[class_idx], span); + return (!span->heap->owner_thread || (span->heap->owner_thread == get_thread_id())); +#else + return (span->heap->owner_thread == get_thread_id()); #endif - ++heap->full_span_count; - return block; +} + +static inline page_t* +span_get_page_from_block(span_t* span, void* block) { + return (page_t*)((uintptr_t)block & span->page_address_mask); +} + +//! Find or allocate a page from the given span +static inline page_t* +span_allocate_page(span_t* span) { + // Allocate path, initialize a new chunk of memory for a page in the given span + rpmalloc_assert(span->page_initialized < span->page_count, "Page initialization internal failure"); + heap_t* heap = span->heap; + page_t* page = pointer_offset(span, span->page_size * span->page_initialized); + +#if ENABLE_DECOMMIT + // Reserve-only spans commit later pages on demand; fully committed spans are already + // committed from the map and must not be committed per page + if (span->page_initialized && span->page.commit_on_demand) { + if (global_memory_interface->memory_commit(page, span->page_size) != 0) + return 0; +#if RPMALLOC_HEAP_STATISTICS + heap->stats.committed_size += span->page_size; +#endif + } +#endif + ++span->page_initialized; + + page->page_type = span->page_type; + page->commit_on_demand = span->page.commit_on_demand; + page->commit_prefix_shift = span->page.commit_prefix_shift; + page->is_zero = 1; + page->heap = heap; + rpmalloc_assert(page_is_thread_heap(page), "Page owner thread mismatch"); + + if (span->page_initialized == span->page_count) { + // Span fully utilized + rpmalloc_assert(span == heap->span_partial[span->page_type], "Span partial tracking out of sync"); + heap->span_partial[span->page_type] = 0; + + span->next = heap->span_used[span->page_type]; + heap->span_used[span->page_type] = span; } - //Find a span in one of the cache levels - span = _rpmalloc_heap_extract_new_span(heap, heap_size_class, 1, class_idx); - if (EXPECTED(span != 0)) { - //Mark span as owned by this heap and set base data, return first block - return _rpmalloc_span_initialize_new(heap, heap_size_class, span, class_idx); + return page; +} + +//! Cache recently freed huge block mappings for reuse instead of paying a +//! munmap + mmap + page fault round trip per huge allocation cycle. Entries +//! are bounded by a committed byte budget and unmapped after an idle epoch. +//! A cached mapping is reused when its size fits the request within the size +//! class spacing (25% overshoot). +#ifndef HUGE_CACHE_SLOT_COUNT +#define HUGE_CACHE_SLOT_COUNT 32 +#endif +#ifndef HUGE_CACHE_COMMITTED_LIMIT +#define HUGE_CACHE_COMMITTED_LIMIT (128 * 1024 * 1024) +#endif +//! Largest single mapping the cache will hold - keeps one rare giant from +//! monopolizing the committed budget and starving caching of the smaller, +//! more frequently cycled sizes +#ifndef HUGE_CACHE_ENTRY_LIMIT +#define HUGE_CACHE_ENTRY_LIMIT (HUGE_CACHE_COMMITTED_LIMIT / 4) +#endif +#ifndef HUGE_CACHE_EPOCH_MS +#define HUGE_CACHE_EPOCH_MS 1000 +#endif + +#if HUGE_CACHE_SLOT_COUNT + +//! Coarse monotonic time in milliseconds (no syscall on Linux/vDSO) +static inline uint64_t +monotonic_time_ms(void) { +#if PLATFORM_WINDOWS + return (uint64_t)GetTickCount64(); +#else + struct timespec ts; +#if defined(CLOCK_MONOTONIC_COARSE) + clock_gettime(CLOCK_MONOTONIC_COARSE, &ts); +#else + clock_gettime(CLOCK_MONOTONIC, &ts); +#endif + return ((uint64_t)ts.tv_sec * 1000ULL) + ((uint64_t)ts.tv_nsec / 1000000ULL); +#endif +} + +typedef struct huge_cache_t { + //! Cache lock + atomic_uintptr_t lock; + //! Committed bytes currently cached + size_t committed; + //! Cached mappings with their free timestamp + struct { + span_t* span; + uint64_t free_ms; + } slot[HUGE_CACHE_SLOT_COUNT]; +} huge_cache_t; + +static huge_cache_t global_huge_cache; + +static inline void +huge_cache_lock_acquire(void) { + uintptr_t lock = 0; + uint32_t spin = 0; + while (!atomic_compare_exchange_weak_explicit(&global_huge_cache.lock, &lock, 1, memory_order_acquire, + memory_order_relaxed)) { + lock = 0; + wait_spin(&spin); + } +} + +static inline void +huge_cache_lock_release(void) { + atomic_store_explicit(&global_huge_cache.lock, 0, memory_order_release); +} + +//! Unmap cached mappings that have been idle for an epoch (syscalls are made +//! outside the cache lock) +static void +huge_cache_purge_aged(uint64_t now) { + span_t* purge[HUGE_CACHE_SLOT_COUNT]; + uint32_t purge_count = 0; + huge_cache_lock_acquire(); + for (uint32_t islot = 0; islot < HUGE_CACHE_SLOT_COUNT; ++islot) { + span_t* span = global_huge_cache.slot[islot].span; + if (span && ((now - global_huge_cache.slot[islot].free_ms) >= HUGE_CACHE_EPOCH_MS)) { + global_huge_cache.committed -= (size_t)span->page_count * span->page_size; + global_huge_cache.slot[islot].span = 0; + purge[purge_count++] = span; + } + } + huge_cache_lock_release(); + for (uint32_t ispan = 0; ispan < purge_count; ++ispan) + global_memory_interface->memory_unmap(purge[ispan], purge[ispan]->offset, purge[ispan]->mapped_size); +} + +//! Unmap all cached huge mappings, the cache must not outlive allocator finalization +static void +huge_cache_flush(void) { + span_t* purge[HUGE_CACHE_SLOT_COUNT]; + uint32_t purge_count = 0; + huge_cache_lock_acquire(); + for (uint32_t islot = 0; islot < HUGE_CACHE_SLOT_COUNT; ++islot) { + span_t* span = global_huge_cache.slot[islot].span; + if (span) { + global_huge_cache.committed -= (size_t)span->page_count * span->page_size; + global_huge_cache.slot[islot].span = 0; + purge[purge_count++] = span; + } + } + huge_cache_lock_release(); + for (uint32_t ispan = 0; ispan < purge_count; ++ispan) + global_memory_interface->memory_unmap(purge[ispan], purge[ispan]->offset, purge[ispan]->mapped_size); +} + +//! Try to cache a freed huge mapping, returns nonzero if cached +static int +huge_cache_push(span_t* span) { + size_t committed_size = (size_t)span->page_count * span->page_size; + if (committed_size > HUGE_CACHE_ENTRY_LIMIT) + return 0; + uint64_t now = monotonic_time_ms(); + huge_cache_purge_aged(now); + int cached = 0; + huge_cache_lock_acquire(); + if (global_huge_cache.committed + committed_size <= HUGE_CACHE_COMMITTED_LIMIT) { + for (uint32_t islot = 0; islot < HUGE_CACHE_SLOT_COUNT; ++islot) { + if (!global_huge_cache.slot[islot].span) { + global_huge_cache.slot[islot].span = span; + global_huge_cache.slot[islot].free_ms = now; + global_huge_cache.committed += committed_size; + cached = 1; + break; + } + } + } + huge_cache_lock_release(); + return cached; +} + +//! Try to pop a cached huge mapping fitting the requested size (within the +//! size class spacing), returns 0 on miss +static span_t* +huge_cache_pop(size_t alloc_size) { + // Racy emptiness peek is fine - a missed entry only costs a fresh mapping + int empty = 1; + for (uint32_t islot = 0; islot < HUGE_CACHE_SLOT_COUNT; ++islot) { + if (global_huge_cache.slot[islot].span) { + empty = 0; + break; + } + } + if (empty) + return 0; + size_t size_limit = alloc_size + (alloc_size >> 2); + span_t* best = 0; + size_t best_size = 0; + uint32_t best_slot = 0; + huge_cache_lock_acquire(); + for (uint32_t islot = 0; islot < HUGE_CACHE_SLOT_COUNT; ++islot) { + span_t* span = global_huge_cache.slot[islot].span; + if (!span) + continue; + size_t committed_size = (size_t)span->page_count * span->page_size; + if ((committed_size >= alloc_size) && (committed_size <= size_limit) && + (!best || (committed_size < best_size))) { + best = span; + best_size = committed_size; + best_slot = islot; + } + } + if (best) { + global_huge_cache.slot[best_slot].span = 0; + global_huge_cache.committed -= best_size; + } + huge_cache_lock_release(); + return best; +} + +#endif + +static NOINLINE void +span_deallocate_block(span_t* span, page_t* page, void* block) { + if (UNEXPECTED(page->page_type == PAGE_HUGE)) { +#if ENABLE_STATISTICS + statistics_sub_saturating(&global_statistics.huge_alloc, (size_t)span->page_count * span->page_size); +#endif +#if RPMALLOC_HEAP_STATISTICS + if (span->heap) { + span->heap->stats.mapped_size -= span->mapped_size; +#if ENABLE_DECOMMIT + span->heap->stats.committed_size -= span->page_count * span->page_size; +#else + span->heap->stats.committed_size -= span->mapped_size; +#endif + } +#endif +#if HUGE_CACHE_SLOT_COUNT + if (huge_cache_push(span)) + return; +#endif + global_memory_interface->memory_unmap(span, span->offset, span->mapped_size); + return; } + if (page->has_aligned_block) { + block = page_block_realign(page, block); + } + + int is_thread_local = page_is_thread_heap(page); + if (EXPECTED(is_thread_local != 0)) { + page_put_local_free_block(page, block); + } else { + // Multithreaded deallocation, push to deferred deallocation list. + page_put_thread_free_block(page, block); + } +} + +//////////// +/// +/// Block interface +/// +////// + +static inline span_t* +block_get_span(block_t* block) { + return (span_t*)((uintptr_t)block & SPAN_MASK); +} + +static inline void +block_deallocate(block_t* block) { + span_t* span = (span_t*)((uintptr_t)block & SPAN_MASK); + page_t* page = span_get_page_from_block(span, block); + const int is_thread_local = page_is_thread_heap(page); + +#if RPMALLOC_HEAP_STATISTICS + heap_t* heap = span->heap; + if (heap) { + if (span->page_type <= PAGE_LARGE) + heap->stats.allocated_size -= page->block_size; + else + heap->stats.allocated_size -= ((size_t)span->page_size * (size_t)span->page_count); + } +#endif + + // Optimized path for thread local free with non-huge block in page + // that has no aligned blocks + if (EXPECTED(is_thread_local != 0)) { + if (EXPECTED(page->generic_free == 0)) { + // Page is not huge, not full and has no aligned block - fast path + block->next = page->local_free; + page->local_free = block; + ++page->local_free_count; + _rpmalloc_stat_add_free(page->heap, page->size_class, 1); + if (UNEXPECTED(--page->block_used == 0)) + page_available_to_free(page); + } else { + span_deallocate_block(span, page, block); + } + } else { + span_deallocate_block(span, page, block); + } +} + +static inline size_t +block_usable_size(block_t* block) { + span_t* span = (span_t*)((uintptr_t)block & SPAN_MASK); + if (EXPECTED(span->page_type <= PAGE_LARGE)) { + page_t* page = span_get_page_from_block(span, block); + void* blocks_start = pointer_offset(page, PAGE_HEADER_SIZE); + return page->block_size - ((size_t)pointer_diff(block, blocks_start) % page->block_size); + } else { + return ((size_t)span->page_size * (size_t)span->page_count) - (size_t)pointer_diff(block, span); + } +} + +//////////// +/// +/// Heap interface +/// +////// + +static inline void +heap_lock_acquire(void) { + uintptr_t lock = 0; + uintptr_t this_lock = get_thread_id(); + uint32_t spin = 0; + while (!atomic_compare_exchange_strong(&global_heap_lock, &lock, this_lock)) { + lock = 0; + wait_spin(&spin); + } +} + +static inline void +heap_lock_release(void) { + rpmalloc_assert((uintptr_t)atomic_load_explicit(&global_heap_lock, memory_order_relaxed) == get_thread_id(), + "Bad heap lock"); + atomic_store_explicit(&global_heap_lock, 0, memory_order_release); +} + +static inline heap_t* +heap_initialize(void* block) { + heap_t* heap = block; + memset_const(heap, 0, sizeof(heap_t)); + heap->id = 1 + atomic_fetch_add_explicit(&global_heap_id, 1, memory_order_relaxed); + return heap; +} + +// A heap control structure is much smaller than the mapping page size (and far smaller than a +// huge page), so a single page-aligned mapping is carved into as many heaps as fit, the first +// returned to the caller and the extras queued for reuse. This avoids mapping (and, under huge +// pages, committing) a whole page per heap. Only the first heap records the mapping offset and +// size; it owns the shared mapping and is the one heap that unmaps it at finalize. +// +// Block creation is serialized through global_heap_creating: when no heap is available, one thread +// maps and carves a block while concurrent thread starts wait for the carved heaps to be published, +// so a startup burst maps a single block instead of one block per thread. Ordinary requests reuse a +// released heap first, then a pristine carved one. First-class requests need a heap with no prior +// allocations, so they take only pristine heaps (a carved extra, or a freshly mapped master), never +// a released one, but still wait so they do not map concurrently with another creation. +static heap_t* +heap_allocate_new(int first_class) { + if (!global_config.page_size) + rpmalloc_initialize(0); + + heap_lock_acquire(); + uint32_t spin = 0; + while (1) { + if (!first_class && global_heap_queue) { + heap_t* heap = global_heap_queue; + global_heap_queue = heap->next; + heap_lock_release(); + return heap; + } + if (global_heap_pristine) { + heap_t* heap = global_heap_pristine; + global_heap_pristine = heap->next; + heap_lock_release(); + return heap; + } + if (!global_heap_creating) + break; + heap_lock_release(); + wait_spin(&spin); + heap_lock_acquire(); + } + global_heap_creating = 1; + heap_lock_release(); + + size_t aligned_heap_size = HEAP_ALIGNMENT * ((sizeof(heap_t) + (HEAP_ALIGNMENT - 1)) / HEAP_ALIGNMENT); + size_t block_size = get_page_aligned_size(aligned_heap_size); + size_t offset = 0; + size_t mapped_size = 0; + block_t* block = global_memory_interface->memory_map(block_size, 0, &offset, &mapped_size); +#if ENABLE_DECOMMIT + if (block && os_commit_on_demand() && (global_memory_interface->memory_commit(block, block_size) != 0)) { + global_memory_interface->memory_unmap(block, offset, mapped_size); + block = 0; + } +#endif + if (!block) { + heap_lock_acquire(); + global_heap_creating = 0; + heap_lock_release(); + return 0; + } + + heap_t* heap = heap_initialize((void*)block); + heap->offset = (uint32_t)offset; + heap->mapped_size = mapped_size; + + // Carve the remaining heaps into a local chain, then splice it onto the pristine pool in one + // step so the lock is not held across the per-heap initialization. heap_initialize zeroes each + // structure, leaving mapped_size == 0 so the extras are not treated as mapping owners. They are + // pristine until handed out, so first-class requests may reuse them. + size_t heap_count = mapped_size / aligned_heap_size; + heap_t* chain_head = 0; + heap_t* chain_tail = 0; + heap_t* extra_heap = (heap_t*)pointer_offset(heap, aligned_heap_size); + for (size_t iheap = 1; iheap < heap_count; ++iheap) { + heap_initialize((void*)extra_heap); + if (!chain_tail) + chain_tail = extra_heap; + extra_heap->next = chain_head; + chain_head = extra_heap; + extra_heap = (heap_t*)pointer_offset(extra_heap, aligned_heap_size); + } + + heap_lock_acquire(); + if (chain_tail) { + chain_tail->next = global_heap_pristine; + global_heap_pristine = chain_head; + } + global_heap_creating = 0; + heap_lock_release(); + return heap; +} + +// Unmaps the shared block owned by this heap. INVARIANT: heap blocks are only ever unmapped here, +// at global finalize, never while the allocator is running. Several heaps share a block, and a heap +// may be borrowed by an unrelated owner's thread or by a first-class heap that outlives the thread +// whose request mapped the block (see heap_allocate_new). Unmapping a block mid-run would leave +// those borrowed heaps pointing at freed memory, so any future block reclamation must guarantee no +// heap carved from the block is still live. +static void +heap_unmap(heap_t* heap) { + global_memory_interface->memory_unmap(heap, heap->offset, heap->mapped_size); +} + +static heap_t* +heap_allocate(int first_class) { + heap_t* heap = heap_allocate_new(first_class); + if (heap) { + uintptr_t current_thread_id = get_thread_id(); + heap_lock_acquire(); + heap->next = global_heap_used; + heap->prev = 0; + if (global_heap_used) + global_heap_used->prev = heap; + global_heap_used = heap; + heap_lock_release(); + heap->owner_thread = current_thread_id; +#if ENABLE_STATISTICS + // Counters belong to the heap, not the thread, so alloc_current reflects the blocks live in + // the heap's pages regardless of which thread owns it. + atomic_fetch_add_explicit(&global_statistics.heap_count, 1, memory_order_relaxed); +#endif + } + return heap; +} + +static inline void +heap_release(heap_t* heap) { +#if ENABLE_STATISTICS + statistics_sub_saturating(&global_statistics.heap_count, 1); +#endif + heap_lock_acquire(); + if (heap->prev) + heap->prev->next = heap->next; + if (heap->next) + heap->next->prev = heap->prev; + if (global_heap_used == heap) + global_heap_used = heap->next; + heap->next = global_heap_queue; + global_heap_queue = heap; + heap_lock_release(); +} + +static void +heap_page_free_decommit(heap_t* heap, uint32_t page_type, uint32_t page_retain_count) { + page_t* page = heap->page_free[page_type]; + while (page && page_retain_count) { + page = page->next; + --page_retain_count; + } + while (page && (page->is_decommitted == 0)) { + page_decommit_memory_pages(page); + // Decommit can be refused (decommit disabled, page type not larger than the + // configured page size, or kernel rejecting decommit of huge page mappings), + // in which case remaining pages cannot be decommitted either + if (page->is_decommitted == 0) + break; + --heap->page_free_commit_count[page_type]; + page = page->next; + } +} + +static inline int +heap_make_free_page_available(heap_t* heap, uint32_t size_class, page_t* page) { + page->size_class = size_class; + page->block_size = global_size_class[size_class].block_size; + page->block_count = global_size_class[size_class].block_count; + page->block_used = 0; + page->block_initialized = 0; + page->local_free = 0; + page->local_free_count = 0; + page->is_full = 0; + page->is_free = 0; + page->has_aligned_block = 0; + page->generic_free = 0; + page->heap = heap; + page_t* head = heap->page_available[size_class]; + page->next = head; + page->prev = 0; + atomic_store_explicit(&page->thread_free, 0, memory_order_release); + if (head) + head->prev = page; + heap->page_available[size_class] = page; + if (page->is_decommitted != 0) + return page_commit_memory_pages(page); return 0; } -//! Allocate a small sized memory block from the given heap -static void* -_rpmalloc_allocate_small(heap_t* heap, size_t size) { - rpmalloc_assert(heap, "No thread heap"); - //Small sizes have unique size classes - const uint32_t class_idx = (uint32_t)((size + (SMALL_GRANULARITY - 1)) >> SMALL_GRANULARITY_SHIFT); - heap_size_class_t* heap_size_class = heap->size_class + class_idx; - _rpmalloc_stat_inc_alloc(heap, class_idx); - if (EXPECTED(heap_size_class->free_list != 0)) - return free_list_pop(&heap_size_class->free_list); - return _rpmalloc_allocate_from_heap_fallback(heap, heap_size_class, class_idx); -} +//! Find or allocate a span for the given page type with the given size class +static inline span_t* +heap_get_span(heap_t* heap, page_type_t page_type) { + // Fast path, available span for given page type + if (EXPECTED(heap->span_partial[page_type] != 0)) + return heap->span_partial[page_type]; -//! Allocate a medium sized memory block from the given heap -static void* -_rpmalloc_allocate_medium(heap_t* heap, size_t size) { - rpmalloc_assert(heap, "No thread heap"); - //Calculate the size class index and do a dependent lookup of the final class index (in case of merged classes) - const uint32_t base_idx = (uint32_t)(SMALL_CLASS_COUNT + ((size - (SMALL_SIZE_LIMIT + 1)) >> MEDIUM_GRANULARITY_SHIFT)); - const uint32_t class_idx = _memory_size_class[base_idx].class_idx; - heap_size_class_t* heap_size_class = heap->size_class + class_idx; - _rpmalloc_stat_inc_alloc(heap, class_idx); - if (EXPECTED(heap_size_class->free_list != 0)) - return free_list_pop(&heap_size_class->free_list); - return _rpmalloc_allocate_from_heap_fallback(heap, heap_size_class, class_idx); -} - -//! Allocate a large sized memory block from the given heap -static void* -_rpmalloc_allocate_large(heap_t* heap, size_t size) { - rpmalloc_assert(heap, "No thread heap"); - //Calculate number of needed max sized spans (including header) - //Since this function is never called if size > LARGE_SIZE_LIMIT - //the span_count is guaranteed to be <= LARGE_CLASS_COUNT - size += SPAN_HEADER_SIZE; - size_t span_count = size >> _memory_span_size_shift; - if (size & (_memory_span_size - 1)) - ++span_count; - - //Find a span in one of the cache levels - span_t* span = _rpmalloc_heap_extract_new_span(heap, 0, span_count, SIZE_CLASS_LARGE); - if (!span) - return span; - - //Mark span as owned by this heap and set base data - rpmalloc_assert(span->span_count >= span_count, "Internal failure"); - span->size_class = SIZE_CLASS_LARGE; - span->heap = heap; - -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_add(&heap->large_huge_span, span); + // Fallback path, map more memory + size_t offset = 0; + size_t mapped_size = 0; + span_t* span = global_memory_interface->memory_map(SPAN_SIZE, SPAN_SIZE, &offset, &mapped_size); +#if RPMALLOC_HEAP_STATISTICS + heap->stats.mapped_size += mapped_size; #endif - ++heap->full_span_count; - - return pointer_offset(span, SPAN_HEADER_SIZE); -} - -//! Allocate a huge block by mapping memory pages directly -static void* -_rpmalloc_allocate_huge(heap_t* heap, size_t size) { - rpmalloc_assert(heap, "No thread heap"); - _rpmalloc_heap_cache_adopt_deferred(heap, 0); - size += SPAN_HEADER_SIZE; - size_t num_pages = size >> _memory_page_size_shift; - if (size & (_memory_page_size - 1)) - ++num_pages; - size_t align_offset = 0; - span_t* span = (span_t*)_rpmalloc_mmap(num_pages * _memory_page_size, &align_offset); - if (!span) - return span; - - //Store page count in span_count - span->size_class = SIZE_CLASS_HUGE; - span->span_count = (uint32_t)num_pages; - span->align_offset = (uint32_t)align_offset; - span->heap = heap; - _rpmalloc_stat_add_peak(&_huge_pages_current, num_pages, _huge_pages_peak); - -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_add(&heap->large_huge_span, span); + if (EXPECTED(span != 0)) { + rpmalloc_assert(!((uintptr_t)span & (SPAN_SIZE - 1)), + "memory_map returned a block not aligned to the span size"); + _rpmalloc_stat_inc_span_map(heap, page_type); + uint32_t page_count = 0; + uint32_t page_size = 0; + uintptr_t page_address_mask = 0; + if (page_type == PAGE_SMALL) { + page_count = SPAN_SIZE / SMALL_PAGE_SIZE; + page_size = SMALL_PAGE_SIZE; + page_address_mask = SMALL_PAGE_MASK; + } else if (page_type == PAGE_MEDIUM_SMALL) { + page_count = SPAN_SIZE / MEDIUM_SMALL_PAGE_SIZE; + page_size = MEDIUM_SMALL_PAGE_SIZE; + page_address_mask = MEDIUM_SMALL_PAGE_MASK; + } else if (page_type == PAGE_MEDIUM_LARGE) { + page_count = SPAN_SIZE / MEDIUM_LARGE_PAGE_SIZE; + page_size = MEDIUM_LARGE_PAGE_SIZE; + page_address_mask = MEDIUM_LARGE_PAGE_MASK; + } else { + page_count = SPAN_SIZE / LARGE_PAGE_SIZE; + page_size = LARGE_PAGE_SIZE; + page_address_mask = LARGE_PAGE_MASK; + } + // Commit the first page for reserve-only spans (fully committed spans commit nothing + // here); record the commit model on the span only after its header is committed + int commit_on_demand = os_commit_on_demand(); +#if ENABLE_DECOMMIT + if (commit_on_demand) { + if (global_memory_interface->memory_commit(span, page_size) != 0) { + global_memory_interface->memory_unmap(span, offset, mapped_size); + return 0; + } + } #endif - ++heap->full_span_count; + span->page.commit_on_demand = (uint32_t)commit_on_demand; + uint32_t commit_prefix_shift = 0; + while (((size_t)1 << commit_prefix_shift) < global_config.page_size) + ++commit_prefix_shift; + span->page.commit_prefix_shift = commit_prefix_shift; +#if RPMALLOC_HEAP_STATISTICS +#if ENABLE_DECOMMIT + heap->stats.committed_size += page_size; +#else + heap->stats.committed_size += mapped_size; +#endif +#endif + span->heap = heap; + span->page_type = page_type; + span->page_count = page_count; + span->page_size = page_size; + span->page_address_mask = page_address_mask; + span->offset = (uint32_t)offset; + span->mapped_size = mapped_size; - return pointer_offset(span, SPAN_HEADER_SIZE); + heap->span_partial[page_type] = span; + } + + return span; } -//! Allocate a block of the given size -static void* -_rpmalloc_allocate(heap_t* heap, size_t size) { - _rpmalloc_stat_add64(&_allocation_counter, 1); - if (EXPECTED(size <= SMALL_SIZE_LIMIT)) - return _rpmalloc_allocate_small(heap, size); - else if (size <= _memory_medium_size_limit) - return _rpmalloc_allocate_medium(heap, size); - else if (size <= LARGE_SIZE_LIMIT) - return _rpmalloc_allocate_large(heap, size); - return _rpmalloc_allocate_huge(heap, size); +static page_t* +heap_get_page(heap_t* heap, uint32_t size_class); + +static void +block_deallocate(block_t* block); + +static page_t* +heap_get_page_generic(heap_t* heap, uint32_t size_class) { + page_type_t page_type = get_page_type(size_class); + + // Check if there is a free page from multithreaded deallocations + uintptr_t block_mt = atomic_load_explicit(&heap->thread_free[page_type], memory_order_relaxed); + if (UNEXPECTED(block_mt != 0)) { + uint32_t spin = 0; + while (!atomic_compare_exchange_weak_explicit(&heap->thread_free[page_type], &block_mt, 0, memory_order_acquire, + memory_order_relaxed)) { + wait_spin(&spin); + } + block_t* block = (void*)block_mt; + while (block) { + block_t* next_block = block->next; + block_deallocate(block); + block = next_block; + } + // Retry after processing deferred thread frees + return heap_get_page(heap, size_class); + } + + // Check if there is a free page + page_t* page = heap->page_free[page_type]; + if (EXPECTED(page != 0)) { + heap->page_free[page_type] = page->next; + if (page->is_decommitted == 0) { + rpmalloc_assert(heap->page_free_commit_count[page_type] > 0, "Free committed page count out of sync"); + --heap->page_free_commit_count[page_type]; + } + if (heap_make_free_page_available(heap, size_class, page) != 0) + return 0; + return page; + } + rpmalloc_assert(heap->page_free_commit_count[page_type] == 0, "Free committed page count out of sync"); + + if (heap->id == 0) { + // Thread has not yet initialized, assign heap and try again + rpmalloc_initialize(0); + return heap_get_page(get_thread_heap(), size_class); + } + + // Fallback path, find or allocate span for given size class + // If thread was not initialized, the heap for the new span + // will be different from the local heap variable in this scope + // (which is the default heap) - so use span page heap instead + span_t* span = heap_get_span(heap, page_type); + if (EXPECTED(span != 0)) { + page = span_allocate_page(span); + if (heap_make_free_page_available(page->heap, size_class, page) != 0) + return 0; + } + + return page; } -static void* -_rpmalloc_aligned_allocate(heap_t* heap, size_t alignment, size_t size) { +//! Find or allocate a page for the given size class +static page_t* +heap_get_page(heap_t* heap, uint32_t size_class) { + // Fast path, available page for given size class + page_t* page = heap->page_available[size_class]; + if (EXPECTED(page != 0)) + return page; + return heap_get_page_generic(heap, size_class); +} + +//! Pop a block from the heap local free list +static inline RPMALLOC_ALLOCATOR void* +heap_pop_local_free(heap_t* heap, uint32_t size_class) { + block_t** free_list = heap->local_free + size_class; + block_t* block = *free_list; + if (EXPECTED(block != 0)) + *free_list = block->next; + return block; +} + +//! Generic allocation path from heap pages, spans or new mapping +static NOINLINE RPMALLOC_ALLOCATOR void* +heap_allocate_block_small_to_large(heap_t* heap, uint32_t size_class, unsigned int zero) { + page_t* page = heap_get_page(heap, size_class); + if (EXPECTED(page != 0)) { + // Count on the page owner, which may differ from heap when an uninitialized thread is routed + // to its real heap, so the allocation and its later free are accounted on the same heap + _rpmalloc_stat_inc_alloc(page->heap, size_class); + return page_allocate_block(page, zero); + } + return 0; +} + +//! Generic allocation path from heap pages, spans or new mapping +static NOINLINE RPMALLOC_ALLOCATOR void* +heap_allocate_block_huge(heap_t* heap, size_t size, unsigned int zero) { + if (heap->id == 0) { + // Thread has not yet initialized, assign heap and try again + rpmalloc_initialize(0); + heap = get_thread_heap(); + } + size_t alloc_size = get_page_aligned_size(size + SPAN_HEADER_SIZE); + size_t offset = 0; + size_t mapped_size = 0; + void* block = 0; + int from_cache = 0; +#if HUGE_CACHE_SLOT_COUNT + // Reuse a recently freed huge mapping of fitting size if available (the + // cached span keeps its own offset/mapped_size/page_count fields) + block = huge_cache_pop(alloc_size); + if (block) + from_cache = 1; +#endif + if (!block) + block = global_memory_interface->memory_map(alloc_size, SPAN_SIZE, &offset, &mapped_size); + if (block) { + span_t* span = block; + rpmalloc_assert(!((uintptr_t)span & (SPAN_SIZE - 1)), + "memory_map returned a block not aligned to the span size"); + if (!from_cache) + _rpmalloc_stat_inc_span_map(heap, PAGE_HUGE); +#if ENABLE_DECOMMIT + if (!from_cache && os_commit_on_demand() && + (global_memory_interface->memory_commit(span, alloc_size) != 0)) { + global_memory_interface->memory_unmap(block, offset, mapped_size); + return 0; + } +#endif +#if RPMALLOC_HEAP_STATISTICS + heap->stats.mapped_size += mapped_size; +#if ENABLE_DECOMMIT + heap->stats.committed_size += alloc_size; +#else + heap->stats.committed_size += mapped_size; +#endif +#endif + span->heap = heap; + span->page_type = PAGE_HUGE; + span->page_address_mask = LARGE_PAGE_MASK; + // Huge blocks never use the per-page commit path; set explicitly so a reused cached + // mapping carries no stale value + span->page.commit_on_demand = 0; + if (!from_cache) { + span->page_size = (uint32_t)global_config.page_size; + span->page_count = (uint32_t)(alloc_size / global_config.page_size); + span->offset = (uint32_t)offset; + span->mapped_size = mapped_size; + } + span->page.heap = heap; + span->page.is_full = 1; + span->page.generic_free = 1; + span->page.page_type = PAGE_HUGE; +#if ENABLE_STATISTICS + size_t huge_alloc_size = (size_t)span->page_count * span->page_size; + size_t huge_alloc_current = + atomic_fetch_add_explicit(&global_statistics.huge_alloc, huge_alloc_size, memory_order_relaxed) + + huge_alloc_size; + size_t huge_alloc_peak = atomic_load_explicit(&global_statistics.huge_alloc_peak, memory_order_relaxed); + while (huge_alloc_current > huge_alloc_peak) { + if (atomic_compare_exchange_weak_explicit(&global_statistics.huge_alloc_peak, &huge_alloc_peak, + huge_alloc_current, memory_order_relaxed, memory_order_relaxed)) + break; + } +#endif + // Keep track of span if first class heap + if (!heap->owner_thread) { + span->next = heap->span_used[PAGE_HUGE]; + heap->span_used[PAGE_HUGE] = span; + } + void* ptr = pointer_offset(block, SPAN_HEADER_SIZE); + if (zero) + memset(ptr, 0, size); +#if RPMALLOC_HEAP_STATISTICS + heap->stats.allocated_size += size; +#endif + return ptr; + } + return 0; +} + +static RPMALLOC_ALLOCATOR NOINLINE void* +heap_allocate_block_generic(heap_t* heap, size_t size, unsigned int zero) { + uint32_t size_class = get_size_class(size); + if (EXPECTED(size_class < SIZE_CLASS_COUNT)) { +#if RPMALLOC_HEAP_STATISTICS + heap->stats.allocated_size += global_size_class[size_class].block_size; +#endif + + block_t* block = heap_pop_local_free(heap, size_class); + if (EXPECTED(block != 0)) { + // Fast track with small block available in heap level local free list; a hit means this + // heap owns the block + _rpmalloc_stat_inc_alloc(heap, size_class); + if (zero) + memset(block, 0, global_size_class[size_class].block_size); + return block; + } + + return heap_allocate_block_small_to_large(heap, size_class, zero); + } + + return heap_allocate_block_huge(heap, size, zero); +} + +//! Find or allocate a block of the given size +static inline RPMALLOC_ALLOCATOR void* +heap_allocate_block(heap_t* heap, size_t size, unsigned int zero) { + if (size <= (SMALL_GRANULARITY * 64)) { + uint32_t size_class = get_size_class_tiny(size); + block_t* block = heap_pop_local_free(heap, size_class); + if (EXPECTED(block != 0)) { + // Fast track with small block available in heap level local free list + if (zero) + memset(block, 0, global_size_class[size_class].block_size); +#if RPMALLOC_HEAP_STATISTICS + heap->stats.allocated_size += global_size_class[size_class].block_size; +#endif + _rpmalloc_stat_inc_alloc(heap, size_class); + return block; + } +#if RPMALLOC_HEAP_STATISTICS + heap->stats.allocated_size += global_size_class[size_class].block_size; +#endif + // The size class is already known - refill directly, skipping the + // generic path size class recomputation and dead local free list pop + // (small_to_large counts the allocation on the owning heap) + return heap_allocate_block_small_to_large(heap, size_class, zero); + } + return heap_allocate_block_generic(heap, size, zero); +} + +static RPMALLOC_ALLOCATOR void* +heap_allocate_block_aligned(heap_t* heap, size_t alignment, size_t size, unsigned int zero) { if (alignment <= SMALL_GRANULARITY) - return _rpmalloc_allocate(heap, size); + return heap_allocate_block(heap, size, zero); #if ENABLE_VALIDATE_ARGS if ((size + alignment) < size) { @@ -2160,749 +2308,157 @@ _rpmalloc_aligned_allocate(heap_t* heap, size_t alignment, size_t size) { return 0; } #endif - - if ((alignment <= SPAN_HEADER_SIZE) && (size < _memory_medium_size_limit)) { - // If alignment is less or equal to span header size (which is power of two), - // and size aligned to span header size multiples is less than size + alignment, - // then use natural alignment of blocks to provide alignment - size_t multiple_size = size ? (size + (SPAN_HEADER_SIZE - 1)) & ~(uintptr_t)(SPAN_HEADER_SIZE - 1) : SPAN_HEADER_SIZE; - rpmalloc_assert(!(multiple_size % SPAN_HEADER_SIZE), "Failed alignment calculation"); - if (multiple_size <= (size + alignment)) - return _rpmalloc_allocate(heap, multiple_size); + if (alignment >= RPMALLOC_MAX_ALIGNMENT) { + errno = EINVAL; + return 0; } - void* ptr = 0; size_t align_mask = alignment - 1; - if (alignment <= _memory_page_size) { - ptr = _rpmalloc_allocate(heap, size + alignment); - if ((uintptr_t)ptr & align_mask) { - ptr = (void*)(((uintptr_t)ptr & ~(uintptr_t)align_mask) + alignment); - //Mark as having aligned blocks - span_t* span = (span_t*)((uintptr_t)ptr & _memory_span_mask); - span->flags |= SPAN_FLAG_ALIGNED_BLOCKS; - } - return ptr; + block_t* block = heap_allocate_block(heap, size + alignment, zero); + if ((uintptr_t)block & align_mask) { + block = (void*)(((uintptr_t)block & ~(uintptr_t)align_mask) + alignment); + // Mark as having aligned blocks + span_t* span = block_get_span(block); + page_t* page = span_get_page_from_block(span, block); + page->has_aligned_block = 1; + page->generic_free = 1; } - - // Fallback to mapping new pages for this request. Since pointers passed - // to rpfree must be able to reach the start of the span by bitmasking of - // the address with the span size, the returned aligned pointer from this - // function must be with a span size of the start of the mapped area. - // In worst case this requires us to loop and map pages until we get a - // suitable memory address. It also means we can never align to span size - // or greater, since the span header will push alignment more than one - // span size away from span start (thus causing pointer mask to give us - // an invalid span start on free) - if (alignment & align_mask) { - errno = EINVAL; - return 0; - } - if (alignment >= _memory_span_size) { - errno = EINVAL; - return 0; - } - - size_t extra_pages = alignment / _memory_page_size; - - // Since each span has a header, we will at least need one extra memory page - size_t num_pages = 1 + (size / _memory_page_size); - if (size & (_memory_page_size - 1)) - ++num_pages; - - if (extra_pages > num_pages) - num_pages = 1 + extra_pages; - - size_t original_pages = num_pages; - size_t limit_pages = (_memory_span_size / _memory_page_size) * 2; - if (limit_pages < (original_pages * 2)) - limit_pages = original_pages * 2; - - size_t mapped_size, align_offset; - span_t* span; - -retry: - align_offset = 0; - mapped_size = num_pages * _memory_page_size; - - span = (span_t*)_rpmalloc_mmap(mapped_size, &align_offset); - if (!span) { - errno = ENOMEM; - return 0; - } - ptr = pointer_offset(span, SPAN_HEADER_SIZE); - - if ((uintptr_t)ptr & align_mask) - ptr = (void*)(((uintptr_t)ptr & ~(uintptr_t)align_mask) + alignment); - - if (((size_t)pointer_diff(ptr, span) >= _memory_span_size) || - (pointer_offset(ptr, size) > pointer_offset(span, mapped_size)) || - (((uintptr_t)ptr & _memory_span_mask) != (uintptr_t)span)) { - _rpmalloc_unmap(span, mapped_size, align_offset, mapped_size); - ++num_pages; - if (num_pages > limit_pages) { - errno = EINVAL; - return 0; - } - goto retry; - } - - //Store page count in span_count - span->size_class = SIZE_CLASS_HUGE; - span->span_count = (uint32_t)num_pages; - span->align_offset = (uint32_t)align_offset; - span->heap = heap; - _rpmalloc_stat_add_peak(&_huge_pages_current, num_pages, _huge_pages_peak); - -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_add(&heap->large_huge_span, span); -#endif - ++heap->full_span_count; - - _rpmalloc_stat_add64(&_allocation_counter, 1); - - return ptr; + return block; } - -//////////// -/// -/// Deallocation entry points -/// -////// - -//! Deallocate the given small/medium memory block in the current thread local heap -static void -_rpmalloc_deallocate_direct_small_or_medium(span_t* span, void* block) { - heap_t* heap = span->heap; - rpmalloc_assert(heap->owner_thread == get_thread_id() || !heap->owner_thread || heap->finalize, "Internal failure"); - //Add block to free list - if (UNEXPECTED(_rpmalloc_span_is_fully_utilized(span))) { - span->used_count = span->block_count; -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_remove(&heap->full_span[span->size_class], span); -#endif - _rpmalloc_span_double_link_list_add(&heap->size_class[span->size_class].partial_span, span); - --heap->full_span_count; - } - *((void**)block) = span->free_list; - --span->used_count; - span->free_list = block; - if (UNEXPECTED(span->used_count == span->list_size)) { - _rpmalloc_span_double_link_list_remove(&heap->size_class[span->size_class].partial_span, span); - _rpmalloc_span_release_to_cache(heap, span); - } -} - -static void -_rpmalloc_deallocate_defer_free_span(heap_t* heap, span_t* span) { - if (span->size_class != SIZE_CLASS_HUGE) - _rpmalloc_stat_inc(&heap->span_use[span->span_count - 1].spans_deferred); - //This list does not need ABA protection, no mutable side state - do { - span->free_list = (void*)atomic_load_ptr(&heap->span_free_deferred); - } while (!atomic_cas_ptr(&heap->span_free_deferred, span, span->free_list)); -} - -//! Put the block in the deferred free list of the owning span -static void -_rpmalloc_deallocate_defer_small_or_medium(span_t* span, void* block) { - // The memory ordering here is a bit tricky, to avoid having to ABA protect - // the deferred free list to avoid desynchronization of list and list size - // we need to have acquire semantics on successful CAS of the pointer to - // guarantee the list_size variable validity + release semantics on pointer store - void* free_list; - do { - free_list = atomic_exchange_ptr_acquire(&span->free_list_deferred, INVALID_POINTER); - } while (free_list == INVALID_POINTER); - *((void**)block) = free_list; - uint32_t free_count = ++span->list_size; - atomic_store_ptr_release(&span->free_list_deferred, block); - if (free_count == span->block_count) { - // Span was completely freed by this block. Due to the INVALID_POINTER spin lock - // no other thread can reach this state simultaneously on this span. - // Safe to move to owner heap deferred cache - _rpmalloc_deallocate_defer_free_span(span->heap, span); - } -} - -static void -_rpmalloc_deallocate_small_or_medium(span_t* span, void* p) { - _rpmalloc_stat_inc_free(span->heap, span->size_class); - if (span->flags & SPAN_FLAG_ALIGNED_BLOCKS) { - //Realign pointer to block start - void* blocks_start = pointer_offset(span, SPAN_HEADER_SIZE); - uint32_t block_offset = (uint32_t)pointer_diff(p, blocks_start); - p = pointer_offset(p, -(int32_t)(block_offset % span->block_size)); - } - //Check if block belongs to this heap or if deallocation should be deferred -#if RPMALLOC_FIRST_CLASS_HEAPS - int defer = (span->heap->owner_thread && (span->heap->owner_thread != get_thread_id()) && !span->heap->finalize); -#else - int defer = ((span->heap->owner_thread != get_thread_id()) && !span->heap->finalize); -#endif - if (!defer) - _rpmalloc_deallocate_direct_small_or_medium(span, p); - else - _rpmalloc_deallocate_defer_small_or_medium(span, p); -} - -//! Deallocate the given large memory block to the current heap -static void -_rpmalloc_deallocate_large(span_t* span) { - rpmalloc_assert(span->size_class == SIZE_CLASS_LARGE, "Bad span size class"); - rpmalloc_assert(!(span->flags & SPAN_FLAG_MASTER) || !(span->flags & SPAN_FLAG_SUBSPAN), "Span flag corrupted"); - rpmalloc_assert((span->flags & SPAN_FLAG_MASTER) || (span->flags & SPAN_FLAG_SUBSPAN), "Span flag corrupted"); - //We must always defer (unless finalizing) if from another heap since we cannot touch the list or counters of another heap -#if RPMALLOC_FIRST_CLASS_HEAPS - int defer = (span->heap->owner_thread && (span->heap->owner_thread != get_thread_id()) && !span->heap->finalize); -#else - int defer = ((span->heap->owner_thread != get_thread_id()) && !span->heap->finalize); -#endif - if (defer) { - _rpmalloc_deallocate_defer_free_span(span->heap, span); - return; - } - rpmalloc_assert(span->heap->full_span_count, "Heap span counter corrupted"); - --span->heap->full_span_count; -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_remove(&span->heap->large_huge_span, span); -#endif -#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS - //Decrease counter - size_t idx = span->span_count - 1; - atomic_decr32(&span->heap->span_use[idx].current); -#endif - heap_t* heap = span->heap; - rpmalloc_assert(heap, "No thread heap"); -#if ENABLE_THREAD_CACHE - const int set_as_reserved = ((span->span_count > 1) && (heap->span_cache.count == 0) && !heap->finalize && !heap->spans_reserved); -#else - const int set_as_reserved = ((span->span_count > 1) && !heap->finalize && !heap->spans_reserved); -#endif - if (set_as_reserved) { - heap->span_reserve = span; - heap->spans_reserved = span->span_count; - if (span->flags & SPAN_FLAG_MASTER) { - heap->span_reserve_master = span; - } else { //SPAN_FLAG_SUBSPAN - span_t* master = (span_t*)pointer_offset(span, -(intptr_t)((size_t)span->offset_from_master * _memory_span_size)); - heap->span_reserve_master = master; - rpmalloc_assert(master->flags & SPAN_FLAG_MASTER, "Span flag corrupted"); - rpmalloc_assert(atomic_load32(&master->remaining_spans) >= (int32_t)span->span_count, "Master span count corrupted"); - } - _rpmalloc_stat_inc(&heap->span_use[idx].spans_to_reserved); - } else { - //Insert into cache list - _rpmalloc_heap_cache_insert(heap, span); - } -} - -//! Deallocate the given huge span -static void -_rpmalloc_deallocate_huge(span_t* span) { - rpmalloc_assert(span->heap, "No span heap"); -#if RPMALLOC_FIRST_CLASS_HEAPS - int defer = (span->heap->owner_thread && (span->heap->owner_thread != get_thread_id()) && !span->heap->finalize); -#else - int defer = ((span->heap->owner_thread != get_thread_id()) && !span->heap->finalize); -#endif - if (defer) { - _rpmalloc_deallocate_defer_free_span(span->heap, span); - return; - } - rpmalloc_assert(span->heap->full_span_count, "Heap span counter corrupted"); - --span->heap->full_span_count; -#if RPMALLOC_FIRST_CLASS_HEAPS - _rpmalloc_span_double_link_list_remove(&span->heap->large_huge_span, span); -#endif - - //Oversized allocation, page count is stored in span_count - size_t num_pages = span->span_count; - _rpmalloc_unmap(span, num_pages * _memory_page_size, span->align_offset, num_pages * _memory_page_size); - _rpmalloc_stat_sub(&_huge_pages_current, num_pages); -} - -//! Deallocate the given block -static void -_rpmalloc_deallocate(void* p) { - _rpmalloc_stat_add64(&_deallocation_counter, 1); - //Grab the span (always at start of span, using span alignment) - span_t* span = (span_t*)((uintptr_t)p & _memory_span_mask); - if (UNEXPECTED(!span)) - return; - if (EXPECTED(span->size_class < SIZE_CLASS_COUNT)) - _rpmalloc_deallocate_small_or_medium(span, p); - else if (span->size_class == SIZE_CLASS_LARGE) - _rpmalloc_deallocate_large(span); - else - _rpmalloc_deallocate_huge(span); -} - -//////////// -/// -/// Reallocation entry points -/// -////// - -static size_t -_rpmalloc_usable_size(void* p); - -//! Reallocate the given block to the given size static void* -_rpmalloc_reallocate(heap_t* heap, void* p, size_t size, size_t oldsize, unsigned int flags) { - if (p) { - //Grab the span using guaranteed span alignment - span_t* span = (span_t*)((uintptr_t)p & _memory_span_mask); - if (EXPECTED(span->size_class < SIZE_CLASS_COUNT)) { - //Small/medium sized block - rpmalloc_assert(span->span_count == 1, "Span counter corrupted"); - void* blocks_start = pointer_offset(span, SPAN_HEADER_SIZE); - uint32_t block_offset = (uint32_t)pointer_diff(p, blocks_start); - uint32_t block_idx = block_offset / span->block_size; - void* block = pointer_offset(blocks_start, (size_t)block_idx * span->block_size); - if (!oldsize) - oldsize = (size_t)((ptrdiff_t)span->block_size - pointer_diff(p, block)); - if ((size_t)span->block_size >= size) { - //Still fits in block, never mind trying to save memory, but preserve data if alignment changed - if ((p != block) && !(flags & RPMALLOC_NO_PRESERVE)) - memmove(block, p, oldsize); - return block; - } - } else if (span->size_class == SIZE_CLASS_LARGE) { - //Large block - size_t total_size = size + SPAN_HEADER_SIZE; - size_t num_spans = total_size >> _memory_span_size_shift; - if (total_size & (_memory_span_mask - 1)) - ++num_spans; - size_t current_spans = span->span_count; - void* block = pointer_offset(span, SPAN_HEADER_SIZE); - if (!oldsize) - oldsize = (current_spans * _memory_span_size) - (size_t)pointer_diff(p, block) - SPAN_HEADER_SIZE; - if ((current_spans >= num_spans) && (total_size >= (oldsize / 2))) { - //Still fits in block, never mind trying to save memory, but preserve data if alignment changed - if ((p != block) && !(flags & RPMALLOC_NO_PRESERVE)) - memmove(block, p, oldsize); - return block; +heap_reallocate_block(heap_t* heap, void* block, size_t size, size_t old_size, unsigned int flags) { + if (block) { + // Grab the span using guaranteed span alignment + span_t* span = block_get_span(block); + if (EXPECTED(span->page_type <= PAGE_LARGE)) { + // Normal sized block + page_t* page = span_get_page_from_block(span, block); + void* blocks_start = pointer_offset(page, PAGE_HEADER_SIZE); + uint32_t block_offset = (uint32_t)pointer_diff(block, blocks_start); + uint32_t block_idx = block_offset / page->block_size; + void* block_origin = pointer_offset(blocks_start, (size_t)block_idx * page->block_size); + if (!old_size) + old_size = (size_t)((ptrdiff_t)page->block_size - pointer_diff(block, block_origin)); + if ((size_t)page->block_size >= size) { + // Still fits in block, never mind trying to save memory, but preserve data if alignment changed + if ((block != block_origin) && !(flags & RPMALLOC_NO_PRESERVE)) + memmove(block_origin, block, old_size); + return block_origin; } } else { - //Oversized block - size_t total_size = size + SPAN_HEADER_SIZE; - size_t num_pages = total_size >> _memory_page_size_shift; - if (total_size & (_memory_page_size - 1)) - ++num_pages; - //Page count is stored in span_count - size_t current_pages = span->span_count; - void* block = pointer_offset(span, SPAN_HEADER_SIZE); - if (!oldsize) - oldsize = (current_pages * _memory_page_size) - (size_t)pointer_diff(p, block) - SPAN_HEADER_SIZE; - if ((current_pages >= num_pages) && (num_pages >= (current_pages / 2))) { - //Still fits in block, never mind trying to save memory, but preserve data if alignment changed - if ((p != block) && !(flags & RPMALLOC_NO_PRESERVE)) - memmove(block, p, oldsize); - return block; + // Huge block + void* block_start = pointer_offset(span, SPAN_HEADER_SIZE); + if (!old_size) + old_size = ((size_t)span->page_size * (size_t)span->page_count) - (size_t)pointer_diff(block, span); + if ((size < old_size) && (size >= (old_size / 2)) && (size > LARGE_BLOCK_SIZE_LIMIT)) { + // Still fits in block, still huge and saves less than half the memory, + // never mind trying to save memory, but preserve data if alignment changed + if ((block_start != block) && !(flags & RPMALLOC_NO_PRESERVE)) + memmove(block_start, block, old_size); + return block_start; } } } else { - oldsize = 0; + old_size = 0; } if (!!(flags & RPMALLOC_GROW_OR_FAIL)) return 0; - //Size is greater than block size, need to allocate a new block and deallocate the old - //Avoid hysteresis by overallocating if increase is small (below 37%) - size_t lower_bound = oldsize + (oldsize >> 2) + (oldsize >> 3); - size_t new_size = (size > lower_bound) ? size : ((size > oldsize) ? lower_bound : size); - void* block = _rpmalloc_allocate(heap, new_size); - if (p && block) { + // Size is greater than block size or saves enough memory to resize, need to allocate a new block + // and deallocate the old. Avoid hysteresis by overallocating if increase is small (below 37%) + size_t lower_bound = old_size + (old_size >> 2) + (old_size >> 3); + size_t new_size = (size > lower_bound) ? size : ((size > old_size) ? lower_bound : size); + void* old_block = block; + block = heap_allocate_block(heap, new_size, 0); + if (block && old_block) { if (!(flags & RPMALLOC_NO_PRESERVE)) - memcpy(block, p, oldsize < new_size ? oldsize : new_size); - _rpmalloc_deallocate(p); + memcpy(block, old_block, old_size < new_size ? old_size : new_size); + block_deallocate(old_block); } return block; } static void* -_rpmalloc_aligned_reallocate(heap_t* heap, void* ptr, size_t alignment, size_t size, size_t oldsize, - unsigned int flags) { +heap_reallocate_block_aligned(heap_t* heap, void* block, size_t alignment, size_t size, size_t old_size, + unsigned int flags) { if (alignment <= SMALL_GRANULARITY) - return _rpmalloc_reallocate(heap, ptr, size, oldsize, flags); + return heap_reallocate_block(heap, block, size, old_size, flags); int no_alloc = !!(flags & RPMALLOC_GROW_OR_FAIL); - size_t usablesize = (ptr ? _rpmalloc_usable_size(ptr) : 0); - if ((usablesize >= size) && !((uintptr_t)ptr & (alignment - 1))) { - if (no_alloc || (size >= (usablesize / 2))) - return ptr; + size_t usable_size = (block ? block_usable_size(block) : 0); + if ((usable_size >= size) && !((uintptr_t)block & (alignment - 1))) { + if (no_alloc || (size >= (usable_size / 2))) + return block; } // Aligned alloc marks span as having aligned blocks - void* block = (!no_alloc ? _rpmalloc_aligned_allocate(heap, alignment, size) : 0); + void* old_block = block; + block = (!no_alloc ? heap_allocate_block_aligned(heap, alignment, size, 0) : 0); if (EXPECTED(block != 0)) { - if (!(flags & RPMALLOC_NO_PRESERVE) && ptr) { - if (!oldsize) - oldsize = usablesize; - memcpy(block, ptr, oldsize < size ? oldsize : size); + if (!(flags & RPMALLOC_NO_PRESERVE) && old_block) { + if (!old_size) + old_size = usable_size; + memcpy(block, old_block, old_size < size ? old_size : size); } - _rpmalloc_deallocate(ptr); + if (EXPECTED(old_block != 0)) + block_deallocate(old_block); } return block; } +static void +heap_free_all(heap_t* heap) { + for (int itype = 0; itype < 4; ++itype) { + span_t* span = heap->span_partial[itype]; + while (span) { + span_t* span_next = span->next; + global_memory_interface->memory_unmap(span, span->offset, span->mapped_size); + span = span_next; + } + heap->span_partial[itype] = 0; + heap->page_free[itype] = 0; + heap->page_free_commit_count[itype] = 0; + atomic_store_explicit(&heap->thread_free[itype], 0, memory_order_release); + } + for (int itype = 0; itype < 5; ++itype) { + span_t* span = heap->span_used[itype]; + while (span) { + span_t* span_next = span->next; +#if ENABLE_STATISTICS + if (itype == PAGE_HUGE) + statistics_sub_saturating(&global_statistics.huge_alloc, + (size_t)span->page_count * span->page_size); +#endif + global_memory_interface->memory_unmap(span, span->offset, span->mapped_size); + span = span_next; + } + heap->span_used[itype] = 0; + } + memset(heap->local_free, 0, sizeof(heap->local_free)); + memset(heap->page_available, 0, sizeof(heap->page_available)); + +#if ENABLE_STATISTICS + // Every block in this heap has been released, so reverse the per size class allocation counters + for (uint32_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { + heap->size_use[iclass].free_total += heap->size_use[iclass].alloc_current; + heap->size_use[iclass].alloc_current = 0; + } +#endif +} //////////// /// -/// Initialization, finalization and utility +/// Extern interface /// ////// -//! Get the usable size of the given block -static size_t -_rpmalloc_usable_size(void* p) { - //Grab the span using guaranteed span alignment - span_t* span = (span_t*)((uintptr_t)p & _memory_span_mask); - if (span->size_class < SIZE_CLASS_COUNT) { - //Small/medium block - void* blocks_start = pointer_offset(span, SPAN_HEADER_SIZE); - return span->block_size - ((size_t)pointer_diff(p, blocks_start) % span->block_size); - } - if (span->size_class == SIZE_CLASS_LARGE) { - //Large block - size_t current_spans = span->span_count; - return (current_spans * _memory_span_size) - (size_t)pointer_diff(p, span); - } - //Oversized block, page count is stored in span_count - size_t current_pages = span->span_count; - return (current_pages * _memory_page_size) - (size_t)pointer_diff(p, span); -} - -//! Adjust and optimize the size class properties for the given class -static void -_rpmalloc_adjust_size_class(size_t iclass) { - size_t block_size = _memory_size_class[iclass].block_size; - size_t block_count = (_memory_span_size - SPAN_HEADER_SIZE) / block_size; - - _memory_size_class[iclass].block_count = (uint16_t)block_count; - _memory_size_class[iclass].class_idx = (uint16_t)iclass; - - //Check if previous size classes can be merged - if (iclass >= SMALL_CLASS_COUNT) { - size_t prevclass = iclass; - while (prevclass > 0) { - --prevclass; - //A class can be merged if number of pages and number of blocks are equal - if (_memory_size_class[prevclass].block_count == _memory_size_class[iclass].block_count) - memcpy(_memory_size_class + prevclass, _memory_size_class + iclass, sizeof(_memory_size_class[iclass])); - else - break; - } - } -} - -//! Initialize the allocator and setup global data -extern inline int -rpmalloc_initialize(void) { - if (_rpmalloc_initialized) { - rpmalloc_thread_initialize(); - return 0; - } - return rpmalloc_initialize_config(0); -} - -static int -rpmalloc_initialize_config(const rpmalloc_config_t* config) { - if (_rpmalloc_initialized) { - rpmalloc_thread_initialize(); - return 0; - } - _rpmalloc_initialized = 1; - - if (config) - memcpy(&_memory_config, config, sizeof(rpmalloc_config_t)); - else - memset(&_memory_config, 0, sizeof(rpmalloc_config_t)); - - if (!_memory_config.memory_map || !_memory_config.memory_unmap) { - _memory_config.memory_map = _rpmalloc_mmap_os; - _memory_config.memory_unmap = _rpmalloc_unmap_os; - } - -#if PLATFORM_WINDOWS - SYSTEM_INFO system_info; - memset(&system_info, 0, sizeof(system_info)); - GetSystemInfo(&system_info); - _memory_map_granularity = system_info.dwAllocationGranularity; -#else - _memory_map_granularity = (size_t)sysconf(_SC_PAGESIZE); -#endif - -#if RPMALLOC_CONFIGURABLE - _memory_page_size = _memory_config.page_size; -#else - _memory_page_size = 0; -#endif - _memory_huge_pages = 0; - if (!_memory_page_size) { -#if PLATFORM_WINDOWS - _memory_page_size = system_info.dwPageSize; -#else - _memory_page_size = _memory_map_granularity; - if (_memory_config.enable_huge_pages) { -#if defined(__linux__) - size_t huge_page_size = 0; - FILE* meminfo = fopen("/proc/meminfo", "r"); - if (meminfo) { - char line[128]; - while (!huge_page_size && fgets(line, sizeof(line) - 1, meminfo)) { - line[sizeof(line) - 1] = 0; - if (strstr(line, "Hugepagesize:")) - huge_page_size = (size_t)strtol(line + 13, 0, 10) * 1024; - } - fclose(meminfo); - } - if (huge_page_size) { - _memory_huge_pages = 1; - _memory_page_size = huge_page_size; - _memory_map_granularity = huge_page_size; - } -#elif defined(__FreeBSD__) - int rc; - size_t sz = sizeof(rc); - - if (sysctlbyname("vm.pmap.pg_ps_enabled", &rc, &sz, NULL, 0) == 0 && rc == 1) { - _memory_huge_pages = 1; - _memory_page_size = 2 * 1024 * 1024; - _memory_map_granularity = _memory_page_size; - } -#elif defined(__APPLE__) || defined(__NetBSD__) - _memory_huge_pages = 1; - _memory_page_size = 2 * 1024 * 1024; - _memory_map_granularity = _memory_page_size; -#endif - } -#endif - } else { - if (_memory_config.enable_huge_pages) - _memory_huge_pages = 1; - } - -#if PLATFORM_WINDOWS - if (_memory_config.enable_huge_pages) { - HANDLE token = 0; - size_t large_page_minimum = GetLargePageMinimum(); - if (large_page_minimum) - OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token); - if (token) { - LUID luid; - if (LookupPrivilegeValue(0, SE_LOCK_MEMORY_NAME, &luid)) { - TOKEN_PRIVILEGES token_privileges; - memset(&token_privileges, 0, sizeof(token_privileges)); - token_privileges.PrivilegeCount = 1; - token_privileges.Privileges[0].Luid = luid; - token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - if (AdjustTokenPrivileges(token, FALSE, &token_privileges, 0, 0, 0)) { - if (GetLastError() == ERROR_SUCCESS) - _memory_huge_pages = 1; - } - } - CloseHandle(token); - } - if (_memory_huge_pages) { - if (large_page_minimum > _memory_page_size) - _memory_page_size = large_page_minimum; - if (large_page_minimum > _memory_map_granularity) - _memory_map_granularity = large_page_minimum; - } - } -#endif - - size_t min_span_size = 256; - size_t max_page_size; -#if UINTPTR_MAX > 0xFFFFFFFF - max_page_size = 4096ULL * 1024ULL * 1024ULL; -#else - max_page_size = 4 * 1024 * 1024; -#endif - if (_memory_page_size < min_span_size) - _memory_page_size = min_span_size; - if (_memory_page_size > max_page_size) - _memory_page_size = max_page_size; - _memory_page_size_shift = 0; - size_t page_size_bit = _memory_page_size; - while (page_size_bit != 1) { - ++_memory_page_size_shift; - page_size_bit >>= 1; - } - _memory_page_size = ((size_t)1 << _memory_page_size_shift); - -#if RPMALLOC_CONFIGURABLE - if (!_memory_config.span_size) { - _memory_span_size = _memory_default_span_size; - _memory_span_size_shift = _memory_default_span_size_shift; - _memory_span_mask = _memory_default_span_mask; - } else { - size_t span_size = _memory_config.span_size; - if (span_size > (256 * 1024)) - span_size = (256 * 1024); - _memory_span_size = 4096; - _memory_span_size_shift = 12; - while (_memory_span_size < span_size) { - _memory_span_size <<= 1; - ++_memory_span_size_shift; - } - _memory_span_mask = ~(uintptr_t)(_memory_span_size - 1); - } -#endif - - _memory_span_map_count = ( _memory_config.span_map_count ? _memory_config.span_map_count : DEFAULT_SPAN_MAP_COUNT); - if ((_memory_span_size * _memory_span_map_count) < _memory_page_size) - _memory_span_map_count = (_memory_page_size / _memory_span_size); - if ((_memory_page_size >= _memory_span_size) && ((_memory_span_map_count * _memory_span_size) % _memory_page_size)) - _memory_span_map_count = (_memory_page_size / _memory_span_size); - _memory_heap_reserve_count = (_memory_span_map_count > DEFAULT_SPAN_MAP_COUNT) ? DEFAULT_SPAN_MAP_COUNT : _memory_span_map_count; - - _memory_config.page_size = _memory_page_size; - _memory_config.span_size = _memory_span_size; - _memory_config.span_map_count = _memory_span_map_count; - _memory_config.enable_huge_pages = _memory_huge_pages; - -#if ((defined(__APPLE__) || defined(__HAIKU__)) && ENABLE_PRELOAD) || defined(__TINYC__) - if (pthread_key_create(&_memory_thread_heap, _rpmalloc_heap_release_raw_fc)) - return -1; -#endif -#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK) - fls_key = FlsAlloc(&_rpmalloc_thread_destructor); -#endif - - //Setup all small and medium size classes - size_t iclass = 0; - _memory_size_class[iclass].block_size = SMALL_GRANULARITY; - _rpmalloc_adjust_size_class(iclass); - for (iclass = 1; iclass < SMALL_CLASS_COUNT; ++iclass) { - size_t size = iclass * SMALL_GRANULARITY; - _memory_size_class[iclass].block_size = (uint32_t)size; - _rpmalloc_adjust_size_class(iclass); - } - //At least two blocks per span, then fall back to large allocations - _memory_medium_size_limit = (_memory_span_size - SPAN_HEADER_SIZE) >> 1; - if (_memory_medium_size_limit > MEDIUM_SIZE_LIMIT) - _memory_medium_size_limit = MEDIUM_SIZE_LIMIT; - for (iclass = 0; iclass < MEDIUM_CLASS_COUNT; ++iclass) { - size_t size = SMALL_SIZE_LIMIT + ((iclass + 1) * MEDIUM_GRANULARITY); - if (size > _memory_medium_size_limit) - break; - _memory_size_class[SMALL_CLASS_COUNT + iclass].block_size = (uint32_t)size; - _rpmalloc_adjust_size_class(SMALL_CLASS_COUNT + iclass); - } - - _memory_orphan_heaps = 0; -#if RPMALLOC_FIRST_CLASS_HEAPS - _memory_first_class_orphan_heaps = 0; -#endif -#if ENABLE_STATISTICS - atomic_store32(&_memory_active_heaps, 0); - atomic_store32(&_mapped_pages, 0); - _mapped_pages_peak = 0; - atomic_store32(&_master_spans, 0); - atomic_store32(&_mapped_total, 0); - atomic_store32(&_unmapped_total, 0); - atomic_store32(&_mapped_pages_os, 0); - atomic_store32(&_huge_pages_current, 0); - _huge_pages_peak = 0; -#endif - memset(_memory_heaps, 0, sizeof(_memory_heaps)); - atomic_store32_release(&_memory_global_lock, 0); - - //Initialize this thread - rpmalloc_thread_initialize(); - return 0; -} - -//! Finalize the allocator -void -rpmalloc_finalize(void) { - rpmalloc_thread_finalize(1); - //rpmalloc_dump_statistics(stdout); - - if (_memory_global_reserve) { - atomic_add32(&_memory_global_reserve_master->remaining_spans, -(int32_t)_memory_global_reserve_count); - _memory_global_reserve_master = 0; - _memory_global_reserve_count = 0; - _memory_global_reserve = 0; - } - atomic_store32_release(&_memory_global_lock, 0); - - //Free all thread caches and fully free spans - for (size_t list_idx = 0; list_idx < HEAP_ARRAY_SIZE; ++list_idx) { - heap_t* heap = _memory_heaps[list_idx]; - while (heap) { - heap_t* next_heap = heap->next_heap; - heap->finalize = 1; - _rpmalloc_heap_global_finalize(heap); - heap = next_heap; - } - } - -#if ENABLE_GLOBAL_CACHE - //Free global caches - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) - _rpmalloc_global_cache_finalize(&_memory_span_cache[iclass]); -#endif - -#if (defined(__APPLE__) || defined(__HAIKU__)) && ENABLE_PRELOAD - pthread_key_delete(_memory_thread_heap); -#endif -#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK) - FlsFree(fls_key); - fls_key = 0; -#endif -#if ENABLE_STATISTICS - //If you hit these asserts you probably have memory leaks (perhaps global scope data doing dynamic allocations) or double frees in your code - rpmalloc_assert(atomic_load32(&_mapped_pages) == 0, "Memory leak detected"); - rpmalloc_assert(atomic_load32(&_mapped_pages_os) == 0, "Memory leak detected"); -#endif - - _rpmalloc_initialized = 0; -} - -//! Initialize thread, assign heap -extern inline void -rpmalloc_thread_initialize(void) { - if (!get_thread_heap_raw()) { - heap_t* heap = _rpmalloc_heap_allocate(0); - if (heap) { - _rpmalloc_stat_inc(&_memory_active_heaps); - set_thread_heap(heap); -#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK) - FlsSetValue(fls_key, heap); -#endif - } - } -} - -//! Finalize thread, orphan heap -void -rpmalloc_thread_finalize(int release_caches) { - heap_t* heap = get_thread_heap_raw(); - if (heap) - _rpmalloc_heap_release_raw(heap, release_caches); - set_thread_heap(0); -#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK) - FlsSetValue(fls_key, 0); -#endif -} - int rpmalloc_is_thread_initialized(void) { - return (get_thread_heap_raw() != 0) ? 1 : 0; + return (get_thread_heap() != global_heap_default) ? 1 : 0; } -const rpmalloc_config_t* -rpmalloc_config(void) { - return &_memory_config; -} - -// Extern interface - extern inline RPMALLOC_ALLOCATOR void* rpmalloc(size_t size) { #if ENABLE_VALIDATE_ARGS @@ -2912,12 +2468,26 @@ rpmalloc(size_t size) { } #endif heap_t* heap = get_thread_heap(); - return _rpmalloc_allocate(heap, size); + return heap_allocate_block(heap, size, 0); +} + +extern inline RPMALLOC_ALLOCATOR void* +rpzalloc(size_t size) { +#if ENABLE_VALIDATE_ARGS + if (size >= MAX_ALLOC_SIZE) { + errno = EINVAL; + return 0; + } +#endif + heap_t* heap = get_thread_heap(); + return heap_allocate_block(heap, size, 1); } extern inline void rpfree(void* ptr) { - _rpmalloc_deallocate(ptr); + if (UNEXPECTED(ptr == 0)) + return; + block_deallocate(ptr); } extern inline RPMALLOC_ALLOCATOR void* @@ -2941,10 +2511,7 @@ rpcalloc(size_t num, size_t size) { total = num * size; #endif heap_t* heap = get_thread_heap(); - void* block = _rpmalloc_allocate(heap, total); - if (block) - memset(block, 0, total); - return block; + return heap_allocate_block(heap, total, 1); } extern inline RPMALLOC_ALLOCATOR void* @@ -2956,26 +2523,31 @@ rprealloc(void* ptr, size_t size) { } #endif heap_t* heap = get_thread_heap(); - return _rpmalloc_reallocate(heap, ptr, size, 0, 0); + return heap_reallocate_block(heap, ptr, size, 0, 0); } extern RPMALLOC_ALLOCATOR void* -rpaligned_realloc(void* ptr, size_t alignment, size_t size, size_t oldsize, - unsigned int flags) { +rpaligned_realloc(void* ptr, size_t alignment, size_t size, size_t oldsize, unsigned int flags) { #if ENABLE_VALIDATE_ARGS - if ((size + alignment < size) || (alignment > _memory_page_size)) { + if ((size + alignment < size) || (alignment > SMALL_PAGE_SIZE)) { errno = EINVAL; return 0; } #endif heap_t* heap = get_thread_heap(); - return _rpmalloc_aligned_reallocate(heap, ptr, alignment, size, oldsize, flags); + return heap_reallocate_block_aligned(heap, ptr, alignment, size, oldsize, flags); } extern RPMALLOC_ALLOCATOR void* rpaligned_alloc(size_t alignment, size_t size) { heap_t* heap = get_thread_heap(); - return _rpmalloc_aligned_allocate(heap, alignment, size); + return heap_allocate_block_aligned(heap, alignment, size, 0); +} + +extern RPMALLOC_ALLOCATOR void* +rpaligned_zalloc(size_t alignment, size_t size) { + heap_t* heap = get_thread_heap(); + return heap_allocate_block_aligned(heap, alignment, size, 1); } extern inline RPMALLOC_ALLOCATOR void* @@ -2998,21 +2570,21 @@ rpaligned_calloc(size_t alignment, size_t num, size_t size) { #else total = num * size; #endif - void* block = rpaligned_alloc(alignment, total); - if (block) - memset(block, 0, total); - return block; + heap_t* heap = get_thread_heap(); + return heap_allocate_block_aligned(heap, alignment, total, 1); } extern inline RPMALLOC_ALLOCATOR void* rpmemalign(size_t alignment, size_t size) { - return rpaligned_alloc(alignment, size); + heap_t* heap = get_thread_heap(); + return heap_allocate_block_aligned(heap, alignment, size, 0); } extern inline int -rpposix_memalign(void **memptr, size_t alignment, size_t size) { +rpposix_memalign(void** memptr, size_t alignment, size_t size) { + heap_t* heap = get_thread_heap(); if (memptr) - *memptr = rpaligned_alloc(alignment, size); + *memptr = heap_allocate_block_aligned(heap, alignment, size, 0); else return EINVAL; return *memptr ? 0 : ENOMEM; @@ -3020,244 +2592,629 @@ rpposix_memalign(void **memptr, size_t alignment, size_t size) { extern inline size_t rpmalloc_usable_size(void* ptr) { - return (ptr ? _rpmalloc_usable_size(ptr) : 0); + return (ptr ? block_usable_size(ptr) : 0); } -extern inline void +extern void +rpmalloc_linker_reference(void) { +} + +//////////// +/// +/// Initialization and finalization +/// +////// + +static void +rpmalloc_thread_destructor(void* value) { + // If this is called on main thread assume it means rpmalloc_finalize + // has not been called and shutdown is forced (through _exit) or unclean + if (get_thread_id() == global_main_thread_id) + return; + if (value) + rpmalloc_thread_finalize(); +} + +#if defined(__linux__) || defined(__ANDROID__) +//! Read a small (pseudo) file such as /proc/meminfo into a caller provided stack buffer +//! using raw syscalls. This deliberately avoids stdio (fopen/fgets), which allocates an +//! internal buffer through malloc - during rpmalloc_initialize that allocation would +//! re-enter the allocator (when the malloc override is enabled) before the page size is +//! established. Returns the number of bytes read (buffer is always null terminated), or 0. +static size_t +os_read_system_file(const char* path, char* buffer, size_t capacity) { + if (capacity < 2) + return 0; + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return 0; + size_t total = 0; + while ((total + 1) < capacity) { + ssize_t got = read(fd, buffer + total, (capacity - 1) - total); + if (got <= 0) + break; + total += (size_t)got; + } + close(fd); + buffer[total] = 0; + return total; +} +#endif + +extern int +rpmalloc_initialize_config(rpmalloc_interface_t* memory_interface, rpmalloc_config_t* config) { + if (atomic_load_explicit(&global_rpmalloc_init_state, memory_order_acquire) == RPMALLOC_INIT_DONE) { + rpmalloc_thread_initialize(); + if (config) + *config = global_config; + return 0; + } + + if (config) + global_config = *config; + + int result = rpmalloc_initialize(memory_interface); + + if (config) + *config = global_config; + + return result; +} + +extern int +rpmalloc_initialize(rpmalloc_interface_t* memory_interface) { + for (;;) { + int state = atomic_load_explicit(&global_rpmalloc_init_state, memory_order_acquire); + if (state == RPMALLOC_INIT_DONE) { + rpmalloc_thread_initialize(); + return 0; + } + if (state == RPMALLOC_INIT_RUNNING) { + while (atomic_load_explicit(&global_rpmalloc_init_state, memory_order_acquire) == + RPMALLOC_INIT_RUNNING) + thread_yield(); + continue; + } + int expected = RPMALLOC_INIT_UNINIT; + if (atomic_compare_exchange_strong_explicit(&global_rpmalloc_init_state, &expected, + RPMALLOC_INIT_RUNNING, memory_order_acq_rel, + memory_order_acquire)) + break; + } + + // Remember whether the caller explicitly requested huge pages, the detection below + // overwrites global_config.enable_huge_pages with what is actually available. + const int huge_pages_requested = global_config.enable_huge_pages; + + global_memory_interface = memory_interface ? memory_interface : &global_memory_interface_default; + if (!global_memory_interface->memory_map || !global_memory_interface->memory_unmap) { + global_memory_interface->memory_map = os_mmap; + global_memory_interface->memory_commit = os_mcommit; + global_memory_interface->memory_decommit = os_mdecommit; + global_memory_interface->memory_unmap = os_munmap; + } + +#if ENABLE_OVERRIDE + // With the standard library override, rpmalloc backs the C runtime's own allocations (for + // example per-thread TLS allocated by the loader). Unmapping everything at finalize while the + // process keeps running would pull that memory out from under the runtime, so the option + // cannot be honored here; clear it (also reflected back through the effective config). + global_config.unmap_on_finalize = 0; +#endif + +#if PLATFORM_WINDOWS + SYSTEM_INFO system_info; + memset(&system_info, 0, sizeof(system_info)); + GetSystemInfo(&system_info); + os_map_granularity = system_info.dwAllocationGranularity; + os_virtualalloc2 = 0; + { + HMODULE kernelbase = GetModuleHandleW(L"kernelbase.dll"); + if (kernelbase) + os_virtualalloc2 = (virtualalloc2_fn)(void (*)(void))GetProcAddress(kernelbase, "VirtualAlloc2"); + } +#else + os_map_granularity = (size_t)sysconf(_SC_PAGESIZE); +#endif + +#if PLATFORM_WINDOWS + os_page_size = system_info.dwPageSize; +#else + os_page_size = os_map_granularity; +#endif + os_huge_pages = 0; + os_thp = 0; + os_huge_page_shift = 0; + + rpmalloc_assert(!(global_config.page_size & (global_config.page_size - 1)), + "Configured page size must be a power of two"); + + // Establish a valid (normal) page size up front so the allocator never observes a + // zero page size during the rest of initialization. Huge page detection below may + // raise it to the huge page size once availability has been confirmed. + if (!memory_interface || (global_config.page_size < os_page_size)) + global_config.page_size = os_page_size; + + if (global_config.enable_huge_pages) { +#if PLATFORM_WINDOWS + HANDLE token = 0; +#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM) + size_t large_page_minimum = GetLargePageMinimum(); +#else + size_t large_page_minimum = 2 * 1024 * 1024; +#endif + if (large_page_minimum) + OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token); + if (token) { + LUID luid; + if (LookupPrivilegeValue(0, SE_LOCK_MEMORY_NAME, &luid)) { + TOKEN_PRIVILEGES token_privileges; + memset(&token_privileges, 0, sizeof(token_privileges)); + token_privileges.PrivilegeCount = 1; + token_privileges.Privileges[0].Luid = luid; + token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + if (AdjustTokenPrivileges(token, FALSE, &token_privileges, 0, 0, 0)) { + if (GetLastError() == ERROR_SUCCESS) + os_huge_pages = 1; + } + } + CloseHandle(token); + } + // Disable huge pages if the system large page size is not a power of two that fits the builtin geometry + if (os_huge_pages && ((large_page_minimum & (large_page_minimum - 1)) || (large_page_minimum > LARGE_PAGE_SIZE))) + os_huge_pages = 0; + if (os_huge_pages) { + if (large_page_minimum > os_page_size) + os_page_size = large_page_minimum; + if (large_page_minimum > os_map_granularity) + os_map_granularity = large_page_minimum; + } +#elif defined(__linux__) + size_t huge_page_size = 0; + char meminfo[4096]; + if (os_read_system_file("/proc/meminfo", meminfo, sizeof(meminfo))) { + const char* line = strstr(meminfo, "Hugepagesize:"); + if (line) + huge_page_size = (size_t)strtol(line + 13, 0, 10) * 1024; + } + // Sanity check the detected default huge page size, the builtin page geometry + // cannot use huge pages larger than the largest builtin page size (e.g. 1GiB + // default huge pages). Since the huge page size is passed explicitly to mmap, + // a non-default 2MiB huge page pool can still be used in that case. + if (huge_page_size & (huge_page_size - 1)) + huge_page_size = 0; + if (huge_page_size > LARGE_PAGE_SIZE) + huge_page_size = 2 * 1024 * 1024; +#if defined(MAP_HUGETLB) + if (huge_page_size) { + // Hugepagesize in /proc/meminfo only reports the configured huge page size, not + // whether any huge pages are actually available (the static pool can be empty, + // HugePages_Total == 0). Probe by mapping a single huge page with the same flags + // used for real mappings and only enable huge pages if the request can actually + // be satisfied (static pool or overcommit). This also covers the case where the + // page size is reported but the kernel rejects that specific MAP_HUGE_* size. + size_t huge_shift = 0; + while (((size_t)1 << huge_shift) < huge_page_size) + ++huge_shift; + int probe_flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB; +#if defined(MAP_HUGE_SHIFT) + probe_flags |= (int)(huge_shift << MAP_HUGE_SHIFT); +#endif + void* probe = mmap(0, huge_page_size, PROT_READ | PROT_WRITE, probe_flags, -1, 0); + if ((probe != MAP_FAILED) && probe) { + munmap(probe, huge_page_size); + os_huge_pages = 1; + os_huge_page_shift = huge_shift; + os_page_size = huge_page_size; + os_map_granularity = huge_page_size; + } + } +#endif +#elif defined(__FreeBSD__) + int rc; + size_t sz = sizeof(rc); + + if (sysctlbyname("vm.pmap.pg_ps_enabled", &rc, &sz, NULL, 0) == 0 && rc == 1) { + os_huge_pages = 1; + os_page_size = 2 * 1024 * 1024; + os_map_granularity = os_page_size; + } +#elif defined(__APPLE__) +#if defined(__x86_64__) && !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR + // Superpages are only supported on x86-64, Apple silicon has no huge page support + os_huge_pages = 1; + os_page_size = 2 * 1024 * 1024; + os_map_granularity = os_page_size; +#endif +#elif defined(__NetBSD__) + os_huge_pages = 1; + os_page_size = 2 * 1024 * 1024; + os_map_granularity = os_page_size; +#endif + } + + if (huge_pages_requested && !os_huge_pages) { + // Explicit huge pages were requested but are not available on this system. Fail + // initialization rather than silently backing the heap with normal pages behind a + // huge page size. Leave the allocator uninitialized (and the requested flag cleared) + // so the caller can detect this and re-initialize without huge pages if desired. + global_config.enable_huge_pages = 0; + atomic_store_explicit(&global_rpmalloc_init_state, RPMALLOC_INIT_UNINIT, memory_order_release); + return -1; + } + + global_config.enable_huge_pages = os_huge_pages; + + if (os_huge_pages) { + while (((size_t)1 << os_huge_page_shift) < os_page_size) + ++os_huge_page_shift; + } + + if (!memory_interface || (global_config.page_size < os_page_size)) + global_config.page_size = os_page_size; + +#if PLATFORM_WINDOWS + // Large pages on Windows must be committed when mapped and can never be decommitted + if (global_config.enable_huge_pages) + global_config.disable_decommit = 1; +#endif + +#if defined(__linux__) || defined(__ANDROID__) + // Transparent huge pages, advise mappings to be huge page backed without requiring + // a preallocated huge page pool and without affecting page size or decommit + if (global_config.enable_thp && !os_huge_pages && !global_config.disable_thp) { + // When THP is disabled system-wide (mode "never") madvise(MADV_HUGEPAGE) is a + // no-op, so report it as disabled rather than claiming THP is in use. + char thp_state[64]; + int thp_never = 0; + if (os_read_system_file("/sys/kernel/mm/transparent_hugepage/enabled", thp_state, sizeof(thp_state))) + thp_never = (strstr(thp_state, "[never]") != 0); + if (!thp_never) + os_thp = 1; + } + if (global_config.disable_thp) + (void)prctl(PR_SET_THP_DISABLE, 1, 0, 0, 0); +#endif + global_config.enable_thp = os_thp; + + // Decommit of free pages only applies to page types larger than the configured + // page size, disable the free page overflow pass for page types where it can + // never apply (always the case when huge pages or a large page size is in use) + const uint32_t page_free_overflow_default[4] = {16, 8, 4, 2}; + const uint32_t builtin_page_size[4] = {SMALL_PAGE_SIZE, MEDIUM_SMALL_PAGE_SIZE, MEDIUM_LARGE_PAGE_SIZE, + LARGE_PAGE_SIZE}; + for (unsigned int itype = 0; itype < 4; ++itype) { + int page_can_decommit = + !global_config.disable_decommit && ((size_t)builtin_page_size[itype] > global_config.page_size); + global_page_free_overflow[itype] = page_can_decommit ? page_free_overflow_default[itype] : 0xFFFFFFFFU; + } + +#ifdef _WIN32 + fls_key = FlsAlloc(&rpmalloc_thread_destructor); +#else + pthread_key_create(&pthread_key, rpmalloc_thread_destructor); +#endif + + global_main_thread_id = get_thread_id(); + + atomic_store_explicit(&global_rpmalloc_init_state, RPMALLOC_INIT_DONE, memory_order_release); + + rpmalloc_thread_initialize(); + + return 0; +} + +extern const rpmalloc_config_t* +rpmalloc_config(void) { + return &global_config; +} + +#if ENABLE_LEAK_DETECTION +//! Number of size class blocks still allocated across every heap. A non-zero value once all threads +//! have finalized means the application has not freed all its allocations (leak or double free). +static long long +statistics_outstanding_blocks(void) { + heap_t* lists[3] = {global_heap_used, global_heap_queue, global_heap_pristine}; + long long outstanding = 0; + for (int ilist = 0; ilist < 3; ++ilist) { + for (heap_t* heap = lists[ilist]; heap; heap = heap->next) { + for (uint32_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) + outstanding += heap->size_use[iclass].alloc_current; + } + } + return outstanding; +} + +//! Number of cross-thread freed blocks parked in a span's per page deferred lists, counting every +//! initialized page (a full page is not reachable from page_available but can still hold deferred +//! frees, since adoption is skipped while a page has a local free list). Page count is in the token +//! high bits. +static long long +span_deferred_block_count(span_t* span) { + long long deferred = 0; + for (uint32_t ipage = 0; ipage < span->page_initialized; ++ipage) { + page_t* page = (page_t*)pointer_offset(span, (size_t)span->page_size * ipage); + uint64_t token = atomic_load_explicit(&page->thread_free, memory_order_relaxed); + deferred += (long long)(uint32_t)(token >> 32ULL); + } + return deferred; +} + +//! Number of blocks freed cross-thread but not yet applied to the owning heap's alloc_current, +//! waiting in the deferred free lists. These are accounted in alloc_current until processed, so +//! subtracting them from the outstanding count yields the blocks the application has truly leaked. +static long long +statistics_pending_deferred_blocks(void) { + heap_t* lists[3] = {global_heap_used, global_heap_queue, global_heap_pristine}; + long long deferred = 0; + for (int ilist = 0; ilist < 3; ++ilist) { + for (heap_t* heap = lists[ilist]; heap; heap = heap->next) { + // Page types small through large carry the per heap full page deferred list and the per + // page deferred lists of every span. Huge blocks are never deferred per block. + for (uint32_t itype = 0; itype < 4; ++itype) { + block_t* block = (block_t*)atomic_load_explicit(&heap->thread_free[itype], memory_order_relaxed); + while (block) { + ++deferred; + block = block->next; + } + if (heap->span_partial[itype]) + deferred += span_deferred_block_count(heap->span_partial[itype]); + for (span_t* span = heap->span_used[itype]; span; span = span->next) + deferred += span_deferred_block_count(span); + } + } + } + return deferred; +} +#endif + +extern void +rpmalloc_finalize(void) { + rpmalloc_thread_finalize(); + +#if HUGE_CACHE_SLOT_COUNT + // Release cached huge mappings, the cache must not hold memory across a finalize + // (and potential re-initialize with a different page size) + huge_cache_flush(); +#endif + +#if ENABLE_LEAK_DETECTION && ENABLE_ASSERTS + // Leak detection: every thread has finalized, so blocks still allocated and not merely waiting + // in a deferred cross-thread free list are blocks the application never freed (or freed twice). + rpmalloc_assert(statistics_outstanding_blocks() <= statistics_pending_deferred_blocks(), + "Memory leak detected"); + rpmalloc_assert(atomic_load_explicit(&global_statistics.huge_alloc, memory_order_relaxed) == 0, + "Memory leak detected"); +#endif + + + if (global_config.unmap_on_finalize) { + // Heaps can share a mapping (heap_allocate_new); only the owner carries mapped_size != 0. + // Resources are freed while every heap is still mapped, then owners are unmapped in a + // separate pass so a heap is never dereferenced after its shared mapping is gone. + heap_t* owners = 0; + heap_t* heap = global_heap_pristine; + global_heap_pristine = 0; + while (heap) { + heap_t* heap_next = heap->next; + heap_free_all(heap); + if (heap->mapped_size) { + heap->next = owners; + owners = heap; + } + heap = heap_next; + } + heap = global_heap_queue; + global_heap_queue = 0; + while (heap) { + heap_t* heap_next = heap->next; + heap_free_all(heap); + if (heap->mapped_size) { + heap->next = owners; + owners = heap; + } + heap = heap_next; + } + heap = global_heap_used; + global_heap_used = 0; + while (heap) { + heap_t* heap_next = heap->next; + heap_free_all(heap); + if (heap->mapped_size) { + heap->next = owners; + owners = heap; + } + heap = heap_next; + } + while (owners) { + heap_t* owner_next = owners->next; + heap_unmap(owners); + owners = owner_next; + } +#if ENABLE_STATISTICS + memset(&global_statistics, 0, sizeof(global_statistics)); +#endif + } + +#ifdef _WIN32 + FlsFree(fls_key); + fls_key = 0; +#else + pthread_key_delete(pthread_key); + pthread_key = 0; +#endif + + global_heap_creating = 0; + global_main_thread_id = 0; + atomic_store_explicit(&global_rpmalloc_init_state, RPMALLOC_INIT_UNINIT, memory_order_release); +} + +extern void +rpmalloc_thread_initialize(void) { + if (!get_thread_heap() || get_thread_heap() == global_heap_default) + get_thread_heap_allocate(); +} + +extern void +rpmalloc_thread_finalize(void) { + heap_t* heap = get_thread_heap(); + if (heap != global_heap_default) { + heap_release(heap); + set_thread_heap(global_heap_default); + } +} + +extern void rpmalloc_thread_collect(void) { } void rpmalloc_thread_statistics(rpmalloc_thread_statistics_t* stats) { memset(stats, 0, sizeof(rpmalloc_thread_statistics_t)); - heap_t* heap = get_thread_heap_raw(); - if (!heap) +#if ENABLE_STATISTICS + heap_t* heap = get_thread_heap(); + if (!heap || (heap->id == 0)) return; - for (size_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { - size_class_t* size_class = _memory_size_class + iclass; - span_t* span = heap->size_class[iclass].partial_span; - while (span) { - size_t free_count = span->list_size; - size_t block_count = size_class->block_count; - if (span->free_list_limit < block_count) - block_count = span->free_list_limit; - free_count += (block_count - span->used_count); - stats->sizecache = free_count * size_class->block_size; - span = span->next; - } + // Size class cache: blocks available without mapping a new page. A page's block_used counts the + // blocks held on the heap free list, so those are counted from the heap list and each page adds + // its remaining blocks (page free list plus the not yet initialized tail). + for (uint32_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { + size_t block_size = global_size_class[iclass].block_size; + size_t free_count = 0; + for (block_t* block = heap->local_free[iclass]; block; block = block->next) + ++free_count; + for (page_t* page = heap->page_available[iclass]; page; page = page->next) + free_count += (size_t)(page->block_count - page->block_used); + stats->sizecache += free_count * block_size; + + stats->size_use[iclass].alloc_current = (size_t)heap->size_use[iclass].alloc_current; + stats->size_use[iclass].alloc_peak = (size_t)heap->size_use[iclass].alloc_peak; + stats->size_use[iclass].alloc_total = (size_t)heap->size_use[iclass].alloc_total; + stats->size_use[iclass].free_total = (size_t)heap->size_use[iclass].free_total; } -#if ENABLE_THREAD_CACHE - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - span_cache_t* span_cache; - if (!iclass) - span_cache = &heap->span_cache; - else - span_cache = (span_cache_t*)(heap->span_large_cache + (iclass - 1)); - stats->spancache = span_cache->count * (iclass + 1) * _memory_span_size; + // Span cache: free but still committed pages retained per page type + static const size_t page_type_size[4] = {SMALL_PAGE_SIZE, MEDIUM_SMALL_PAGE_SIZE, MEDIUM_LARGE_PAGE_SIZE, + LARGE_PAGE_SIZE}; + for (uint32_t itype = 0; itype < 4; ++itype) + stats->spancache += (size_t)heap->page_free_commit_count[itype] * page_type_size[itype]; + + // Per page type span use: current spans in use computed live (partial plus full), map calls counted + for (uint32_t itype = 0; itype < 5; ++itype) { + size_t current = 0; + if ((itype < 4) && heap->span_partial[itype]) + ++current; + for (span_t* span = heap->span_used[itype]; span; span = span->next) + ++current; + stats->span_use[itype].current = current; + stats->span_use[itype].map_calls = (size_t)heap->span_map_calls[itype]; } #endif +} - span_t* deferred = (span_t*)atomic_load_ptr(&heap->span_free_deferred); - while (deferred) { - if (deferred->size_class != SIZE_CLASS_HUGE) - stats->spancache = (size_t)deferred->span_count * _memory_span_size; - deferred = (span_t*)deferred->free_list; - } - +void +rpmalloc_dump_statistics(void* file) { #if ENABLE_STATISTICS - stats->thread_to_global = (size_t)atomic_load64(&heap->thread_to_global); - stats->global_to_thread = (size_t)atomic_load64(&heap->global_to_thread); + fprintf(file, "Mapped pages: %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.page_mapped, memory_order_relaxed)); + fprintf(file, "Mapped pages (peak): %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.page_mapped_peak, memory_order_relaxed)); + fprintf(file, "Active pages: %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.page_active, memory_order_relaxed)); + fprintf(file, "Active pages (peak): %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.page_active_peak, memory_order_relaxed)); + fprintf(file, "Pages committed: %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.page_commit, memory_order_relaxed)); + fprintf(file, "Pages decommitted: %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.page_decommit, memory_order_relaxed)); + fprintf(file, "Huge bytes: %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.huge_alloc, memory_order_relaxed)); + fprintf(file, "Huge bytes (peak): %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.huge_alloc_peak, memory_order_relaxed)); + fprintf(file, "Heaps in use: %llu\n", + (unsigned long long)atomic_load_explicit(&global_statistics.heap_count, memory_order_relaxed)); +#if ENABLE_LEAK_DETECTION + fprintf(file, "Outstanding blocks: %lld\n", + statistics_outstanding_blocks() - statistics_pending_deferred_blocks()); +#endif - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - stats->span_use[iclass].current = (size_t)atomic_load32(&heap->span_use[iclass].current); - stats->span_use[iclass].peak = (size_t)atomic_load32(&heap->span_use[iclass].high); - stats->span_use[iclass].to_global = (size_t)atomic_load32(&heap->span_use[iclass].spans_to_global); - stats->span_use[iclass].from_global = (size_t)atomic_load32(&heap->span_use[iclass].spans_from_global); - stats->span_use[iclass].to_cache = (size_t)atomic_load32(&heap->span_use[iclass].spans_to_cache); - stats->span_use[iclass].from_cache = (size_t)atomic_load32(&heap->span_use[iclass].spans_from_cache); - stats->span_use[iclass].to_reserved = (size_t)atomic_load32(&heap->span_use[iclass].spans_to_reserved); - stats->span_use[iclass].from_reserved = (size_t)atomic_load32(&heap->span_use[iclass].spans_from_reserved); - stats->span_use[iclass].map_calls = (size_t)atomic_load32(&heap->span_use[iclass].spans_map_calls); + // Aggregate per size class and per page type counters across all in-use heaps. This walks live + // heaps without stopping the world, so the values are a best-effort snapshot. + heap_size_use_t size_use[SIZE_CLASS_COUNT]; + memset(size_use, 0, sizeof(size_use)); + uint64_t span_map_calls[5]; + memset(span_map_calls, 0, sizeof(span_map_calls)); + heap_lock_acquire(); + for (heap_t* heap = global_heap_used; heap; heap = heap->next) { + for (uint32_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { + size_use[iclass].alloc_current += heap->size_use[iclass].alloc_current; + size_use[iclass].alloc_peak += heap->size_use[iclass].alloc_peak; + size_use[iclass].alloc_total += heap->size_use[iclass].alloc_total; + size_use[iclass].free_total += heap->size_use[iclass].free_total; + } + for (uint32_t itype = 0; itype < 5; ++itype) + span_map_calls[itype] += heap->span_map_calls[itype]; } - for (size_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { - stats->size_use[iclass].alloc_current = (size_t)atomic_load32(&heap->size_class_use[iclass].alloc_current); - stats->size_use[iclass].alloc_peak = (size_t)heap->size_class_use[iclass].alloc_peak; - stats->size_use[iclass].alloc_total = (size_t)atomic_load32(&heap->size_class_use[iclass].alloc_total); - stats->size_use[iclass].free_total = (size_t)atomic_load32(&heap->size_class_use[iclass].free_total); - stats->size_use[iclass].spans_to_cache = (size_t)atomic_load32(&heap->size_class_use[iclass].spans_to_cache); - stats->size_use[iclass].spans_from_cache = (size_t)atomic_load32(&heap->size_class_use[iclass].spans_from_cache); - stats->size_use[iclass].spans_from_reserved = (size_t)atomic_load32(&heap->size_class_use[iclass].spans_from_reserved); - stats->size_use[iclass].map_calls = (size_t)atomic_load32(&heap->size_class_use[iclass].spans_map_calls); + heap_lock_release(); + + fprintf(file, "SizeClass CurAlloc PeakAlloc TotAlloc TotFree BlockSize\n"); + for (uint32_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { + if (!size_use[iclass].alloc_total) + continue; + fprintf(file, "%9u %9d %9d %9d %9d %9u\n", iclass, size_use[iclass].alloc_current, + size_use[iclass].alloc_peak, size_use[iclass].alloc_total, size_use[iclass].free_total, + global_size_class[iclass].block_size); } + fprintf(file, "PageType MapCalls\n"); + for (uint32_t itype = 0; itype < 5; ++itype) { + if (!span_map_calls[itype]) + continue; + fprintf(file, "%8u %9llu\n", itype, (unsigned long long)span_map_calls[itype]); + } +#else + (void)sizeof(file); #endif } void rpmalloc_global_statistics(rpmalloc_global_statistics_t* stats) { - memset(stats, 0, sizeof(rpmalloc_global_statistics_t)); #if ENABLE_STATISTICS - stats->mapped = (size_t)atomic_load32(&_mapped_pages) * _memory_page_size; - stats->mapped_peak = (size_t)_mapped_pages_peak * _memory_page_size; - stats->mapped_total = (size_t)atomic_load32(&_mapped_total) * _memory_page_size; - stats->unmapped_total = (size_t)atomic_load32(&_unmapped_total) * _memory_page_size; - stats->huge_alloc = (size_t)atomic_load32(&_huge_pages_current) * _memory_page_size; - stats->huge_alloc_peak = (size_t)_huge_pages_peak * _memory_page_size; -#endif -#if ENABLE_GLOBAL_CACHE - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) - stats->cached += _memory_span_cache[iclass].count * (iclass + 1) * _memory_span_size; -#endif -} - -#if ENABLE_STATISTICS - -static void -_memory_heap_dump_statistics(heap_t* heap, void* file) { - fprintf(file, "Heap %d stats:\n", heap->id); - fprintf(file, "Class CurAlloc PeakAlloc TotAlloc TotFree BlkSize BlkCount SpansCur SpansPeak PeakAllocMiB ToCacheMiB FromCacheMiB FromReserveMiB MmapCalls\n"); - for (size_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { - if (!atomic_load32(&heap->size_class_use[iclass].alloc_total)) - continue; - fprintf(file, "%3u: %10u %10u %10u %10u %8u %8u %8d %9d %13zu %11zu %12zu %14zu %9u\n", (uint32_t)iclass, - atomic_load32(&heap->size_class_use[iclass].alloc_current), - heap->size_class_use[iclass].alloc_peak, - atomic_load32(&heap->size_class_use[iclass].alloc_total), - atomic_load32(&heap->size_class_use[iclass].free_total), - _memory_size_class[iclass].block_size, - _memory_size_class[iclass].block_count, - atomic_load32(&heap->size_class_use[iclass].spans_current), - heap->size_class_use[iclass].spans_peak, - ((size_t)heap->size_class_use[iclass].alloc_peak * (size_t)_memory_size_class[iclass].block_size) / (size_t)(1024 * 1024), - ((size_t)atomic_load32(&heap->size_class_use[iclass].spans_to_cache) * _memory_span_size) / (size_t)(1024 * 1024), - ((size_t)atomic_load32(&heap->size_class_use[iclass].spans_from_cache) * _memory_span_size) / (size_t)(1024 * 1024), - ((size_t)atomic_load32(&heap->size_class_use[iclass].spans_from_reserved) * _memory_span_size) / (size_t)(1024 * 1024), - atomic_load32(&heap->size_class_use[iclass].spans_map_calls)); - } - fprintf(file, "Spans Current Peak Deferred PeakMiB Cached ToCacheMiB FromCacheMiB ToReserveMiB FromReserveMiB ToGlobalMiB FromGlobalMiB MmapCalls\n"); - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - if (!atomic_load32(&heap->span_use[iclass].high) && !atomic_load32(&heap->span_use[iclass].spans_map_calls)) - continue; - fprintf(file, "%4u: %8d %8u %8u %8zu %7u %11zu %12zu %12zu %14zu %11zu %13zu %10u\n", (uint32_t)(iclass + 1), - atomic_load32(&heap->span_use[iclass].current), - atomic_load32(&heap->span_use[iclass].high), - atomic_load32(&heap->span_use[iclass].spans_deferred), - ((size_t)atomic_load32(&heap->span_use[iclass].high) * (size_t)_memory_span_size * (iclass + 1)) / (size_t)(1024 * 1024), -#if ENABLE_THREAD_CACHE - (unsigned int)(!iclass ? heap->span_cache.count : heap->span_large_cache[iclass - 1].count), - ((size_t)atomic_load32(&heap->span_use[iclass].spans_to_cache) * (iclass + 1) * _memory_span_size) / (size_t)(1024 * 1024), - ((size_t)atomic_load32(&heap->span_use[iclass].spans_from_cache) * (iclass + 1) * _memory_span_size) / (size_t)(1024 * 1024), + stats->mapped = global_config.page_size * atomic_load_explicit(&global_statistics.page_mapped, memory_order_relaxed); + stats->mapped_peak = global_config.page_size * atomic_load_explicit(&global_statistics.page_mapped_peak, memory_order_relaxed); + stats->committed = global_config.page_size * atomic_load_explicit(&global_statistics.page_commit, memory_order_relaxed); + stats->decommitted = global_config.page_size * atomic_load_explicit(&global_statistics.page_decommit, memory_order_relaxed); + stats->active = global_config.page_size * atomic_load_explicit(&global_statistics.page_active, memory_order_relaxed); + stats->active_peak = global_config.page_size * atomic_load_explicit(&global_statistics.page_active_peak, memory_order_relaxed); + stats->huge_alloc = atomic_load_explicit(&global_statistics.huge_alloc, memory_order_relaxed); + stats->huge_alloc_peak = atomic_load_explicit(&global_statistics.huge_alloc_peak, memory_order_relaxed); + stats->heap_count = atomic_load_explicit(&global_statistics.heap_count, memory_order_relaxed); #else - 0, (size_t)0, (size_t)0, + memset(stats, 0, sizeof(rpmalloc_global_statistics_t)); #endif - ((size_t)atomic_load32(&heap->span_use[iclass].spans_to_reserved) * (iclass + 1) * _memory_span_size) / (size_t)(1024 * 1024), - ((size_t)atomic_load32(&heap->span_use[iclass].spans_from_reserved) * (iclass + 1) * _memory_span_size) / (size_t)(1024 * 1024), - ((size_t)atomic_load32(&heap->span_use[iclass].spans_to_global) * (size_t)_memory_span_size * (iclass + 1)) / (size_t)(1024 * 1024), - ((size_t)atomic_load32(&heap->span_use[iclass].spans_from_global) * (size_t)_memory_span_size * (iclass + 1)) / (size_t)(1024 * 1024), - atomic_load32(&heap->span_use[iclass].spans_map_calls)); - } - fprintf(file, "Full spans: %zu\n", heap->full_span_count); - fprintf(file, "ThreadToGlobalMiB GlobalToThreadMiB\n"); - fprintf(file, "%17zu %17zu\n", (size_t)atomic_load64(&heap->thread_to_global) / (size_t)(1024 * 1024), (size_t)atomic_load64(&heap->global_to_thread) / (size_t)(1024 * 1024)); -} - -#endif - -void -rpmalloc_dump_statistics(void* file) { -#if ENABLE_STATISTICS - for (size_t list_idx = 0; list_idx < HEAP_ARRAY_SIZE; ++list_idx) { - heap_t* heap = _memory_heaps[list_idx]; - while (heap) { - int need_dump = 0; - for (size_t iclass = 0; !need_dump && (iclass < SIZE_CLASS_COUNT); ++iclass) { - if (!atomic_load32(&heap->size_class_use[iclass].alloc_total)) { - rpmalloc_assert(!atomic_load32(&heap->size_class_use[iclass].free_total), "Heap statistics counter mismatch"); - rpmalloc_assert(!atomic_load32(&heap->size_class_use[iclass].spans_map_calls), "Heap statistics counter mismatch"); - continue; - } - need_dump = 1; - } - for (size_t iclass = 0; !need_dump && (iclass < LARGE_CLASS_COUNT); ++iclass) { - if (!atomic_load32(&heap->span_use[iclass].high) && !atomic_load32(&heap->span_use[iclass].spans_map_calls)) - continue; - need_dump = 1; - } - if (need_dump) - _memory_heap_dump_statistics(heap, file); - heap = heap->next_heap; - } - } - fprintf(file, "Global stats:\n"); - size_t huge_current = (size_t)atomic_load32(&_huge_pages_current) * _memory_page_size; - size_t huge_peak = (size_t)_huge_pages_peak * _memory_page_size; - fprintf(file, "HugeCurrentMiB HugePeakMiB\n"); - fprintf(file, "%14zu %11zu\n", huge_current / (size_t)(1024 * 1024), huge_peak / (size_t)(1024 * 1024)); - - fprintf(file, "GlobalCacheMiB\n"); - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - global_cache_t* cache = _memory_span_cache + iclass; - size_t global_cache = (size_t)cache->count * iclass * _memory_span_size; - - size_t global_overflow_cache = 0; - span_t* span = cache->overflow; - while (span) { - global_overflow_cache += iclass * _memory_span_size; - span = span->next; - } - if (global_cache || global_overflow_cache || cache->insert_count || cache->extract_count) - fprintf(file, "%4zu: %8zuMiB (%8zuMiB overflow) %14zu insert %14zu extract\n", iclass + 1, global_cache / (size_t)(1024 * 1024), global_overflow_cache / (size_t)(1024 * 1024), cache->insert_count, cache->extract_count); - } - - size_t mapped = (size_t)atomic_load32(&_mapped_pages) * _memory_page_size; - size_t mapped_os = (size_t)atomic_load32(&_mapped_pages_os) * _memory_page_size; - size_t mapped_peak = (size_t)_mapped_pages_peak * _memory_page_size; - size_t mapped_total = (size_t)atomic_load32(&_mapped_total) * _memory_page_size; - size_t unmapped_total = (size_t)atomic_load32(&_unmapped_total) * _memory_page_size; - fprintf(file, "MappedMiB MappedOSMiB MappedPeakMiB MappedTotalMiB UnmappedTotalMiB\n"); - fprintf(file, "%9zu %11zu %13zu %14zu %16zu\n", - mapped / (size_t)(1024 * 1024), - mapped_os / (size_t)(1024 * 1024), - mapped_peak / (size_t)(1024 * 1024), - mapped_total / (size_t)(1024 * 1024), - unmapped_total / (size_t)(1024 * 1024)); - - fprintf(file, "\n"); -#if 0 - int64_t allocated = atomic_load64(&_allocation_counter); - int64_t deallocated = atomic_load64(&_deallocation_counter); - fprintf(file, "Allocation count: %lli\n", allocated); - fprintf(file, "Deallocation count: %lli\n", deallocated); - fprintf(file, "Current allocations: %lli\n", (allocated - deallocated)); - fprintf(file, "Master spans: %d\n", atomic_load32(&_master_spans)); - fprintf(file, "Dangling master spans: %d\n", atomic_load32(&_unmapped_master_spans)); -#endif -#endif - (void)sizeof(file); } #if RPMALLOC_FIRST_CLASS_HEAPS -extern inline rpmalloc_heap_t* +rpmalloc_heap_t* rpmalloc_heap_acquire(void) { - // Must be a pristine heap from newly mapped memory pages, or else memory blocks - // could already be allocated from the heap which would (wrongly) be released when - // heap is cleared with rpmalloc_heap_free_all(). Also heaps guaranteed to be - // pristine from the dedicated orphan list can be used. - heap_t* heap = _rpmalloc_heap_allocate(1); + // Must be a pristine heap, or else memory blocks could already be allocated from the heap + // which would (wrongly) be released when heap is cleared with rpmalloc_heap_free_all(). + // heap_allocate(1) returns either a never-used heap carved from a shared block (whether that + // block was mapped for an ordinary heap or a prior first-class heap) or a freshly mapped one. + heap_t* heap = heap_allocate(1); + rpmalloc_assume(heap != 0); heap->owner_thread = 0; - _rpmalloc_stat_inc(&_memory_active_heaps); return heap; } -extern inline void +void rpmalloc_heap_release(rpmalloc_heap_t* heap) { if (heap) - _rpmalloc_heap_release(heap, 1, 1); + heap_release(heap); } -extern inline RPMALLOC_ALLOCATOR void* +RPMALLOC_ALLOCATOR void* rpmalloc_heap_alloc(rpmalloc_heap_t* heap, size_t size) { #if ENABLE_VALIDATE_ARGS if (size >= MAX_ALLOC_SIZE) { @@ -3265,10 +3222,10 @@ rpmalloc_heap_alloc(rpmalloc_heap_t* heap, size_t size) { return 0; } #endif - return _rpmalloc_allocate(heap, size); + return heap_allocate_block(heap, size, 0); } -extern inline RPMALLOC_ALLOCATOR void* +RPMALLOC_ALLOCATOR void* rpmalloc_heap_aligned_alloc(rpmalloc_heap_t* heap, size_t alignment, size_t size) { #if ENABLE_VALIDATE_ARGS if (size >= MAX_ALLOC_SIZE) { @@ -3276,12 +3233,41 @@ rpmalloc_heap_aligned_alloc(rpmalloc_heap_t* heap, size_t alignment, size_t size return 0; } #endif - return _rpmalloc_aligned_allocate(heap, alignment, size); + return heap_allocate_block_aligned(heap, alignment, size, 0); } -extern inline RPMALLOC_ALLOCATOR void* +RPMALLOC_ALLOCATOR void* +rpmalloc_heap_aligned_zalloc(rpmalloc_heap_t* heap, size_t alignment, size_t size) { +#if ENABLE_VALIDATE_ARGS + if (size >= MAX_ALLOC_SIZE) { + errno = EINVAL; + return 0; + } +#endif + return heap_allocate_block_aligned(heap, alignment, size, 1); +} + +RPMALLOC_ALLOCATOR void* rpmalloc_heap_calloc(rpmalloc_heap_t* heap, size_t num, size_t size) { - return rpmalloc_heap_aligned_calloc(heap, 0, num, size); + size_t total; +#if ENABLE_VALIDATE_ARGS +#if PLATFORM_WINDOWS + int err = SizeTMult(num, size, &total); + if ((err != S_OK) || (total >= MAX_ALLOC_SIZE)) { + errno = EINVAL; + return 0; + } +#else + int err = __builtin_umull_overflow(num, size, &total); + if (err || (total >= MAX_ALLOC_SIZE)) { + errno = EINVAL; + return 0; + } +#endif +#else + total = num * size; +#endif + return heap_allocate_block(heap, total, 1); } extern inline RPMALLOC_ALLOCATOR void* @@ -3304,13 +3290,10 @@ rpmalloc_heap_aligned_calloc(rpmalloc_heap_t* heap, size_t alignment, size_t num #else total = num * size; #endif - void* block = _rpmalloc_aligned_allocate(heap, alignment, total); - if (block) - memset(block, 0, total); - return block; + return heap_allocate_block_aligned(heap, alignment, total, 1); } -extern inline RPMALLOC_ALLOCATOR void* +RPMALLOC_ALLOCATOR void* rpmalloc_heap_realloc(rpmalloc_heap_t* heap, void* ptr, size_t size, unsigned int flags) { #if ENABLE_VALIDATE_ARGS if (size >= MAX_ALLOC_SIZE) { @@ -3318,105 +3301,62 @@ rpmalloc_heap_realloc(rpmalloc_heap_t* heap, void* ptr, size_t size, unsigned in return ptr; } #endif - return _rpmalloc_reallocate(heap, ptr, size, 0, flags); + return heap_reallocate_block(heap, ptr, size, 0, flags); } -extern inline RPMALLOC_ALLOCATOR void* +RPMALLOC_ALLOCATOR void* rpmalloc_heap_aligned_realloc(rpmalloc_heap_t* heap, void* ptr, size_t alignment, size_t size, unsigned int flags) { #if ENABLE_VALIDATE_ARGS - if ((size + alignment < size) || (alignment > _memory_page_size)) { + if ((size + alignment < size) || (alignment > SMALL_PAGE_SIZE)) { errno = EINVAL; return 0; } #endif - return _rpmalloc_aligned_reallocate(heap, ptr, alignment, size, 0, flags); + return heap_reallocate_block_aligned(heap, ptr, alignment, size, 0, flags); } -extern inline void +void rpmalloc_heap_free(rpmalloc_heap_t* heap, void* ptr) { (void)sizeof(heap); - _rpmalloc_deallocate(ptr); + block_deallocate(ptr); } -extern inline void +//! Free all memory allocated by the heap +void rpmalloc_heap_free_all(rpmalloc_heap_t* heap) { - span_t* span; - span_t* next_span; + heap_free_all(heap); +} - _rpmalloc_heap_cache_adopt_deferred(heap, 0); - - for (size_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { - span = heap->size_class[iclass].partial_span; - while (span) { - next_span = span->next; - _rpmalloc_heap_cache_insert(heap, span); - span = next_span; - } - heap->size_class[iclass].partial_span = 0; - span = heap->full_span[iclass]; - while (span) { - next_span = span->next; - _rpmalloc_heap_cache_insert(heap, span); - span = next_span; - } - } - memset(heap->size_class, 0, sizeof(heap->size_class)); - memset(heap->full_span, 0, sizeof(heap->full_span)); - - span = heap->large_huge_span; - while (span) { - next_span = span->next; - if (UNEXPECTED(span->size_class == SIZE_CLASS_HUGE)) - _rpmalloc_deallocate_huge(span); - else - _rpmalloc_heap_cache_insert(heap, span); - span = next_span; - } - heap->large_huge_span = 0; - heap->full_span_count = 0; - -#if ENABLE_THREAD_CACHE - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - span_cache_t* span_cache; - if (!iclass) - span_cache = &heap->span_cache; - else - span_cache = (span_cache_t*)(heap->span_large_cache + (iclass - 1)); - if (!span_cache->count) - continue; -#if ENABLE_GLOBAL_CACHE - _rpmalloc_stat_add64(&heap->thread_to_global, span_cache->count * (iclass + 1) * _memory_span_size); - _rpmalloc_stat_add(&heap->span_use[iclass].spans_to_global, span_cache->count); - _rpmalloc_global_cache_insert_spans(span_cache->span, iclass + 1, span_cache->count); -#else - for (size_t ispan = 0; ispan < span_cache->count; ++ispan) - _rpmalloc_span_unmap(span_cache->span[ispan]); -#endif - span_cache->count = 0; - } -#endif - -#if ENABLE_STATISTICS - for (size_t iclass = 0; iclass < SIZE_CLASS_COUNT; ++iclass) { - atomic_store32(&heap->size_class_use[iclass].alloc_current, 0); - atomic_store32(&heap->size_class_use[iclass].spans_current, 0); - } - for (size_t iclass = 0; iclass < LARGE_CLASS_COUNT; ++iclass) { - atomic_store32(&heap->span_use[iclass].current, 0); +struct rpmalloc_heap_statistics_t +rpmalloc_heap_statistics(rpmalloc_heap_t* heap) { +#if RPMALLOC_HEAP_STATISTICS + if (heap) { + return heap->stats; } #endif + (void)sizeof(heap); + struct rpmalloc_heap_statistics_t stats = {0}; + return stats; } extern inline void rpmalloc_heap_thread_set_current(rpmalloc_heap_t* heap) { - heap_t* prev_heap = get_thread_heap_raw(); + heap_t* prev_heap = get_thread_heap(); if (prev_heap != heap) { set_thread_heap(heap); if (prev_heap) - rpmalloc_heap_release(prev_heap); + heap_release(prev_heap); } } +rpmalloc_heap_t* +rpmalloc_get_heap_for_ptr(void* ptr) { + span_t* span = (span_t*)((uintptr_t)ptr & SPAN_MASK); + if (span) + return span_get_page_from_block(span, ptr)->heap; + return 0; +} + #endif #include "glue.h" diff --git a/src/malloc/rpmalloc/rpmalloc.h b/src/malloc/rpmalloc/rpmalloc.h index 02d73f36..f18972c3 100644 --- a/src/malloc/rpmalloc/rpmalloc.h +++ b/src/malloc/rpmalloc/rpmalloc.h @@ -1,117 +1,128 @@ -/* rpmalloc.h - Memory allocator - Public Domain - 2016 Mattias Jansson +/* rpmalloc.h - Memory allocator - 2016-2024 Mattias Jansson * - * This library provides a cross-platform lock free thread caching malloc implementation in C11. - * The latest source code is always available at + * SPDX-FileCopyrightText: 2016-2024 Mattias Jansson + * SPDX-License-Identifier: Unlicense OR MIT + * + * This library provides a cross-platform lock free thread caching malloc + * implementation in C11. The latest source code is always available at * * https://github.com/mjansson/rpmalloc * - * This library is put in the public domain; you can redistribute it and/or modify it without any restrictions. + * This library is put in the public domain; you can redistribute it and/or + * modify it without any restrictions. Or, if you choose, you can use it under + * the MIT license. * */ #pragma once +//! rpmalloc version. RPMALLOC_VERSION is a human-readable string and may carry a pre-release +// suffix such as "-rc1". RPMALLOC_VERSION_NUMBER is a monotonic integer for comparisons, +// computed as major*10000 + minor*100 + patch (pre-release suffixes are not encoded). +#define RPMALLOC_VERSION "2.0.1" +#define RPMALLOC_VERSION_MAJOR 2 +#define RPMALLOC_VERSION_MINOR 0 +#define RPMALLOC_VERSION_PATCH 1 +#define RPMALLOC_VERSION_NUMBER \ + (RPMALLOC_VERSION_MAJOR * 10000 + RPMALLOC_VERSION_MINOR * 100 + RPMALLOC_VERSION_PATCH) + #include #ifdef __cplusplus extern "C" { #endif +#define RPMALLOC_CACHE_LINE_SIZE 64 #if defined(__clang__) || defined(__GNUC__) -# define RPMALLOC_EXPORT static -# define RPMALLOC_ALLOCATOR -# if (defined(__clang_major__) && (__clang_major__ < 4)) || (defined(__GNUC__) && defined(ENABLE_PRELOAD) && ENABLE_PRELOAD) -# define RPMALLOC_ATTRIB_MALLOC -# define RPMALLOC_ATTRIB_ALLOC_SIZE(size) -# define RPMALLOC_ATTRIB_ALLOC_SIZE2(count, size) -# else -# define RPMALLOC_ATTRIB_MALLOC __attribute__((__malloc__)) -# define RPMALLOC_ATTRIB_ALLOC_SIZE(size) __attribute__((alloc_size(size))) -# define RPMALLOC_ATTRIB_ALLOC_SIZE2(count, size) __attribute__((alloc_size(count, size))) -# endif -# define RPMALLOC_CDECL -#elif defined(_MSC_VER) -# define RPMALLOC_EXPORT -# define RPMALLOC_ALLOCATOR __declspec(allocator) __declspec(restrict) -# define RPMALLOC_ATTRIB_MALLOC -# define RPMALLOC_ATTRIB_ALLOC_SIZE(size) -# define RPMALLOC_ATTRIB_ALLOC_SIZE2(count,size) -# define RPMALLOC_CDECL __cdecl +#define RPMALLOC_EXPORT static +#define RPMALLOC_RESTRICT __restrict +#define RPMALLOC_ALLOCATOR +#define RPMALLOC_CACHE_ALIGNED __attribute__((aligned(RPMALLOC_CACHE_LINE_SIZE))) +#if (defined(__clang_major__) && (__clang_major__ < 4)) || (!defined(__clang_major__) && defined(__GNUC__)) +#define RPMALLOC_ATTRIB_MALLOC +#define RPMALLOC_ATTRIB_ALLOC_SIZE(size) +#define RPMALLOC_ATTRIB_ALLOC_SIZE2(count, size) #else -# define RPMALLOC_EXPORT -# define RPMALLOC_ALLOCATOR -# define RPMALLOC_ATTRIB_MALLOC -# define RPMALLOC_ATTRIB_ALLOC_SIZE(size) -# define RPMALLOC_ATTRIB_ALLOC_SIZE2(count,size) -# define RPMALLOC_CDECL +#define RPMALLOC_ATTRIB_MALLOC __attribute__((__malloc__)) +#define RPMALLOC_ATTRIB_ALLOC_SIZE(size) __attribute__((alloc_size(size))) +#define RPMALLOC_ATTRIB_ALLOC_SIZE2(count, size) __attribute__((alloc_size(count, size))) +#endif +#define RPMALLOC_CDECL +#elif defined(_MSC_VER) +#define RPMALLOC_EXPORT +#define RPMALLOC_RESTRICT __declspec(restrict) +#define RPMALLOC_ALLOCATOR __declspec(allocator) __declspec(restrict) +#define RPMALLOC_CACHE_ALIGNED __declspec(align(RPMALLOC_CACHE_LINE_SIZE)) +#define RPMALLOC_ATTRIB_MALLOC +#define RPMALLOC_ATTRIB_ALLOC_SIZE(size) +#define RPMALLOC_ATTRIB_ALLOC_SIZE2(count, size) +#define RPMALLOC_CDECL __cdecl +#else +#define RPMALLOC_EXPORT +#define RPMALLOC_ALLOCATOR +#define RPMALLOC_ATTRIB_MALLOC +#define RPMALLOC_ATTRIB_ALLOC_SIZE(size) +#define RPMALLOC_ATTRIB_ALLOC_SIZE2(count, size) +#define RPMALLOC_CDECL #endif -//! Define RPMALLOC_CONFIGURABLE to enable configuring sizes. Will introduce -// a very small overhead due to some size calculations not being compile time constants -#ifndef RPMALLOC_CONFIGURABLE -#define RPMALLOC_CONFIGURABLE 0 -#endif +#define RPMALLOC_MAX_ALIGNMENT (256 * 1024) -//! Define RPMALLOC_FIRST_CLASS_HEAPS to enable heap based API (rpmalloc_heap_* functions). -// Will introduce a very small overhead to track fully allocated spans in heaps +//! Define RPMALLOC_FIRST_CLASS_HEAPS to non-zero to enable heap based API (rpmalloc_heap_* functions). #ifndef RPMALLOC_FIRST_CLASS_HEAPS #define RPMALLOC_FIRST_CLASS_HEAPS 0 #endif +//! Define RPMALLOC_HEAP_STATISTICS to non-zero to enable first class heap statistics gathering. +#ifndef RPMALLOC_HEAP_STATISTICS +#define RPMALLOC_HEAP_STATISTICS 0 +#endif + //! Flag to rpaligned_realloc to not preserve content in reallocation -#define RPMALLOC_NO_PRESERVE 1 +#define RPMALLOC_NO_PRESERVE 1 //! Flag to rpaligned_realloc to fail and return null pointer if grow cannot be done in-place, // in which case the original pointer is still valid (just like a call to realloc which failes to allocate // a new block). -#define RPMALLOC_GROW_OR_FAIL 2 +#define RPMALLOC_GROW_OR_FAIL 2 typedef struct rpmalloc_global_statistics_t { - //! Current amount of virtual memory mapped, all of which might not have been committed (only if ENABLE_STATISTICS=1) + //! Current amount of virtual memory mapped, all of which might not have been committed (only if + //! ENABLE_STATISTICS=1) size_t mapped; //! Peak amount of virtual memory mapped, all of which might not have been committed (only if ENABLE_STATISTICS=1) size_t mapped_peak; - //! Current amount of memory in global caches for small and medium sizes (<32KiB) - size_t cached; - //! Current amount of memory allocated in huge allocations, i.e larger than LARGE_SIZE_LIMIT which is 2MiB by default (only if ENABLE_STATISTICS=1) + //! Running counter of total amount of memory committed (only if ENABLE_STATISTICS=1) + size_t committed; + //! Running counter of total amount of memory decommitted (only if ENABLE_STATISTICS=1) + size_t decommitted; + //! Current amount of virtual memory active and committed (only if ENABLE_STATISTICS=1) + size_t active; + //! Peak amount of virtual memory active and committed (only if ENABLE_STATISTICS=1) + size_t active_peak; + //! Current amount of memory allocated in huge block allocations, i.e blocks above the + //! largest size class (only if ENABLE_STATISTICS=1) size_t huge_alloc; - //! Peak amount of memory allocated in huge allocations, i.e larger than LARGE_SIZE_LIMIT which is 2MiB by default (only if ENABLE_STATISTICS=1) + //! Peak amount of memory allocated in huge block allocations, i.e blocks above the + //! largest size class (only if ENABLE_STATISTICS=1) size_t huge_alloc_peak; - //! Total amount of memory mapped since initialization (only if ENABLE_STATISTICS=1) - size_t mapped_total; - //! Total amount of memory unmapped since initialization (only if ENABLE_STATISTICS=1) - size_t unmapped_total; + //! Current heap count (only if ENABLE_STATISTICS=1) + size_t heap_count; } rpmalloc_global_statistics_t; typedef struct rpmalloc_thread_statistics_t { - //! Current number of bytes available in thread size class caches for small and medium sizes (<32KiB) + //! Current number of bytes available in thread size class caches (only if ENABLE_STATISTICS=1) size_t sizecache; - //! Current number of bytes available in thread span caches for small and medium sizes (<32KiB) + //! Current number of bytes available in thread page caches (only if ENABLE_STATISTICS=1) size_t spancache; - //! Total number of bytes transitioned from thread cache to global cache (only if ENABLE_STATISTICS=1) - size_t thread_to_global; - //! Total number of bytes transitioned from global cache to thread cache (only if ENABLE_STATISTICS=1) - size_t global_to_thread; - //! Per span count statistics (only if ENABLE_STATISTICS=1) + //! Per page type span statistics, indexed by page type (small, medium-small, medium-large, + //! large, huge) struct { - //! Currently used number of spans + //! Currently mapped number of spans of this page type size_t current; - //! High water mark of spans used - size_t peak; - //! Number of spans transitioned to global cache - size_t to_global; - //! Number of spans transitioned from global cache - size_t from_global; - //! Number of spans transitioned to thread cache - size_t to_cache; - //! Number of spans transitioned from thread cache - size_t from_cache; - //! Number of spans transitioned to reserved state - size_t to_reserved; - //! Number of spans transitioned from reserved state - size_t from_reserved; - //! Number of raw memory map calls (not hitting the reserve spans but resulting in actual OS mmap calls) + //! Number of raw memory map calls for this page type resulting in actual OS mmap calls + //! (only if ENABLE_STATISTICS=1) size_t map_calls; - } span_use[64]; + } span_use[5]; //! Per size class statistics (only if ENABLE_STATISTICS=1) struct { //! Current number of allocations @@ -122,62 +133,41 @@ typedef struct rpmalloc_thread_statistics_t { size_t alloc_total; //! Total number of frees size_t free_total; - //! Number of spans transitioned to cache - size_t spans_to_cache; - //! Number of spans transitioned from cache - size_t spans_from_cache; - //! Number of spans transitioned from reserved state - size_t spans_from_reserved; - //! Number of raw memory map calls (not hitting the reserve spans but resulting in actual OS mmap calls) - size_t map_calls; } size_use[128]; } rpmalloc_thread_statistics_t; -typedef struct rpmalloc_config_t { - //! Map memory pages for the given number of bytes. The returned address MUST be - // aligned to the rpmalloc span size, which will always be a power of two. - // Optionally the function can store an alignment offset in the offset variable - // in case it performs alignment and the returned pointer is offset from the - // actual start of the memory region due to this alignment. The alignment offset - // will be passed to the memory unmap function. The alignment offset MUST NOT be - // larger than 65535 (storable in an uint16_t), if it is you must use natural - // alignment to shift it into 16 bits. If you set a memory_map function, you - // must also set a memory_unmap function or else the default implementation will - // be used for both. This function must be thread safe, it can be called by - // multiple threads simultaneously. - void* (*memory_map)(size_t size, size_t* offset); - //! Unmap the memory pages starting at address and spanning the given number of bytes. - // If release is set to non-zero, the unmap is for an entire span range as returned by - // a previous call to memory_map and that the entire range should be released. The - // release argument holds the size of the entire span range. If release is set to 0, - // the unmap is a partial decommit of a subset of the mapped memory range. - // If you set a memory_unmap function, you must also set a memory_map function or - // else the default implementation will be used for both. This function must be thread - // safe, it can be called by multiple threads simultaneously. - void (*memory_unmap)(void* address, size_t size, size_t offset, size_t release); - //! Called when an assert fails, if asserts are enabled. Will use the standard assert() - // if this is not set. - void (*error_callback)(const char* message); - //! Called when a call to map memory pages fails (out of memory). If this callback is - // not set or returns zero the library will return a null pointer in the allocation - // call. If this callback returns non-zero the map call will be retried. The argument - // passed is the number of bytes that was requested in the map call. Only used if - // the default system memory map function is used (memory_map callback is not set). +typedef struct rpmalloc_interface_t { + //! Map memory pages for the given number of bytes. The returned address MUST be aligned to the given alignment, + //! which will always be either 0 or the span size. The function can store an alignment offset in the offset + //! variable in case it performs alignment and the returned pointer is offset from the actual start of the memory + //! region due to this alignment. This alignment offset will be passed to the memory unmap function. The mapped size + //! can be stored in the mapped_size variable, which will also be passed to the memory unmap function as the release + //! parameter once the entire mapped region is ready to be released. If you set a memory_map function, you must also + //! set a memory_unmap function or else the default implementation will be used for both. This function must be + //! thread safe, it can be called by multiple threads simultaneously. + void* (*memory_map)(size_t size, size_t alignment, size_t* offset, size_t* mapped_size); + //! Commit a range of memory pages. Return non-zero if the operation failed and the address range could not be committed. + int (*memory_commit)(void* address, size_t size); + //! Decommit a range of memory pages. Return non-zero if the operation failed and the address range could not be decommitted. + int (*memory_decommit)(void* address, size_t size); + //! Unmap the memory pages starting at address and spanning the given number of bytes. If you set a memory_unmap + //! function, you must also set a memory_map function or else the default implementation will be used for both. This + //! function must be thread safe, it can be called by multiple threads simultaneously. + void (*memory_unmap)(void* address, size_t offset, size_t mapped_size); + //! Called when a call to map memory pages fails (out of memory). If this callback is not set or returns zero the + //! library will return a null pointer in the allocation call. If this callback returns non-zero the map call will + //! be retried. The argument passed is the number of bytes that was requested in the map call. Only used if the + //! default system memory map function is used (memory_map callback is not set). int (*map_fail_callback)(size_t size); + //! Called when an assert fails, if asserts are enabled. Will use the standard assert() if this is not set. + void (*error_callback)(const char* message); +} rpmalloc_interface_t; + +typedef struct rpmalloc_config_t { //! Size of memory pages. The page size MUST be a power of two. All memory mapping // requests to memory_map will be made with size set to a multiple of the page size. - // Used if RPMALLOC_CONFIGURABLE is defined to 1, otherwise system page size is used. + // Set to 0 to use the OS default page size. size_t page_size; - //! Size of a span of memory blocks. MUST be a power of two, and in [4096,262144] - // range (unless 0 - set to 0 to use the default span size). Used if RPMALLOC_CONFIGURABLE - // is defined to 1. - size_t span_size; - //! Number of spans to map at each request to map new virtual memory blocks. This can - // be used to minimize the system call overhead at the cost of virtual memory address - // space. The extra mapped pages will not be written until actually used, so physical - // committed memory should not be affected in the default implementation. Will be - // aligned to a multiple of spans that match memory page size in case of huge pages. - size_t span_map_count; //! Enable use of large/huge pages. If this flag is set to non-zero and page size is // zero, the allocator will try to enable huge pages and auto detect the configuration. // If this is set to non-zero and page_size is also non-zero, the allocator will @@ -186,16 +176,45 @@ typedef struct rpmalloc_config_t { // For Windows, see https://docs.microsoft.com/en-us/windows/desktop/memory/large-page-support // For Linux, see https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt int enable_huge_pages; - int unused; + //! Enable use of transparent huge pages, advising the kernel to back large memory + // mappings with huge pages without requiring a preallocated huge page pool. Unlike + // enable_huge_pages this does not affect page size or accounting, and unused memory + // ranges can still be decommitted. Ignored if enable_huge_pages is in effect or if + // the platform has no transparent huge page support (currently implemented for + // Linux and Android only). After initialization the config value reflects if + // transparent huge pages are actually used. + int enable_thp; + //! Disable decommitting unused pages when allocator determines the memory pressure + // is low and there is enough active pages cached. If set to 1, keep all pages committed. + int disable_decommit; + //! Allocated pages names for systems supporting it to be able to distinguish among anonymous regions. + const char* page_name; + //! Allocated huge pages names for systems supporting it to be able to distinguish among anonymous regions. + const char* huge_page_name; + //! Unmap all memory on finalize if set to 1. Normally you can let the OS unmap all pages + // when process exits, but if using rpmalloc in a dynamic library you might want to unmap + // all pages when the dynamic library unloads to avoid process memory leaks and bloat. + // NOTE: this is ignored when rpmalloc is built with ENABLE_OVERRIDE, because the standard + // library override makes rpmalloc the backing store for the C runtime's own allocations + // (for example per-thread TLS). Returning all mappings to the OS while the process keeps + // running would unmap memory the runtime still uses. Only honored without the override. + int unmap_on_finalize; +#if defined(__linux__) || defined(__ANDROID__) + ///! Allows to disable the Transparent Huge Page feature on Linux on a process basis, + /// rather than enabling/disabling system-wise (done via /sys/kernel/mm/transparent_hugepage/enabled). + /// It can possibly improve performance and reduced allocation overhead in some contexts, albeit + /// THP is usually enabled by default. + int disable_thp; +#endif } rpmalloc_config_t; -//! Initialize allocator with default configuration +//! Initialize allocator RPMALLOC_EXPORT int -rpmalloc_initialize(void); +rpmalloc_initialize(rpmalloc_interface_t* memory_interface); -//! Initialize allocator with given configuration +//! Initialize allocator RPMALLOC_EXPORT int -rpmalloc_initialize_config(const rpmalloc_config_t* config); +rpmalloc_initialize_config(rpmalloc_interface_t* memory_interface, rpmalloc_config_t* config); //! Get allocator configuration RPMALLOC_EXPORT const rpmalloc_config_t* @@ -211,7 +230,7 @@ rpmalloc_thread_initialize(void); //! Finalize allocator for calling thread RPMALLOC_EXPORT void -rpmalloc_thread_finalize(int release_caches); +rpmalloc_thread_finalize(void); //! Perform deferred deallocations pending for the calling thread heap RPMALLOC_EXPORT void @@ -237,9 +256,9 @@ rpmalloc_dump_statistics(void* file); RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* rpmalloc(size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(1); -//! Free the given memory block -RPMALLOC_EXPORT void -rpfree(void* ptr); +//! Allocate a zero initialized memory block of at least the given size +RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* +rpzalloc(size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(1); //! Allocate a memory block of at least the given size and zero initialize it RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* @@ -252,43 +271,53 @@ rprealloc(void* ptr, size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_S //! Reallocate the given block to at least the given size and alignment, // with optional control flags (see RPMALLOC_NO_PRESERVE). // Alignment must be a power of two and a multiple of sizeof(void*), -// and should ideally be less than memory page size. A caveat of rpmalloc -// internals is that this must also be strictly less than the span size (default 64KiB) +// and should ideally be less than memory page size. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* -rpaligned_realloc(void* ptr, size_t alignment, size_t size, size_t oldsize, unsigned int flags) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(3); +rpaligned_realloc(void* ptr, size_t alignment, size_t size, size_t oldsize, unsigned int flags) RPMALLOC_ATTRIB_MALLOC + RPMALLOC_ATTRIB_ALLOC_SIZE(3); //! Allocate a memory block of at least the given size and alignment. // Alignment must be a power of two and a multiple of sizeof(void*), -// and should ideally be less than memory page size. A caveat of rpmalloc -// internals is that this must also be strictly less than the span size (default 64KiB) +// and should ideally be less than memory page size. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* rpaligned_alloc(size_t alignment, size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(2); +//! Allocate a memory block of at least the given size and alignment. +// Alignment must be a power of two and a multiple of sizeof(void*), +// and should ideally be less than memory page size. +RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* +rpaligned_zalloc(size_t alignment, size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(2); + //! Allocate a memory block of at least the given size and alignment, and zero initialize it. // Alignment must be a power of two and a multiple of sizeof(void*), -// and should ideally be less than memory page size. A caveat of rpmalloc -// internals is that this must also be strictly less than the span size (default 64KiB) +// and should ideally be less than memory page size. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* rpaligned_calloc(size_t alignment, size_t num, size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE2(2, 3); //! Allocate a memory block of at least the given size and alignment. // Alignment must be a power of two and a multiple of sizeof(void*), -// and should ideally be less than memory page size. A caveat of rpmalloc -// internals is that this must also be strictly less than the span size (default 64KiB) +// and should ideally be less than memory page size. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* rpmemalign(size_t alignment, size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(2); //! Allocate a memory block of at least the given size and alignment. // Alignment must be a power of two and a multiple of sizeof(void*), -// and should ideally be less than memory page size. A caveat of rpmalloc -// internals is that this must also be strictly less than the span size (default 64KiB) +// and should ideally be less than memory page size. RPMALLOC_EXPORT int rpposix_memalign(void** memptr, size_t alignment, size_t size); +//! Free the given memory block +RPMALLOC_EXPORT void +rpfree(void* ptr); + //! Query the usable size of the given memory block (from given pointer to the end of block) RPMALLOC_EXPORT size_t rpmalloc_usable_size(void* ptr); +//! Dummy empty function for forcing linker symbol inclusion +RPMALLOC_EXPORT void +rpmalloc_linker_reference(void); + #if RPMALLOC_FIRST_CLASS_HEAPS //! Heap type @@ -300,7 +329,8 @@ typedef struct heap_t rpmalloc_heap_t; RPMALLOC_EXPORT rpmalloc_heap_t* rpmalloc_heap_acquire(void); -//! Release a heap (does NOT free the memory allocated by the heap, use rpmalloc_heap_free_all before destroying the heap). +//! Release a heap (does NOT free the memory allocated by the heap, use rpmalloc_heap_free_all before destroying the +//! heap). // Releasing a heap will enable it to be reused by other threads. Safe to pass a null pointer. RPMALLOC_EXPORT void rpmalloc_heap_release(rpmalloc_heap_t* heap); @@ -311,34 +341,43 @@ rpmalloc_heap_alloc(rpmalloc_heap_t* heap, size_t size) RPMALLOC_ATTRIB_MALLOC R //! Allocate a memory block of at least the given size using the given heap. The returned // block will have the requested alignment. Alignment must be a power of two and a multiple of sizeof(void*), -// and should ideally be less than memory page size. A caveat of rpmalloc -// internals is that this must also be strictly less than the span size (default 64KiB). +// and should ideally be less than memory page size. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* -rpmalloc_heap_aligned_alloc(rpmalloc_heap_t* heap, size_t alignment, size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(3); +rpmalloc_heap_aligned_alloc(rpmalloc_heap_t* heap, size_t alignment, size_t size) RPMALLOC_ATTRIB_MALLOC + RPMALLOC_ATTRIB_ALLOC_SIZE(3); + +//! Allocate a zero initialized memory block of at least the given size using the given heap. The returned +// block will have the requested alignment. Alignment must be a power of two and a multiple of sizeof(void*), +// and should ideally be less than memory page size. +RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* +rpmalloc_heap_aligned_zalloc(rpmalloc_heap_t* heap, size_t alignment, size_t size) RPMALLOC_ATTRIB_MALLOC + RPMALLOC_ATTRIB_ALLOC_SIZE(3); //! Allocate a memory block of at least the given size using the given heap and zero initialize it. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* -rpmalloc_heap_calloc(rpmalloc_heap_t* heap, size_t num, size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE2(2, 3); +rpmalloc_heap_calloc(rpmalloc_heap_t* heap, size_t num, size_t size) RPMALLOC_ATTRIB_MALLOC + RPMALLOC_ATTRIB_ALLOC_SIZE2(2, 3); //! Allocate a memory block of at least the given size using the given heap and zero initialize it. The returned -// block will have the requested alignment. Alignment must either be zero, or a power of two and a multiple of sizeof(void*), -// and should ideally be less than memory page size. A caveat of rpmalloc -// internals is that this must also be strictly less than the span size (default 64KiB). +// block will have the requested alignment. Alignment must either be zero, or a power of two and a multiple of +// sizeof(void*), and should ideally be less than memory page size. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* -rpmalloc_heap_aligned_calloc(rpmalloc_heap_t* heap, size_t alignment, size_t num, size_t size) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE2(2, 3); +rpmalloc_heap_aligned_calloc(rpmalloc_heap_t* heap, size_t alignment, size_t num, size_t size) RPMALLOC_ATTRIB_MALLOC + RPMALLOC_ATTRIB_ALLOC_SIZE2(3, 4); //! Reallocate the given block to at least the given size. The memory block MUST be allocated // by the same heap given to this function. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* -rpmalloc_heap_realloc(rpmalloc_heap_t* heap, void* ptr, size_t size, unsigned int flags) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(3); +rpmalloc_heap_realloc(rpmalloc_heap_t* heap, void* ptr, size_t size, unsigned int flags) RPMALLOC_ATTRIB_MALLOC + RPMALLOC_ATTRIB_ALLOC_SIZE(3); //! Reallocate the given block to at least the given size. The memory block MUST be allocated // by the same heap given to this function. The returned block will have the requested alignment. // Alignment must be either zero, or a power of two and a multiple of sizeof(void*), and should ideally be -// less than memory page size. A caveat of rpmalloc internals is that this must also be strictly less than -// the span size (default 64KiB). +// less than memory page size. RPMALLOC_EXPORT RPMALLOC_ALLOCATOR void* -rpmalloc_heap_aligned_realloc(rpmalloc_heap_t* heap, void* ptr, size_t alignment, size_t size, unsigned int flags) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(4); +rpmalloc_heap_aligned_realloc(rpmalloc_heap_t* heap, void* ptr, size_t alignment, size_t size, + unsigned int flags) RPMALLOC_ATTRIB_MALLOC RPMALLOC_ATTRIB_ALLOC_SIZE(4); //! Free the given memory block from the given heap. The memory block MUST be allocated // by the same heap given to this function. @@ -349,12 +388,29 @@ rpmalloc_heap_free(rpmalloc_heap_t* heap, void* ptr); RPMALLOC_EXPORT void rpmalloc_heap_free_all(rpmalloc_heap_t* heap); +struct rpmalloc_heap_statistics_t { + // Number of bytes allocated + size_t allocated_size; + // Number of bytes committed + size_t committed_size; + // Number of bytes mapped + size_t mapped_size; +}; + +//! Get heap statistics (if enabled in build) +RPMALLOC_EXPORT struct rpmalloc_heap_statistics_t +rpmalloc_heap_statistics(rpmalloc_heap_t* heap); + //! Set the given heap as the current heap for the calling thread. A heap MUST only be current heap // for a single thread, a heap can never be shared between multiple threads. The previous // current heap for the calling thread is released to be reused by other threads. RPMALLOC_EXPORT void rpmalloc_heap_thread_set_current(rpmalloc_heap_t* heap); +//! Returns which heap the given pointer is allocated on +RPMALLOC_EXPORT rpmalloc_heap_t* +rpmalloc_get_heap_for_ptr(void* ptr); + #endif #ifdef __cplusplus