23#pragma clang diagnostic ignored "-Wunused-macros"
24#pragma clang diagnostic ignored "-Wunused-function"
25#if __has_warning("-Wreserved-identifier")
26#pragma clang diagnostic ignored "-Wreserved-identifier"
28#if __has_warning("-Wstatic-in-inline")
29#pragma clang diagnostic ignored "-Wstatic-in-inline"
31#elif defined(__GNUC__)
32#pragma GCC diagnostic ignored "-Wunused-macros"
33#pragma GCC diagnostic ignored "-Wunused-function"
36#if !defined(__has_builtin)
37#define __has_builtin(b) 0
40#if defined(__GNUC__) || defined(__clang__)
42#if __has_builtin(__builtin_memcpy_inline)
43#define _rpmalloc_memcpy_const(x, y, s) __builtin_memcpy_inline(x, y, s)
45#define _rpmalloc_memcpy_const(x, y, s) \
47 _Static_assert(__builtin_choose_expr(__builtin_constant_p(s), 1, 0), \
48 "len must be a constant integer"); \
53#if __has_builtin(__builtin_memset_inline)
54#define _rpmalloc_memset_const(x, y, s) __builtin_memset_inline(x, y, s)
56#define _rpmalloc_memset_const(x, y, s) \
58 _Static_assert(__builtin_choose_expr(__builtin_constant_p(s), 1, 0), \
59 "len must be a constant integer"); \
64#define _rpmalloc_memcpy_const(x, y, s) memcpy(x, y, s)
65#define _rpmalloc_memset_const(x, y, s) memset(x, y, s)
68#if __has_builtin(__builtin_assume)
69#define rpmalloc_assume(cond) __builtin_assume(cond)
70#elif defined(__GNUC__)
71#define rpmalloc_assume(cond) \
73 if (!__builtin_expect(cond, 0)) \
74 __builtin_unreachable(); \
76#elif defined(_MSC_VER)
77#define rpmalloc_assume(cond) __assume(cond)
79#define rpmalloc_assume(cond) 0
82#ifndef HEAP_ARRAY_SIZE
84#define HEAP_ARRAY_SIZE 47
86#ifndef ENABLE_THREAD_CACHE
88#define ENABLE_THREAD_CACHE 1
90#ifndef ENABLE_GLOBAL_CACHE
92#define ENABLE_GLOBAL_CACHE 1
94#ifndef ENABLE_VALIDATE_ARGS
96#define ENABLE_VALIDATE_ARGS 0
98#ifndef ENABLE_STATISTICS
100#define ENABLE_STATISTICS 0
102#ifndef ENABLE_ASSERTS
104#define ENABLE_ASSERTS 0
106#ifndef ENABLE_OVERRIDE
108#define ENABLE_OVERRIDE 0
110#ifndef ENABLE_PRELOAD
112#define ENABLE_PRELOAD 0
116#define DISABLE_UNMAP 0
118#ifndef ENABLE_UNLIMITED_CACHE
120#define ENABLE_UNLIMITED_CACHE 0
122#ifndef ENABLE_ADAPTIVE_THREAD_CACHE
124#define ENABLE_ADAPTIVE_THREAD_CACHE 0
126#ifndef DEFAULT_SPAN_MAP_COUNT
129#define DEFAULT_SPAN_MAP_COUNT 64
131#ifndef GLOBAL_CACHE_MULTIPLIER
133#define GLOBAL_CACHE_MULTIPLIER 8
136#if DISABLE_UNMAP && !ENABLE_GLOBAL_CACHE
137#error Must use global cache if unmap is disabled
141#undef ENABLE_UNLIMITED_CACHE
142#define ENABLE_UNLIMITED_CACHE 1
145#if !ENABLE_GLOBAL_CACHE
146#undef ENABLE_UNLIMITED_CACHE
147#define ENABLE_UNLIMITED_CACHE 0
150#if !ENABLE_THREAD_CACHE
151#undef ENABLE_ADAPTIVE_THREAD_CACHE
152#define ENABLE_ADAPTIVE_THREAD_CACHE 0
155#if defined(_WIN32) || defined(__WIN32__) || defined(_WIN64)
156#define PLATFORM_WINDOWS 1
157#define PLATFORM_POSIX 0
159#define PLATFORM_WINDOWS 0
160#define PLATFORM_POSIX 1
164#if defined(_MSC_VER) && !defined(__clang__)
165#pragma warning(disable : 5105)
167#define FORCEINLINE inline __forceinline
169#define _Static_assert static_assert
172#define FORCEINLINE inline __attribute__((__always_inline__))
176#ifndef WIN32_LEAN_AND_MEAN
177#define WIN32_LEAN_AND_MEAN
180#if ENABLE_VALIDATE_ARGS
188#if defined(__linux__) || defined(__ANDROID__)
189#include <sys/prctl.h>
190#if !defined(PR_SET_VMA)
191#define PR_SET_VMA 0x53564d41
192#define PR_SET_VMA_ANON_NAME 0
195#if defined(__APPLE__)
196#include <TargetConditionals.h>
197#if !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
198#include <mach/mach_vm.h>
199#include <mach/vm_statistics.h>
203#if defined(__HAIKU__) || defined(__TINYC__)
212#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK)
213#include <fibersapi.h>
221#include <sys/sysctl.h>
222#define MAP_HUGETLB MAP_ALIGNED_SUPER
230extern int madvise(caddr_t,
size_t,
int);
232#ifndef MAP_UNINITIALIZED
233#define MAP_UNINITIALIZED 0
240#if defined(_MSC_VER) && !defined(_DEBUG)
244#define RPMALLOC_TOSTRING_M(x) #x
245#define RPMALLOC_TOSTRING(x) RPMALLOC_TOSTRING_M(x)
246#define rpmalloc_assert(truth, message) \
249 if (_memory_config.error_callback) { \
250 _memory_config.error_callback(message " (" RPMALLOC_TOSTRING( \
251 truth) ") at " __FILE__ ":" RPMALLOC_TOSTRING(__LINE__)); \
253 assert((truth) && message); \
258#define rpmalloc_assert(truth, message) \
272#if defined(_MSC_VER) && !defined(__clang__)
274typedef volatile long atomic32_t;
275typedef volatile long long atomic64_t;
276typedef volatile void *atomicptr_t;
278static FORCEINLINE int32_t atomic_load32(atomic32_t *src) {
return *src; }
283 return (int32_t)InterlockedIncrement(val);
286 return (int32_t)InterlockedDecrement(val);
289 return (int32_t)InterlockedExchangeAdd(val, add) +
add;
293 return (InterlockedCompareExchange(dst, val, ref) == ref) ? 1 : 0;
300 return (int64_t)InterlockedExchangeAdd64(val, add) +
add;
313 return (
void *)InterlockedExchangePointer((
void *
volatile *)dst, val);
316 return (InterlockedCompareExchangePointer((
void *
volatile *)dst, val, ref) ==
322#define EXPECTED(x) (x)
323#define UNEXPECTED(x) (x)
327#include <stdatomic.h>
330typedef volatile _Atomic(int64_t) atomic64_t;
331typedef volatile _Atomic(
void *) atomicptr_t;
333static FORCEINLINE int32_t atomic_load32(atomic32_t *src) {
334 return atomic_load_explicit(src, memory_order_relaxed);
337 atomic_store_explicit(dst, val, memory_order_relaxed);
340 return atomic_fetch_add_explicit(val, 1, memory_order_relaxed) + 1;
343 return atomic_fetch_add_explicit(val, -1, memory_order_relaxed) - 1;
346 return atomic_fetch_add_explicit(val, add, memory_order_relaxed) + add;
350 return atomic_compare_exchange_weak_explicit(
351 dst, &ref, val, memory_order_acquire, memory_order_relaxed);
354 atomic_store_explicit(dst, val, memory_order_release);
357 return atomic_load_explicit(val, memory_order_relaxed);
360 return atomic_fetch_add_explicit(val, add, memory_order_relaxed) + add;
363 return atomic_load_explicit(src, memory_order_relaxed);
366 atomic_store_explicit(dst, val, memory_order_relaxed);
369 atomic_store_explicit(dst, val, memory_order_release);
373 return atomic_exchange_explicit(dst, val, memory_order_acquire);
376 return atomic_compare_exchange_weak_explicit(
377 dst, &ref, val, memory_order_relaxed, memory_order_relaxed);
380#define EXPECTED(x) __builtin_expect((x), 1)
381#define UNEXPECTED(x) __builtin_expect((x), 0)
393#define _rpmalloc_stat_inc(counter) atomic_incr32(counter)
394#define _rpmalloc_stat_dec(counter) atomic_decr32(counter)
395#define _rpmalloc_stat_add(counter, value) \
396 atomic_add32(counter, (int32_t)(value))
397#define _rpmalloc_stat_add64(counter, value) \
398 atomic_add64(counter, (int64_t)(value))
399#define _rpmalloc_stat_add_peak(counter, value, peak) \
401 int32_t _cur_count = atomic_add32(counter, (int32_t)(value)); \
402 if (_cur_count > (peak)) \
405#define _rpmalloc_stat_sub(counter, value) \
406 atomic_add32(counter, -(int32_t)(value))
407#define _rpmalloc_stat_inc_alloc(heap, class_idx) \
409 int32_t alloc_current = \
410 atomic_incr32(&heap->size_class_use[class_idx].alloc_current); \
411 if (alloc_current > heap->size_class_use[class_idx].alloc_peak) \
412 heap->size_class_use[class_idx].alloc_peak = alloc_current; \
413 atomic_incr32(&heap->size_class_use[class_idx].alloc_total); \
415#define _rpmalloc_stat_inc_free(heap, class_idx) \
417 atomic_decr32(&heap->size_class_use[class_idx].alloc_current); \
418 atomic_incr32(&heap->size_class_use[class_idx].free_total); \
421#define _rpmalloc_stat_inc(counter) \
424#define _rpmalloc_stat_dec(counter) \
427#define _rpmalloc_stat_add(counter, value) \
430#define _rpmalloc_stat_add64(counter, value) \
433#define _rpmalloc_stat_add_peak(counter, value, peak) \
436#define _rpmalloc_stat_sub(counter, value) \
439#define _rpmalloc_stat_inc_alloc(heap, class_idx) \
442#define _rpmalloc_stat_inc_free(heap, class_idx) \
452#define SMALL_GRANULARITY 16
454#define SMALL_GRANULARITY_SHIFT 4
456#define SMALL_CLASS_COUNT 65
458#define SMALL_SIZE_LIMIT (SMALL_GRANULARITY * (SMALL_CLASS_COUNT - 1))
460#define MEDIUM_GRANULARITY 512
462#define MEDIUM_GRANULARITY_SHIFT 9
464#define MEDIUM_CLASS_COUNT 61
466#define SIZE_CLASS_COUNT (SMALL_CLASS_COUNT + MEDIUM_CLASS_COUNT)
468#define LARGE_CLASS_COUNT 63
470#define MEDIUM_SIZE_LIMIT \
471 (SMALL_SIZE_LIMIT + (MEDIUM_GRANULARITY * MEDIUM_CLASS_COUNT))
473#define LARGE_SIZE_LIMIT \
474 ((LARGE_CLASS_COUNT * _memory_span_size) - SPAN_HEADER_SIZE)
477#define SPAN_HEADER_SIZE 128
479#define MAX_THREAD_SPAN_CACHE 400
481#define THREAD_SPAN_CACHE_TRANSFER 64
484#define MAX_THREAD_SPAN_LARGE_CACHE 100
486#define THREAD_SPAN_LARGE_CACHE_TRANSFER 6
489 "Small granularity must be power of two");
491 "Span header size must be power of two");
493#if ENABLE_VALIDATE_ARGS
496#define MAX_ALLOC_SIZE (((size_t) - 1) - _memory_span_size)
499#define pointer_offset(ptr, ofs) (void *)((char *)(ptr) + (ptrdiff_t)(ofs))
500#define pointer_diff(first, second) \
501 (ptrdiff_t)((const char *)(first) - (const char *)(second))
503#define INVALID_POINTER ((void *)((uintptr_t) - 1))
505#define SIZE_CLASS_LARGE SIZE_CLASS_COUNT
506#define SIZE_CLASS_HUGE ((uint32_t) - 1)
528#define SPAN_FLAG_MASTER 1U
530#define SPAN_FLAG_SUBSPAN 2U
532#define SPAN_FLAG_ALIGNED_BLOCKS 4U
534#define SPAN_FLAG_UNMAPPED_MASTER 8U
536#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS
544 atomic32_t spans_deferred;
546 atomic32_t spans_to_global;
548 atomic32_t spans_from_global;
550 atomic32_t spans_to_cache;
552 atomic32_t spans_from_cache;
554 atomic32_t spans_to_reserved;
556 atomic32_t spans_from_reserved;
558 atomic32_t spans_map_calls;
561typedef struct span_use_t span_use_t;
565struct size_class_use_t {
567 atomic32_t alloc_current;
571 atomic32_t alloc_total;
573 atomic32_t free_total;
575 atomic32_t spans_current;
579 atomic32_t spans_to_cache;
581 atomic32_t spans_from_cache;
583 atomic32_t spans_from_reserved;
585 atomic32_t spans_map_calls;
588typedef struct size_class_use_t size_class_use_t;
671#if ENABLE_THREAD_CACHE
697#if ENABLE_THREAD_CACHE
701#if RPMALLOC_FIRST_CLASS_HEAPS
709#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS
717 atomic64_t thread_to_global;
719 atomic64_t global_to_thread;
743 size_t extract_count;
758#define _memory_default_span_size (64 * 1024)
759#define _memory_default_span_size_shift 16
760#define _memory_default_span_mask (~((uintptr_t)(_memory_span_size - 1)))
774#if RPMALLOC_CONFIGURABLE
783#define _memory_span_size _memory_default_span_size
784#define _memory_span_size_shift _memory_default_span_size_shift
785#define _memory_span_mask _memory_default_span_mask
799#if ENABLE_GLOBAL_CACHE
815#if RPMALLOC_FIRST_CLASS_HEAPS
817static heap_t *_memory_first_class_orphan_heaps;
821static atomic64_t _allocation_counter;
823static atomic64_t _deallocation_counter;
825static atomic32_t _memory_active_heaps;
827static atomic32_t _mapped_pages;
829static int32_t _mapped_pages_peak;
831static atomic32_t _master_spans;
833static atomic32_t _unmapped_master_spans;
835static atomic32_t _mapped_total;
837static atomic32_t _unmapped_total;
839static atomic32_t _mapped_pages_os;
841static atomic32_t _huge_pages_current;
843static int32_t _huge_pages_peak;
853#if ((defined(__APPLE__) || defined(__HAIKU__)) && ENABLE_PRELOAD) || \
855static pthread_key_t _memory_thread_heap;
858#define _Thread_local __declspec(thread)
862#define TLS_MODEL __attribute__((tls_model("initial-exec")))
866#if !defined(__clang__) && defined(__GNUC__)
867#define _Thread_local __thread
874#if (defined(__APPLE__) || defined(__HAIKU__)) && ENABLE_PRELOAD
875 return pthread_getspecific(_memory_thread_heap);
877 return _memory_thread_heap;
897 return (uintptr_t)((
void *)NtCurrentTeb());
898#elif (defined(__GNUC__) || defined(__clang__)) && !defined(__CYGWIN__)
901 __asm__(
"movl %%gs:0, %0" :
"=r"(tid) : :);
902#elif defined(__x86_64__)
904 __asm__(
"movq %%gs:0, %0" :
"=r"(tid) : :);
906 __asm__(
"movq %%fs:0, %0" :
"=r"(tid) : :);
908#elif defined(__arm__)
909 __asm__
volatile(
"mrc p15, 0, %0, c13, c0, 3" :
"=r"(tid));
910#elif defined(__aarch64__)
913 __asm__
volatile(
"mrs %0, tpidrro_el0" :
"=r"(tid));
915 __asm__
volatile(
"mrs %0, tpidr_el0" :
"=r"(tid));
918#error This platform needs implementation of get_thread_id()
922#error This platform needs implementation of get_thread_id()
928#if ((defined(__APPLE__) || defined(__HAIKU__)) && ENABLE_PRELOAD) || \
930 pthread_setspecific(_memory_thread_heap, heap);
932 _memory_thread_heap = heap;
952#elif defined(__x86_64__) || defined(__i386__)
953 __asm__
volatile(
"pause" :::
"memory");
954#elif defined(__aarch64__) || (defined(__arm__) && __ARM_ARCH >= 7)
955 __asm__
volatile(
"yield" :::
"memory");
956#elif defined(__powerpc__) || defined(__powerpc64__)
958 __asm__
volatile(
"or 27,27,27");
959#elif defined(__sparc__)
960 __asm__
volatile(
"rd %ccr, %g0 \n\trd %ccr, %g0 \n\trd %ccr, %g0");
962 struct timespec ts = {0};
967#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK)
968static void NTAPI _rpmalloc_thread_destructor(
void *
value) {
987#if defined(__linux__) || defined(__ANDROID__)
990 if (address == MAP_FAILED || !
name)
994 (void)prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, (uintptr_t)address, size,
998 (void)
sizeof(address);
1012 _mapped_pages_peak);
1028 "Invalid unmap size");
1049 void *ptr = VirtualAlloc(0, size + padding,
1051 MEM_RESERVE | MEM_COMMIT,
1063 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_UNINITIALIZED;
1064#if defined(__APPLE__) && !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
1065 int fd = (int)VM_MAKE_TAG(240U);
1067 fd |= VM_FLAGS_SUPERPAGE_SIZE_2MB;
1068 void *ptr = mmap(0, size + padding, PROT_READ | PROT_WRITE, flags, fd, 0);
1069#elif defined(MAP_HUGETLB)
1070 void *ptr = mmap(0, size + padding,
1071 PROT_READ | PROT_WRITE | PROT_MAX(PROT_READ | PROT_WRITE),
1073#if defined(MADV_HUGEPAGE)
1078 ptr = mmap(0, size + padding, PROT_READ | PROT_WRITE, flags, -1, 0);
1079 if (ptr && ptr != MAP_FAILED) {
1080 int prm = madvise(ptr, size + padding, MADV_HUGEPAGE);
1087#elif defined(MAP_ALIGNED)
1088 const size_t align =
1089 (
sizeof(size_t) * 8) - (size_t)(__builtin_clzl(size - 1));
1091 mmap(0, size + padding, PROT_READ | PROT_WRITE,
1093#elif defined(MAP_ALIGN)
1095 void *ptr = mmap(base, size + padding, PROT_READ | PROT_WRITE,
1098 void *ptr = mmap(0, size + padding, PROT_READ | PROT_WRITE, flags, -1, 0);
1100 if ((ptr == MAP_FAILED) || !ptr) {
1104 }
else if (errno != ENOMEM) {
1106 "Failed to map virtual memory block");
1116 "Internal failure in padding");
1117 rpmalloc_assert(final_padding <= padding,
"Internal failure in padding");
1120 *offset = final_padding >> 3;
1124 "Internal failure in padding");
1133 "Invalid unmap size");
1135 if (release && offset) {
1146 if (!VirtualFree(address, release ? 0 : size,
1147 release ? MEM_RELEASE : MEM_DECOMMIT)) {
1152 if (munmap(address, release)) {
1156#if defined(MADV_FREE_REUSABLE)
1158 while ((ret = madvise(address, size, MADV_FREE_REUSABLE)) == -1 &&
1161 if ((ret == -1) && (errno != 0)) {
1162#elif defined(MADV_DONTNEED)
1163 if (madvise(address, size, MADV_DONTNEED)) {
1164#elif defined(MADV_PAGEOUT)
1165 if (madvise(address, size, MADV_PAGEOUT)) {
1166#elif defined(MADV_FREE)
1167 if (madvise(address, size, MADV_FREE)) {
1169 if (posix_madvise(address, size, POSIX_MADV_DONTNEED)) {
1202 size_t reserve_span_count) {
1217 (*head)->prev = span;
1234 if (*head == span) {
1239 prev_span->
next = next_span;
1241 next_span->
prev = prev_span;
1257 size_t reserve_span_count);
1263 size_t span_count) {
1265 "Span master pointer and/or flag mismatch");
1266 if (subspan != master) {
1279 size_t span_count) {
1304 return request_count;
1309 size_t span_count,
size_t align_offset) {
1322 size_t span_count) {
1327 size_t align_offset = 0;
1336 if (aligned_span_count > span_count) {
1339 size_t reserved_count = aligned_span_count - span_count;
1349 "Global spin lock not held as expected");
1371 if (span_count <= heap->spans_reserved)
1374 int use_global_reserve =
1377 if (use_global_reserve) {
1382 size_t reserve_count =
1388 if (reserve_count > span_count) {
1393 reserve_count - span_count);
1402 if (use_global_reserve)
1412 "Span flag corrupted");
1415 "Span flag corrupted");
1424 "Span flag corrupted");
1447 "Span flag corrupted");
1464 "Invalid span size class");
1466#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS
1485 void *page_start,
void *block_start,
1489 *first_block = block_start;
1490 if (block_count > 1) {
1498 if (page_end < block_end)
1499 block_end = page_end;
1504 while (next_block < block_end) {
1505 *((
void **)free_block) = next_block;
1506 free_block = next_block;
1510 *((
void **)free_block) = 0;
1526 span->
flags &= ~SPAN_FLAG_ALIGNED_BLOCKS;
1546#if RPMALLOC_FIRST_CLASS_HEAPS
1570 "Span free list corrupted");
1578 if (span == class_span) {
1581 void *last_block = 0;
1593 *((
void **)last_block) = free_list;
1620#if ENABLE_GLOBAL_CACHE
1623static void _rpmalloc_global_cache_finalize(
global_cache_t *cache) {
1627 for (
size_t ispan = 0; ispan < cache->
count; ++ispan)
1640static void _rpmalloc_global_cache_insert_spans(
span_t **span,
1643 const size_t cache_limit =
1650 size_t insert_count =
count;
1654#if ENABLE_STATISTICS
1655 cache->insert_count +=
count;
1657 if ((cache->
count + insert_count) > cache_limit)
1658 insert_count = cache_limit - cache->
count;
1660 memcpy(cache->
span + cache->
count, span,
sizeof(
span_t *) * insert_count);
1663#if ENABLE_UNLIMITED_CACHE
1664 while (insert_count < count) {
1671 span_t *current_span = span[insert_count++];
1678 for (
size_t ispan = insert_count; ispan <
count; ++ispan) {
1679 span_t *current_span = span[ispan];
1684 current_span->
next = keep;
1685 keep = current_span;
1697 for (; islot < cache->
count; ++islot) {
1704 cache->
span[islot] = keep;
1708 if (islot == cache->
count)
1725static size_t _rpmalloc_global_cache_extract_spans(
span_t **span,
1730 size_t extract_count = 0;
1734#if ENABLE_STATISTICS
1735 cache->extract_count +=
count;
1737 size_t want =
count - extract_count;
1738 if (want > cache->
count)
1739 want = cache->
count;
1741 memcpy(span + extract_count, cache->
span + (cache->
count - want),
1742 sizeof(
span_t *) * want);
1744 extract_count += want;
1746 while ((extract_count < count) && cache->
overflow) {
1748 span[extract_count++] = current_span;
1753 for (
size_t ispan = 0; ispan < extract_count; ++ispan) {
1755 "Global cache span count mismatch");
1761 return extract_count;
1777 size_t reserve_span_count) {
1796#if RPMALLOC_FIRST_CLASS_HEAPS
1802 if (single_span && !*single_span)
1803 *single_span = span;
1811 "Span size class invalid");
1814#if RPMALLOC_FIRST_CLASS_HEAPS
1820 if (!idx && single_span && !*single_span)
1821 *single_span = span;
1851#if ENABLE_THREAD_CACHE
1855 span_cache = &heap->span_cache;
1857 span_cache = (
span_cache_t *)(heap->span_large_cache + (iclass - 1));
1858 for (
size_t ispan = 0; ispan < span_cache->
count; ++ispan)
1860 span_cache->
count = 0;
1879 if (list_heap == heap) {
1882 while (list_heap->next_heap != heap)
1898#if ENABLE_THREAD_CACHE
1901 if (span_count == 1) {
1903 span_cache->
span[span_cache->
count++] = span;
1905 const size_t remain_count =
1907#if ENABLE_GLOBAL_CACHE
1912 _rpmalloc_global_cache_insert_spans(span_cache->
span + remain_count,
1919 span_cache->
count = remain_count;
1922 size_t cache_idx = span_count - 2;
1924 span_cache->
span[span_cache->
count++] = span;
1925 const size_t cache_limit =
1927 if (span_cache->
count == cache_limit) {
1928 const size_t transfer_limit = 2 + (cache_limit >> 2);
1929 const size_t transfer_count =
1933 const size_t remain_count = cache_limit - transfer_count;
1934#if ENABLE_GLOBAL_CACHE
1939 _rpmalloc_global_cache_insert_spans(span_cache->
span + remain_count,
1940 span_count, transfer_count);
1942 for (
size_t ispan = 0; ispan < transfer_count; ++ispan)
1945 span_cache->
count = remain_count;
1956 size_t span_count) {
1958#if ENABLE_THREAD_CACHE
1960 if (span_count == 1)
1961 span_cache = &heap->span_cache;
1963 span_cache = (
span_cache_t *)(heap->span_large_cache + (span_count - 2));
1964 if (span_cache->
count) {
1966 return span_cache->
span[--span_cache->
count];
1973 size_t span_count) {
1975 if (span_count == 1) {
1985 size_t span_count) {
1993 size_t span_count) {
1994#if ENABLE_GLOBAL_CACHE
1995#if ENABLE_THREAD_CACHE
1997 size_t wanted_count;
1998 if (span_count == 1) {
1999 span_cache = &heap->span_cache;
2002 span_cache = (
span_cache_t *)(heap->span_large_cache + (span_count - 2));
2005 span_cache->
count = _rpmalloc_global_cache_extract_spans(
2006 span_cache->
span, span_count, wanted_count);
2007 if (span_cache->
count) {
2012 return span_cache->
span[--span_cache->
count];
2016 size_t count = _rpmalloc_global_cache_extract_spans(&span, span_count, 1);
2027 (void)
sizeof(span_count);
2034 (void)
sizeof(span_count);
2035 (void)
sizeof(class_idx);
2036#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS
2040 if (current_count > (
uint32_t)atomic_load32(&heap->span_use[idx].high))
2041 atomic_store32(&heap->span_use[idx].high, (int32_t)current_count);
2043 heap->size_class_use[class_idx].spans_peak);
2052 size_t span_count,
uint32_t class_idx) {
2054#if ENABLE_THREAD_CACHE
2055 if (heap_size_class && heap_size_class->
cache) {
2056 span = heap_size_class->
cache;
2057 heap_size_class->
cache =
2058 (heap->span_cache.count
2059 ? heap->span_cache.span[--heap->span_cache.count]
2065 (void)
sizeof(class_idx);
2067 size_t base_span_count = span_count;
2068 size_t limit_span_count =
2069 (span_count > 2) ? (span_count + (span_count >> 1)) : span_count;
2098 }
while (span_count <= limit_span_count);
2119#if RPMALLOC_FIRST_CLASS_HEAPS
2123 (void)
sizeof(first_class);
2136 size_t heap_size =
sizeof(
heap_t);
2137 size_t aligned_heap_size = 16 * ((heap_size + 15) / 16);
2138 size_t request_heap_count = 16;
2139 size_t heap_span_count = ((aligned_heap_size * request_heap_count) +
2143 size_t span_count = heap_span_count;
2155 size_t possible_heap_count =
2156 (block_size -
sizeof(
span_t)) / aligned_heap_size;
2157 if (possible_heap_count >= (request_heap_count * 16))
2158 request_heap_count *= 16;
2159 else if (possible_heap_count < request_heap_count)
2160 request_heap_count = possible_heap_count;
2161 heap_span_count = ((aligned_heap_size * request_heap_count) +
2166 size_t align_offset = 0;
2181 size_t num_heaps = remain_size / aligned_heap_size;
2182 if (num_heaps < request_heap_count)
2183 num_heaps = request_heap_count;
2186 while (num_heaps > 1) {
2194 if (span_count > heap_span_count) {
2196 size_t remain_count = span_count - heap_span_count;
2197 size_t reserve_count =
2204 if (remain_count > reserve_count) {
2208 reserve_count = remain_count - reserve_count;
2217 heap_t *heap = *heap_list;
2227 if (first_class == 0)
2229#if RPMALLOC_FIRST_CLASS_HEAPS
2242 int release_cache) {
2248 if (release_cache || heap->
finalize) {
2249#if ENABLE_THREAD_CACHE
2253 span_cache = &heap->span_cache;
2255 span_cache = (
span_cache_t *)(heap->span_large_cache + (iclass - 1));
2256 if (!span_cache->
count)
2258#if ENABLE_GLOBAL_CACHE
2260 for (
size_t ispan = 0; ispan < span_cache->
count; ++ispan)
2268 _rpmalloc_global_cache_insert_spans(span_cache->
span, iclass + 1,
2272 for (
size_t ispan = 0; ispan < span_cache->
count; ++ispan)
2275 span_cache->
count = 0;
2283#if ENABLE_STATISTICS
2286 "Still active heaps during finalization");
2333#if RPMALLOC_FIRST_CLASS_HEAPS
2334 list = &heap->full_span[iclass];
2346#if ENABLE_THREAD_CACHE
2350 span_cache = &heap->span_cache;
2352 span_cache = (
span_cache_t *)(heap->span_large_cache + (iclass - 1));
2353 for (
size_t ispan = 0; ispan < span_cache->
count; ++ispan)
2355 span_cache->
count = 0;
2359 "Heaps still active during finalization");
2370 void *
block = *list;
2371 *list = *((
void **)
block);
2383 "Span block count corrupted");
2385 "Internal failure");
2405 "Span block count corrupted");
2421#if RPMALLOC_FIRST_CLASS_HEAPS
2492#if RPMALLOC_FIRST_CLASS_HEAPS
2508 size_t align_offset = 0;
2521#if RPMALLOC_FIRST_CLASS_HEAPS
2546#if ENABLE_VALIDATE_ARGS
2547 if ((size + alignment) < size) {
2551 if (alignment & (alignment - 1)) {
2566 "Failed alignment calculation");
2567 if (multiple_size <= (size + alignment))
2572 size_t align_mask = alignment - 1;
2575 if ((uintptr_t)ptr & align_mask) {
2576 ptr = (
void *)(((uintptr_t)ptr & ~(uintptr_t)align_mask) + alignment);
2593 if (alignment & align_mask) {
2609 if (extra_pages > num_pages)
2610 num_pages = 1 + extra_pages;
2612 size_t original_pages = num_pages;
2614 if (limit_pages < (original_pages * 2))
2615 limit_pages = original_pages * 2;
2617 size_t mapped_size, align_offset;
2631 if ((uintptr_t)ptr & align_mask)
2632 ptr = (
void *)(((uintptr_t)ptr & ~(uintptr_t)align_mask) + alignment);
2639 if (num_pages > limit_pages) {
2653#if RPMALLOC_FIRST_CLASS_HEAPS
2676 "Internal failure");
2680#if RPMALLOC_FIRST_CLASS_HEAPS
2733 *((
void **)
block) = free_list;
2735 int all_deferred_free = (free_count == span->
block_count);
2737 if (all_deferred_free) {
2754#if RPMALLOC_FIRST_CLASS_HEAPS
2773 "Span flag corrupted");
2776 "Span flag corrupted");
2779#if RPMALLOC_FIRST_CLASS_HEAPS
2793#if RPMALLOC_FIRST_CLASS_HEAPS
2796#if ENABLE_ADAPTIVE_THREAD_CACHE || ENABLE_STATISTICS
2803#if ENABLE_THREAD_CACHE
2804 const int set_as_reserved =
2805 ((span->
span_count > 1) && (heap->span_cache.count == 0) &&
2808 const int set_as_reserved =
2811 if (set_as_reserved) {
2824 "Master span count corrupted");
2836#if RPMALLOC_FIRST_CLASS_HEAPS
2850#if RPMALLOC_FIRST_CLASS_HEAPS
2886 size_t oldsize,
unsigned int flags) {
2905 memmove(
block, p, oldsize);
2919 if ((current_spans >= num_spans) && (total_size >= (oldsize / 2))) {
2923 memmove(
block, p, oldsize);
2938 if ((current_pages >= num_pages) && (num_pages >= (current_pages / 2))) {
2942 memmove(
block, p, oldsize);
2956 size_t lower_bound = oldsize + (oldsize >> 2) + (oldsize >> 3);
2958 (size > lower_bound) ? size : ((size > oldsize) ? lower_bound : size);
2962 memcpy(
block, p, oldsize < new_size ? oldsize : new_size);
2970 size_t alignment,
size_t size,
2971 size_t oldsize,
unsigned int flags) {
2977 if ((usablesize >= size) && !((uintptr_t)ptr & (alignment - 1))) {
2978 if (no_alloc || (size >= (usablesize / 2)))
2987 oldsize = usablesize;
2988 memcpy(
block, ptr, oldsize < size ? oldsize : size);
3031 size_t prevclass = iclass;
3032 while (prevclass > 0) {
3073 SYSTEM_INFO system_info;
3074 memset(&system_info, 0,
sizeof(system_info));
3075 GetSystemInfo(&system_info);
3081#if RPMALLOC_CONFIGURABLE
3093#if defined(__linux__)
3094 size_t huge_page_size = 0;
3095 FILE *meminfo = fopen(
"/proc/meminfo",
"r");
3098 while (!huge_page_size && fgets(line,
sizeof(line) - 1, meminfo)) {
3099 line[
sizeof(line) - 1] = 0;
3100 if (strstr(line,
"Hugepagesize:"))
3101 huge_page_size = (
size_t)strtol(line + 13, 0, 10) * 1024;
3105 if (huge_page_size) {
3110#elif defined(__FreeBSD__)
3112 size_t sz =
sizeof(
rc);
3114 if (sysctlbyname(
"vm.pmap.pg_ps_enabled", &
rc, &sz, NULL, 0) == 0 &&
3116 static size_t defsize = 2 * 1024 * 1024;
3118 size_t sizes[4] = {0};
3121 if ((nsize = getpagesizes(sizes, 4)) >= 2) {
3123 for (
size_t csize = sizes[nsize]; nsize >= 0 && csize;
3124 --nsize, csize = sizes[nsize]) {
3127 "Invalid page size");
3128 if (defsize < csize) {
3136#elif defined(__APPLE__) || defined(__NetBSD__)
3151 size_t large_page_minimum = GetLargePageMinimum();
3152 if (large_page_minimum)
3153 OpenProcessToken(GetCurrentProcess(),
3154 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token);
3157 if (LookupPrivilegeValue(0, SE_LOCK_MEMORY_NAME, &luid)) {
3158 TOKEN_PRIVILEGES token_privileges;
3159 memset(&token_privileges, 0,
sizeof(token_privileges));
3160 token_privileges.PrivilegeCount = 1;
3161 token_privileges.Privileges[0].Luid = luid;
3162 token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
3163 if (AdjustTokenPrivileges(token, FALSE, &token_privileges, 0, 0, 0)) {
3164 if (GetLastError() == ERROR_SUCCESS)
3179 size_t min_span_size = 256;
3180 size_t max_page_size;
3181#if UINTPTR_MAX > 0xFFFFFFFF
3182 max_page_size = 4096ULL * 1024ULL * 1024ULL;
3184 max_page_size = 4 * 1024 * 1024;
3192 while (page_size_bit != 1) {
3194 page_size_bit >>= 1;
3198#if RPMALLOC_CONFIGURABLE
3205 if (span_size > (256 * 1024))
3206 span_size = (256 * 1024);
3234#if ((defined(__APPLE__) || defined(__HAIKU__)) && ENABLE_PRELOAD) || \
3239#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK)
3240 fls_key = FlsAlloc(&_rpmalloc_thread_destructor);
3268#if RPMALLOC_FIRST_CLASS_HEAPS
3269 _memory_first_class_orphan_heaps = 0;
3271#if ENABLE_STATISTICS
3274 _mapped_pages_peak = 0;
3280 _huge_pages_peak = 0;
3317#if ENABLE_GLOBAL_CACHE
3320 _rpmalloc_global_cache_finalize(&_memory_span_cache[iclass]);
3323#if (defined(__APPLE__) || defined(__HAIKU__)) && ENABLE_PRELOAD
3324 pthread_key_delete(_memory_thread_heap);
3326#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK)
3330#if ENABLE_STATISTICS
3333 rpmalloc_assert(atomic_load32(&_mapped_pages) == 0,
"Memory leak detected");
3335 "Memory leak detected");
3348#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK)
3349 FlsSetValue(fls_key, heap);
3361#if defined(_WIN32) && (!defined(BUILD_DYNAMIC_LINK) || !BUILD_DYNAMIC_LINK)
3362 FlsSetValue(fls_key, 0);
3375#if ENABLE_VALIDATE_ARGS
3376 if (size >= MAX_ALLOC_SIZE) {
3389#if ENABLE_VALIDATE_ARGS
3391 int err = SizeTMult(num, size, &total);
3392 if ((err != S_OK) || (total >= MAX_ALLOC_SIZE)) {
3397 int err = __builtin_umull_overflow(num, size, &total);
3398 if (err || (total >= MAX_ALLOC_SIZE)) {
3409 memset(
block, 0, total);
3414#if ENABLE_VALIDATE_ARGS
3415 if (size >= MAX_ALLOC_SIZE) {
3425 size_t size,
size_t oldsize,
3426 unsigned int flags) {
3427#if ENABLE_VALIDATE_ARGS
3446#if ENABLE_VALIDATE_ARGS
3448 int err = SizeTMult(num, size, &total);
3449 if ((err != S_OK) || (total >= MAX_ALLOC_SIZE)) {
3454 int err = __builtin_umull_overflow(num, size, &total);
3455 if (err || (total >= MAX_ALLOC_SIZE)) {
3465 memset(
block, 0, total);
3480 return *memptr ? 0 : ENOMEM;
3503 free_count += (block_count - span->
used_count);
3509#if ENABLE_THREAD_CACHE
3513 span_cache = &heap->span_cache;
3515 span_cache = (
span_cache_t *)(heap->span_large_cache + (iclass - 1));
3527#if ENABLE_STATISTICS
3532 stats->span_use[iclass].current =
3533 (size_t)atomic_load32(&heap->span_use[iclass].current);
3534 stats->span_use[iclass].peak =
3535 (size_t)atomic_load32(&heap->span_use[iclass].high);
3536 stats->span_use[iclass].to_global =
3537 (size_t)atomic_load32(&heap->span_use[iclass].spans_to_global);
3538 stats->span_use[iclass].from_global =
3539 (size_t)atomic_load32(&heap->span_use[iclass].spans_from_global);
3540 stats->span_use[iclass].to_cache =
3541 (size_t)atomic_load32(&heap->span_use[iclass].spans_to_cache);
3542 stats->span_use[iclass].from_cache =
3543 (size_t)atomic_load32(&heap->span_use[iclass].spans_from_cache);
3544 stats->span_use[iclass].to_reserved =
3545 (size_t)atomic_load32(&heap->span_use[iclass].spans_to_reserved);
3546 stats->span_use[iclass].from_reserved =
3547 (size_t)atomic_load32(&heap->span_use[iclass].spans_from_reserved);
3548 stats->span_use[iclass].map_calls =
3549 (size_t)atomic_load32(&heap->span_use[iclass].spans_map_calls);
3552 stats->size_use[iclass].alloc_current =
3553 (size_t)atomic_load32(&heap->size_class_use[iclass].alloc_current);
3554 stats->size_use[iclass].alloc_peak =
3555 (size_t)heap->size_class_use[iclass].alloc_peak;
3556 stats->size_use[iclass].alloc_total =
3557 (
size_t)atomic_load32(&heap->size_class_use[iclass].alloc_total);
3558 stats->size_use[iclass].free_total =
3559 (size_t)atomic_load32(&heap->size_class_use[iclass].free_total);
3560 stats->size_use[iclass].spans_to_cache =
3561 (size_t)atomic_load32(&heap->size_class_use[iclass].spans_to_cache);
3562 stats->size_use[iclass].spans_from_cache =
3563 (size_t)atomic_load32(&heap->size_class_use[iclass].spans_from_cache);
3564 stats->size_use[iclass].spans_from_reserved = (size_t)atomic_load32(
3565 &heap->size_class_use[iclass].spans_from_reserved);
3566 stats->size_use[iclass].map_calls =
3567 (size_t)atomic_load32(&heap->size_class_use[iclass].spans_map_calls);
3574#if ENABLE_STATISTICS
3577 stats->mapped_total =
3579 stats->unmapped_total =
3585#if ENABLE_GLOBAL_CACHE
3591#if ENABLE_UNLIMITED_CACHE
3593 while (current_span) {
3595 current_span = current_span->
next;
3604#if ENABLE_STATISTICS
3606static void _memory_heap_dump_statistics(
heap_t *heap,
void *
file) {
3607 fprintf(
file,
"Heap %d stats:\n", heap->
id);
3608 fprintf(
file,
"Class CurAlloc PeakAlloc TotAlloc TotFree BlkSize "
3609 "BlkCount SpansCur SpansPeak PeakAllocMiB ToCacheMiB "
3610 "FromCacheMiB FromReserveMiB MmapCalls\n");
3612 if (!atomic_load32(&heap->size_class_use[iclass].alloc_total))
3616 "%3u: %10u %10u %10u %10u %8u %8u %8d %9d %13zu %11zu %12zu %14zu "
3619 atomic_load32(&heap->size_class_use[iclass].alloc_current),
3620 heap->size_class_use[iclass].alloc_peak,
3621 atomic_load32(&heap->size_class_use[iclass].alloc_total),
3622 atomic_load32(&heap->size_class_use[iclass].free_total),
3625 atomic_load32(&heap->size_class_use[iclass].spans_current),
3626 heap->size_class_use[iclass].spans_peak,
3627 ((
size_t)heap->size_class_use[iclass].alloc_peak *
3629 (
size_t)(1024 * 1024),
3630 ((
size_t)atomic_load32(&heap->size_class_use[iclass].spans_to_cache) *
3632 (
size_t)(1024 * 1024),
3633 ((
size_t)atomic_load32(&heap->size_class_use[iclass].spans_from_cache) *
3635 (
size_t)(1024 * 1024),
3636 ((
size_t)atomic_load32(
3637 &heap->size_class_use[iclass].spans_from_reserved) *
3639 (
size_t)(1024 * 1024),
3640 atomic_load32(&heap->size_class_use[iclass].spans_map_calls));
3642 fprintf(
file,
"Spans Current Peak Deferred PeakMiB Cached ToCacheMiB "
3643 "FromCacheMiB ToReserveMiB FromReserveMiB ToGlobalMiB "
3644 "FromGlobalMiB MmapCalls\n");
3646 if (!atomic_load32(&heap->span_use[iclass].high) &&
3647 !atomic_load32(&heap->span_use[iclass].spans_map_calls))
3651 "%4u: %8d %8u %8u %8zu %7u %11zu %12zu %12zu %14zu %11zu %13zu %10u\n",
3652 (
uint32_t)(iclass + 1), atomic_load32(&heap->span_use[iclass].current),
3653 atomic_load32(&heap->span_use[iclass].high),
3654 atomic_load32(&heap->span_use[iclass].spans_deferred),
3655 ((
size_t)atomic_load32(&heap->span_use[iclass].high) *
3657 (
size_t)(1024 * 1024),
3659 (
unsigned int)(!iclass ? heap->span_cache.count
3660 : heap->span_large_cache[iclass - 1].count),
3661 ((
size_t)atomic_load32(&heap->span_use[iclass].spans_to_cache) *
3663 (
size_t)(1024 * 1024),
3664 ((
size_t)atomic_load32(&heap->span_use[iclass].spans_from_cache) *
3666 (
size_t)(1024 * 1024),
3668 0, (
size_t)0, (
size_t)0,
3670 ((
size_t)atomic_load32(&heap->span_use[iclass].spans_to_reserved) *
3672 (
size_t)(1024 * 1024),
3673 ((
size_t)atomic_load32(&heap->span_use[iclass].spans_from_reserved) *
3675 (
size_t)(1024 * 1024),
3676 ((
size_t)atomic_load32(&heap->span_use[iclass].spans_to_global) *
3678 (
size_t)(1024 * 1024),
3679 ((
size_t)atomic_load32(&heap->span_use[iclass].spans_from_global) *
3681 (
size_t)(1024 * 1024),
3682 atomic_load32(&heap->span_use[iclass].spans_map_calls));
3685 fprintf(
file,
"ThreadToGlobalMiB GlobalToThreadMiB\n");
3687 file,
"%17zu %17zu\n",
3688 (
size_t)
atomic_load64(&heap->thread_to_global) / (
size_t)(1024 * 1024),
3689 (
size_t)
atomic_load64(&heap->global_to_thread) / (
size_t)(1024 * 1024));
3695#if ENABLE_STATISTICS
3702 if (!atomic_load32(&heap->size_class_use[iclass].alloc_total)) {
3704 !atomic_load32(&heap->size_class_use[iclass].free_total),
3705 "Heap statistics counter mismatch");
3707 !atomic_load32(&heap->size_class_use[iclass].spans_map_calls),
3708 "Heap statistics counter mismatch");
3715 if (!atomic_load32(&heap->span_use[iclass].high) &&
3716 !atomic_load32(&heap->span_use[iclass].spans_map_calls))
3721 _memory_heap_dump_statistics(heap,
file);
3725 fprintf(
file,
"Global stats:\n");
3726 size_t huge_current =
3729 fprintf(
file,
"HugeCurrentMiB HugePeakMiB\n");
3730 fprintf(
file,
"%14zu %11zu\n", huge_current / (
size_t)(1024 * 1024),
3731 huge_peak / (
size_t)(1024 * 1024));
3733#if ENABLE_GLOBAL_CACHE
3734 fprintf(
file,
"GlobalCacheMiB\n");
3739 size_t global_overflow_cache = 0;
3745 if (global_cache || global_overflow_cache || cache->insert_count ||
3746 cache->extract_count)
3748 "%4zu: %8zuMiB (%8zuMiB overflow) %14zu insert %14zu extract\n",
3749 iclass + 1, global_cache / (
size_t)(1024 * 1024),
3750 global_overflow_cache / (
size_t)(1024 * 1024),
3751 cache->insert_count, cache->extract_count);
3759 size_t mapped_total =
3761 size_t unmapped_total =
3765 "MappedMiB MappedOSMiB MappedPeakMiB MappedTotalMiB UnmappedTotalMiB\n");
3766 fprintf(
file,
"%9zu %11zu %13zu %14zu %16zu\n",
3767 mapped / (
size_t)(1024 * 1024), mapped_os / (
size_t)(1024 * 1024),
3768 mapped_peak / (
size_t)(1024 * 1024),
3769 mapped_total / (
size_t)(1024 * 1024),
3770 unmapped_total / (
size_t)(1024 * 1024));
3772 fprintf(
file,
"\n");
3775 int64_t deallocated =
atomic_load64(&_deallocation_counter);
3776 fprintf(
file,
"Allocation count: %lli\n", allocated);
3777 fprintf(
file,
"Deallocation count: %lli\n", deallocated);
3778 fprintf(
file,
"Current allocations: %lli\n", (allocated - deallocated));
3779 fprintf(
file,
"Master spans: %d\n", atomic_load32(&_master_spans));
3780 fprintf(
file,
"Dangling master spans: %d\n", atomic_load32(&_unmapped_master_spans));
3786#if RPMALLOC_FIRST_CLASS_HEAPS
3788extern inline rpmalloc_heap_t *rpmalloc_heap_acquire(
void) {
3800extern inline void rpmalloc_heap_release(rpmalloc_heap_t *heap) {
3806rpmalloc_heap_alloc(rpmalloc_heap_t *heap,
size_t size) {
3807#if ENABLE_VALIDATE_ARGS
3808 if (size >= MAX_ALLOC_SIZE) {
3817rpmalloc_heap_aligned_alloc(rpmalloc_heap_t *heap,
size_t alignment,
3819#if ENABLE_VALIDATE_ARGS
3820 if (size >= MAX_ALLOC_SIZE) {
3829rpmalloc_heap_calloc(rpmalloc_heap_t *heap,
size_t num,
size_t size) {
3830 return rpmalloc_heap_aligned_calloc(heap, 0, num, size);
3834rpmalloc_heap_aligned_calloc(rpmalloc_heap_t *heap,
size_t alignment,
3835 size_t num,
size_t size) {
3837#if ENABLE_VALIDATE_ARGS
3839 int err = SizeTMult(num, size, &total);
3840 if ((err != S_OK) || (total >= MAX_ALLOC_SIZE)) {
3845 int err = __builtin_umull_overflow(num, size, &total);
3846 if (err || (total >= MAX_ALLOC_SIZE)) {
3856 memset(
block, 0, total);
3861rpmalloc_heap_realloc(rpmalloc_heap_t *heap,
void *ptr,
size_t size,
3862 unsigned int flags) {
3863#if ENABLE_VALIDATE_ARGS
3864 if (size >= MAX_ALLOC_SIZE) {
3873rpmalloc_heap_aligned_realloc(rpmalloc_heap_t *heap,
void *ptr,
3874 size_t alignment,
size_t size,
3875 unsigned int flags) {
3876#if ENABLE_VALIDATE_ARGS
3885extern inline void rpmalloc_heap_free(rpmalloc_heap_t *heap,
void *ptr) {
3890extern inline void rpmalloc_heap_free_all(rpmalloc_heap_t *heap) {
3897 span = heap->
size_class[iclass].partial_span;
3899 next_span = span->
next;
3904 span = heap->full_span[iclass];
3906 next_span = span->
next;
3914 heap->size_class[iclass].cache = 0;
3916 memset(heap->size_class, 0,
sizeof(heap->size_class));
3917 memset(heap->full_span, 0,
sizeof(heap->full_span));
3919 span = heap->large_huge_span;
3921 next_span = span->
next;
3928 heap->large_huge_span = 0;
3929 heap->full_span_count = 0;
3931#if ENABLE_THREAD_CACHE
3935 span_cache = &heap->span_cache;
3937 span_cache = (
span_cache_t *)(heap->span_large_cache + (iclass - 1));
3938 if (!span_cache->
count)
3940#if ENABLE_GLOBAL_CACHE
3945 _rpmalloc_global_cache_insert_spans(span_cache->
span, iclass + 1,
3948 for (
size_t ispan = 0; ispan < span_cache->
count; ++ispan)
3951 span_cache->
count = 0;
3955#if ENABLE_STATISTICS
3966extern inline void rpmalloc_heap_thread_set_current(rpmalloc_heap_t *heap) {
3968 if (prev_heap != heap) {
3971 rpmalloc_heap_release(prev_heap);
3975extern inline rpmalloc_heap_t *rpmalloc_get_heap_for_ptr(
void *ptr) {
3986#if ENABLE_PRELOAD || ENABLE_OVERRIDE
Given that RA is a live value
while(!ToSimplify.empty())
dot regions Print regions of function to dot file(with no function bodies)"
unify loop Fixup each natural loop to have a single exit block
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
#define SMALL_GRANULARITY
Preconfigured limits and sizes.
static FORCEINLINE void * atomic_exchange_ptr_acquire(atomicptr_t *dst, void *val)
#define LARGE_CLASS_COUNT
Number of large block size classes.
#define _memory_default_span_size
Global data.
static FORCEINLINE int64_t atomic_load64(atomic64_t *val)
#define _memory_span_size_shift
static void * _rpmalloc_allocate_from_heap_fallback(heap_t *heap, heap_size_class_t *heap_size_class, uint32_t class_idx)
Allocate a small/medium sized memory block from the given heap.
static heap_t * _rpmalloc_heap_allocate(int first_class)
Allocate a new heap, potentially reusing a previously orphaned heap.
#define MEDIUM_GRANULARITY
Granularity of a medium allocation block.
static void _rpmalloc_heap_unmap(heap_t *heap)
_Static_assert((SMALL_GRANULARITY &(SMALL_GRANULARITY - 1))==0, "Small granularity must be power of two")
#define SPAN_FLAG_UNMAPPED_MASTER
Flag indicating an unmapped master span.
static heap_t * get_thread_heap_raw(void)
void rpfree(void *ptr)
Free the given memory block.
#define rpmalloc_assume(cond)
static size_t _memory_global_reserve_count
Global reserved count.
static void _rpmalloc_span_unmap(span_t *span)
Unmap memory pages for the given number of spans (or mark as unused if no partial unmappings)
static void _rpmalloc_heap_release(void *heapptr, int first_class, int release_cache)
static atomic32_t _memory_global_lock
Used to restrict access to mapping memory for huge pages.
static span_t * _memory_global_reserve_master
Global reserved master.
static size_t _memory_map_granularity
Granularity at which memory pages are mapped by OS.
static FORCEINLINE int32_t atomic_incr32(atomic32_t *val)
static FORCEINLINE int atomic_cas32_acquire(atomic32_t *dst, int32_t val, int32_t ref)
static void _rpmalloc_adjust_size_class(size_t iclass)
Adjust and optimize the size class properties for the given class.
#define THREAD_SPAN_CACHE_TRANSFER
Number of spans to transfer between thread and global cache.
RPMALLOC_ALLOCATOR void * rpmalloc(size_t size)
Allocate a memory block of at least the given size.
static void * _rpmalloc_aligned_reallocate(heap_t *heap, void *ptr, size_t alignment, size_t size, size_t oldsize, unsigned int flags)
static void _rpmalloc_heap_finalize(heap_t *heap)
static span_t * _rpmalloc_span_map_aligned_count(heap_t *heap, size_t span_count)
Map an aligned set of spans, taking configured mapping granularity and the page size into account.
static FORCEINLINE void atomic_store32_release(atomic32_t *dst, int32_t val)
int rpmalloc_initialize_config(const rpmalloc_config_t *config)
Initialize allocator with given configuration.
#define THREAD_SPAN_LARGE_CACHE_TRANSFER
Number of spans to transfer between thread and global cache for large spans.
static void _rpmalloc_heap_global_finalize(heap_t *heap)
#define SPAN_FLAG_SUBSPAN
Flag indicating span is a secondary (sub) span of a split superspan.
static FORCEINLINE int atomic_cas_ptr(atomicptr_t *dst, void *val, void *ref)
static void _rpmalloc_spin(void)
static size_class_t _memory_size_class[SIZE_CLASS_COUNT]
Global size classes.
static size_t _memory_page_size
Memory page size.
static void _rpmalloc_heap_release_raw_fc(void *heapptr)
static void * _rpmalloc_allocate(heap_t *heap, size_t size)
Allocate a block of the given size.
#define TLS_MODEL
Thread local heap and ID.
static size_t _memory_span_map_count
Number of spans to map in each map call.
static void * _rpmalloc_allocate_small(heap_t *heap, size_t size)
Allocate a small sized memory block from the given heap.
#define _memory_default_span_size_shift
static heap_t * _memory_heaps[HEAP_ARRAY_SIZE]
All heaps.
#define _memory_span_mask
static span_t * _memory_global_reserve
Global reserved spans.
const rpmalloc_config_t * rpmalloc_config(void)
Get allocator configuration.
volatile _Atomic(int32_t)
Atomic access abstraction (since MSVC does not do C11 yet)
static FORCEINLINE int64_t atomic_add64(atomic64_t *val, int64_t add)
static void _rpmalloc_span_double_link_list_pop_head(span_t **head, span_t *span)
Pop head span from double linked list.
#define _rpmalloc_stat_add64(counter, value)
static void set_thread_heap(heap_t *heap)
Set the current thread heap.
#define _rpmalloc_stat_add(counter, value)
static void * _rpmalloc_aligned_allocate(heap_t *heap, size_t alignment, size_t size)
static int _memory_huge_pages
Huge page support.
static FORCEINLINE int32_t atomic_decr32(atomic32_t *val)
RPMALLOC_ALLOCATOR void * rpaligned_realloc(void *ptr, size_t alignment, size_t size, size_t oldsize, unsigned int flags)
Reallocate the given block to at least the given size and alignment,.
#define MAX_THREAD_SPAN_LARGE_CACHE
Number of spans in thread cache for large spans (must be greater than LARGE_CLASS_COUNT / 2)
void rpmalloc_set_main_thread(void)
Set main thread ID.
#define MEDIUM_CLASS_COUNT
Number of medium block size classes.
static void _rpmalloc_inc_span_statistics(heap_t *heap, size_t span_count, uint32_t class_idx)
RPMALLOC_ALLOCATOR void * rpcalloc(size_t num, size_t size)
static void _rpmalloc_deallocate_large(span_t *span)
Deallocate the given large memory block to the current heap.
#define _memory_span_size
Hardwired span size.
static void _rpmalloc_heap_initialize(heap_t *heap)
#define _rpmalloc_stat_add_peak(counter, value, peak)
static void _rpmalloc_heap_orphan(heap_t *heap, int first_class)
RPMALLOC_ALLOCATOR void * rpmemalign(size_t alignment, size_t size)
Allocate a memory block of at least the given size and alignment.
static void _rpmalloc_deallocate_huge(span_t *)
Global cache.
static void _rpmalloc_span_release_to_cache(heap_t *heap, span_t *span)
Move the span (used for small or medium allocations) to the heap thread cache.
static int _rpmalloc_initialized
Initialized flag.
#define SPAN_HEADER_SIZE
Size of a span header (must be a multiple of SMALL_GRANULARITY and a power of two)
static heap_t * _rpmalloc_heap_allocate_new(void)
Allocate a new heap from newly mapped memory pages.
static void * _rpmalloc_span_initialize_new(heap_t *heap, heap_size_class_t *heap_size_class, span_t *span, uint32_t class_idx)
Initialize an unused span (from cache or mapped) to be new active span, putting the initial free list...
#define SMALL_GRANULARITY_SHIFT
Small granularity shift count.
static void _rpmalloc_set_name(void *address, size_t size)
Low level memory map/unmap.
static size_t _rpmalloc_span_align_count(size_t span_count)
Get the aligned number of spans to map in based on wanted count, configured mapping granularity and t...
#define LARGE_SIZE_LIMIT
Maximum size of a large block.
static void _rpmalloc_unmap_os(void *address, size_t size, size_t offset, size_t release)
Default implementation to unmap pages from virtual memory.
#define ENABLE_THREAD_CACHE
Enable per-thread cache.
static void _rpmalloc_deallocate_direct_small_or_medium(span_t *span, void *block)
Deallocation entry points.
static void _rpmalloc_deallocate_defer_small_or_medium(span_t *span, void *block)
Put the block in the deferred free list of the owning span.
void rpmalloc_thread_collect(void)
Perform deferred deallocations pending for the calling thread heap.
void rpmalloc_thread_finalize(int release_caches)
Finalize thread, orphan heap.
int rpmalloc_is_thread_initialized(void)
Query if allocator is initialized for calling thread.
void rpmalloc_linker_reference(void)
Dummy empty function for forcing linker symbol inclusion.
#define FORCEINLINE
Platform and arch specifics.
void rpmalloc_dump_statistics(void *file)
Dump all statistics in human readable format to file (should be a FILE*)
RPMALLOC_ALLOCATOR void * rpaligned_alloc(size_t alignment, size_t size)
Allocate a memory block of at least the given size and alignment.
size_t rpmalloc_usable_size(void *ptr)
Query the usable size of the given memory block (from given pointer to the end of block)
static void _rpmalloc_deallocate_small_or_medium(span_t *span, void *p)
static span_t * _rpmalloc_global_get_reserved_spans(size_t span_count)
Use global reserved spans to fulfill a memory map request (reserve size must be checked by caller)
#define _rpmalloc_stat_sub(counter, value)
static void * _rpmalloc_mmap_os(size_t size, size_t *offset)
Default implementation to map new pages to virtual memory.
#define _rpmalloc_memcpy_const(x, y, s)
static uintptr_t get_thread_id(void)
Fast thread ID.
void rpmalloc_thread_initialize(void)
Initialize thread, assign heap.
static span_t * _rpmalloc_heap_thread_cache_deferred_extract(heap_t *heap, size_t span_count)
static void * _rpmalloc_allocate_large(heap_t *heap, size_t size)
Allocate a large sized memory block from the given heap.
RPMALLOC_ALLOCATOR void * rprealloc(void *ptr, size_t size)
Reallocate the given block to at least the given size.
static FORCEINLINE void * atomic_load_ptr(atomicptr_t *src)
static void _rpmalloc_span_mark_as_subspan_unless_master(span_t *master, span_t *subspan, size_t span_count)
Declare the span to be a subspan and store distance from master span and span count.
static FORCEINLINE void atomic_store_ptr_release(atomicptr_t *dst, void *val)
#define MEDIUM_GRANULARITY_SHIFT
Medium granularity shift count.
static size_t _memory_medium_size_limit
Run-time size limit of medium blocks.
#define SPAN_FLAG_MASTER
Flag indicating span is the first (master) span of a split superspan.
static void * _rpmalloc_reallocate(heap_t *heap, void *p, size_t size, size_t oldsize, unsigned int flags)
Reallocate the given block to the given size.
int rpmalloc_initialize(void)
Initialize the allocator and setup global data.
static span_t * _rpmalloc_heap_reserved_extract(heap_t *heap, size_t span_count)
static size_t _memory_page_size_shift
Shift to divide by page size.
static FORCEINLINE void atomic_store32(atomic32_t *dst, int32_t val)
static void _rpmalloc_heap_release_raw(void *heapptr, int release_cache)
static void _rpmalloc_global_set_reserved_spans(span_t *master, span_t *reserve, size_t reserve_span_count)
Store the given spans as global reserve (must only be called from within new heap allocation,...
#define SIZE_CLASS_COUNT
Total number of small + medium size classes.
static int _rpmalloc_span_finalize(heap_t *heap, size_t iclass, span_t *span, span_t **list_head)
#define _rpmalloc_stat_dec(counter)
static uintptr_t _rpmalloc_main_thread_id
Main thread ID.
#define _rpmalloc_stat_inc_free(heap, class_idx)
static span_t * _rpmalloc_heap_thread_cache_extract(heap_t *heap, size_t span_count)
Extract the given number of spans from the different cache levels.
#define pointer_offset(ptr, ofs)
#define _rpmalloc_stat_inc(counter)
Statistics related functions (evaluate to nothing when statistics not enabled)
#define _rpmalloc_memset_const(x, y, s)
static void * _rpmalloc_allocate_huge(heap_t *heap, size_t size)
Allocate a huge block by mapping memory pages directly.
#define _rpmalloc_stat_inc_alloc(heap, class_idx)
static void _rpmalloc_heap_cache_insert(heap_t *heap, span_t *span)
Span control.
static span_t * _rpmalloc_heap_global_cache_extract(heap_t *heap, size_t span_count)
Extract a span from the global cache.
static void _rpmalloc_unmap(void *address, size_t size, size_t offset, size_t release)
Unmap virtual memory.
static void _rpmalloc_span_double_link_list_add(span_t **head, span_t *span)
Span linked list management.
static void * _rpmalloc_allocate_medium(heap_t *heap, size_t size)
Allocate a medium sized memory block from the given heap.
#define HEAP_ARRAY_SIZE
Size of heap hashmap.
static void _rpmalloc_deallocate_defer_free_span(heap_t *heap, span_t *span)
static void * free_list_pop(void **list)
Allocation entry points.
void rpmalloc_thread_statistics(rpmalloc_thread_statistics_t *stats)
Get per-thread statistics.
static heap_t * _rpmalloc_heap_extract_orphan(heap_t **heap_list)
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)
Get a span from one of the cache levels (thread cache, reserved, global cache) or fallback to mapping...
#define rpmalloc_assert(truth, message)
#define SPAN_FLAG_ALIGNED_BLOCKS
Flag indicating span has blocks with increased alignment.
static void _rpmalloc_span_initialize(span_t *span, size_t total_span_count, size_t span_count, size_t align_offset)
Setup a newly mapped span.
#define _memory_default_span_mask
static size_t _memory_heap_reserve_count
Number of spans to keep reserved in each heap.
static size_t _rpmalloc_usable_size(void *p)
Reallocation entry points.
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)
Initialize a (partial) free list up to next system memory page, while reserving the first block as al...
static int _rpmalloc_span_is_fully_utilized(span_t *span)
static rpmalloc_config_t _memory_config
Configuration.
static FORCEINLINE void atomic_store_ptr(atomicptr_t *dst, void *val)
static void _rpmalloc_deallocate(void *p)
Deallocate the given block.
static heap_t * _memory_orphan_heaps
Orphaned heaps.
static span_t * _rpmalloc_span_map(heap_t *heap, size_t span_count)
Map in memory pages for the given number of spans (or use previously reserved pages)
static void _rpmalloc_heap_set_reserved_spans(heap_t *heap, span_t *master, span_t *reserve, size_t reserve_span_count)
Store the given spans as reserve in the given heap.
RPMALLOC_ALLOCATOR void * rpaligned_calloc(size_t alignment, size_t num, size_t size)
void rpmalloc_global_statistics(rpmalloc_global_statistics_t *stats)
Get global statistics.
int rpposix_memalign(void **memptr, size_t alignment, size_t size)
Allocate a memory block of at least the given size and alignment.
#define MAX_THREAD_SPAN_CACHE
Number of spans in thread cache.
static void _rpmalloc_span_double_link_list_remove(span_t **head, span_t *span)
Remove a span from double linked list.
#define GLOBAL_CACHE_MULTIPLIER
Multiplier for global cache.
#define MEDIUM_SIZE_LIMIT
Maximum size of a medium block.
#define SMALL_SIZE_LIMIT
Maximum size of a small block.
static void _rpmalloc_span_extract_free_list_deferred(span_t *span)
struct span_list_t span_list_t
Span list.
static FORCEINLINE int32_t atomic_add32(atomic32_t *val, int32_t add)
static atomic32_t _memory_heap_id
Heap ID counter.
static void _rpmalloc_heap_cache_adopt_deferred(heap_t *heap, span_t **single_span)
Adopt the deferred span cache list, optionally extracting the first single span for immediate re-use.
#define pointer_diff(first, second)
struct span_active_t span_active_t
Span active data.
#define DEFAULT_SPAN_MAP_COUNT
Default number of spans to map in call to map more virtual memory (default values yield 4MiB here)
static span_t * _rpmalloc_span_map_from_reserve(heap_t *heap, size_t span_count)
Use reserved spans to fulfill a memory map request (reserve size must be checked by caller)
static void * _rpmalloc_mmap(size_t size, size_t *offset)
Map more virtual memory.
static heap_t * get_thread_heap(void)
Get the current thread heap.
#define SMALL_CLASS_COUNT
Number of small block size classes.
void rpmalloc_finalize(void)
Finalize the allocator.
#define RPMALLOC_ALLOCATOR
#define RPMALLOC_GROW_OR_FAIL
Flag to rpaligned_realloc to fail and return null pointer if grow cannot be done in-place,...
#define RPMALLOC_NO_PRESERVE
Flag to rpaligned_realloc to not preserve content in reallocation.
uint32_t count
Cache count.
span_t * overflow
Unlimited cache overflow.
atomic32_t lock
Cache lock.
span_t * span[GLOBAL_CACHE_MULTIPLIER *MAX_THREAD_SPAN_CACHE]
Cached spans.
span_t * cache
Early level cache of fully free spans.
void * free_list
Free list of active span.
span_t * partial_span
Double linked list of partially used spans with free blocks.
int finalize
Finalization state flag.
heap_t * master_heap
Master heap owning the memory pages.
atomicptr_t span_free_deferred
List of deferred free spans (single linked list)
uintptr_t owner_thread
Owning thread ID.
atomic32_t child_count
Child count.
size_t full_span_count
Number of full spans.
heap_size_class_t size_class[SIZE_CLASS_COUNT]
Free lists for each size class.
heap_t * next_heap
Next heap in id list.
heap_t * next_orphan
Next heap in orphan list.
uint32_t spans_reserved
Number of mapped but unused spans.
span_t * span_reserve
Mapped but unused spans.
span_t * span_reserve_master
Master span for mapped but unused spans.
void(* memory_unmap)(void *address, size_t size, size_t offset, size_t release)
Unmap the memory pages starting at address and spanning the given number of bytes.
int(* map_fail_callback)(size_t size)
Called when a call to map memory pages fails (out of memory).
size_t span_map_count
Number of spans to map at each request to map new virtual memory blocks.
const char * page_name
Respectively allocated pages and huge allocated pages names for systems.
int enable_huge_pages
Enable use of large/huge pages.
const char * huge_page_name
size_t span_size
Size of a span of memory blocks.
void *(* memory_map)(size_t size, size_t *offset)
Map memory pages for the given number of bytes.
size_t page_size
Size of memory pages.
uint32_t block_size
Size of blocks in this class.
uint16_t class_idx
Class index this class is merged with.
uint16_t block_count
Number of blocks in each chunk.
span_t * span[MAX_THREAD_SPAN_CACHE]
span_t * span[MAX_THREAD_SPAN_LARGE_CACHE]
uint32_t offset_from_master
Offset from master span for subspans.
uint32_t align_offset
Alignment offset.
atomicptr_t free_list_deferred
Deferred free list.
heap_t * heap
Owning heap.
span_t * prev
Previous span.
atomic32_t remaining_spans
Remaining span counter, for master spans.
uint32_t flags
Flags and counters.
uint32_t size_class
Size class.
uint32_t block_count
Total block count of size class.
void * free_list
Free list.
uint32_t block_size
Size of a block.
uint32_t used_count
Number of used blocks remaining when in partial state.
uint32_t list_size
Size of deferred free list, or list of spans when part of a cache list.
uint32_t span_count
Number of spans.
uint32_t free_list_limit
Index of last block initialized in free list.
uint32_t total_spans
Total span counter for master spans.