bcmalloc 0.1.0

A scalable global allocator that reserves its memory up front, for long-lived, highly concurrent programs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! The `#[global_allocator]` front end.
//!
//! [`Bcmalloc`] is a `static` that creates its [`Region`] the first time anything allocates, and
//! gives every thread a [`Heap`](crate::Heap) of its own. After that a call looks like this.
//!
//! ```text
//!    alloc(layout)
//!         |
//!         v
//!    read this thread's heap from its slot (see the tls module)
//!         |
//!         +-- found ---> table lookup, then pop the hot list ... the fast path, no atomics
//!         |
//!         +-- empty ---> reserve the region if this is the first call, claim a heap,
//!                        bind it to the thread, and allocate from it
//! ```
//!
//! # Thread start-up and teardown
//!
//! A thread binds its heap on its first allocation or free, and a key destructor releases the
//! heap when the thread exits. Other destructors may still allocate or free after that one has
//! run. At that point the slot is empty and the thread is marked as gone, so it has no heap of its
//! own, as described next.
//!
//! # Threads without a heap
//!
//! The region has a few spare heaps past `max_heaps` that no thread binds. A thread that finds
//! every heap taken, or that gave its heap back at exit, borrows a spare for each allocation with
//! one compare-and-swap and gives it back when the call returns. Its frees go home through
//! [`Region::dealloc`], which needs no heap. Such a thread binds a heap of its own on its first
//! call after one is given back. The spares are shared, so these threads allocate more slowly than
//! threads with a heap, but they do not fail for want of one.
//!
//! # Failure
//!
//! A failed allocation returns null, and the standard library turns that into an abort. That
//! happens when the region is full or when the alignment is above
//! [`MAX_ALIGN`](crate::MAX_ALIGN).

use crate::{
    chunks::CHUNK_SHIFT,
    config::Config,
    heap::HeapData,
    region::{Entry, Error, Mapping, Region, Stats},
    size_class::{MAX_SMALL, MIN_ALIGN, TABLE_MAX},
    sync::{AtomicPtr, AtomicU64, AtomicUsize, Ordering},
    sys, tls,
};
use core::{
    alloc::{GlobalAlloc, Layout},
    ptr::{self, NonNull},
};

/// The smallest region the lazy start-up settles for when the OS refuses a bigger one.
const MIN_CAPACITY: usize = 256 << 20;

/// How many spare heaps the region has for threads without a heap of their own, per online CPU.
/// With one per CPU, the threads that run at once often found every spare held and had to yield,
/// and 64 threads on 32 CPUs allocated six times slower than with four.
const SPARE_HEAPS_PER_CPU: usize = 4;

/// The bounds on the number of spare heaps. Each costs as much address space as a heap slot, and
/// memory only once a thread uses it.
const MIN_SPARE_HEAPS: usize = 8;
const MAX_SPARE_HEAPS: usize = 1024;

/// Zeroed requests below this many bytes are cleared without asking whether the memory is fresh,
/// as [`HeapData::alloc_zeroed`] does.
const SMALL_ZEROED: usize = 1024;

/// Sets the calling thread's `errno` to `ENOMEM`, as C's allocation functions do when they fail.
fn set_out_of_memory() {
    // SAFETY: the location is the calling thread's errno, valid for as long as the thread lives.
    #[cfg(target_os = "linux")]
    unsafe {
        *libc::__errno_location() = libc::ENOMEM;
    }
    // SAFETY: as above.
    #[cfg(target_vendor = "apple")]
    unsafe {
        *libc::__error() = libc::ENOMEM;
    }
}

/// A global allocator that reserves its memory up front.
///
/// Declare one as the program's allocator and everything else follows.
///
/// ```
/// use bcmalloc::Bcmalloc;
///
/// #[global_allocator]
/// static GLOBAL: Bcmalloc = Bcmalloc::new();
///
/// let numbers: Vec<u64> = (0..1000).collect();
/// assert_eq!(numbers.iter().sum::<u64>(), 499_500);
/// ```
///
/// The region is reserved on first use with the default [`Config`]. Use [`Bcmalloc::with_config`]
/// to size it for the program. If the operating system refuses the reservation, the allocator
/// retries with half the capacity, down to 256 MiB.
///
/// ```
/// use bcmalloc::{Bcmalloc, Commit, Config};
///
/// #[global_allocator]
/// static GLOBAL: Bcmalloc =
///     Bcmalloc::with_config(Config::new().capacity(8 << 30).max_heaps(256).commit(Commit::Lazy));
///
/// let text = String::from("allocated from an 8 GiB region");
/// assert_eq!(GLOBAL.stats().unwrap().heaps_in_use, 1);
/// # drop(text);
/// ```
///
/// # As an `Allocator`
///
/// With the `allocator-api` feature, a `Bcmalloc` can also serve a single collection through
/// the standard library's [`Allocator`](core::alloc::Allocator) trait, whether or not it is the
/// global allocator.
///
/// ```
/// # #[cfg(feature = "allocator-api")] {
/// use bcmalloc::Bcmalloc;
///
/// static ALLOCATOR: Bcmalloc = Bcmalloc::new();
///
/// let mut numbers = Vec::new_in(&ALLOCATOR);
/// numbers.extend(0..1000_u32);
/// assert_eq!(numbers.iter().sum::<u32>(), 499_500);
///
/// let boxed = Box::new_in([7_u8; 100], &ALLOCATOR);
/// assert_eq!(boxed[99], 7);
/// # }
/// ```
///
/// A zero-sized request never reaches the allocator. A block is exactly as long as it was asked to
/// be, zeroed requests clear all of it, and a resize that changes the alignment moves the block.
#[derive(Debug)]
pub struct Bcmalloc {
    config: Config,
    region: AtomicPtr<Region<'static>>,
    /// The thread-specific key under which threads keep their heap, or `tls::NO_KEY`.
    key: AtomicUsize,
    directory: Directory,
}

