Coverage Report

Created: 2026-10-31 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/mimalloc/arena.c
Line
Count
Source
1
/* ----------------------------------------------------------------------------
2
Copyright (c) 2019-2024, 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
/* ----------------------------------------------------------------------------
9
"Arenas" are fixed area's of OS memory from which we can allocate
10
large blocks (>= MI_ARENA_MIN_BLOCK_SIZE, 4MiB).
11
In contrast to the rest of mimalloc, the arenas are shared between
12
threads and need to be accessed using atomic operations.
13
14
Arenas are also used to for huge OS page (1GiB) reservations or for reserving
15
OS memory upfront which can be improve performance or is sometimes needed
16
on embedded devices. We can also employ this with WASI or `sbrk` systems
17
to reserve large arenas upfront and be able to reuse the memory more effectively.
18
19
The arena allocation needs to be thread safe and we use an atomic bitmap to allocate.
20
-----------------------------------------------------------------------------*/
21
22
#include "mimalloc.h"
23
#include "mimalloc/internal.h"
24
#include "mimalloc/atomic.h"
25
#include "bitmap.h"
26
27
28
/* -----------------------------------------------------------
29
  Arena allocation
30
----------------------------------------------------------- */
31
32
// A memory arena descriptor
33
typedef struct mi_arena_s {
34
  mi_arena_id_t       id;                   // arena id; 0 for non-specific
35
  mi_memid_t          memid;                // memid of the memory area
36
  _Atomic(uint8_t*)   start;                // the start of the memory area
37
  size_t              block_count;          // size of the area in arena blocks (of `MI_ARENA_BLOCK_SIZE`)
38
  size_t              field_count;          // number of bitmap fields (where `field_count * MI_BITMAP_FIELD_BITS >= block_count`)
39
  size_t              meta_size;            // size of the arena structure itself (including its bitmaps)
40
  mi_memid_t          meta_memid;           // memid of the arena structure itself (OS or static allocation)
41
  int                 numa_node;            // associated NUMA node
42
  bool                exclusive;            // only allow allocations if specifically for this arena
43
  bool                is_large;             // memory area consists of large- or huge OS pages (always committed)
44
  mi_lock_t           abandoned_visit_lock; // lock is only used when abandoned segments are being visited
45
  _Atomic(size_t)     search_idx;           // optimization to start the search for free blocks
46
  _Atomic(mi_msecs_t) purge_expire;         // expiration time when blocks should be purged from `blocks_purge`.
47
48
  mi_bitmap_field_t*  blocks_dirty;         // are the blocks potentially non-zero?
49
  mi_bitmap_field_t*  blocks_committed;     // are the blocks committed? (can be NULL for memory that cannot be decommitted)
50
  mi_bitmap_field_t*  blocks_purge;         // blocks that can be (reset) decommitted. (can be NULL for memory that cannot be (reset) decommitted)
51
  mi_bitmap_field_t*  blocks_abandoned;     // blocks that start with an abandoned segment. (This crosses API's but it is convenient to have here)
52
  mi_bitmap_field_t   blocks_inuse[1];      // in-place bitmap of in-use blocks (of size `field_count`)
53
  // do not add further fields here as the dirty, committed, purged, and abandoned bitmaps follow the inuse bitmap fields.
54
} mi_arena_t;
55
56
57
0
#define MI_ARENA_BLOCK_SIZE   (MI_SEGMENT_SIZE)        // 64MiB  (must be at least MI_SEGMENT_ALIGN)
58
0
#define MI_ARENA_MIN_OBJ_SIZE (MI_ARENA_BLOCK_SIZE/2)  // 32MiB
59
0
#define MI_MAX_ARENAS         (132)                    // Limited as the reservation exponentially increases (and takes up .bss)
60
61
// The available arenas
62
static mi_decl_cache_align _Atomic(mi_arena_t*) mi_arenas[MI_MAX_ARENAS];
63
static mi_decl_cache_align _Atomic(size_t)      mi_arena_count; // = 0
64
static mi_decl_cache_align _Atomic(int64_t)     mi_arenas_purge_expire; // set if there exist purgeable arenas
65
66
#define MI_IN_ARENA_C
67
#include "arena-abandon.c"
68
#undef MI_IN_ARENA_C
69
70
/* -----------------------------------------------------------
71
  Arena id's
72
  id = arena_index + 1
73
----------------------------------------------------------- */
74
75
0
size_t mi_arena_id_index(mi_arena_id_t id) {
76
0
  return (size_t)(id <= 0 ? MI_MAX_ARENAS : id - 1);
77
0
}
78
79
0
static mi_arena_id_t mi_arena_id_create(size_t arena_index) {
80
0
  mi_assert_internal(arena_index < MI_MAX_ARENAS);
81
0
  return (int)arena_index + 1;
82
0
}
83
84
0
mi_arena_id_t _mi_arena_id_none(void) {
85
0
  return 0;
86
0
}
87
88
0
static bool mi_arena_id_is_suitable(mi_arena_id_t arena_id, bool arena_is_exclusive, mi_arena_id_t req_arena_id) {
89
0
  return ((!arena_is_exclusive && req_arena_id == _mi_arena_id_none()) ||
90
0
          (arena_id == req_arena_id));
91
0
}
92
93
0
bool _mi_arena_memid_is_suitable(mi_memid_t memid, mi_arena_id_t request_arena_id) {
94
0
  if (memid.memkind == MI_MEM_ARENA) {
95
0
    return mi_arena_id_is_suitable(memid.mem.arena.id, memid.mem.arena.is_exclusive, request_arena_id);
96
0
  }
97
0
  else {
98
0
    return mi_arena_id_is_suitable(_mi_arena_id_none(), false, request_arena_id);
99
0
  }
100
0
}
101
102
0
bool _mi_arena_memid_is_os_allocated(mi_memid_t memid) {
103
0
  return (memid.memkind == MI_MEM_OS);
104
0
}
105
106
0
size_t mi_arena_get_count(void) {
107
0
  return mi_atomic_load_relaxed(&mi_arena_count);
108
0
}
109
110
0
mi_arena_t* mi_arena_from_index(size_t idx) {
111
0
  mi_assert_internal(idx < mi_arena_get_count());
112
0
  return mi_atomic_load_ptr_acquire(mi_arena_t, &mi_arenas[idx]);
113
0
}
114
115
116
/* -----------------------------------------------------------
117
  Arena allocations get a (currently) 16-bit memory id where the
118
  lower 8 bits are the arena id, and the upper bits the block index.
119
----------------------------------------------------------- */
120
121
0
static size_t mi_block_count_of_size(size_t size) {
122
0
  return _mi_divide_up(size, MI_ARENA_BLOCK_SIZE);
123
0
}
124
125
0
static size_t mi_arena_block_size(size_t bcount) {
126
0
  return (bcount * MI_ARENA_BLOCK_SIZE);
127
0
}
128
129
0
static size_t mi_arena_size(mi_arena_t* arena) {
130
0
  return mi_arena_block_size(arena->block_count);
131
0
}
132
133
0
static mi_memid_t mi_memid_create_arena(mi_arena_id_t id, bool is_exclusive, mi_bitmap_index_t bitmap_index) {
134
0
  mi_memid_t memid = _mi_memid_create(MI_MEM_ARENA);
135
0
  memid.mem.arena.id = id;
136
0
  memid.mem.arena.block_index = bitmap_index;
137
0
  memid.mem.arena.is_exclusive = is_exclusive;
138
0
  return memid;
139
0
}
140
141
0
bool mi_arena_memid_indices(mi_memid_t memid, size_t* arena_index, mi_bitmap_index_t* bitmap_index) {
142
0
  mi_assert_internal(memid.memkind == MI_MEM_ARENA);
143
0
  *arena_index = mi_arena_id_index(memid.mem.arena.id);
144
0
  *bitmap_index = memid.mem.arena.block_index;
145
0
  return memid.mem.arena.is_exclusive;
146
0
}
147
148
149
150
/* -----------------------------------------------------------
151
  Special static area for mimalloc internal structures
152
  to avoid OS calls (for example, for the arena metadata (~= 256b))
153
----------------------------------------------------------- */
154
155
0
#define MI_ARENA_STATIC_MAX  ((MI_INTPTR_SIZE/2)*MI_KiB)  // 4 KiB on 64-bit
156
157
static mi_decl_cache_align uint8_t mi_arena_static[MI_ARENA_STATIC_MAX];  // must be cache aligned, see issue #895
158
static mi_decl_cache_align _Atomic(size_t) mi_arena_static_top;
159
160
0
static void* mi_arena_static_zalloc(size_t size, size_t alignment, mi_memid_t* memid) {
161
0
  *memid = _mi_memid_none();
162
0
  if (size == 0 || size > MI_ARENA_STATIC_MAX) return NULL;
163
0
  const size_t toplow = mi_atomic_load_relaxed(&mi_arena_static_top);
164
0
  if ((toplow + size) > MI_ARENA_STATIC_MAX) return NULL;
165
166
  // try to claim space
167
0
  if (alignment < MI_MAX_ALIGN_SIZE) { alignment = MI_MAX_ALIGN_SIZE; }
168
0
  const size_t oversize = size + alignment - 1;
169
0
  if (toplow + oversize > MI_ARENA_STATIC_MAX) return NULL;
170
0
  const size_t oldtop = mi_atomic_add_acq_rel(&mi_arena_static_top, oversize);
171
0
  size_t top = oldtop + oversize;
172
0
  if (top > MI_ARENA_STATIC_MAX) {
173
    // try to roll back, ok if this fails
174
0
    mi_atomic_cas_strong_acq_rel(&mi_arena_static_top, &top, oldtop);
175
0
    return NULL;
176
0
  }
177
178
  // success
179
0
  *memid = _mi_memid_create(MI_MEM_STATIC);
180
0
  memid->initially_zero = true;
181
0
  const size_t start = _mi_align_up(oldtop, alignment);
182
0
  uint8_t* const p = &mi_arena_static[start];
183
0
  _mi_memzero_aligned(p, size);
184
0
  return p;
185
0
}
186
187
0
void* _mi_arena_meta_zalloc(size_t size, mi_memid_t* memid) {
188
0
  *memid = _mi_memid_none();
189
190
  // try static
191
0
  void* p = mi_arena_static_zalloc(size, MI_MAX_ALIGN_SIZE, memid);
192
0
  if (p != NULL) return p;
193
194
  // or fall back to the OS
195
0
  p = _mi_os_zalloc(size, memid);
196
0
  if (p == NULL) return NULL;
197
198
0
  return p;
199
0
}
200
201
0
void _mi_arena_meta_free(void* p, mi_memid_t memid, size_t size) {
202
0
  if (mi_memkind_is_os(memid.memkind)) {
203
0
    _mi_os_free(p, size, memid);
204
0
  }
205
0
  else {
206
0
    mi_assert(memid.memkind == MI_MEM_STATIC);
207
0
  }
208
0
}
209
210
0
void* mi_arena_block_start(mi_arena_t* arena, mi_bitmap_index_t bindex) {
211
0
  return (arena->start + mi_arena_block_size(mi_bitmap_index_bit(bindex)));
212
0
}
213
214
215
/* -----------------------------------------------------------
216
  Thread safe allocation in an arena
217
----------------------------------------------------------- */
218
219
// claim the `blocks_inuse` bits
220
static bool mi_arena_try_claim(mi_arena_t* arena, size_t blocks, mi_bitmap_index_t* bitmap_idx)
221
0
{
222
0
  size_t idx = 0; // mi_atomic_load_relaxed(&arena->search_idx);  // start from last search; ok to be relaxed as the exact start does not matter
223
0
  if (_mi_bitmap_try_find_from_claim_across(arena->blocks_inuse, arena->field_count, idx, blocks, bitmap_idx)) {
224
0
    mi_atomic_store_relaxed(&arena->search_idx, mi_bitmap_index_field(*bitmap_idx));  // start search from found location next time around
225
0
    return true;
226
0
  };
227
0
  return false;
228
0
}
229
230
231
/* -----------------------------------------------------------
232
  Arena Allocation
233
----------------------------------------------------------- */
234
235
static mi_decl_noinline void* mi_arena_try_alloc_at(mi_arena_t* arena, size_t arena_index, size_t needed_bcount,
236
                                                    bool commit, mi_memid_t* memid)
