Skip to content

Commit 91218f3

Browse files
robobunJarred-Sumner
authored andcommitted
heap: a heap that is being released abandons its pages unmapped
`mi_heap_delete` and `mi_heap_destroy` abandon every page of the heap (step 2 of the teardown) and then claim each one back through the `arena_pages->pages` bitmap (step 3). With the per-bin abandoned maps allocated on first abandon, step 2 allocated a map for every size class the heap had used, from the meta-data heap and under its lock, only to free them with the heap a moment later. A process that creates and destroys a heap per job on several threads (bun creates one per transpile, on a thread pool) paid that on every job, and the threads contended on the meta lock: with 300 imports, bun used about 4 ms more CPU than with the maps allocated up front. The heap now records that its release has started (`heap->releasing`). `_mi_arenas_page_abandon` leaves the pages of such a heap out of the per-bin maps, as it already does for a full page, and a concurrent free does not re-map them. Step 3 finds them through `pages` as before, and `_mi_arenas_page_unabandon` already handles an unmapped page. A heap that lives only to be released now never allocates a map, and its `arena_pages` block holds just the `pages` bitmap. test-abandoned-lazy counts the maps published while heaps are created, used, destroyed and deleted on one thread (a debug-build counter, as test-heap-teardown uses a debug hook): 0 now, 600 without this change. It also deletes heaps on four threads while four other threads free their blocks during the delete.
1 parent 787be2a commit 91218f3

4 files changed

Lines changed: 178 additions & 1 deletion

File tree