/// Where the chunk map entry of a block is, copied out of the region.
///
/// A free reads the entry of its block's chunk. Found through the thread's heap, that load waits
/// for the thread-local load and then for the heap's fields. Kept in the allocator, which is a
/// `static`, the loads it needs depend on nothing and run alongside the thread-local one, which
/// takes a step off the longest chain of loads in every free.
///
/// Every thread that binds a heap writes the fields first, all from the one published region, so
/// the values never differ and a thread with a heap always sees them.
#[derive(Debug)]
struct Directory {
    /// The address of the region's first chunk.
    base: AtomicUsize,
    /// The length of the managed memory in bytes.
    span: AtomicUsize,
    /// The region's chunk map.
    map: AtomicPtr<AtomicU64>,
}

impl Directory {
    const fn new() -> Self {
        Self {
            base: AtomicUsize::new(0),
            span: AtomicUsize::new(0),
            map: AtomicPtr::new(ptr::null_mut()),
        }
    }

    /// Records where `region`'s chunks and chunk map are.
    fn publish(&self, region: &Region<'_>) {
        self.base.store(region.chunk_ptr(0).addr(), Ordering::Relaxed);
        self.span.store(region.span(), Ordering::Relaxed);
        self.map.store(region.map_ptr().cast_mut(), Ordering::Relaxed);
    }

    /// The chunk map entry of the block at `ptr`.
    ///
    /// # Safety
    ///
    /// The calling thread must have published the directory, and `ptr` must lie in the region.
    #[inline(always)]
    unsafe fn entry(&self, ptr: *const u8) -> Entry {
        // SAFETY: forwarded.
        unsafe { self.entry_at(ptr.addr() - self.base.load(Ordering::Relaxed)) }
    }

    /// The chunk map entry of the block at `ptr`, or `None` if `ptr` is not in the region.
    ///
    /// # Safety
    ///
    /// The calling thread must have published the directory.
    #[inline(always)]
    unsafe fn entry_in_region(&self, ptr: *const u8) -> Option<Entry> {
        let offset = ptr.addr().wrapping_sub(self.base.load(Ordering::Relaxed));
        // SAFETY: the offset shows that the pointer lies in the region.
        (offset < self.span.load(Ordering::Relaxed)).then(|| unsafe { self.entry_at(offset) })
    }

    /// The chunk map entry of the chunk `offset` bytes into the managed memory.
    ///
    /// # Safety
    ///
    /// As for [`entry`](Self::entry), and the offset must be inside the managed memory.
    #[inline(always)]
    unsafe fn entry_at(&self, offset: usize) -> Entry {
        // SAFETY: the offset is inside the region, whose map has an entry for every chunk.
        let slot = unsafe { &*self.map.load(Ordering::Relaxed).add(offset >> CHUNK_SHIFT) };
        Entry(slot.load(Ordering::Relaxed))
    }
}

impl Bcmalloc {
    /// An allocator with the default [`Config`].
    pub const fn new() -> Self {
        Self::with_config(Config::new())
    }

    /// An allocator with the given configuration.
    pub const fn with_config(config: Config) -> Self {
        Self {
            config,
            region: AtomicPtr::new(ptr::null_mut()),
            key: AtomicUsize::new(tls::NO_KEY),
            directory: Directory::new(),
        }
    }

    /// The configuration the region was or will be created with.
    pub const fn config(&self) -> &Config {
        &self.config
    }

    /// A snapshot of the region, or `None` if nothing has been allocated yet.
    pub fn stats(&self) -> Option<Stats> {
        self.existing().map(Region::stats)
    }

    /// A snapshot of the allocator's metrics, or `None` if nothing has been allocated yet. See
    /// [`Region::metrics`].
    #[cfg(feature = "metrics")]
    pub fn metrics(&self) -> Option<crate::Metrics> {
        self.existing().map(Region::metrics)
    }

    /// Returns the memory of idle heaps and free chunks to the operating system. See
    /// [`Region::trim`] for what that costs.
    pub fn trim(&self) {
        if let Some(region) = self.existing() {
            region.trim();
        }
    }