237
0
{
238
0
  MI_UNUSED(arena_index);
239
0
  mi_assert_internal(mi_arena_id_index(arena->id) == arena_index);
240
241
0
  mi_bitmap_index_t bitmap_index;
242
0
  if (!mi_arena_try_claim(arena, needed_bcount, &bitmap_index)) return NULL;
243
244
  // claimed it!
245
0
  void* p = mi_arena_block_start(arena, bitmap_index);
246
0
  *memid = mi_memid_create_arena(arena->id, arena->exclusive, bitmap_index);
247
0
  memid->is_pinned = arena->memid.is_pinned;
248
249
  // none of the claimed blocks should be scheduled for a decommit
250
0
  if (arena->blocks_purge != NULL) {
251
    // this is thread safe as a potential purge only decommits parts that are not yet claimed as used (in `blocks_inuse`).
252
0
    _mi_bitmap_unclaim_across(arena->blocks_purge, arena->field_count, needed_bcount, bitmap_index);
253
0
  }
254
255
  // set the dirty bits (todo: no need for an atomic op here?)
256
0
  if (arena->memid.initially_zero && arena->blocks_dirty != NULL) {
257
0
    memid->initially_zero = _mi_bitmap_claim_across(arena->blocks_dirty, arena->field_count, needed_bcount, bitmap_index, NULL, NULL);
258
0
  }
259
260
  // set commit state
261
0
  if (arena->blocks_committed == NULL) {
262
    // always committed
263
0
    memid->initially_committed = true;
264
0
  }
265
0
  else if (commit) {
266
    // commit requested, but the range may not be committed as a whole: ensure it is committed now
267
0
    memid->initially_committed = true;
268
0
    const size_t commit_size = mi_arena_block_size(needed_bcount);
269
0
    bool any_uncommitted;
270
0
    size_t already_committed = 0;
271
0
    _mi_bitmap_claim_across(arena->blocks_committed, arena->field_count, needed_bcount, bitmap_index, &any_uncommitted, &already_committed);
272
0
    if (any_uncommitted) {
273
0
      mi_assert_internal(already_committed < needed_bcount);
274
0
      const size_t stat_commit_size = commit_size - mi_arena_block_size(already_committed);
275
0
      bool commit_zero = false;
276
0
      if (!_mi_os_commit_ex(p, commit_size, &commit_zero, stat_commit_size)) {
277
        // set all as uncommitted on commit failure
278
0
        _mi_bitmap_unclaim_across(arena->blocks_committed, arena->field_count, needed_bcount, bitmap_index);
279
0
        memid->initially_committed = false;
280
0
      }
281
0
      else {
282
0
        if (commit_zero) { memid->initially_zero = true; }
283
0
      }
284
0
    }
285
0
    else {
286
      // all are already committed: signal that we are reusing memory in case it was purged before
287
0
      _mi_os_reuse( p, commit_size );
288
0
    }
289
0
  }
290
0
  else {
291
    // no need to commit, but check if already fully committed
292
0
    size_t already_committed = 0;
293
0
    memid->initially_committed = _mi_bitmap_is_claimed_across(arena->blocks_committed, arena->field_count, needed_bcount, bitmap_index, &already_committed);
294
0
    if (!memid->initially_committed && already_committed > 0) {
295
      // partially committed: as it will be committed at some time, adjust the stats and pretend the range is fully uncommitted.
296
0
      mi_assert_internal(already_committed < needed_bcount);
297
0
      _mi_stat_decrease(&_mi_stats_main.committed, mi_arena_block_size(already_committed));
298
0
      _mi_bitmap_unclaim_across(arena->blocks_committed, arena->field_count, needed_bcount, bitmap_index);
299
0
    }
300
0
  }
301
302
0
  return p;
303
0
}
304
305
// allocate in a specific arena
306
static void* mi_arena_try_alloc_at_id(mi_arena_id_t arena_id, bool match_numa_node, int numa_node, size_t size, size_t alignment,
307
                                       bool commit, bool allow_large, mi_arena_id_t req_arena_id, mi_memid_t* memid )