‎include/mimalloc/types.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,7 @@ typedef struct mi_heap_s {
628628
mi_lock_t theaps_lock; // lock for the theaps list operations
629629

630630
_Atomic(size_t) abandoned_count[MI_BIN_COUNT]; // total count of abandoned pages in this heap
631+
_Atomic(uintptr_t) releasing; // set when `mi_heap_delete`/`mi_heap_destroy` starts: its pages are abandoned unmapped
631632
mi_page_t* os_abandoned_pages; // list of pages that are OS allocated and not in an arena
632633
mi_lock_t os_abandoned_pages_lock; // lock for the os abandoned pages list (this lock protects list operations)
633634

‎src/arena.c‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1211,8 +1211,9 @@ void _mi_arenas_page_abandon(mi_page_t* page, mi_theap_t* current_theapx) {
12111211
// mi_assert_internal(current_theap == _mi_page_associated_theap(page));
12121212

12131213
// add to abandoned?
1214+
// (not for a heap that is being released: its teardown claims every page through `pages`, see `mi_heap_release_pages`)
12141215
mi_heap_t* heap = mi_page_heap(page);
1215-
if (page->memid.memkind==MI_MEM_ARENA && !mi_page_is_full(page)) {
1216+
if (page->memid.memkind==MI_MEM_ARENA && !mi_page_is_full(page) && mi_atomic_load_relaxed(&heap->releasing) == 0) {
12161217
// make available for allocations
12171218
size_t bin = _mi_bin(mi_page_block_size(page));
12181219
mi_assert_internal(bin < MI_ARENA_BIN_COUNT);
@@ -1272,6 +1273,9 @@ bool _mi_arenas_page_try_reabandon_to_mapped(mi_page_t* page) {
12721273
if (mi_page_is_full(page) || mi_page_is_abandoned_mapped(page) || page->memid.memkind != MI_MEM_ARENA) {
12731274
return false;
12741275
}
1276+
else if (mi_atomic_load_relaxed(&mi_page_heap(page)->releasing) != 0) {
1277+
return false; // the heap is being released and claims the page through `pages` (see `mi_heap_release_pages`)
1278+
}
12751279
else {
12761280
// Account on the heap and not on this thread's theap for it (`_mi_page_associated_theap_peek`): the theap
12771281
// was only used for its statistics here, and a concurrent `mi_heap_delete` may be detaching and merging it.
@@ -1728,6 +1732,10 @@ static mi_bitmap_t* mi_arena_pages_abandoned(mi_arena_pages_t* arena_pages, size
17281732
// foreign free re-abandoning a page), where allocating from a regular heap is not. Publishing
17291733
// is a CAS so no lock is needed: a loser frees its copy and uses the winner's. Returns NULL only
17301734
// if the allocation failed.
1735+
#if MI_DEBUG > 0
1736+
mi_decl_export _Atomic(uintptr_t) mi_debug_abandoned_maps_allocated; // test hook (test-abandoned-lazy): per-bin abandoned maps published so far
1737+
#endif
1738+
17311739
static mi_bitmap_t* mi_arena_pages_abandoned_ensure(mi_arena_t* arena, mi_arena_pages_t* arena_pages, size_t bin) {
17321740
mi_bitmap_t* bitmap = mi_arena_pages_abandoned(arena_pages, bin);
17331741
if mi_likely(bitmap != NULL) return bitmap;
@@ -1738,6 +1746,9 @@ static mi_bitmap_t* mi_arena_pages_abandoned_ensure(mi_arena_t* arena, mi_arena_
17381746
mi_bitmap_init(fresh, slice_count, true /* already zero */);
17391747
mi_bitmap_t* expected = NULL;
17401748
if (mi_atomic_cas_ptr_strong_acq_rel(mi_bitmap_t, &arena_pages->pages_abandoned[bin], &expected, fresh)) {
1749+
#if MI_DEBUG > 0
1750+
mi_atomic_increment_relaxed(&mi_debug_abandoned_maps_allocated);
1751+
#endif
17411752
return fresh;
17421753
}
17431754
// another thread published one first
@@ -1750,6 +1761,7 @@ static mi_bitmap_t* mi_arena_pages_abandoned_ensure(mi_arena_t* arena, mi_arena_
17501761
// the `arena_pages` allocation itself).
17511762
static void mi_arena_pages_free_abandoned(mi_arena_pages_t* arena_pages) {
17521763
for (size_t bin = 0; bin < MI_ARENA_BIN_COUNT; bin++) {
1764+
if (mi_atomic_load_ptr_relaxed(mi_bitmap_t, &arena_pages->pages_abandoned[bin]) == NULL) continue; // the common case
17531765
mi_bitmap_t* bitmap = mi_atomic_exchange_ptr_acq_rel(mi_bitmap_t, &arena_pages->pages_abandoned[bin], NULL);
17541766
if (bitmap != NULL) { _mi_free_subproc_safe(bitmap); }
17551767
}

‎src/heap.c‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,10 @@ mi_heap_t* mi_heap_new(void) {
181181
static void mi_heap_release_pages(mi_heap_t* heap, mi_heap_t* heap_target) {
182182
_mi_heap_detach_theaps(heap);
183183
if (_mi_is_heap_main(heap)) return; // (`_mi_heap_force_destroy` of a main heap at sub-process teardown: the arenas go as a whole)
184+
// Step 3 claims every page through the `arena_pages->pages` bitmap, so the pages abandoned in step 2
185+
// do not need to be findable by size class: `_mi_arenas_page_abandon` leaves them out of the
186+
// per-bin abandoned maps, which are then never allocated for a heap that only lives to be released.
187+
mi_atomic_store_release(&heap->releasing, (uintptr_t)1);
184188
mi_lock(&heap->theaps_lock) {
185189
for (mi_theap_t* theap = heap->theaps; theap != NULL; theap = theap->hnext) {
186190
mi_assert_internal(_mi_theap_heap_peek(theap)==NULL);

‎test/test-abandoned-lazy.c‎

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,15 @@ terms of the MIT license.
1717
- the same with the main heap, whose bitmaps are never freed, and with blocks
1818
freed by a thread that never allocated (re-abandon of a mostly free page).
1919
20+
A heap that is deleted or destroyed abandons all of its pages during its own
21+
teardown, which claims them back through the `pages` bitmap. Those pages are
22+
not mapped, so a heap that lives only to be released never allocates a map:
23+
24+
- a debug build counts the maps allocated while heaps are created, used and
25+
destroyed on one thread, and the count must not move;
26+
- several threads create, use and delete heaps while other threads free the
27+
blocks of each heap during its delete (a free that would re-map a page).
28+
2029
A debug build checks the bitmap invariants on each of these paths.
2130
2231
> mimalloc-test-abandoned-lazy [ITER]
@@ -125,6 +134,116 @@ static void run_round(bool use_main_heap) {
125134
}
126135
}
127136

137+
/* -----------------------------------------------------------
138+
Released heaps: no maps
139+
----------------------------------------------------------- */
140+
141+
#if !defined(NDEBUG)
142+
#ifdef __cplusplus
143+
#include <atomic>
144+
extern "C" std::atomic<uintptr_t> mi_debug_abandoned_maps_allocated;
145+
static uintptr_t maps_allocated(void) { return mi_debug_abandoned_maps_allocated.load(); }
146+
#else
147+
#include <stdatomic.h>
148+
extern _Atomic(uintptr_t) mi_debug_abandoned_maps_allocated;
149+
static uintptr_t maps_allocated(void) { return atomic_load(&mi_debug_abandoned_maps_allocated); }
150+
#endif
151+
#define HAS_MAP_COUNTER 1
152+
#else
153+
#define HAS_MAP_COUNTER 0
154+
#endif
155+
156+
static void fill_heap(mi_heap_t* heap, void** keep) {
157+
for (int s = 0; s < NSIZES; s++) {
158+
for (int b = 0; b < NBLOCKS; b++) {
159+
void* p = mi_heap_malloc(heap, sizes[s]);
160+
if (p == NULL) { fprintf(stderr, "allocation failed\n"); abort(); }
161+
memset(p, s + 1, sizes[s]);
162+
if (keep != NULL) { keep[s*NBLOCKS + b] = p; }
163+
}
164+
}
165+
}
166+
167+
static void released_heaps_map_nothing(void) {
168+
static void* keep[NSIZES*NBLOCKS];
169+
// one delete first: the main heap takes the moved pages and maps them, and its maps stay
170+
mi_heap_t* heap = mi_heap_new();
171+
fill_heap(heap, keep);
172+
mi_heap_delete(heap);
173+
for (int i = 0; i < NSIZES*NBLOCKS; i++) { mi_free(keep[i]); }
174+
175+
#if HAS_MAP_COUNTER
176+
const uintptr_t before = maps_allocated();
177+
#endif
178+
for (int n = 0; n < 50; n++) {
179+
heap = mi_heap_new();
180+
fill_heap(heap, NULL);
181+
mi_heap_destroy(heap);
182+
183+
heap = mi_heap_new();
184+
fill_heap(heap, keep);
185+
mi_heap_delete(heap); // the blocks now belong to the main heap
186+
for (int i = 0; i < NSIZES*NBLOCKS; i++) { mi_free(keep[i]); }
187+
}
188+
#if HAS_MAP_COUNTER
189+
const uintptr_t after = maps_allocated();
190+
if (after != before) {
191+
fprintf(stderr, "released heaps allocated %lu abandoned maps\n", (unsigned long)(after - before));
192+
abort();
193+
}
194+
#endif
195+
}
196+
197+
/* -----------------------------------------------------------
198+
Concurrent delete: blocks freed by another thread while their heap is deleted
199+
----------------------------------------------------------- */
200+
201+
#define NPAIRS 4 // a deleter and a freer each
202+
#define DBLOCKS 8 // per size: the pages stay mostly free, so a free would re-map them
203+
204+
static void* atomic_exchange_ptr(volatile void** p, void* newval);
205+
static long atomic_load_long(volatile long* p);
206+
static void atomic_store_long(volatile long* p, long x);
207+
208+
static volatile void* dslots[NPAIRS][NSIZES*DBLOCKS];
209+
static volatile long dgo[NPAIRS];
210+
static volatile long ddone[NPAIRS];
211+
static int dround_count;
212+
213+
static void delete_pair(intptr_t tid) {
214+
const int pair = (int)(tid / 2);
215+
if ((tid % 2) == 0) {
216+
// deleter: allocate, let the freer start, and delete while it frees
217+
for (int r = 1; r <= dround_count; r++) {
218+
mi_heap_t* heap = mi_heap_new();
219+
for (int s = 0; s < NSIZES; s++) {
220+
for (int b = 0; b < DBLOCKS; b++) {
221+
void* p = mi_heap_malloc(heap, sizes[s]);
222+
if (p == NULL) { fprintf(stderr, "allocation failed\n"); abort(); }
223+
memset(p, s + 1, sizes[s]);
224+
atomic_exchange_ptr(&dslots[pair][s*DBLOCKS + b], p);
225+
}
226+
}
227+
atomic_store_long(&dgo[pair], r);
228+
mi_heap_delete(heap);
229+
while (atomic_load_long(&ddone[pair]) != r) { /* spin */ }
230+
}
231+
}
232+
else {
233+
// freer: never allocates from the heap, so it may free into it during the delete
234+
for (int r = 1; r <= dround_count; r++) {
235+
while (atomic_load_long(&dgo[pair]) != r) { /* spin */ }
236+
for (int i = 0; i < NSIZES*DBLOCKS; i++) {
237+
unsigned char* p = (unsigned char*)atomic_exchange_ptr(&dslots[pair][i], NULL);
238+
if (p == NULL) { fprintf(stderr, "missing block\n"); abort(); }
239+
if (p[0] != (unsigned char)(i / DBLOCKS + 1)) { fprintf(stderr, "block corrupted\n"); abort(); }
240+
mi_free(p);
241+
}
242+
atomic_store_long(&ddone[pair], r);
243+
}
244+
}
245+
}
246+
128247
int main(int argc, char** argv) {
129248
if (argc >= 2) {
130249
char* end;
@@ -135,6 +254,9 @@ int main(int argc, char** argv) {
135254
run_round(false);
136255
run_round(true);
137256
}
257+
released_heaps_map_nothing();
258+
dround_count = ITER;
259+
run_os_threads(NPAIRS*2, &delete_pair);
138260
printf("test-abandoned-lazy: %d rounds, ok\n", ITER);
139261
mi_stats_print(NULL);
140262
return 0;
@@ -173,6 +295,20 @@ static void run_os_threads(size_t nthreads, thread_entry_fun_t* fun) {
173295
free(thandles);
174296
}
175297

298+
static void* atomic_exchange_ptr(volatile void** p, void* newval) {
299+
#if (INTPTR_MAX == INT32_MAX)
300+
return (void*)InterlockedExchange((volatile LONG*)p, (LONG)newval);
301+
#else
302+
return (void*)InterlockedExchange64((volatile LONG64*)p, (LONG64)newval);
303+
#endif
304+
}
305+
static long atomic_load_long(volatile long* p) {
306+
return InterlockedCompareExchange(p, 0, 0);
307+
}
308+
static void atomic_store_long(volatile long* p, long x) {
309+
InterlockedExchange(p, x);
310+
}
311+
176312
#else
177313

178314
#include <pthread.h>
@@ -197,4 +333,28 @@ static void run_os_threads(size_t nthreads, thread_entry_fun_t* fun) {
197333
free(threads);
198334
}
199335

336+
#ifdef __cplusplus
337+
#include <atomic>
338+
static void* atomic_exchange_ptr(volatile void** p, void* newval) {
339+
return std::atomic_exchange((volatile std::atomic<void*>*)p, newval);
340+
}
341+
static long atomic_load_long(volatile long* p) {
342+
return std::atomic_load((volatile std::atomic<long>*)p);
343+
}
344+
static void atomic_store_long(volatile long* p, long x) {
345+
std::atomic_store((volatile std::atomic<long>*)p, x);
346+
}
347+
#else
348+
#include <stdatomic.h>
349+
static void* atomic_exchange_ptr(volatile void** p, void* newval) {
350+
return atomic_exchange((volatile _Atomic(void*)*)p, newval);
351+
}
352+
static long atomic_load_long(volatile long* p) {
353+
return atomic_load((volatile _Atomic(long)*)p);
354+
}
355+
static void atomic_store_long(volatile long* p, long x) {
356+
atomic_store((volatile _Atomic(long)*)p, x);
357+
}
358+
#endif
359+
200360
#endif

0 commit comments

Comments
 (0)