    /// The layout of the whole block that `ptr` points to: its full usable size, and an alignment
    /// of
    /// 16. It is None if `ptr` is not in this allocator's region.
    ///
    /// The answer is only meaningful when `ptr` is the start of a live block from this allocator.
    /// It is what a C interface needs to implement `free` and `malloc_usable_size`, which get no
    /// size, and the layout it returns is a valid one to free or reallocate the block with.
    pub fn block_layout(&self, ptr: NonNull<u8>) -> Option<Layout> {
        self.existing()?.block_layout(ptr.as_ptr())
    }

    /// Allocates `size` bytes aligned to 16, as C's `malloc` does, or returns null and sets `errno`
    /// to `ENOMEM` if there is no room. A size of zero gets a block of its own.
    #[inline]
    pub fn malloc(&self, size: usize) -> *mut u8 {
        if size <= TABLE_MAX &&
            let Some(data) = self.thread_heap() &&
            let Some(block) = data.pop_table(size, true)
        {
            return block;
        }
        self.malloc_slow(size)
    }

    /// Allocates what [`malloc`](Self::malloc) does not take off a bin: a size the table does not
    /// cover, an empty bin, or a thread without a heap. Failure sets `errno` here, so that the
    /// fast path ends in a jump to this function and needs no stack frame of its own.
    #[cold]
    #[inline(never)]
    fn malloc_slow(&self, size: usize) -> *mut u8 {
        let block = match self.thread_heap() {
            // SAFETY: a thread's bound heap is claimed by that thread alone, and the table covers
            // the size.
            Some(data) if size <= TABLE_MAX => unsafe { data.alloc_table(size, true) },
            _ => {
                Layout::from_size_align(size.max(1), MIN_ALIGN).map_or(ptr::null_mut(), |layout| {
                    // SAFETY: the layout has a non-zero size.
                    unsafe { GlobalAlloc::alloc(self, layout) }
                })
            }
        };
        if block.is_null() {
            set_out_of_memory();
        }
        block
    }

    /// Allocates zeroed memory for `count` items of `size` bytes, aligned to 16, as C's `calloc`
    /// does, or returns null and sets `errno` to `ENOMEM` if there is no room or the size
    /// overflows.
    #[inline]
    pub fn calloc(&self, count: usize, size: usize) -> *mut u8 {
        // Small blocks are cleared without asking whether they are fresh, which costs less than
        // finding out, so they come straight off a bin.
        if let Some(bytes) = count.checked_mul(size) &&
            bytes < SMALL_ZEROED &&
            let Some(data) = self.thread_heap() &&
            let Some(block) = data.pop_table(bytes, true)
        {
            // SAFETY: the block holds at least `bytes` bytes and is ours.
            unsafe { block.write_bytes(0, bytes) };
            return block;
        }
        self.calloc_slow(count, size)
    }

    /// Allocates what [`calloc`](Self::calloc) does not take off a bin, and sets `errno` when it
    /// fails.
    #[cold]
    #[inline(never)]
    fn calloc_slow(&self, count: usize, size: usize) -> *mut u8 {
        let layout = count
            .checked_mul(size)
            .and_then(|bytes| Layout::from_size_align(bytes.max(1), MIN_ALIGN).ok());
        // SAFETY: the layout has a non-zero size.
        let block = layout
            .map_or(ptr::null_mut(), |layout| unsafe { GlobalAlloc::alloc_zeroed(self, layout) });
        if block.is_null() {
            set_out_of_memory();
        }
        block
    }

    /// How many bytes the block that `ptr` points to holds, as C's `malloc_usable_size` tells, or
    /// `None` if `ptr` is not in this allocator's region. The answer is only meaningful when `ptr`
    /// is the start of a live block from this allocator.
    #[inline]
    pub fn usable_size(&self, ptr: NonNull<u8>) -> Option<usize> {
        self.thread_heap().map_or_else(
            || self.block_layout(ptr).map(|layout| layout.size()),
            |data| data.usable_size(ptr),
        )
    }

    /// Resizes the block that `ptr` points to without its layout, as C's `realloc` does, keeping
    /// an alignment of 16. Returns null, and leaves the block as it was, if there is no room or
    /// the size is too large, or if `ptr` is not in this allocator's region.
    ///
    /// # Safety
    ///
    /// `ptr` must be the start of a live block from this allocator, and `new_size` must not be
    /// zero.
    pub unsafe fn realloc_unsized(&self, ptr: NonNull<u8>, new_size: usize) -> *mut u8 {
        let Some(size) = self.usable_size(ptr) else { return ptr::null_mut() };
        if Layout::from_size_align(new_size, MIN_ALIGN).is_err() {
            return ptr::null_mut();
        }
        // SAFETY: the block holds `size` bytes at an alignment of at least 16, which is a layout it
        // can be freed and resized with, and the new size is valid for that alignment.
        unsafe {
            let old = Layout::from_size_align_unchecked(size, MIN_ALIGN);
            GlobalAlloc::realloc(self, ptr.as_ptr(), old, new_size)
        }
    }