308
0
{
309
0
  MI_UNUSED_RELEASE(alignment);
310
0
  mi_assert(alignment <= MI_SEGMENT_ALIGN);
311
0
  const size_t bcount = mi_block_count_of_size(size);
312
0
  const size_t arena_index = mi_arena_id_index(arena_id);
313
0
  mi_assert_internal(arena_index < mi_atomic_load_relaxed(&mi_arena_count));
314
0
  mi_assert_internal(size <= mi_arena_block_size(bcount));
315
316
  // Check arena suitability
317
0
  mi_arena_t* arena = mi_arena_from_index(arena_index);
318
0
  if (arena == NULL) return NULL;
319
0
  if (!allow_large && arena->is_large) return NULL;
320
0
  if (!mi_arena_id_is_suitable(arena->id, arena->exclusive, req_arena_id)) return NULL;
321
0
  if (req_arena_id == _mi_arena_id_none()) { // in not specific, check numa affinity
322
0
    const bool numa_suitable = (numa_node < 0 || arena->numa_node < 0 || arena->numa_node == numa_node);
323
0
    if (match_numa_node) { if (!numa_suitable) return NULL; }
324
0
                    else { if (numa_suitable) return NULL; }
325
0
  }
326
327
  // try to allocate
328
0
  void* p = mi_arena_try_alloc_at(arena, arena_index, bcount, commit, memid);
329
0
  mi_assert_internal(p == NULL || _mi_is_aligned(p, alignment));
330
0
  return p;
331
0
}
332
333
334
// allocate from an arena with fallback to the OS
335
static mi_decl_noinline void* mi_arena_try_alloc(int numa_node, size_t size, size_t alignment,
336
                                                  bool commit, bool allow_large,
337
                                                  mi_arena_id_t req_arena_id, mi_memid_t* memid )
338
0
{
339
0
  MI_UNUSED(alignment);
340
0
  mi_assert_internal(alignment <= MI_SEGMENT_ALIGN);
341
0
  const size_t max_arena = mi_atomic_load_relaxed(&mi_arena_count);
342
0
  if mi_likely(max_arena == 0) return NULL;
343
344
0
  if (req_arena_id != _mi_arena_id_none()) {
345
    // try a specific arena if requested
346
0
    if (mi_arena_id_index(req_arena_id) < max_arena) {
347
0
      void* p = mi_arena_try_alloc_at_id(req_arena_id, true, numa_node, size, alignment, commit, allow_large, req_arena_id, memid);
348
0
      if (p != NULL) return p;
349
0
    }
350
0
  }
351
0
  else {
352
    // try numa affine allocation
353
0
    for (size_t i = 0; i < max_arena; i++) {
354
0
      void* p = mi_arena_try_alloc_at_id(mi_arena_id_create(i), true, numa_node, size, alignment, commit, allow_large, req_arena_id, memid);
355
0
      if (p != NULL) return p;
356
0
    }
357
358
    // try from another numa node instead..
359
0
    if (numa_node >= 0) {  // if numa_node was < 0 (no specific affinity requested), all arena's have been tried already
360
0
      for (size_t i = 0; i < max_arena; i++) {
361
0
        void* p = mi_arena_try_alloc_at_id(mi_arena_id_create(i), false /* only proceed if not numa local */, numa_node, size, alignment, commit, allow_large, req_arena_id, memid);
362
0
        if (p != NULL) return p;
363
0
      }
364
0
    }
365
0
  }
366
0
  return NULL;
367
0
}
368
369
// try to reserve a fresh arena space
370
static bool mi_arena_reserve(size_t req_size, bool allow_large, mi_arena_id_t *arena_id)
371
0
{
372
0
  if (_mi_preloading()) return false;  // use OS only while pre loading
373
374
0
  const size_t arena_count = mi_atomic_load_acquire(&mi_arena_count);
375
0
  if (arena_count > (MI_MAX_ARENAS - 4)) return false;
376
377
0
  size_t arena_reserve = mi_option_get_size(mi_option_arena_reserve);
378
0
  if (arena_reserve == 0) return false;
379
380
0
  if (!_mi_os_has_virtual_reserve()) {
381
0
    arena_reserve = arena_reserve/4;  // be conservative if virtual reserve is not supported (for WASM for example)
382
0
  }
383
0
  arena_reserve = _mi_align_up(arena_reserve, MI_ARENA_BLOCK_SIZE);
384
0
  arena_reserve = _mi_align_up(arena_reserve, MI_SEGMENT_SIZE);
385
0
  if (arena_count >= 8 && arena_count <= 128) {
386
    // scale up the arena sizes exponentially every 8 entries (128 entries get to 589TiB)
387
0
    const size_t multiplier = (size_t)1 << _mi_clamp(arena_count/8, 0, 16 );
388
0
    size_t reserve = 0;
389
0
    if (!mi_mul_overflow(multiplier, arena_reserve, &reserve)) {
390
0
      arena_reserve = reserve;
391
0
    }
392
0
  }
393
0
  if (arena_reserve < req_size) return false;  // should be able to at least handle the current allocation size
394
395
  // commit eagerly?
396
0
  bool arena_commit = false;
397
0
  if (mi_option_get(mi_option_arena_eager_commit) == 2)      { arena_commit = _mi_os_has_overcommit() || mi_option_is_enabled(mi_option_allow_large_os_pages); }
398
0
  else if (mi_option_get(mi_option_arena_eager_commit) == 1) { arena_commit = true; }
399
400
0
  return (mi_reserve_os_memory_ex(arena_reserve, arena_commit, allow_large, false /* exclusive? */, arena_id) == 0);
401
0
}
402
403
404
void* _mi_arena_alloc_aligned(size_t size, size_t alignment, size_t align_offset, bool commit, bool allow_large,
405
                              mi_arena_id_t req_arena_id, mi_memid_t* memid)
