Skip to content

Commit a26c5de

Browse files
committed
heap: order the delete walk against concurrent frees, and test heap release on many threads
`mi_heap_delete` walks `arena_pages->pages` and then frees the heap and the bitmap, while a foreign `mi_free` that frees a page of that heap reads both and clears the page's bit as its last access. The walk's loads were relaxed, so nothing formally ordered those reads before the free of the memory they read. They are acquire now. The walk also located the page struct (which reads `block_size` with separated page meta) before pinning the slice, when the slice may already be freed or be a fresh page of another heap. It is located after the pin now. On macOS the theap TLS slot is a raw slot in the thread's control block, which the OS reuses for a later thread: the exiting thread's last store and the next thread's first load are the same address from two threads. Use relaxed atomics there (same single load/store). `test/test-heap-release-mt.c` (new): heaps created and deleted/destroyed on 8 threads while 4 threads free their blocks and batches of short-lived threads allocate from them and exit. Clean under TSAN, ASAN and MI_DEBUG_FULL; before this it produced TSAN reports on the base branch as well.
1 parent 91218f3 commit a26c5de

5 files changed

Lines changed: 202 additions & 12 deletions

File tree

‎CMakeLists.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -877,7 +877,7 @@ if (MI_BUILD_TESTS)
877877
enable_testing()
878878

879879
# static link tests
880-
set(mi_static_tests api api-fill stress-heaps stress-subprocs stress heap-mt heap-teardown heap-delete-race heap-churn heap-aba heap-burst-destroy abandoned-lazy fork-user-heap snapshot prof prof-adversarial purge-zero park-handoff free-before-init)
880+
set(mi_static_tests api api-fill stress-heaps stress-subprocs stress heap-mt heap-teardown heap-delete-race heap-churn heap-release-mt heap-aba heap-burst-destroy abandoned-lazy fork-user-heap snapshot prof prof-adversarial purge-zero park-handoff free-before-init)
881881
if(NOT (MI_DEBUG_TSAN OR MI_TRACK_ASAN OR MI_DEBUG_UBSAN))
882882
list(APPEND mi_static_tests thp-optout) # counts madvise calls by interposing it, which a sanitizer runtime does first
883883
endif()

‎include/mimalloc/prim-tls.h‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,23 @@ static inline void* mi_prim_tls_slot(size_t slot) {
149149
#else
150150
return mi_prim_thread_pointer()[slot];
151151
#endif
152+
#elif defined(__GNUC__) || defined(__clang__)
153+
// The slot lives in the thread's control block, which the OS reuses for a later thread, so the
154+
// exiting thread's last store (`_mi_thread_done`) and a new thread's first load touch the same
155+
// address from different threads. A relaxed atomic is the same single load/store instruction and
156+
// states that this is by design (and keeps TSAN quiet about it).
157+
return __atomic_load_n(&mi_prim_thread_pointer()[slot], __ATOMIC_RELAXED);
152158
#else
153159
return mi_prim_thread_pointer()[slot];
154160
#endif
155161
}
156162

157163
static inline void mi_prim_tls_slot_set(size_t slot, void* value) {
164+
#if defined(__GNUC__) || defined(__clang__)
165+
__atomic_store_n(&mi_prim_thread_pointer()[slot], value, __ATOMIC_RELAXED);
166+
#else
158167
mi_prim_thread_pointer()[slot] = value;
168+
#endif
159169
}
160170
#endif
161171