    /// Frees the block that `ptr` points to without its layout, as C's `free` does, and ignores
    /// a pointer outside the region.
    ///
    /// # Safety
    ///
    /// A pointer inside the region must be the start of a live block from this allocator, and the
    /// block must not be used again.
    #[inline]
    pub unsafe fn free_unsized(&self, ptr: NonNull<u8>) {
        let Some(data) = self.thread_heap() else {
            // SAFETY: the caller vouches for the block.
            return unsafe { self.free_unsized_unbound(ptr) };
        };
        // SAFETY: a thread with a heap published the directory when it bound the heap.
        if let Some(entry) = unsafe { self.directory.entry_in_region(ptr.as_ptr()) } {
            // SAFETY: a thread's bound heap is claimed by that thread alone, its region is this
            // allocator's, the entry is the block's, and the caller vouches for the block.
            unsafe { data.free_with_entry(ptr, entry) };
        }
    }

    /// Frees without a layout for a thread that has no heap yet.
    #[cold]
    #[inline(never)]
    unsafe fn free_unsized_unbound(&self, ptr: NonNull<u8>) {
        if let Some(layout) = self.block_layout(ptr) {
            // SAFETY: the layout is the one the allocator holds for the block.
            unsafe { self.dealloc_unbound(ptr, layout) };
        }
    }

    /// Hands back the blocks that the calling thread's heap keeps for reuse: its bins, its
    /// outboxes and what other threads sent it, and then its empty slabs.
    ///
    /// A thread that is about to go quiet for a while calls this so that its cached memory is not
    /// held while it sleeps, as jemalloc offers with its thread cache flush. Heaps of exited
    /// threads are handed back on their own, and [`trim`](Self::trim) covers heaps nobody holds.
    pub fn flush_thread(&self) {
        if let (Some(data), Some(region)) = (self.bound_heap(), self.existing()) {
            // SAFETY: a thread's bound heap is claimed by that thread alone, and so is its region.
            unsafe { data.flush(region) };
        }
    }

    /// The region if it exists.
    fn existing(&self) -> Option<&'static Region<'static>> {
        // SAFETY: a non-null pointer is a leaked mapping, which lives for the rest of the program.
        unsafe { self.region.load(Ordering::Acquire).as_ref() }
    }

    /// The region, creating it on first use.
    #[inline]
    fn region(&self) -> Option<&'static Region<'static>> {
        self.existing().or_else(|| self.create())
    }

    #[cold]
    fn create(&self) -> Option<&'static Region<'static>> {
        let mut config = self.config;
        let spares =
            (SPARE_HEAPS_PER_CPU * sys::online_cpus()).clamp(MIN_SPARE_HEAPS, MAX_SPARE_HEAPS);
        let mapping = loop {
            match Mapping::with_spare_heaps(&config, spares) {
                Ok(mapping) => break mapping,
                Err(Error::OutOfAddressSpace) if config.capacity_bytes() / 2 >= MIN_CAPACITY => {
                    config = config.capacity(config.capacity_bytes() / 2);
                }
                Err(_) => return None,
            }
        };
        let candidate = ptr::from_ref(mapping.region()).cast::<Region<'static>>().cast_mut();
        match self.region.compare_exchange(
            ptr::null_mut(),
            candidate,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(_) => Some(mapping.leak()),
            // Another thread got there first. Our mapping has no users, so dropping it unmaps it.
            Err(existing) => {
                drop(mapping);
                // SAFETY: the winner leaked its mapping.
                unsafe { existing.as_ref() }
            }
        }
    }
}

impl Default for Bcmalloc {
    fn default() -> Self {
        Self::new()
    }
}