406
0
{
407
0
  mi_assert_internal(memid != NULL);
408
0
  mi_assert_internal(size > 0);
409
0
  *memid = _mi_memid_none();
410
411
0
  const int numa_node = _mi_os_numa_node(); // current numa node
412
413
  // try to allocate in an arena if the alignment is small enough and the object is not too small (as for heap meta data)
414
0
  if (!mi_option_is_enabled(mi_option_disallow_arena_alloc)) {  // is arena allocation allowed?
415
0
    if (size >= MI_ARENA_MIN_OBJ_SIZE && alignment <= MI_SEGMENT_ALIGN && align_offset == 0)
416
0
    {
417
0
      void* p = mi_arena_try_alloc(numa_node, size, alignment, commit, allow_large, req_arena_id, memid);
418
0
      if (p != NULL) return p;
419
420
      // otherwise, try to first eagerly reserve a new arena
421
0
      if (req_arena_id == _mi_arena_id_none()) {
422
0
        mi_arena_id_t arena_id = 0;
423
0
        if (mi_arena_reserve(size, allow_large, &arena_id)) {
424
          // and try allocate in there
425
0
          mi_assert_internal(req_arena_id == _mi_arena_id_none());
426
0
          p = mi_arena_try_alloc_at_id(arena_id, true, numa_node, size, alignment, commit, allow_large, req_arena_id, memid);
427
0
          if (p != NULL) return p;
428
0
        }
429
0
      }
430
0
    }
431
0
  }
432
433
  // if we cannot use OS allocation, return NULL
434
0
  if (mi_option_is_enabled(mi_option_disallow_os_alloc) || req_arena_id != _mi_arena_id_none()) {
435
0
    errno = ENOMEM;
436
0
    return NULL;
437
0
  }
438
439
  // finally, fall back to the OS
440
0
  if (align_offset > 0) {
441
0
    return _mi_os_alloc_aligned_at_offset(size, alignment, align_offset, commit, allow_large, memid);
442
0
  }
443
0
  else {
444
0
    return _mi_os_alloc_aligned(size, alignment, commit, allow_large, memid);
445
0
  }
446
0
}
447
448
void* _mi_arena_alloc(size_t size, bool commit, bool allow_large, mi_arena_id_t req_arena_id, mi_memid_t* memid)
449
0
{
450
0
  return _mi_arena_alloc_aligned(size, MI_ARENA_BLOCK_SIZE, 0, commit, allow_large, req_arena_id, memid);
451
0
}
452
453
454
0
void* mi_arena_area(mi_arena_id_t arena_id, size_t* size) {
455
0
  if (size != NULL) *size = 0;
456
0
  size_t arena_index = mi_arena_id_index(arena_id);
457
0
  if (arena_index >= MI_MAX_ARENAS) return NULL;
458
0
  mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &mi_arenas[arena_index]);
459
0
  if (arena == NULL) return NULL;
460
0
  if (size != NULL) { *size = mi_arena_block_size(arena->block_count); }
461
0
  return arena->start;