‎src/arena.c‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2640,7 +2640,10 @@ static bool mi_heap_visit_page(mi_page_t* page, mi_heap_visit_info_t* vinfo) {
26402640
// owned we give the bit back and retry; once we own it nobody else can free it and the bit goes back too.
26412641
// This is the same protocol the abandoned-page map uses (`mi_arena_try_claim_abandoned`,
26422642
// `mi_arena_page_purge_holes_at` against `_mi_arenas_page_unabandon`).
2643-
// Returns `true` if we own the page, `false` if it is gone.
2643+
// The page struct is only located (`mi_arena_page_at_slice`, which reads `block_size` with separated page
2644+
// meta) once the slice is pinned: before that a concurrent `mi_free` may be freeing the page and the slice
2645+
// may already be a fresh page of another heap.
2646+
// Returns the page if we own it, or NULL if it is gone.
26442647
#if MI_DEBUG > 0
26452648
mi_decl_export _Atomic(uintptr_t) mi_debug_stall_in_heap_delete_claim; // test hook (test-heap-teardown): stall while a page is pinned but not yet claimed
26462649
#endif
@@ -2651,11 +2654,13 @@ static void mi_heap_visit_page_seize(mi_page_t* page) {
26512654
mi_page_set_theap(page, NULL);
26522655
}
26532656

2654-
static bool mi_heap_visit_page_claim(mi_heap_visit_info_t* vinfo, mi_page_t* page, size_t slice_index) {
2657+
static mi_page_t* mi_heap_visit_page_claim(mi_heap_visit_info_t* vinfo, mi_arena_t* arena, size_t slice_index) {
26552658
mi_bitmap_t* const pages = vinfo->arena_pages->pages;
2659+
mi_page_t* page = NULL;
26562660
for (;;) {
2657-
if (!mi_bitmap_clear(pages, slice_index)) return false; // freed by a concurrent `mi_free`
2658-
// pinned
2661+
if (!mi_bitmap_clear(pages, slice_index)) return NULL; // freed by a concurrent `mi_free`
2662+
// pinned: now it is a page of this heap and stays one while we hold the bit
2663+
page = mi_arena_page_at_slice(arena, slice_index);
26592664
#if MI_DEBUG > 0
26602665
if (mi_atomic_load_acquire(&mi_debug_stall_in_heap_delete_claim) == 1) {
26612666
mi_atomic_store_release(&mi_debug_stall_in_heap_delete_claim, (uintptr_t)2); // signal: pinned, not yet claimed
@@ -2666,8 +2671,8 @@ static bool mi_heap_visit_page_claim(mi_heap_visit_info_t* vinfo, mi_page_t* pag
26662671
// After a multi-threaded fork() the child may inherit a torn snapshot of a page that another
26672672
// thread was allocating or freeing: the bit propagated but the page-map entry or the owned bit
26682673
// did not, and that thread is gone. Re-derive what we can and take the page.
2669-
if (mi_page_start(page) == NULL) return false; // the page struct never made it across: leave it unpublished
2670-
if (_mi_safe_ptr_page(mi_page_start(page)) != page && !_mi_page_map_register(page)) return false;
2674+
if (mi_page_start(page) == NULL) return NULL; // the page struct never made it across: leave it unpublished
2675+
if (_mi_safe_ptr_page(mi_page_start(page)) != page && !_mi_page_map_register(page)) return NULL;
26712676
mi_page_claim_ownership(page); // ours now, whether or not the dead thread held it
26722677
mi_bitmap_set(pages, slice_index);
26732678
if (!mi_page_is_abandoned(page)) { mi_heap_visit_page_seize(page); }
@@ -2693,15 +2698,19 @@ static bool mi_heap_visit_page_claim(mi_heap_visit_info_t* vinfo, mi_page_t* pag
26932698
mi_assert_internal(mi_page_is_owned(page) && mi_page_is_abandoned(page));
26942699
mi_assert_internal(mi_bitmap_is_set(pages, slice_index));
26952700
mi_assert_internal(_mi_ptr_page(mi_page_start(page)) == page && mi_page_heap(page) == vinfo->heap);
2696-
return true;
2701+
return page;
26972702
}
26982703

26992704
static bool mi_heap_visit_page_at(size_t slice_index, size_t slice_count, mi_arena_t* arena, void* arg) {
27002705
MI_UNUSED(slice_count);
27012706
mi_heap_visit_info_t* vinfo = (mi_heap_visit_info_t*)arg;
2702-
mi_page_t* page = mi_arena_page_at_slice(arena, slice_index);
2707+
mi_page_t* page;
27032708
if (vinfo->claim_pages) {
2704-
if (!mi_heap_visit_page_claim(vinfo, page, slice_index)) return true;
2709+
page = mi_heap_visit_page_claim(vinfo, arena, slice_index);
2710+
if (page == NULL) return true; // gone: freed by a concurrent `mi_free`
2711+
}
2712+
else {
2713+
page = mi_arena_page_at_slice(arena, slice_index);
27052714
}
27062715
return mi_heap_visit_page(page, vinfo);
27072716
}

‎src/bitmap.c‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1433,12 +1433,16 @@ void mi_bitmap_clear_once_set(mi_subproc_t* subproc, mi_bitmap_t* bitmap, size_t
14331433

14341434

14351435
// Visit all set bits in a bitmap.
1436+
// The loads are acquire: `mi_heap_delete` walks its `arena_pages->pages` with this and then frees the heap and
1437+
// the bitmap itself, while a concurrent `mi_free` that frees a page of the heap reads both and then clears the
1438+
// page's bit (release) as its last access (`mi_arenas_page_free_prim`). Seeing that bit clear here is what
1439+
// orders those reads before our free of the memory they read.
14361440
// todo: optimize further? maybe use avx512 to directly get all indices using a mask_compressstore?
14371441
bool _mi_bitmap_forall_set(mi_bitmap_t* bitmap, mi_forall_set_fun_t* visit, mi_arena_t* arena, void* arg) {
14381442
// for all chunkmap entries
14391443
const size_t chunkmap_max = _mi_divide_up(mi_bitmap_chunk_count(bitmap), MI_BFIELD_BITS);
14401444
for(size_t i = 0; i < chunkmap_max; i++) {
1441-
mi_bfield_t cmap_entry = mi_atomic_load_relaxed(&bitmap->chunkmap.bfields[i]);
1445+
mi_bfield_t cmap_entry = mi_atomic_load_acquire(&bitmap->chunkmap.bfields[i]);
14421446
size_t cmap_idx;
14431447
// for each chunk (corresponding to a set bit in a chunkmap entry)
14441448
while (mi_bfield_foreach_bit(&cmap_entry, &cmap_idx)) {
@@ -1447,7 +1451,7 @@ bool _mi_bitmap_forall_set(mi_bitmap_t* bitmap, mi_forall_set_fun_t* visit, mi_a
14471451
mi_bchunk_t* const chunk = &bitmap->chunks[chunk_idx];
14481452
for (size_t j = 0; j < MI_BCHUNK_FIELDS; j++) {
14491453
const size_t base_idx = (chunk_idx*MI_BCHUNK_BITS) + (j*MI_BFIELD_BITS);
1450-
mi_bfield_t b = mi_atomic_load_relaxed(&chunk->bfields[j]);
1454+
mi_bfield_t b = mi_atomic_load_acquire(&chunk->bfields[j]);
14511455
size_t bidx;
14521456
while (mi_bfield_foreach_bit(&b, &bidx)) {
14531457
const size_t idx = base_idx + bidx;

‎test/test-heap-release-mt.c‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
/* ----------------------------------------------------------------------------
2+
Copyright (c) 2026, Microsoft Research, Daan Leijen
3+
This is free software; you can redistribute it and/or modify it under the
4+
terms of the MIT license.
5+
-----------------------------------------------------------------------------*/
6+
7+
/* Release heaps on many threads at once while other threads free into them.
8+
9+
- NCHURN threads loop: `mi_heap_new`, allocate mixed sizes, hand a third of the blocks to a shared
10+
ring, free a third, leak a third, then `mi_heap_delete` (or `mi_heap_destroy` when nothing was
11+
handed out). Some heaps are also published for a while so that short-lived threads allocate from
12+
them and exit with their blocks live (the abandon path, and the per-bin abandoned maps).
13+
- NFREE threads pop blocks from the ring and `mi_free` them: those frees land before, during and
14+
after the delete of the owning heap, so pages are freed and re-abandoned by a foreign thread while
15+
`mi_heap_delete` claims them (`arena.c:mi_heap_visit_page_claim` against `mi_arenas_page_free_prim`).
16+
- NSPAWN threads keep creating batches of threads that allocate from a published heap (or the main
17+
heap) and exit at once.
18+
19+
Meant to be run under TSAN and ASAN as well as with MI_DEBUG_FULL: it must finish without a report.
20+
21+
> mimalloc-test-heap-release-mt [SECONDS]
22+
*/
23+
#if defined(_WIN32)
24+
#include <stdio.h>
25+
int main(void) { printf("test-heap-release-mt: skipped on Windows (uses pthreads)\n"); return 0; }
26+
#else
27+
28+
#include <mimalloc.h>
29+
#include <pthread.h>
30+
#include <stdatomic.h>
31+
#include <stdio.h>
32+
#include <stdlib.h>
33+
#include <string.h>
34+
#include <unistd.h>
35+
36+
#define NCHURN 8
37+
#define NFREE 4
38+
#define NSPAWN 4
39+
#define RING (1<<16)
40+
static _Atomic(void*) ring[RING];
41+
static _Atomic unsigned long ring_head, ring_tail;
42+
static _Atomic int stop;
43+
static _Atomic unsigned long heaps_done, frees_done, exits_done;
44+
45+
static const size_t sizes[] = {8,16,48,96,200,512,1024,2048,5000,8192,20000,40000,70000,200000};
46+
#define NS (sizeof(sizes)/sizeof(sizes[0]))
47+
48+
static void push(void* p) {
49+
for (;;) {
50+
unsigned long h = atomic_fetch_add(&ring_head, 1);
51+
void* expect = NULL;
52+
if (atomic_compare_exchange_strong(&ring[h % RING], &expect, p)) return;
53+
// slot busy: free it ourselves instead of spinning
54+
mi_free(p); return;
55+
}
56+
}
57+
static void* pop(void) {
58+
unsigned long t = atomic_fetch_add(&ring_tail, 1);
59+
return atomic_exchange(&ring[t % RING], NULL);
60+
}
61+
62+
static unsigned rnd(unsigned* s){ *s = *s*1103515245u+12345u; return *s>>8; }
63+
64+
// shared live heaps for the exiting threads
65+
#define NSHARED 4
66+
static _Atomic(mi_heap_t*) shared[NSHARED];
67+
static _Atomic int users[NSHARED];
68+
69+
static void* churn(void* arg) {
70+
unsigned seed = (unsigned)(uintptr_t)arg * 7919u + 1;
71+
while (!atomic_load(&stop)) {
72+
mi_heap_t* h = mi_heap_new();
73+
int slot = -1;
74+
// sometimes publish as a shared heap for exiting threads to allocate from
75+
if ((rnd(&seed) % 4) == 0) {
76+
slot = rnd(&seed) % NSHARED;
77+
mi_heap_t* expect = NULL;
78+
if (!atomic_compare_exchange_strong(&shared[slot], &expect, h)) slot = -1;
79+
}
80+
int handed = 0;
81+
int n = 50 + rnd(&seed) % 400;
82+
for (int i = 0; i < n; i++) {
83+
size_t sz = sizes[rnd(&seed) % NS];
84+
void* p = mi_heap_malloc(h, sz);
85+
if (!p) { fprintf(stderr,"oom\n"); abort(); }
86+
memset(p, 0xAB, sz < 64 ? sz : 64);
87+
unsigned r = rnd(&seed) % 3;
88+
if (r == 0) { push(p); handed++; }
89+
else if (r == 1) mi_free(p);
90+
// else leak into the heap; delete moves it to main / destroy frees it
91+
}
92+
if (slot >= 0) {
93+
// let exiting threads use it for a bit, then unpublish
94+
usleep(200);
95+
atomic_store(&shared[slot], NULL);
96+
while (atomic_load(&users[slot]) != 0) usleep(10); // in-flight allocators finish (contract: no alloc during delete)
97+
handed = 1; // exiting threads may hold blocks: must delete, not destroy
98+
}
99+
if (handed == 0 && (rnd(&seed) & 1)) mi_heap_destroy(h);
100+
else mi_heap_delete(h);
101+
atomic_fetch_add(&heaps_done, 1);
102+
}
103+
return NULL;
104+
}
105+
106+
static void* freer(void* arg) {
107+
(void)arg;
108+
while (!atomic_load(&stop) || atomic_load(&ring_tail) < atomic_load(&ring_head)) {
109+
void* p = pop();
110+
if (p) { mi_free(p); atomic_fetch_add(&frees_done,1); }
111+
else if (atomic_load(&stop)) break;
112+
}
113+
return NULL;
114+
}
115+
116+
static void* exiter(void* arg) {
117+
unsigned seed = (unsigned)(uintptr_t)arg;
118+
int slot = rnd(&seed) % NSHARED;
119+
atomic_fetch_add(&users[slot], 1);
120+
mi_heap_t* h = atomic_load(&shared[slot]);
121+
for (int i = 0; i < 40; i++) {
122+
size_t sz = sizes[rnd(&seed) % 8];
123+
void* p = h ? mi_heap_malloc(h, sz) : mi_malloc(sz);
124+
if (p) { memset(p, 0xCD, sz < 64 ? sz : 64); push(p); }
125+
}
126+
atomic_fetch_sub(&users[slot], 1);
127+
atomic_fetch_add(&exits_done,1);
128+
return NULL; // exit with blocks live -> pages abandoned (mapped, lazy bitmap alloc)
129+
}
130+
131+
static void* spawner(void* arg) {
132+
unsigned k = (unsigned)(uintptr_t)arg * 100000u;
133+
while (!atomic_load(&stop)) {
134+
pthread_t t[8];
135+
for (int i = 0; i < 8; i++) pthread_create(&t[i], NULL, exiter, (void*)(uintptr_t)(k++));
136+
for (int i = 0; i < 8; i++) pthread_join(t[i], NULL);
137+
}
138+
return NULL;
139+
}
140+
141+
int main(int argc, char** argv) {
142+
int secs = (argc > 1 ? atoi(argv[1]) : 0);
143+
if (secs <= 0) {
144+
#if defined(MI_TSAN) || !defined(NDEBUG)
145+
secs = 4;
146+
#else
147+
secs = 6;
148+
#endif
149+
}
150+
pthread_t tc[NCHURN], tf[NFREE], ts[NSPAWN];
151+
for (long i = 0; i < NFREE; i++) pthread_create(&tf[i], NULL, freer, (void*)i);
152+
for (long i = 0; i < NCHURN; i++) pthread_create(&tc[i], NULL, churn, (void*)(i+1));
153+
for (long i = 0; i < NSPAWN; i++) pthread_create(&ts[i], NULL, spawner, (void*)(i+1));
154+
sleep(secs);
155+
atomic_store(&stop, 1);
156+
for (int i = 0; i < NCHURN; i++) pthread_join(tc[i], NULL);
157+
for (int i = 0; i < NSPAWN; i++) pthread_join(ts[i], NULL);
158+
for (int i = 0; i < NFREE; i++) pthread_join(tf[i], NULL);
159+
// drain
160+
void* p; while (atomic_load(&ring_tail) < atomic_load(&ring_head) && (p = pop(), 1)) { if (p) mi_free(p); }
161+
for (unsigned i = 0; i < RING; i++) { void* q = atomic_exchange(&ring[i], NULL); if (q) mi_free(q); }
162+
mi_collect(true);
163+
printf("test-heap-release-mt: ok (heaps=%lu frees=%lu thread-exits=%lu)\n", (unsigned long)heaps_done, (unsigned long)frees_done, (unsigned long)exits_done);
164+
return 0;
165+
}
166+
167+
#endif

0 commit comments

Comments
 (0)