impl Bcmalloc {
    /// This thread's heap, or `None` if it has not bound one or the fast lookup cannot tell.
    #[inline(always)]
    fn thread_heap(&self) -> Option<&'static HeapData> {
        tls::get(self.key.load(Ordering::Relaxed))
    }

    /// This thread's heap, or `None` if it has not bound one. This is the slow lookup that settles
    /// what [`thread_heap`](Self::thread_heap) could not.
    fn bound_heap(&self) -> Option<&'static HeapData> {
        tls::lookup(self.key.load(Ordering::Relaxed))
    }

    /// The key under which threads bind their heap, created on first use.
    fn key(&self) -> Option<usize> {
        let key = self.key.load(Ordering::Acquire);
        if key != tls::NO_KEY {
            return Some(key);
        }
        let created = tls::create_key()?;
        match self.key.compare_exchange(tls::NO_KEY, created, Ordering::AcqRel, Ordering::Acquire) {
            Ok(_) => Some(created),
            // Another thread created the key first. Ours has no users.
            Err(existing) => {
                tls::delete_key(created);
                Some(existing)
            }
        }
    }

    /// Claims a heap for this thread and binds it, or returns None if the thread is exiting, no
    /// heap is free or the system has no key to give.
    #[cold]
    fn bind(&self, region: &'static Region<'static>) -> Option<&'static HeapData> {
        if tls::exiting() || tls::binding() {
            return None;
        }
        tls::set_binding(true);
        let bound = self.bind_now(region);
        tls::set_binding(false);
        bound
    }

    /// The body of [`bind`](Self::bind), which runs with the binding flag set.
    fn bind_now(&self, region: &'static Region<'static>) -> Option<&'static HeapData> {
        let key = self.key()?;
        let heap = region.heap()?;
        // The fast frees read the directory once this thread has a heap. A thread that finds no
        // heap does not write it, because it tries again on every call and every free reads it.
        self.directory.publish(region);
        // The heap releases its claim if the system refuses to remember it.
        let data = heap.leak();
        if tls::bind(key, data) {
            Some(data)
        } else {
            // SAFETY: the claim was taken just above and nothing else uses the heap.
            unsafe { data.give_up() };
            None
        }
    }

    /// Allocates for a thread that has no heap yet.
    #[cold]
    #[inline(never)]
    unsafe fn alloc_unbound(&self, layout: Layout) -> *mut u8 {
        if let Some(data) = self.bound_heap() {
            // SAFETY: a thread's bound heap is claimed by that thread alone.
            return unsafe { data.alloc(layout) };
        }
        let Some(region) = self.region() else { return ptr::null_mut() };
        if let Some(data) = self.bind(region) {
            // SAFETY: binding claimed the heap for this thread.
            return unsafe { data.alloc(layout) };
        }
        // SAFETY: the spare is borrowed for the call.
        with_spare(region, |data| unsafe { data.alloc(layout) })
    }

    /// Frees for a thread that has no heap yet.
    #[cold]
    #[inline(never)]
    unsafe fn dealloc_unbound(&self, ptr: NonNull<u8>, layout: Layout) {
        if let Some(data) = self.bound_heap() {
            // SAFETY: a thread's bound heap is claimed by that thread alone, and the caller vouches
            // for the block.
            return unsafe { data.dealloc(ptr, layout) };
        }
        let Some(region) = self.existing() else { return };
        if let Some(data) = self.bind(region) {
            // SAFETY: binding claimed the heap for this thread, and the caller vouches for the
            // block.
            unsafe { data.dealloc(ptr, layout) };
        } else {
            // SAFETY: as above.
            unsafe { region.dealloc(ptr, layout) };
        }
    }

    /// Resizes for a thread that has no heap yet.
    #[cold]
    #[inline(never)]
    unsafe fn realloc_unbound(&self, ptr: NonNull<u8>, layout: Layout, new_size: usize) -> *mut u8 {
        if let Some(data) = self.bound_heap() {
            // SAFETY: a thread's bound heap is claimed by that thread alone, and the caller vouches
            // for the block and the size.
            return unsafe { data.realloc(ptr, layout, new_size) };
        }
        let Some(region) = self.existing() else { return ptr::null_mut() };
        if let Some(data) = self.bind(region) {
            // SAFETY: binding claimed the heap for this thread, and the caller vouches for the
            // block and the size.
            return unsafe { data.realloc(ptr, layout, new_size) };
        }
        // SAFETY: the spare is borrowed for the call, and the caller vouches for the block and the
        // size.
        with_spare(region, |data| unsafe { data.realloc(ptr, layout, new_size) })
    }
}

/// Runs `op` on a spare heap of `region`, for a thread that has no heap of its own. The thread
/// asks for the spare it had last time, so that threads sharing the spares settle on different
/// ones.
fn with_spare<T>(region: &Region<'_>, op: impl FnOnce(&HeapData) -> T) -> T {
    let (spare, data) = region.borrow_spare(tls::spare());
    tls::set_spare(spare);
    let result = op(data);
    data.release_claim();
    result
}