462
0
}
463
464
465
/* -----------------------------------------------------------
466
  Arena purge
467
----------------------------------------------------------- */
468
469
0
static long mi_arena_purge_delay(void) {
470
  // <0 = no purging allowed, 0=immediate purging, >0=milli-second delay
471
0
  return (mi_option_get(mi_option_purge_delay) * mi_option_get(mi_option_arena_purge_mult));
472
0
}
473
474
// reset or decommit in an arena and update the committed/decommit bitmaps
475
// assumes we own the area (i.e. blocks_in_use is claimed by us)
476
0
static void mi_arena_purge(mi_arena_t* arena, size_t bitmap_idx, size_t blocks) {
477
0
  mi_assert_internal(arena->blocks_committed != NULL);
478
0
  mi_assert_internal(arena->blocks_purge != NULL);
479
0
  mi_assert_internal(!arena->memid.is_pinned);
480
0
  const size_t size = mi_arena_block_size(blocks);
481
0
  void* const p = mi_arena_block_start(arena, bitmap_idx);
482
0
  bool needs_recommit;
483
0
  size_t already_committed = 0;
484
0
  if (_mi_bitmap_is_claimed_across(arena->blocks_committed, arena->field_count, blocks, bitmap_idx, &already_committed)) {
485
    // all blocks are committed, we can purge freely
486
0
    mi_assert_internal(already_committed == blocks);
487
0
    needs_recommit = _mi_os_purge(p, size);
488
0
  }
489
0
  else {
490
    // some blocks are not committed -- this can happen when a partially committed block is freed
491
    // in `_mi_arena_free` and it is conservatively marked as uncommitted but still scheduled for a purge
492
    // we need to ensure we do not try to reset (as that may be invalid for uncommitted memory).
493
0
    mi_assert_internal(already_committed < blocks);
494
0
    mi_assert_internal(mi_option_is_enabled(mi_option_purge_decommits));
495
0
    needs_recommit = _mi_os_purge_ex(p, size, false /* allow reset? */, mi_arena_block_size(already_committed));
496
0
  }
497
498
  // clear the purged blocks
499
0
  _mi_bitmap_unclaim_across(arena->blocks_purge, arena->field_count, blocks, bitmap_idx);
500
  // update committed bitmap
501
0
  if (needs_recommit) {
502
0
    _mi_bitmap_unclaim_across(arena->blocks_committed, arena->field_count, blocks, bitmap_idx);
503
0
  }
504
0
}
505
506
// Schedule a purge. This is usually delayed to avoid repeated decommit/commit calls.
507
// Note: assumes we (still) own the area as we may purge immediately
508
0
static void mi_arena_schedule_purge(mi_arena_t* arena, size_t bitmap_idx, size_t blocks) {
509
0
  mi_assert_internal(arena->blocks_purge != NULL);
510
0
  const long delay = mi_arena_purge_delay();
511
0
  if (delay < 0) return;  // is purging allowed at all?
512
513
0
  if (_mi_preloading() || delay == 0) {
514
    // decommit directly
515
0
    mi_arena_purge(arena, bitmap_idx, blocks);
516
0
  }
517
0
  else {
518
    // schedule purge
519
0
    const mi_msecs_t expire = _mi_clock_now() + delay;
520
0
    mi_msecs_t expire0 = 0;
521
0
    if (mi_atomic_casi64_strong_acq_rel(&arena->purge_expire, &expire0, expire)) {
522
      // expiration was not yet set
523
      // maybe set the global arenas expire as well (if it wasn't set already)
524
0
      mi_atomic_casi64_strong_acq_rel(&mi_arenas_purge_expire, &expire0, expire);
525
0
    }
526
0
    else {
527
      // already an expiration was set
528
0
    }
529
0
    _mi_bitmap_claim_across(arena->blocks_purge, arena->field_count, blocks, bitmap_idx, NULL, NULL);
530
0
  }
531
0
}
532
533
// purge a range of blocks
534
// return true if the full range was purged.
535
// assumes we own the area (i.e. blocks_in_use is claimed by us)
536
0
static bool mi_arena_purge_range(mi_arena_t* arena, size_t idx, size_t startidx, size_t bitlen, size_t purge) {
537
0
  const size_t endidx = startidx + bitlen;
538
0
  size_t bitidx = startidx;
539
0
  bool all_purged = false;
540
0
  while (bitidx < endidx) {
541
    // count consecutive ones in the purge mask
542
0
    size_t count = 0;
543
0
    while (bitidx + count < endidx && (purge & ((size_t)1 << (bitidx + count))) != 0) {
544
0
      count++;
545
0
    }
546
0
    if (count > 0) {
547
      // found range to be purged
548
0
      const mi_bitmap_index_t range_idx = mi_bitmap_index_create(idx, bitidx);
549
0
      mi_arena_purge(arena, range_idx, count);
550
0
      if (count == bitlen) {
551
0
        all_purged = true;
552
0
      }
553
0
    }
554
0
    bitidx += (count+1); // +1 to skip the zero bit (or end)
555
0
  }
556
0
  return all_purged;
557
0
}
558
559
// returns
560
// -1 = nothing was purged
561
// 0  = nothing was purged yet because have not yet reached the expire time
562
// 1  = some pages in the arena were purged
563
static int mi_arena_try_purge(mi_arena_t* arena, mi_msecs_t now, bool force)
564
0
{
565
  // check pre-conditions
566
0
  if (arena->memid.is_pinned) return -1;
567
568
  // expired yet?
569
0
  mi_msecs_t expire = mi_atomic_loadi64_relaxed(&arena->purge_expire);
570
0
  if (!force) {
571
0
    if (expire == 0)  return -1;
572
0
    if (expire > now) return 0;
573
0
  }
574
575
  // reset expire (if not already set concurrently)
576
0
  mi_atomic_casi64_strong_acq_rel(&arena->purge_expire, &expire, (mi_msecs_t)0);
577
0
  _mi_stat_counter_increase(&_mi_stats_main.arena_purges, 1);
578
579
  // potential purges scheduled, walk through the bitmap
580
0
  bool any_purged = false;
581
0
  bool full_purge = true;
582
0
  for (size_t i = 0; i < arena->field_count; i++) {
583
0
    size_t purge = mi_atomic_load_relaxed(&arena->blocks_purge[i]);
584
0
    if (purge != 0) {
585
0
      size_t bitidx = 0;
586
0
      while (bitidx < MI_BITMAP_FIELD_BITS) {
587
        // find consecutive range of ones in the purge mask
588
0
        size_t bitlen = 0;
589
0
        while (bitidx + bitlen < MI_BITMAP_FIELD_BITS && (purge & ((size_t)1 << (bitidx + bitlen))) != 0) {
590
0
          bitlen++;
591
0
        }
592
        // temporarily claim the purge range as "in-use" to be thread-safe with allocation
593
        // try to claim the longest range of corresponding in_use bits
594
0
        const mi_bitmap_index_t bitmap_index = mi_bitmap_index_create(i, bitidx);
595
0
        while( bitlen > 0 ) {
596
0
          if (_mi_bitmap_try_claim(arena->blocks_inuse, arena->field_count, bitlen, bitmap_index)) {
597
0
            break;
598
0
          }
599
0
          bitlen--;
600
0
        }
601
        // actual claimed bits at `in_use`
602
0
        if (bitlen > 0) {
603
          // read purge again now that we have the in_use bits
604
0
          purge = mi_atomic_load_acquire(&arena->blocks_purge[i]);
605
0
          if (!mi_arena_purge_range(arena, i, bitidx, bitlen, purge)) {
606
0
            full_purge = false;
607
0
          }
608
0
          any_purged = true;
609
          // release the claimed `in_use` bits again
610
0
          _mi_bitmap_unclaim(arena->blocks_inuse, arena->field_count, bitlen, bitmap_index);
611
0
        }
612
0
        bitidx += (bitlen+1);  // +1 to skip the zero (or end)
613
0
      } // while bitidx
614
0
    } // purge != 0
615
0
  }
616
  // if not fully purged, make sure to purge again in the future
617
0
  if (!full_purge) {
618
0
    const long delay = mi_arena_purge_delay();
619
0
    mi_msecs_t expected = 0;
620
0
    mi_atomic_casi64_strong_acq_rel(&arena->purge_expire,&expected,_mi_clock_now() + delay);
621
0
  }
622
0
  return (any_purged ? 1 : -1);
623
0
}
624
625
static void mi_arenas_try_purge( bool force, bool visit_all )
626
0
{
627
0
  if (_mi_preloading() || mi_arena_purge_delay() <= 0) return;  // nothing will be scheduled
628
629
  // check if any arena needs purging?
630
0
  const mi_msecs_t now = _mi_clock_now();
631
0
  mi_msecs_t arenas_expire = mi_atomic_loadi64_acquire(&mi_arenas_purge_expire);
632
0
  if (!force && (arenas_expire == 0 || arenas_expire > now)) return;
633
634
0
  const size_t max_arena = mi_atomic_load_acquire(&mi_arena_count);
635
0
  if (max_arena == 0) return;
636
637
  // allow only one thread to purge at a time
638
0
  static mi_atomic_guard_t purge_guard;
639
0
  mi_atomic_guard(&purge_guard)
640
0
  {
641
    // increase global expire: at most one purge per delay cycle
642
0
    mi_atomic_storei64_release(&mi_arenas_purge_expire, now + mi_arena_purge_delay());
643
0
    size_t max_purge_count = (visit_all ? max_arena : 2);
644
0
    bool all_visited = true;
645
0
    bool any_purged = false;
646
0
    for (size_t i = 0; i < max_arena; i++) {
647
0
      mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &mi_arenas[i]);
648
0
      if (arena != NULL) {
649
0
        int purged = mi_arena_try_purge(arena, now, force);
650
0
        if (purged >= 0) {    // purged, or not yet the expire-time reached
651
0
          any_purged = true;
652
0
          if (purged >= 1) {  // purged at least one page
653
0
            if (max_purge_count <= 1) {
654
0
              all_visited = false;
655
0
              break;
656
0
            }
657
0
            max_purge_count--;
658
0
          }
659
0
        }
660
0
      }
661
0
    }
662
0
    if (all_visited && !any_purged) {
663
      // all arena's were visited and nothing needed to be purged: reset global expire
664
0
      mi_atomic_storei64_release(&mi_arenas_purge_expire, (mi_msecs_t)0);
665
0
    }
666
0
  }
