Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/system/lib/mimalloc/src/theap.c
14369 views
1
/*----------------------------------------------------------------------------
2
Copyright (c) 2018-2025, 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. A copy of the license can be found in the file
5
"LICENSE" at the root of this distribution.
6
-----------------------------------------------------------------------------*/
7
8
#include "mimalloc.h"
9
#include "mimalloc/internal.h"
10
#include "mimalloc/prim.h" // _mi_theap_default
11
12
#if defined(_MSC_VER) && (_MSC_VER < 1920)
13
#pragma warning(disable:4204) // non-constant aggregate initializer
14
#endif
15
16
/* -----------------------------------------------------------
17
Helpers
18
----------------------------------------------------------- */
19
20
// return `true` if ok, `false` to break
21
typedef bool (theap_page_visitor_fun)(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2);
22
23
// Visit all pages in a theap; returns `false` if break was called.
24
static bool mi_theap_visit_pages(mi_theap_t* theap, theap_page_visitor_fun* fn, bool include_full, void* arg1, void* arg2)
25
{
26
if (theap==NULL || theap->page_count==0) return 0;
27
28
// visit all pages
29
#if MI_DEBUG>1
30
size_t total = theap->page_count;
31
size_t count = 0;
32
#endif
33
34
const size_t max_bin = (include_full ? MI_BIN_FULL : MI_BIN_FULL - 1);
35
for (size_t i = 0; i <= max_bin; i++) {
36
mi_page_queue_t* pq = &theap->pages[i];
37
mi_page_t* page = pq->first;
38
while(page != NULL) {
39
mi_page_t* next = page->next; // save next in case the page gets removed from the queue
40
mi_assert_internal(mi_page_theap(page) == theap);
41
#if MI_DEBUG>1
42
count++;
43
#endif
44
if (!fn(theap, pq, page, arg1, arg2)) return false;
45
page = next; // and continue
46
}
47
}
48
mi_assert_internal(!include_full || count == total);
49
return true;
50
}
51
52
53
#if MI_DEBUG>=2
54
static bool mi_theap_page_is_valid(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {
55
MI_UNUSED(arg1);
56
MI_UNUSED(arg2);
57
MI_UNUSED(pq);
58
mi_assert_internal(mi_page_theap(page) == theap);
59
mi_assert_expensive(_mi_page_is_valid(page));
60
return true;
61
}
62
#endif
63
#if MI_DEBUG>=3
64
static bool mi_theap_is_valid(mi_theap_t* theap) {
65
mi_assert_internal(theap!=NULL);
66
mi_theap_visit_pages(theap, &mi_theap_page_is_valid, true, NULL, NULL);
67
for (size_t bin = 0; bin < MI_BIN_COUNT; bin++) {
68
mi_assert_internal(_mi_page_queue_is_valid(theap, &theap->pages[bin]));
69
}
70
return true;
71
}
72
#endif
73
74
75
76
77
/* -----------------------------------------------------------
78
"Collect" pages by migrating `local_free` and `thread_free`
79
lists and freeing empty pages. This is done when a thread
80
stops (and in that case abandons pages if there are still
81
blocks alive)
82
----------------------------------------------------------- */
83
84
typedef enum mi_collect_e {
85
MI_NORMAL,
86
MI_FORCE,
87
MI_ABANDON
88
} mi_collect_t;
89
90
91
static bool mi_theap_page_collect(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg_collect, void* arg2 ) {
92
MI_UNUSED(arg2);
93
MI_UNUSED(theap);
94
mi_assert_internal(mi_theap_page_is_valid(theap, pq, page, NULL, NULL));
95
mi_collect_t collect = *((mi_collect_t*)arg_collect);
96
_mi_page_free_collect(page, collect >= MI_FORCE);
97
if (mi_page_all_free(page)) {
98
// no more used blocks, possibly free the page.
99
if (collect >= MI_FORCE || page->retire_expire == 0) { // either forced/abandon, or not already retired
100
// note: this will potentially free retired pages as well.
101
_mi_page_free(page, pq);
102
}
103
}
104
else if (collect == MI_ABANDON) {
105
// still used blocks but the thread is done; abandon the page
106
_mi_page_abandon(page, pq);
107
}
108
return true; // don't break
109
}
110
111
static void mi_theap_merge_stats(mi_theap_t* theap) {
112
mi_assert_internal(mi_theap_is_initialized(theap));
113
_mi_stats_merge_into(&_mi_theap_heap(theap)->stats, &theap->stats);
114
}
115
116
static void mi_theap_collect_ex(mi_theap_t* theap, mi_collect_t collect)
117
{
118
if (theap==NULL || !mi_theap_is_initialized(theap)) return;
119
mi_assert_expensive(mi_theap_is_valid(theap));
120
121
const bool force = (collect >= MI_FORCE);
122
_mi_deferred_free(theap, force);
123
124
// python/cpython#112532: we may be called from a thread that is not the owner of the theap
125
// const bool is_main_thread = (_mi_is_main_thread() && theap->thread_id == _mi_thread_id());
126
127
// collect retired pages
128
_mi_theap_collect_retired(theap, force);
129
130
// collect all pages owned by this thread
131
mi_theap_visit_pages(theap, &mi_theap_page_collect, (collect!=MI_NORMAL), &collect, NULL); // dont normally visit full pages, see issue #1220
132
133
// collect arenas (this is program wide so don't force purges on abandonment of threads)
134
//mi_atomic_storei64_release(&theap->tld->subproc->purge_expire, 1);
135
_mi_arenas_collect(collect == MI_FORCE /* force purge? */, collect >= MI_FORCE /* visit all? */, theap->tld);
136
137
// merge statistics
138
mi_theap_merge_stats(theap);
139
}
140
141
void _mi_theap_collect_abandon(mi_theap_t* theap) {
142
mi_theap_collect_ex(theap, MI_ABANDON);
143
}
144
145
void mi_theap_collect(mi_theap_t* theap, bool force) mi_attr_noexcept {
146
mi_theap_collect_ex(theap, (force ? MI_FORCE : MI_NORMAL));
147
}
148
149
void mi_collect(bool force) mi_attr_noexcept {
150
// cannot really collect process wide, just a theap..
151
mi_theap_collect(_mi_theap_default(), force);
152
}
153
154
void mi_heap_collect(mi_heap_t* heap, bool force) {
155
// cannot really collect a heap, just a theap..
156
mi_theap_collect(mi_heap_theap(heap), force);
157
}
158
159
/* -----------------------------------------------------------
160
Heap new
161
----------------------------------------------------------- */
162
163
mi_theap_t* mi_theap_get_default(void) {
164
mi_theap_t* theap = _mi_theap_default();
165
if mi_unlikely(!mi_theap_is_initialized(theap)) {
166
mi_thread_init();
167
theap = _mi_theap_default();
168
mi_assert_internal(mi_theap_is_initialized(theap));
169
}
170
return theap;
171
}
172
173
// todo: make order of parameters consistent (but would that break compat with CPython?)
174
void _mi_theap_init(mi_theap_t* theap, mi_heap_t* heap, mi_tld_t* tld)
175
{
176
mi_assert_internal(theap!=NULL);
177
mi_assert_internal(heap!=NULL);
178
mi_memid_t memid = theap->memid;
179
_mi_memcpy_aligned(theap, &_mi_theap_empty, sizeof(mi_theap_t));
180
theap->memid = memid;
181
theap->refcount = 1;
182
theap->tld = tld; // avoid reading the thread-local tld during initialization
183
mi_atomic_store_ptr_relaxed(mi_heap_t,&theap->heap,heap);
184
185
_mi_theap_options_init(theap);
186
if (theap->tld->is_in_threadpool) {
187
// if we run as part of a thread pool it is better to not arbitrarily reclaim abandoned pages into our theap.
188
// this is checked in `free.c:mi_free_try_collect_mt`
189
// .. but abandoning is good in this case: halve the full page retain (possibly to 0)
190
// (so blocked threads do not hold on to too much memory)
191
if (theap->page_full_retain > 0) {
192
theap->page_full_retain = theap->page_full_retain / 4;
193
}
194
}
195
196
// push on the thread local theaps list
197
mi_theap_t* head = NULL;
198
mi_lock(&theap->tld->theaps_lock) {
199
head = theap->tld->theaps;
200
theap->tprev = NULL;
201
theap->tnext = head;
202
if (head!=NULL) { head->tprev = theap; }
203
theap->tld->theaps = theap;
204
}
205
206
// initialize random
207
if (head == NULL) { // first theap in this thread?
208
#if defined(_WIN32) && !defined(MI_SHARED_LIB)
209
_mi_random_init_weak(&theap->random); // prevent allocation failure during bcrypt dll initialization with static linking (issue #1185)
210
#else
211
_mi_random_init(&theap->random);
212
#endif
213
}
214
else {
215
_mi_random_split(&head->random, &theap->random);
216
}
217
theap->cookie = _mi_theap_random_next(theap) | 1;
218
_mi_theap_guarded_init(theap);
219
mi_subproc_stat_increase(_mi_subproc(),theaps,1);
220
221
// push on the heap's theap list
222
mi_lock(&heap->theaps_lock) {
223
head = heap->theaps;
224
theap->hprev = NULL;
225
theap->hnext = head;
226
if (head!=NULL) { head->hprev = theap; }
227
heap->theaps = theap;
228
}
229
}
230
231
mi_theap_t* _mi_theap_create(mi_heap_t* heap, mi_tld_t* tld) {
232
mi_assert_internal(tld!=NULL);
233
mi_assert_internal(heap!=NULL);
234
// allocate and initialize a theap
235
mi_memid_t memid;
236
mi_theap_t* theap;
237
//if (!_mi_is_heap_main(heap)) {
238
// theap = (mi_theap_t*)mi_heap_zalloc(mi_heap_main(),sizeof(mi_theap_t));
239
// memid = _mi_memid_create(MI_MEM_HEAP_MAIN);
240
// memid.initially_zero = memid.initially_committed = true;
241
//}
242
//else
243
if (heap->exclusive_arena == NULL) {
244
theap = (mi_theap_t*)_mi_meta_zalloc(sizeof(mi_theap_t), &memid);
245
}
246
else {
247
// theaps associated with a specific arena are allocated in that arena
248
// note: takes up at least one slice which is quite wasteful...
249
const size_t size = _mi_align_up(sizeof(mi_theap_t),MI_ARENA_MIN_OBJ_SIZE);
250
theap = (mi_theap_t*)_mi_arenas_alloc(heap, size, true, true, heap->exclusive_arena, tld->thread_seq, tld->numa_node, &memid);
251
mi_assert_internal(memid.mem.os.size >= size);
252
}
253
if (theap==NULL) {
254
_mi_error_message(ENOMEM, "unable to allocate theap meta-data\n");
255
return NULL;
256
}
257
theap->memid = memid;
258
_mi_theap_init(theap, heap, tld);
259
return theap;
260
}
261
262
uintptr_t _mi_theap_random_next(mi_theap_t* theap) {
263
return _mi_random_next(&theap->random);
264
}
265
266
static void mi_theap_free_mem(mi_theap_t* theap) {
267
if (theap!=NULL) {
268
mi_subproc_stat_decrease(_mi_subproc(),theaps,1);
269
// free the used memory
270
if (theap->memid.memkind == MI_MEM_HEAP_MAIN) { // note: for now unused as it would access theap_default stats in mi_free of the current theap
271
mi_assert_internal(_mi_is_heap_main(mi_heap_of(theap)));
272
mi_free(theap);
273
}
274
else if (theap->memid.memkind == MI_MEM_META) {
275
_mi_meta_free(theap, sizeof(*theap), theap->memid);
276
}
277
else {
278
_mi_arenas_free(theap, _mi_align_up(sizeof(*theap),MI_ARENA_MIN_OBJ_SIZE), theap->memid ); // issue #1168, avoid assertion failure
279
}
280
}
281
}
282
283
void _mi_theap_incref(mi_theap_t* theap) {
284
if (theap!=NULL && theap->memid.memkind > MI_MEM_STATIC) {
285
mi_atomic_increment_acq_rel(&theap->refcount);
286
}
287
}
288
289
void _mi_theap_decref(mi_theap_t* theap) {
290
if (theap!=NULL && theap->memid.memkind > MI_MEM_STATIC) {
291
if (mi_atomic_decrement_acq_rel(&theap->refcount) == 1) {
292
mi_theap_free_mem(theap);
293
}
294
}
295
}
296
297
298
// called from `mi_theap_delete` to free the internal theap resources.
299
bool _mi_theap_free(mi_theap_t* theap, bool acquire_heap_theaps_lock, bool acquire_tld_theaps_lock) {
300
mi_assert(theap != NULL);
301
if (theap==NULL) return true;
302
303
mi_heap_t* const heap = mi_atomic_exchange_ptr_acq_rel(mi_heap_t, &theap->heap, NULL);
304
if (heap==NULL) {
305
// concurrent interaction, retry in an outer loop (as the other thread may be blocked on our lock)
306
return false;
307
}
308
else {
309
// merge stats to the owning heap
310
_mi_stats_merge_into(&heap->stats, &theap->stats);
311
312
// remove ourselves from the heap theaps list
313
mi_lock_maybe(&heap->theaps_lock, acquire_heap_theaps_lock) {
314
if (theap->hnext != NULL) { theap->hnext->hprev = theap->hprev; }
315
if (theap->hprev != NULL) { theap->hprev->hnext = theap->hnext; }
316
else { mi_assert_internal(heap->theaps == theap); heap->theaps = theap->hnext; }
317
theap->hnext = theap->hprev = NULL;
318
}
319
320
// remove ourselves from the thread local theaps list
321
mi_lock_maybe(&theap->tld->theaps_lock, acquire_tld_theaps_lock) {
322
if (theap->tnext != NULL) { theap->tnext->tprev = theap->tprev; }
323
if (theap->tprev != NULL) { theap->tprev->tnext = theap->tnext; }
324
else { mi_assert_internal(theap->tld->theaps == theap); theap->tld->theaps = theap->tnext; }
325
theap->tnext = theap->tprev = NULL;
326
}
327
theap->tld = NULL;
328
_mi_theap_decref(theap);
329
return true;
330
}
331
}
332
333
334
/* -----------------------------------------------------------
335
Heap destroy
336
----------------------------------------------------------- */
337
/*
338
339
// zero out the page queues
340
static void mi_theap_reset_pages(mi_theap_t* theap) {
341
mi_assert_internal(theap != NULL);
342
mi_assert_internal(mi_theap_is_initialized(theap));
343
// TODO: copy full empty theap instead?
344
_mi_memset(&theap->pages_free_direct, 0, sizeof(theap->pages_free_direct));
345
_mi_memcpy_aligned(&theap->pages, &_mi_theap_empty.pages, sizeof(theap->pages));
346
// theap->thread_delayed_free = NULL;
347
theap->page_count = 0;
348
}
349
350
static bool _mi_theap_page_destroy(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {
351
MI_UNUSED(arg1);
352
MI_UNUSED(arg2);
353
MI_UNUSED(pq);
354
355
// ensure no more thread_delayed_free will be added
356
//_mi_page_use_delayed_free(page, MI_NEVER_DELAYED_FREE, false);
357
358
// stats
359
const size_t bsize = mi_page_block_size(page);
360
if (bsize > MI_LARGE_MAX_OBJ_SIZE) {
361
mi_theap_stat_decrease(theap, malloc_huge, bsize);
362
}
363
#if (MI_STAT>0)
364
_mi_page_free_collect(page, false); // update used count
365
const size_t inuse = page->used;
366
if (bsize <= MI_LARGE_MAX_OBJ_SIZE) {
367
mi_theap_stat_decrease(theap, malloc_normal, bsize * inuse);
368
#if (MI_STAT>1)
369
mi_theap_stat_decrease(theap, malloc_bins[_mi_bin(bsize)], inuse);
370
#endif
371
}
372
// mi_theap_stat_decrease(theap, malloc_requested, bsize * inuse); // todo: off for aligned blocks...
373
#endif
374
375
/// pretend it is all free now
376
mi_assert_internal(mi_page_thread_free(page) == NULL);
377
page->used = 0;
378
379
// and free the page
380
// mi_page_free(page,false);
381
page->next = NULL;
382
page->prev = NULL;
383
mi_page_set_theap(page, NULL);
384
_mi_arenas_page_free(page, theap);
385
386
return true; // keep going
387
}
388
389
void _mi_theap_destroy_pages(mi_theap_t* theap) {
390
mi_theap_visit_pages(theap, &_mi_theap_page_destroy, NULL, NULL);
391
mi_theap_reset_pages(theap);
392
}
393
394
#if MI_TRACK_HEAP_DESTROY
395
static bool mi_cdecl mi_theap_track_block_free(const mi_theap_t* theap, const mi_theap_area_t* area, void* block, size_t block_size, void* arg) {
396
MI_UNUSED(theap); MI_UNUSED(area); MI_UNUSED(arg); MI_UNUSED(block_size);
397
mi_track_free_size(block,mi_usable_size(block));
398
return true;
399
}
400
#endif
401
402
void mi_theap_destroy(mi_theap_t* theap) {
403
mi_assert(theap != NULL);
404
mi_assert(mi_theap_is_initialized(theap));
405
mi_assert(!theap->allow_page_reclaim);
406
mi_assert(!theap->allow_page_abandon);
407
mi_assert_expensive(mi_theap_is_valid(theap));
408
if (theap==NULL || !mi_theap_is_initialized(theap)) return;
409
#if MI_GUARDED
410
// _mi_warning_message("'mi_theap_destroy' called but MI_GUARDED is enabled -- using `mi_theap_delete` instead (theap at %p)\n", theap);
411
mi_theap_delete(theap);
412
return;
413
#else
414
if (theap->allow_page_reclaim) {
415
_mi_warning_message("'mi_theap_destroy' called but ignored as the theap was not created with 'allow_destroy' (theap at %p)\n", theap);
416
// don't free in case it may contain reclaimed pages,
417
mi_theap_delete(theap);
418
}
419
else {
420
// track all blocks as freed
421
#if MI_TRACK_HEAP_DESTROY
422
mi_theap_visit_blocks(theap, true, mi_theap_track_block_free, NULL);
423
#endif
424
// free all pages
425
_mi_theap_destroy_pages(theap);
426
mi_theap_free(theap,true);
427
}
428
#endif
429
}
430
431
// forcefully destroy all theaps in the current thread
432
void _mi_theap_unsafe_destroy_all(mi_theap_t* theap) {
433
mi_assert_internal(theap != NULL);
434
if (theap == NULL) return;
435
mi_theap_t* curr = theap->tld->theaps;
436
while (curr != NULL) {
437
mi_theap_t* next = curr->next;
438
if (!curr->allow_page_reclaim) {
439
mi_theap_destroy(curr);
440
}
441
else {
442
_mi_theap_destroy_pages(curr);
443
}
444
curr = next;
445
}
446
}
447
*/
448
449
/* -----------------------------------------------------------
450
Safe Heap delete
451
----------------------------------------------------------- */
452
453
// Safe delete a theap without freeing any still allocated blocks in that theap.
454
void _mi_theap_delete(mi_theap_t* theap, bool acquire_tld_theaps_lock)
455
{
456
mi_assert(theap != NULL);
457
mi_assert(mi_theap_is_initialized(theap));
458
mi_assert_expensive(mi_theap_is_valid(theap));
459
if (theap==NULL || !mi_theap_is_initialized(theap)) return;
460
461
// abandon all pages
462
_mi_theap_collect_abandon(theap);
463
464
mi_assert_internal(theap->page_count==0);
465
_mi_theap_free(theap, true /* acquire heap->theaps_lock */, acquire_tld_theaps_lock);
466
}
467
468
469
470
/* -----------------------------------------------------------
471
Load/unload theaps
472
----------------------------------------------------------- */
473
/*
474
void mi_theap_unload(mi_theap_t* theap) {
475
mi_assert(mi_theap_is_initialized(theap));
476
mi_assert_expensive(mi_theap_is_valid(theap));
477
if (theap==NULL || !mi_theap_is_initialized(theap)) return;
478
if (_mi_theap_heap(theap)->exclusive_arena == NULL) {
479
_mi_warning_message("cannot unload theaps that are not associated with an exclusive arena\n");
480
return;
481
}
482
483
// abandon all pages so all thread'id in the pages are cleared
484
_mi_theap_collect_abandon(theap);
485
mi_assert_internal(theap->page_count==0);
486
487
// remove from theap list
488
mi_theap_free(theap, false); // but don't actually free the memory
489
490
// disassociate from the current thread-local and static state
491
theap->tld = NULL;
492
return;
493
}
494
495
bool mi_theap_reload(mi_theap_t* theap, mi_arena_id_t arena_id) {
496
mi_assert(mi_theap_is_initialized(theap));
497
if (theap==NULL || !mi_theap_is_initialized(theap)) return false;
498
if (_mi_theap_heap(theap)->exclusive_arena == NULL) {
499
_mi_warning_message("cannot reload theaps that were not associated with an exclusive arena\n");
500
return false;
501
}
502
if (theap->tld != NULL) {
503
_mi_warning_message("cannot reload theaps that were not unloaded first\n");
504
return false;
505
}
506
mi_arena_t* arena = _mi_arena_from_id(arena_id);
507
if (_mi_theap_heap(theap)->exclusive_arena != arena) {
508
_mi_warning_message("trying to reload a theap at a different arena address: %p vs %p\n", _mi_theap_heap(theap)->exclusive_arena, arena);
509
return false;
510
}
511
512
mi_assert_internal(theap->page_count==0);
513
514
// re-associate with the current thread-local and static state
515
theap->tld = mi_theap_get_default()->tld;
516
517
// reinit direct pages (as we may be in a different process)
518
mi_assert_internal(theap->page_count == 0);
519
for (size_t i = 0; i < MI_PAGES_DIRECT; i++) {
520
theap->pages_free_direct[i] = (mi_page_t*)&_mi_page_empty;
521
}
522
523
// push on the thread local theaps list
524
theap->tnext = theap->tld->theaps;
525
theap->tld->theaps = theap;
526
return true;
527
}
528
*/
529
530
531
/* -----------------------------------------------------------
532
Visit all theap blocks and areas
533
Todo: enable visiting abandoned pages, and
534
enable visiting all blocks of all theaps across threads
535
----------------------------------------------------------- */
536
537
void _mi_heap_area_init(mi_heap_area_t* area, mi_page_t* page) {
538
const size_t bsize = mi_page_block_size(page);
539
const size_t ubsize = mi_page_usable_block_size(page);
540
area->reserved = page->reserved * bsize;
541
area->committed = page->capacity * bsize;
542
area->blocks = mi_page_start(page);
543
area->used = page->used; // number of blocks in use (#553)
544
area->block_size = ubsize;
545
area->full_block_size = bsize;
546
area->reserved1 = page;
547
}
548
549
static void mi_get_fast_divisor(size_t divisor, uint64_t* magic, size_t* shift) {
550
mi_assert_internal(divisor > 0 && divisor <= UINT32_MAX);
551
*shift = MI_SIZE_BITS - mi_clz(divisor - 1);
552
*magic = ((((uint64_t)1 << 32) * (((uint64_t)1 << *shift) - divisor)) / divisor + 1);
553
}
554
555
static size_t mi_fast_divide(size_t n, uint64_t magic, size_t shift) {
556
mi_assert_internal(n <= UINT32_MAX);
557
const uint64_t hi = ((uint64_t)n * magic) >> 32;
558
return (size_t)((hi + n) >> shift);
559
}
560
561
bool _mi_theap_area_visit_blocks(const mi_heap_area_t* area, mi_page_t* page, mi_block_visit_fun* visitor, void* arg) {
562
mi_assert(area != NULL);
563
if (area==NULL) return true;
564
mi_assert(page != NULL);
565
if (page == NULL) return true;
566
567
_mi_page_free_collect(page,true); // collect both thread_delayed and local_free
568
mi_assert_internal(page->local_free == NULL);
569
if (page->used == 0) return true;
570
571
size_t psize;
572
uint8_t* const pstart = mi_page_area(page, &psize);
573
mi_heap_t* const heap = mi_page_heap(page);
574
const size_t bsize = mi_page_block_size(page);
575
const size_t ubsize = mi_page_usable_block_size(page); // without padding
576
577
// optimize page with one block
578
if (page->capacity == 1) {
579
mi_assert_internal(page->used == 1 && page->free == NULL);
580
return visitor(heap, area, pstart, ubsize, arg);
581
}
582
mi_assert(bsize <= UINT32_MAX);
583
584
// optimize full pages
585
if (page->used == page->capacity) {
586
uint8_t* block = pstart;
587
for (size_t i = 0; i < page->capacity; i++) {
588
if (!visitor(heap, area, block, ubsize, arg)) return false;
589
block += bsize;
590
}
591
return true;
592
}
593
594
// create a bitmap of free blocks.
595
#define MI_MAX_BLOCKS (MI_SMALL_PAGE_SIZE / sizeof(void*))
596
uintptr_t free_map[MI_MAX_BLOCKS / MI_INTPTR_BITS];
597
const uintptr_t bmapsize = _mi_divide_up(page->capacity, MI_INTPTR_BITS);
598
memset(free_map, 0, bmapsize * sizeof(intptr_t));
599
if (page->capacity % MI_INTPTR_BITS != 0) {
600
// mark left-over bits at the end as free
601
size_t shift = (page->capacity % MI_INTPTR_BITS);
602
uintptr_t mask = (UINTPTR_MAX << shift);
603
free_map[bmapsize - 1] = mask;
604
}
605
606
// fast repeated division by the block size
607
uint64_t magic;
608
size_t shift;
609
mi_get_fast_divisor(bsize, &magic, &shift);
610
611
#if MI_DEBUG>1
612
size_t free_count = 0;
613
#endif
614
for (mi_block_t* block = page->free; block != NULL; block = mi_block_next(page, block)) {
615
#if MI_DEBUG>1
616
free_count++;
617
#endif
618
mi_assert_internal((uint8_t*)block >= pstart && (uint8_t*)block < (pstart + psize));
619
size_t offset = (uint8_t*)block - pstart;
620
mi_assert_internal(offset % bsize == 0);
621
mi_assert_internal(offset <= UINT32_MAX);
622
size_t blockidx = mi_fast_divide(offset, magic, shift);
623
mi_assert_internal(blockidx == offset / bsize);
624
mi_assert_internal(blockidx < MI_MAX_BLOCKS);
625
size_t bitidx = (blockidx / MI_INTPTR_BITS);
626
size_t bit = blockidx - (bitidx * MI_INTPTR_BITS);
627
free_map[bitidx] |= ((uintptr_t)1 << bit);
628
}
629
mi_assert_internal(page->capacity == (free_count + page->used));
630
631
// walk through all blocks skipping the free ones
632
#if MI_DEBUG>1
633
size_t used_count = 0;
634
#endif
635
uint8_t* block = pstart;
636
for (size_t i = 0; i < bmapsize; i++) {
637
if (free_map[i] == 0) {
638
// every block is in use
639
for (size_t j = 0; j < MI_INTPTR_BITS; j++) {
640
#if MI_DEBUG>1
641
used_count++;
642
#endif
643
if (!visitor(heap, area, block, ubsize, arg)) return false;
644
block += bsize;
645
}
646
}
647
else {
648
// visit the used blocks in the mask
649
uintptr_t m = ~free_map[i];
650
while (m != 0) {
651
#if MI_DEBUG>1
652
used_count++;
653
#endif
654
size_t bitidx = mi_ctz(m);
655
if (!visitor(heap, area, block + (bitidx * bsize), ubsize, arg)) return false;
656
m &= m - 1; // clear least significant bit
657
}
658
block += bsize * MI_INTPTR_BITS;
659
}
660
}
661
mi_assert_internal(page->used == used_count);
662
return true;
663
}
664
665
666
667
// Separate struct to keep `mi_page_t` out of the public interface
668
typedef struct mi_theap_area_ex_s {
669
mi_heap_area_t area;
670
mi_page_t* page;
671
} mi_theap_area_ex_t;
672
673
typedef bool (mi_theap_area_visit_fun)(const mi_theap_t* theap, const mi_theap_area_ex_t* area, void* arg);
674
675
static bool mi_theap_visit_areas_page(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* vfun, void* arg) {
676
MI_UNUSED(theap);
677
MI_UNUSED(pq);
678
mi_theap_area_visit_fun* fun = (mi_theap_area_visit_fun*)vfun;
679
mi_theap_area_ex_t xarea;
680
xarea.page = page;
681
_mi_heap_area_init(&xarea.area, page);
682
return fun(theap, &xarea, arg);
683
}
684
685
// Visit all theap pages as areas
686
static bool mi_theap_visit_areas(const mi_theap_t* theap, mi_theap_area_visit_fun* visitor, void* arg) {
687
if (visitor == NULL) return false;
688
return mi_theap_visit_pages((mi_theap_t*)theap, &mi_theap_visit_areas_page, true, (void*)(visitor), arg); // note: function pointer to void* :-{
689
}
690
691
// Just to pass arguments
692
typedef struct mi_visit_blocks_args_s {
693
bool visit_blocks;
694
mi_block_visit_fun* visitor;
695
void* arg;
696
} mi_visit_blocks_args_t;
697
698
static bool mi_theap_area_visitor(const mi_theap_t* theap, const mi_theap_area_ex_t* xarea, void* arg) {
699
mi_visit_blocks_args_t* args = (mi_visit_blocks_args_t*)arg;
700
if (!args->visitor(_mi_theap_heap(theap), &xarea->area, NULL, xarea->area.block_size, args->arg)) return false;
701
if (args->visit_blocks) {
702
return _mi_theap_area_visit_blocks(&xarea->area, xarea->page, args->visitor, args->arg);
703
}
704
else {
705
return true;
706
}
707
}
708
709
// Visit all blocks in a theap
710
bool mi_theap_visit_blocks(const mi_theap_t* theap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {
711
mi_visit_blocks_args_t args = { visit_blocks, visitor, arg };
712
return mi_theap_visit_areas(theap, &mi_theap_area_visitor, &args);
713
}
714
715
716