// SAFETY: every method forwards to a heap or region of the allocator, which return blocks that
// are valid, aligned, disjoint and live until freed, and never unwind.
unsafe impl GlobalAlloc for Bcmalloc {
    #[inline]
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        if let Some(data) = self.thread_heap() {
            // SAFETY: a thread's bound heap is claimed by that thread alone.
            return unsafe { data.alloc(layout) };
        }
        // SAFETY: forwarded.
        unsafe { self.alloc_unbound(layout) }
    }

    #[inline]
    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        if let Some(data) = self.thread_heap() {
            // SAFETY: a thread's bound heap is claimed by that thread alone.
            return unsafe { data.alloc_zeroed(layout) };
        }
        // SAFETY: forwarded.
        let block = unsafe { self.alloc_unbound(layout) };
        if !block.is_null() {
            // SAFETY: the block holds the layout's size in bytes.
            unsafe { block.write_bytes(0, layout.size()) };
        }
        block
    }

    #[inline]
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        // SAFETY: the caller guarantees the block is live, so it is not null.
        let ptr = unsafe { NonNull::new_unchecked(ptr) };
        let Some(data) = self.thread_heap() else {
            // SAFETY: the caller guarantees the block came from this allocator with this layout.
            return unsafe { self.dealloc_unbound(ptr, layout) };
        };
        // A small size aligned past a chunk is a huge block, which the chunk map entry tells.
        if layout.size() <= MAX_SMALL {
            // SAFETY: a thread's bound heap is claimed by that thread alone, it published the
            // directory when it bound the heap, and the caller guarantees the block came from
            // this allocator with this layout, so it is a block in the region.
            unsafe { data.free_entry(ptr.as_ptr().cast(), self.directory.entry(ptr.as_ptr())) };
        } else {
            // SAFETY: as above.
            unsafe { data.dealloc(ptr, layout) };
        }
    }

    #[inline]
    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        // SAFETY: the caller guarantees the block is live, so it is not null.
        let ptr = unsafe { NonNull::new_unchecked(ptr) };
        if let Some(data) = self.thread_heap() {
            // SAFETY: a thread's bound heap is claimed by that thread alone, and the caller
            // guarantees the block is live with this layout and that the new size is valid for
            // the alignment.
            return unsafe { data.realloc(ptr, layout, new_size) };
        }
        // SAFETY: as above.
        unsafe { self.realloc_unbound(ptr, layout, new_size) }
    }
}

#[cfg(all(test, not(loom), not(miri)))]
mod test {
    use super::*;
    use crate::config::Commit;
    use core::alloc::Layout;
    use std::{boxed::Box, vec::Vec};