667
0
}
668
669
670
/* -----------------------------------------------------------
671
  Arena free
672
----------------------------------------------------------- */
673
674
0
void _mi_arena_free(void* p, size_t size, size_t committed_size, mi_memid_t memid) {
675
0
  mi_assert_internal(size > 0);
676
0
  mi_assert_internal(committed_size <= size);
677
0
  if (p==NULL) return;
678
0
  if (size==0) return;
679
0
  const bool all_committed = (committed_size == size);
680
0
  const size_t decommitted_size = (committed_size <= size ? size - committed_size : 0);
681
682
  // need to set all memory to undefined as some parts may still be marked as no_access (like padding etc.)
683
0
  mi_track_mem_undefined(p,size);
684
685
0
  if (mi_memkind_is_os(memid.memkind)) {
686
    // was a direct OS allocation, pass through
687
0
    if (!all_committed && decommitted_size > 0) {
688
      // if partially committed, adjust the committed stats (as `_mi_os_free` will decrease commit by the full size)
689
0
      _mi_stat_increase(&_mi_stats_main.committed, decommitted_size);
690
0
    }
691
0
    _mi_os_free(p, size, memid);
692
0
  }
693
0
  else if (memid.memkind == MI_MEM_ARENA) {
694
    // allocated in an arena
695
0
    size_t arena_idx;
696
0
    size_t bitmap_idx;
697
0
    mi_arena_memid_indices(memid, &arena_idx, &bitmap_idx);
698
0
    mi_assert_internal(arena_idx < MI_MAX_ARENAS);
699
0
    mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t,&mi_arenas[arena_idx]);
700
0
    mi_assert_internal(arena != NULL);
701
0
    const size_t blocks = mi_block_count_of_size(size);
702
703
    // checks
704
0
    if (arena == NULL) {
705
0
      _mi_error_message(EINVAL, "trying to free from an invalid arena: %p, size %zu, memkind: 0x%x\n", p, size, memid.memkind);
706
0
      return;
707
0
    }
708
0
    mi_assert_internal(arena->field_count > mi_bitmap_index_field(bitmap_idx));
709
0
    if (arena->field_count <= mi_bitmap_index_field(bitmap_idx)) {
710
0
      _mi_error_message(EINVAL, "trying to free from an invalid arena block: %p, size %zu, memid: 0x%x\n", p, size, memid.memkind);
711
0
      return;
712
0
    }
713
714
    // potentially decommit
715
0
    if (arena->memid.is_pinned || arena->blocks_committed == NULL) {
716
0
      mi_assert_internal(all_committed);
717
0
    }
718
0
    else {
719
0
      mi_assert_internal(arena->blocks_committed != NULL);
720
0
      mi_assert_internal(arena->blocks_purge != NULL);
721
722
0
      if (!all_committed) {
723
        // mark the entire range as no longer committed (so we will recommit the full range when re-using)
724
0
        _mi_bitmap_unclaim_across(arena->blocks_committed, arena->field_count, blocks, bitmap_idx);
725
0
        mi_track_mem_noaccess(p,size);
726
        //if (committed_size > 0) {
727
          // if partially committed, adjust the committed stats (is it will be recommitted when re-using)
728
          // in the delayed purge, we do no longer decrease the commit if the range is not marked entirely as committed.
729
0
          _mi_stat_decrease(&_mi_stats_main.committed, committed_size);
730
        //}
731
        // note: if not all committed, it may be that the purge will reset/decommit the entire range
732
        // that contains already decommitted parts. Since purge consistently uses reset or decommit that
733
        // works (as we should never reset decommitted parts).
734
0
      }
735
      // (delay) purge the entire range
736
0
      mi_arena_schedule_purge(arena, bitmap_idx, blocks);
737
0
    }
738
739
    // and make it available to others again
740
0
    bool all_inuse = _mi_bitmap_unclaim_across(arena->blocks_inuse, arena->field_count, blocks, bitmap_idx);
741
0
    if (!all_inuse) {
742
0
      _mi_error_message(EAGAIN, "trying to free an already freed arena block: %p, size %zu\n", p, size);
743
0
      return;
744
0
    };
745
0
  }
746
0
  else {
747
    // arena was none, external, or static; nothing to do
748
0
    mi_assert_internal(memid.memkind < MI_MEM_OS);
749
0
  }
750
751
  // purge expired decommits
752
0
  mi_arenas_try_purge(false, false);
753
0
}
754
755
// destroy owned arenas; this is unsafe and should only be done using `mi_option_destroy_on_exit`
756
// for dynamic libraries that are unloaded and need to release all their allocated memory.
757
0
static void mi_arenas_unsafe_destroy(void) {
758
0
  const size_t max_arena = mi_atomic_load_relaxed(&mi_arena_count);
759
0
  size_t new_max_arena = 0;
760
0
  for (size_t i = 0; i < max_arena; i++) {
761
0
    mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &mi_arenas[i]);
762
0
    if (arena != NULL) {
763
0
      mi_lock_done(&arena->abandoned_visit_lock);
764
0
      if (arena->start != NULL && mi_memkind_is_os(arena->memid.memkind)) {
765
0
        mi_atomic_store_ptr_release(mi_arena_t, &mi_arenas[i], NULL);
766
0
        _mi_os_free(arena->start, mi_arena_size(arena), arena->memid);
767
0
      }
768
0
      else {
769
0
        new_max_arena = i;
770
0
      }
771
0
      _mi_arena_meta_free(arena, arena->meta_memid, arena->meta_size);
772
0
    }
773
0
  }
774
775
  // try to lower the max arena.
776
0
  size_t expected = max_arena;
777
0
  mi_atomic_cas_strong_acq_rel(&mi_arena_count, &expected, new_max_arena);