    /// An allocator over a small region, leaked so that it can be used as a static would be.
    fn instance() -> &'static Bcmalloc {
        let config = Config::new().capacity(1 << 28).max_heaps(4).commit(Commit::Lazy);
        Box::leak(Box::new(Bcmalloc::with_config(config)))
    }

    #[cfg(feature = "allocator-api")]
    #[test]
    fn collections_can_take_the_allocator_as_a_parameter() {
        let allocator = instance();
        // Joining a spawned thread waits for the operating system thread and so for the
        // destructor that releases its heap, which a scoped thread does not.
        let threads: Vec<_> = (0..4_u64)
            .map(|seed| {
                std::thread::spawn(move || {
                    let mut numbers = Vec::new_in(allocator);
                    numbers.extend((0..100_000).map(|i| i * seed));
                    assert_eq!(numbers[99_999], 99_999 * seed);
                    let boxed = Box::new_in([seed as u8; 64], allocator);
                    assert_eq!(boxed[63], seed as u8);
                })
            })
            .collect();
        for thread in threads {
            thread.join().unwrap();
        }
        assert_eq!(allocator.stats().unwrap().heaps_in_use, 0);
    }

    #[cfg(feature = "allocator-api")]
    #[test]
    fn a_zero_sized_request_does_not_create_the_region() {
        use core::alloc::Allocator;
        let allocator = instance();
        let empty = allocator.allocate(Layout::from_size_align(0, 32).unwrap()).unwrap();
        assert_eq!(empty.len(), 0);
        // SAFETY: the block came from this allocator with this layout.
        unsafe { allocator.deallocate(empty.cast(), Layout::from_size_align(0, 32).unwrap()) };
        assert!(allocator.stats().is_none());
    }

    #[test]
    fn a_block_can_be_freed_and_resized_with_the_layout_the_allocator_reports() {
        let allocator = instance();
        for (size, align) in [(1, 1), (100, 8), (5000, 64), (300_000, 4096), (3 << 20, 16)] {
            let layout = Layout::from_size_align(size, align).unwrap();
            // SAFETY: the layout has a non-zero size.
            let block = NonNull::new(unsafe { allocator.alloc(layout) }).unwrap();
            let held = allocator.block_layout(block).unwrap();
            assert!(held.size() >= size, "{size} fits in what the allocator holds");
            // SAFETY: the block is live, and the reported layout is valid for resizing it.
            let grown = unsafe { allocator.realloc(block.as_ptr(), held, held.size() * 2) };
            let grown = NonNull::new(grown).unwrap();
            let held = allocator.block_layout(grown).unwrap();
            assert!(held.size() >= size * 2);
            // SAFETY: the block is live, and the reported layout is valid for freeing it.
            unsafe { allocator.dealloc(grown.as_ptr(), held) };
        }
        let outside = NonNull::from(&0_u64).cast::<u8>();
        assert_eq!(allocator.block_layout(outside), None, "a pointer outside the region");
    }
    #[test]
    fn frees_without_a_layout_return_everything_from_any_thread() {
        let allocator = instance();
        let sizes = [1, 100, 5000, 300_000, 3 << 20];
        let blocks: Vec<_> = sizes
            .iter()
            .map(|&size| {
                let layout = Layout::from_size_align(size, 16).unwrap();
                // SAFETY: the layout has a non-zero size.
                NonNull::new(unsafe { allocator.alloc(layout) }).unwrap().addr().get()
            })
            .collect();
        let (mine, theirs) = blocks.split_at(2);
        let theirs = theirs.to_vec();
        // A fresh thread has no heap, so its first free takes the path that binds one.
        std::thread::spawn(move || {
            for &addr in &theirs {
                // SAFETY: each block is live and freed once.
                unsafe { allocator.free_unsized(NonNull::new(addr as *mut u8).unwrap()) };
            }
        })
        .join()
        .unwrap();
        let mut outside = 0_u8;
        // SAFETY: as above, and the last pointer is not in the region.
        unsafe {
            for &addr in mine {
                allocator.free_unsized(NonNull::new(addr as *mut u8).unwrap());
            }
            allocator.free_unsized(NonNull::from(&mut outside));
        }
        allocator.flush_thread();
        allocator.trim();
        let stats = allocator.stats().unwrap();
        assert_eq!(stats.free, stats.capacity, "every block went back");
    }

    #[test]
    fn malloc_serves_every_size_aligned_and_refuses_impossible_ones() {
        let allocator = instance();
        let sizes = [0, 1, 15, 16, 17, 8191, 8192, 8193, 100_000, 600_000, 5 << 20];
        let blocks: Vec<_> = sizes.iter().map(|&size| (allocator.malloc(size), size)).collect();
        for &(block, size) in &blocks {
            assert!(!block.is_null(), "{size} bytes");
            assert!(block.addr().is_multiple_of(16), "{size} bytes are aligned to 16");
            let held = allocator.block_layout(NonNull::new(block).unwrap()).unwrap();
            assert!(held.size() >= size.max(1), "{size} bytes fit in the block");
            // SAFETY: the block holds the size in bytes.
            unsafe { block.write_bytes(0xa5, size) };
        }
        let distinct: std::collections::BTreeSet<_> = blocks.iter().map(|&(b, _)| b).collect();
        assert_eq!(distinct.len(), blocks.len(), "a zero-sized request gets a block of its own");
        assert!(allocator.malloc(usize::MAX).is_null());
        assert!(allocator.malloc(usize::MAX / 2).is_null());
        for (block, _) in blocks {
            // SAFETY: each block is live and freed once.
            unsafe { allocator.free_unsized(NonNull::new(block).unwrap()) };
        }
    }
    #[test]
    fn c_style_resizing_and_sizes_need_no_layout() {
        let allocator = instance();
        let block = NonNull::new(allocator.malloc(100)).unwrap();
        assert_eq!(allocator.usable_size(block), Some(112));
        // SAFETY: the block holds 100 bytes.
        unsafe { block.as_ptr().write_bytes(7, 100) };
        // SAFETY: the block is live and the sizes are not zero.
        let same = unsafe { allocator.realloc_unsized(block, 60) };
        assert_eq!(same, block.as_ptr(), "a block that still fits stays");
        // SAFETY: as above.
        let grown = NonNull::new(unsafe { allocator.realloc_unsized(block, 300_000) }).unwrap();
        assert_ne!(grown, block);
        // SAFETY: the grown block holds the first 60 bytes of the old one.
        assert!(unsafe { core::slice::from_raw_parts(grown.as_ptr(), 60) }.iter().all(|&b| b == 7));
        assert_eq!(allocator.usable_size(grown), Some(5 * (64 << 10)));
        // SAFETY: as above.
        assert!(unsafe { allocator.realloc_unsized(grown, usize::MAX) }.is_null());
        let mut outside = 0_u8;
        assert_eq!(allocator.usable_size(NonNull::from(&mut outside)), None);
        // SAFETY: the block is live and freed once.
        unsafe { allocator.free_unsized(grown) };
    }
    #[test]
    fn a_thread_whose_first_call_resizes_or_zeroes_binds_a_heap() {
        let allocator = instance();
        let layout = Layout::from_size_align(100, 8).unwrap();
        // SAFETY: the layout is not zero sized.
        let block = unsafe { allocator.alloc(layout) }.addr();
        std::thread::spawn(move || {
            let block = ptr::with_exposed_provenance_mut::<u8>(block);
            // SAFETY: the block is live with this layout, and the new size is valid.
            let grown = unsafe { allocator.realloc(block, layout, 5000) };
            assert!(!grown.is_null());
            // SAFETY: the grown block is live with the new layout.
            unsafe { allocator.dealloc(grown, Layout::from_size_align(5000, 8).unwrap()) };
        })
        .join()
        .unwrap();
        std::thread::spawn(move || {
            let zeroed = Layout::from_size_align(3000, 16).unwrap();
            // SAFETY: the layout is not zero sized.
            let block = unsafe { allocator.alloc_zeroed(zeroed) };
            // SAFETY: the block holds 3000 bytes.
            assert!(unsafe { core::slice::from_raw_parts(block, 3000) }.iter().all(|&b| b == 0));
            // SAFETY: the block is live with this layout.
            unsafe { allocator.dealloc(block, zeroed) };
        })
        .join()
        .unwrap();
        assert_eq!(allocator.config().heap_count(), 4);
    }

    #[test]
    fn threads_past_max_heaps_borrow_spares_until_a_heap_is_free() {
        use std::sync::mpsc;
        let allocator = instance();
        let layout = Layout::from_size_align(100, 8).unwrap();
        // Four threads take every heap and keep them until they are told to exit.
        let (bound, all_bound) = mpsc::channel();
        let mut holders: Vec<_> = (0..4)
            .map(|_| {
                let bound = bound.clone();
                let (exit, told_to_exit) = mpsc::channel::<()>();
                let thread = std::thread::spawn(move || {
                    // SAFETY: the layout is not zero sized, and the block is freed once.
                    unsafe { allocator.dealloc(allocator.alloc(layout), layout) };
                    bound.send(()).unwrap();
                    told_to_exit.recv().unwrap();
                });
                (exit, thread)
            })
            .collect();
        for _ in 0..4 {
            all_bound.recv().unwrap();
        }
        assert_eq!(allocator.stats().unwrap().heaps_in_use, 4);

        let (borrowed, all_borrowed) = mpsc::channel();
        let (go, told_to_go) = mpsc::channel::<()>();
        let latecomer = std::thread::spawn(move || {
            // Every heap is taken, so each call borrows a spare.
            // SAFETY: the layout is not zero sized.
            let block = unsafe { allocator.alloc(layout) };
            assert!(!block.is_null());
            // SAFETY: the block holds 100 bytes, is live with its layout, and the new size is
            // valid.
            let grown = unsafe {
                block.write_bytes(5, 100);
                allocator.realloc(block, layout, 300_000)
            };
            // SAFETY: the grown block holds at least 100 bytes.
            assert!(unsafe { core::slice::from_raw_parts(grown, 100) }.iter().all(|&b| b == 5));
            // SAFETY: the grown block is live with the new size, and is freed once.
            unsafe { allocator.dealloc(grown, Layout::from_size_align(300_000, 8).unwrap()) };
            let zeroed = NonNull::new(allocator.calloc(10, 100)).unwrap();
            // SAFETY: the block holds 1000 bytes.
            let bytes = unsafe { core::slice::from_raw_parts(zeroed.as_ptr(), 1000) };
            assert!(bytes.iter().all(|&b| b == 0));
            // SAFETY: the block is live, the size is not zero, and the result is freed once.
            unsafe {
                let moved = NonNull::new(allocator.realloc_unsized(zeroed, 5000)).unwrap();
                allocator.free_unsized(moved);
            }
            assert!(allocator.bound_heap().is_none(), "no heap was free to bind");
            borrowed.send(()).unwrap();
            told_to_go.recv().unwrap();
            // SAFETY: as for the first block.
            unsafe { allocator.dealloc(allocator.alloc(layout), layout) };
            assert!(
                allocator.bound_heap().is_some(),
                "the next call after a heap is free binds it"
            );
        });
        all_borrowed.recv().unwrap();
        // Joining a thread waits for its key destructor, which gives its heap back.
        let (exit, thread) = holders.remove(0);
        exit.send(()).unwrap();
        thread.join().unwrap();
        go.send(()).unwrap();
        latecomer.join().unwrap();
        for (exit, thread) in holders {
            exit.send(()).unwrap();
            thread.join().unwrap();
        }
        assert_eq!(allocator.stats().unwrap().heaps_in_use, 0);
        allocator.trim();
        let stats = allocator.stats().unwrap();
        assert_eq!(stats.free, stats.capacity, "the heaps and the spares gave everything back");
    }

    #[test]
    fn flushing_a_thread_returns_what_its_heap_kept() {
        let allocator = instance();
        std::thread::spawn(move || {
            let layout = Layout::new::<[u8; 100]>();
            // SAFETY: the layout is not zero sized.
            let blocks: Vec<_> = (0..1000).map(|_| unsafe { allocator.alloc(layout) }).collect();
            for block in blocks {
                // SAFETY: each block came from this allocator with this layout and is freed once.
                unsafe { allocator.dealloc(block, layout) };
            }
            let held = allocator.stats().unwrap();
            assert!(held.free < held.capacity, "the heap keeps some blocks and a slab");
            allocator.flush_thread();
            let after = allocator.stats().unwrap();
            assert_eq!(after.free, after.capacity, "everything went back to the region");
        })
        .join()
        .unwrap();
    }

    #[test]
    fn a_thread_that_alternates_between_allocators_keeps_one_heap_in_each() {
        let (first, second) = (instance(), instance());
        let layout = Layout::from_size_align(64, 8).unwrap();
        for _ in 0..20 {
            for allocator in [first, second] {
                // SAFETY: the layout is not zero sized, and the block is freed once.
                unsafe {
                    let block = allocator.alloc(layout);
                    assert!(!block.is_null());
                    allocator.dealloc(block, layout);
                }
            }
        }
        assert_eq!(first.stats().unwrap().heaps_in_use, 1);
        assert_eq!(second.stats().unwrap().heaps_in_use, 1);
    }
}