778
0
}
779
780
// Purge the arenas; if `force_purge` is true, amenable parts are purged even if not yet expired
781
0
void _mi_arenas_collect(bool force_purge) {
782
0
  mi_arenas_try_purge(force_purge, force_purge /* visit all? */);
783
0
}
784
785
// destroy owned arenas; this is unsafe and should only be done using `mi_option_destroy_on_exit`
786
// for dynamic libraries that are unloaded and need to release all their allocated memory.
787
0
void _mi_arena_unsafe_destroy_all(void) {
788
0
  mi_arenas_unsafe_destroy();
789
0
  _mi_arenas_collect(true /* force purge */);  // purge non-owned arenas
790
0
}
791
792
// Is a pointer inside any of our arenas?
793
0
bool _mi_arena_contains(const void* p) {
794
0
  const size_t max_arena = mi_atomic_load_relaxed(&mi_arena_count);
795
0
  for (size_t i = 0; i < max_arena; i++) {
796
0
    mi_arena_t* arena = mi_atomic_load_ptr_relaxed(mi_arena_t, &mi_arenas[i]);
797
0
    if (arena != NULL && arena->start <= (const uint8_t*)p && arena->start + mi_arena_block_size(arena->block_count) > (const uint8_t*)p) {
798
0
      return true;
799
0
    }
800
0
  }
801
0
  return false;
802
0
}
803
804
/* -----------------------------------------------------------
805
  Add an arena.
806
----------------------------------------------------------- */
807
808
0
static bool mi_arena_add(mi_arena_t* arena, mi_arena_id_t* arena_id, mi_stats_t* stats) {
809
0
  mi_assert_internal(arena != NULL);
810
0
  mi_assert_internal((uintptr_t)mi_atomic_load_ptr_relaxed(uint8_t,&arena->start) % MI_SEGMENT_ALIGN == 0);
811
0
  mi_assert_internal(arena->block_count > 0);
812
0
  if (arena_id != NULL) { *arena_id = -1; }
813
814
0
  size_t i = mi_atomic_load_relaxed(&mi_arena_count);
815
0
  while (i < MI_MAX_ARENAS) {
816
0
    if (mi_atomic_cas_strong_acq_rel(&mi_arena_count, &i, i+1)) {
817
0
      _mi_stat_counter_increase(&stats->arena_count, 1);
818
0
      arena->id = mi_arena_id_create(i);
819
0
      mi_atomic_store_ptr_release(mi_arena_t, &mi_arenas[i], arena);
820
0
      if (arena_id != NULL) { *arena_id = arena->id; }
821
0
      return true;
822
0
    }
823
0
  }
824
825
0
  return false;
826
0
}
827
828
static bool mi_manage_os_memory_ex2(void* start, size_t size, bool is_large, int numa_node, bool exclusive, mi_memid_t memid, mi_arena_id_t* arena_id) mi_attr_noexcept
829
0
{
830
0
  if (arena_id != NULL) *arena_id = _mi_arena_id_none();
831
0
  if (size < MI_ARENA_BLOCK_SIZE) {
832
0
    _mi_warning_message("the arena size is too small (memory at %p with size %zu)\n", start, size);
833
0
    return false;
834
0
  }
835
0
  if (size > MI_MAX_ALLOC_SIZE) {
836
0
    _mi_error_message(EOVERFLOW, "the arena size is too large (memory at %p with size %zu)\n", start, size);
837
0
    return false;
838
0
  }
839
0
  if (is_large) {
840
0
    mi_assert_internal(memid.initially_committed && memid.is_pinned);
841
0
  }
842
0
  if (!_mi_is_aligned(start, MI_SEGMENT_ALIGN)) {
843
0
    void* const aligned_start = _mi_align_up_ptr(start, MI_SEGMENT_ALIGN);
844
0
    const size_t diff = (uint8_t*)aligned_start - (uint8_t*)start;
845
0
    if (diff >= size || (size - diff) < MI_ARENA_BLOCK_SIZE) {
846
0
      _mi_warning_message("after alignment, the size of the arena becomes too small (memory at %p with size %zu)\n", start, size);
847
0
      return false;
848
0
    }
849
0
    start = aligned_start;
850
0
    size = size - diff;
851
0
  }
852
853
0
  const size_t bcount = size / MI_ARENA_BLOCK_SIZE;
854
0
  const size_t fields = _mi_divide_up(bcount, MI_BITMAP_FIELD_BITS);
855
0
  const size_t bitmaps = (memid.is_pinned ? 3 : 5);
856
0
  const size_t asize  = sizeof(mi_arena_t) + (bitmaps*fields*sizeof(mi_bitmap_field_t));
857
0
  mi_memid_t meta_memid;
858
0
  mi_arena_t* arena   = (mi_arena_t*)_mi_arena_meta_zalloc(asize, &meta_memid);
859
0
  if (arena == NULL) return false;
860
861
  // already zero'd due to zalloc
862
  // _mi_memzero(arena, asize);
863
0
  arena->id = _mi_arena_id_none();
864
0
  arena->memid = memid;
865
0
  arena->exclusive = exclusive;
866
0
  arena->meta_size = asize;
867
0
  arena->meta_memid = meta_memid;
868
0
  arena->block_count = bcount;
869
0
  arena->field_count = fields;
870
0
  arena->start = (uint8_t*)start;
871
0
  arena->numa_node    = numa_node; // TODO: or get the current numa node if -1? (now it allows anyone to allocate on -1)
872
0
  arena->is_large     = is_large;
873
0
  arena->purge_expire = 0;
874
0
  arena->search_idx   = 0;
875
0
  mi_lock_init(&arena->abandoned_visit_lock);
876
  // consecutive bitmaps
877
0
  arena->blocks_dirty     = &arena->blocks_inuse[fields];     // just after inuse bitmap
878
0
  arena->blocks_abandoned = &arena->blocks_inuse[2 * fields]; // just after dirty bitmap
879
0
  arena->blocks_committed = (arena->memid.is_pinned ? NULL : &arena->blocks_inuse[3*fields]); // just after abandoned bitmap
880
0
  arena->blocks_purge     = (arena->memid.is_pinned ? NULL : &arena->blocks_inuse[4*fields]); // just after committed bitmap
881
  // initialize committed bitmap?
882
0
  if (arena->blocks_committed != NULL && arena->memid.initially_committed) {
883
0
    memset((void*)arena->blocks_committed, 0xFF, fields*sizeof(mi_bitmap_field_t)); // cast to void* to avoid atomic warning
884
0
  }
885
886
  // and claim leftover blocks if needed (so we never allocate there)
887
0
  ptrdiff_t post = (fields * MI_BITMAP_FIELD_BITS) - bcount;
888
0
  mi_assert_internal(post >= 0);
889
0
  if (post > 0) {
890
    // don't use leftover bits at the end
891
0
    mi_bitmap_index_t postidx = mi_bitmap_index_create(fields - 1, MI_BITMAP_FIELD_BITS - post);
892
0
    _mi_bitmap_claim(arena->blocks_inuse, fields, post, postidx, NULL);
893
0
  }
894
0
  return mi_arena_add(arena, arena_id, &_mi_stats_main);
895
896
0
}
897
898
0
bool mi_manage_os_memory_ex(void* start, size_t size, bool is_committed, bool is_large, bool is_zero, int numa_node, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept {
899
0
  mi_memid_t memid = _mi_memid_create(MI_MEM_EXTERNAL);
900
0
  memid.initially_committed = is_committed;
901
0
  memid.initially_zero = is_zero;
902
0
  memid.is_pinned = is_large;
903
0
  return mi_manage_os_memory_ex2(start,size,is_large,numa_node,exclusive,memid, arena_id);
904
0
}
905
906
// Reserve a range of regular OS memory
907
0
int mi_reserve_os_memory_ex(size_t size, bool commit, bool allow_large, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept {
908
0
  if (arena_id != NULL) *arena_id = _mi_arena_id_none();
909
0
  if (size < MI_MAX_ALLOC_SIZE) {
910
0
    size = _mi_align_up(size, MI_ARENA_BLOCK_SIZE); // at least one block
911
0
  }
912
0
  if (size > MI_MAX_ALLOC_SIZE) {
913
0
    _mi_error_message(EOVERFLOW, "memory reservation request is too large (size %zu)\n", size);
914
0
    return ENOMEM;
915
0
  }
916
0
  mi_memid_t memid;
917
0
  void* start = _mi_os_alloc_aligned(size, MI_SEGMENT_ALIGN, commit, allow_large, &memid);
918
0
  if (start == NULL) return ENOMEM;
919
0
  const bool is_large = memid.is_pinned; // todo: use separate is_large field?
920
0
  if (!mi_manage_os_memory_ex2(start, size, is_large, -1 /* numa node */, exclusive, memid, arena_id)) {
921
0
    _mi_os_free_ex(start, size, commit, memid);
922
0
    _mi_verbose_message("failed to reserve %zu KiB memory\n", _mi_divide_up(size, 1024));
923
0
    return ENOMEM;
924
0
  }
925
0
  _mi_verbose_message("reserved %zu KiB memory%s\n", _mi_divide_up(size, 1024), is_large ? " (in large os pages)" : "");
926
0
  return 0;
927
0
}
928
929
930
// Manage a range of regular OS memory
931
0
bool mi_manage_os_memory(void* start, size_t size, bool is_committed, bool is_large, bool is_zero, int numa_node) mi_attr_noexcept {
932
0
  return mi_manage_os_memory_ex(start, size, is_committed, is_large, is_zero, numa_node, false /* exclusive? */, NULL);
933
0
}
934
935
// Reserve a range of regular OS memory
936
0
int mi_reserve_os_memory(size_t size, bool commit, bool allow_large) mi_attr_noexcept {
937
0
  return mi_reserve_os_memory_ex(size, commit, allow_large, false, NULL);
938
0
}
939
940
941
/* -----------------------------------------------------------
942
  Debugging
943
----------------------------------------------------------- */
944
945
0
static size_t mi_debug_show_bitmap(const char* prefix, const char* header, size_t block_count, mi_bitmap_field_t* fields, size_t field_count ) {
946
0
  _mi_message("%s%s:\n", prefix, header);
947
0
  size_t bcount = 0;
948
0
  size_t inuse_count = 0;
949
0
  for (size_t i = 0; i < field_count; i++) {
950
0
    char buf[MI_BITMAP_FIELD_BITS + 1];
951
0
    uintptr_t field = mi_atomic_load_relaxed(&fields[i]);
952
0
    for (size_t bit = 0; bit < MI_BITMAP_FIELD_BITS; bit++, bcount++) {
953
0
      if (bcount < block_count) {
954
0
        bool inuse = ((((uintptr_t)1 << bit) & field) != 0);
955
0
        if (inuse) inuse_count++;
956
0
        buf[bit] = (inuse ? 'x' : '.');
957
0
      }
958
0
      else {
959
0
        buf[bit] = ' ';
960
0
      }
961
0
    }
962
0
    buf[MI_BITMAP_FIELD_BITS] = 0;
963
0
    _mi_message("%s  %s\n", prefix, buf);
964
0
  }
965
0
  _mi_message("%s  total ('x'): %zu\n", prefix, inuse_count);
966
0
  return inuse_count;
967
0
}
968
969
0
void mi_debug_show_arenas(void) mi_attr_noexcept {
970
0
  const bool show_inuse = true;
971
0
  size_t max_arenas = mi_atomic_load_relaxed(&mi_arena_count);
972
0
  size_t inuse_total = 0;
973
  //size_t abandoned_total = 0;
974
  //size_t purge_total = 0;
975
0
  for (size_t i = 0; i < max_arenas; i++) {
976
0
    mi_arena_t* arena = mi_atomic_load_ptr_relaxed(mi_arena_t, &mi_arenas[i]);
977
0
    if (arena == NULL) break;
978
0
    _mi_message("arena %zu: %zu blocks of size %zuMiB (in %zu fields) %s\n", i, arena->block_count, (size_t)(MI_ARENA_BLOCK_SIZE / MI_MiB), arena->field_count, (arena->memid.is_pinned ? ", pinned" : ""));
979
0
    if (show_inuse) {
980
0
      inuse_total += mi_debug_show_bitmap("  ", "inuse blocks", arena->block_count, arena->blocks_inuse, arena->field_count);
981
0
    }
982
0
    if (arena->blocks_committed != NULL) {
983
0
      mi_debug_show_bitmap("  ", "committed blocks", arena->block_count, arena->blocks_committed, arena->field_count);
984
0
    }
985
    //if (show_abandoned) {
986
    //  abandoned_total += mi_debug_show_bitmap("  ", "abandoned blocks", arena->block_count, arena->blocks_abandoned, arena->field_count);
987
    //}
988
    //if (show_purge && arena->blocks_purge != NULL) {
989
    //  purge_total += mi_debug_show_bitmap("  ", "purgeable blocks", arena->block_count, arena->blocks_purge, arena->field_count);
990
    //}
991
0
  }
992
0
  if (show_inuse)     _mi_message("total inuse blocks    : %zu\n", inuse_total);
993
  //if (show_abandoned) _mi_message("total abandoned blocks: %zu\n", abandoned_total);
994
  //if (show_purge)     _mi_message("total purgeable blocks: %zu\n", purge_total);
995
0
}
996
997
998
0
void mi_arenas_print(void) mi_attr_noexcept {
999
0
  mi_debug_show_arenas();
1000
0
}
1001
1002
1003
/* -----------------------------------------------------------
1004
  Reserve a huge page arena.
1005
----------------------------------------------------------- */
1006
// reserve at a specific numa node
1007
0
int mi_reserve_huge_os_pages_at_ex(size_t pages, int numa_node, size_t timeout_msecs, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept {
1008
0
  if (arena_id != NULL) *arena_id = -1;
1009
0
  if (pages==0) return 0;
1010
0
  if (numa_node < -1) numa_node = -1;
1011
0
  if (numa_node >= 0) numa_node = numa_node % _mi_os_numa_node_count();
1012
0
  size_t hsize = 0;
1013
0
  size_t pages_reserved = 0;
1014
0
  mi_memid_t memid;
1015
0
  void* p = _mi_os_alloc_huge_os_pages(pages, numa_node, timeout_msecs, &pages_reserved, &hsize, &memid);
1016
0
  if (p==NULL || pages_reserved==0) {
1017
0
    _mi_warning_message("failed to reserve %zu GiB huge pages\n", pages);
1018
0
    return ENOMEM;
1019
0
  }
1020
0
  _mi_verbose_message("numa node %i: reserved %zu GiB huge pages (of the %zu GiB requested)\n", numa_node, pages_reserved, pages);
1021
1022
0
  if (!mi_manage_os_memory_ex2(p, hsize, true, numa_node, exclusive, memid, arena_id)) {
1023
0
    _mi_os_free(p, hsize, memid);
1024
0
    return ENOMEM;
1025
0
  }
1026
0
  return 0;
1027
0
}
1028
1029
0
int mi_reserve_huge_os_pages_at(size_t pages, int numa_node, size_t timeout_msecs) mi_attr_noexcept {
1030
0
  return mi_reserve_huge_os_pages_at_ex(pages, numa_node, timeout_msecs, false, NULL);
1031
0
}
1032
1033
// reserve huge pages evenly among the given number of numa nodes (or use the available ones as detected)
1034
0
int mi_reserve_huge_os_pages_interleave(size_t pages, size_t numa_nodes, size_t timeout_msecs) mi_attr_noexcept {
1035
0
  if (pages == 0) return 0;
1036
1037
  // pages per numa node
1038
0
  int numa_count = (numa_nodes > 0 && numa_nodes <= INT_MAX ? (int)numa_nodes : _mi_os_numa_node_count());
1039
0
  if (numa_count == 0) numa_count = 1;
1040
0
  const size_t pages_per = pages / numa_count;
1041
0
  const size_t pages_mod = pages % numa_count;
1042
0
  const size_t timeout_per = (timeout_msecs==0 ? 0 : (timeout_msecs / numa_count) + 50);
1043
1044
  // reserve evenly among numa nodes
1045
0
  for (int numa_node = 0; numa_node < numa_count && pages > 0; numa_node++) {
1046
0
    size_t node_pages = pages_per;  // can be 0
1047
0
    if ((size_t)numa_node < pages_mod) node_pages++;
1048
0
    int err = mi_reserve_huge_os_pages_at(node_pages, numa_node, timeout_per);
1049
0
    if (err) return err;
1050
0
    if (pages < node_pages) {
1051
0
      pages = 0;
1052
0
    }
1053
0
    else {
1054
0
      pages -= node_pages;
1055
0
    }
1056
0
  }
1057
1058
0
  return 0;
1059
0
}
1060
1061
0
int mi_reserve_huge_os_pages(size_t pages, double max_secs, size_t* pages_reserved) mi_attr_noexcept {
1062
0
  MI_UNUSED(max_secs);
1063
0
  _mi_warning_message("mi_reserve_huge_os_pages is deprecated: use mi_reserve_huge_os_pages_interleave/at instead\n");
1064
0
  if (pages_reserved != NULL) *pages_reserved = 0;
1065
0
  int err = mi_reserve_huge_os_pages_interleave(pages, 0, (size_t)(max_secs * 1000.0));
1066
0
  if (err==0 && pages_reserved!=NULL) *pages_reserved = pages;
1067
0
  return err;
1068
0
}