Skip to main content

c/
alloc.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// Allocator: segregated free lists for small blocks, mmap for large blocks.
5//
6// This replaces the old mmap-per-allocation allocator. Small allocations are
7// carved from page-aligned chunks and recycled through per-size free lists;
8// large allocations still use mmap directly. A single short-lived spin lock
9// protects the free lists. fork() resets it in the child.
10
11const ALLOC_STEP: usize = 16;
12const ALLOC_MIN_CLASS: usize = 32;
13const ALLOC_MAX_CLASS: usize = 32768;
14const ALLOC_CLASSES: usize = ALLOC_MAX_CLASS / ALLOC_STEP + 1;
15const ALLOC_HDR: usize = core::mem::size_of::<AllocBlock>();
16const ALLOC_LARGE: usize = 1usize << 63;
17const ALLOC_ALIGNED: usize = 1usize << 62;
18// Aligned blocks that came from the size-class heap instead of a dedicated
19// mapping store the requested size in the tag and the raw malloc pointer in
20// `next`.  This keeps small over-aligned allocations off the mmap path.
21const ALLOC_OFFSET: usize = 1usize << 61;
22const ALLOC_SIZE_MASK: usize = ALLOC_OFFSET - 1;
23// Page counts live below both tag bits; masking with ALLOC_LARGE - 1 would
24// keep the ALLOC_ALIGNED bit and overstate every aligned block by 2^62 bytes.
25const ALLOC_PAGES_MASK: usize = ALLOC_ALIGNED - 1;
26
27const MREMAP_MAYMOVE: i64 = 1;
28
29const ALLOC_TCACHE_MIN: usize = 32;
30const ALLOC_TCACHE_MAX: usize = 512;
31const ALLOC_TCACHE_SLOTS: usize = (ALLOC_TCACHE_MAX - ALLOC_TCACHE_MIN) / ALLOC_STEP + 1;
32
33#[repr(C)]
34struct AllocBlock {
35    next: *mut AllocBlock,
36    tag: usize,
37}
38
39// One lock per shard instead of one global lock.  Size classes map onto
40// shards, so unrelated classes no longer serialize behind each other.
41// Each lock sits on its own cache line to avoid false sharing.
42const ALLOC_SHARDS: usize = 64;
43
44#[repr(align(64))]
45struct AllocLock(AtomicUsize);
46
47static ALLOC_LOCKS: [AllocLock; ALLOC_SHARDS] =
48    [const { AllocLock(AtomicUsize::new(0)) }; ALLOC_SHARDS];
49static mut ALLOC_FREE: [*mut AllocBlock; ALLOC_CLASSES] =
50    [null_mut(); ALLOC_CLASSES];
51
52#[inline]
53unsafe fn alloc_lock(shard: usize) {
54    while ALLOC_LOCKS[shard].0.swap(1, Ordering::Acquire) != 0 {
55        core::hint::spin_loop();
56    }
57}
58
59#[inline]
60unsafe fn alloc_unlock(shard: usize) {
61    ALLOC_LOCKS[shard].0.store(0, Ordering::Release);
62}
63
64pub(crate) unsafe fn allocator_after_fork() {
65    let mut i = 0;
66    while i < ALLOC_SHARDS {
67        ALLOC_LOCKS[i].0.store(0, Ordering::Release);
68        i += 1;
69    }
70}
71
72#[inline]
73fn alloc_class_for(size: usize) -> Option<usize> {
74    let total = size.checked_add(ALLOC_HDR)?;
75    let class = if total <= ALLOC_MIN_CLASS {
76        ALLOC_MIN_CLASS
77    } else {
78        match total.checked_add(ALLOC_STEP - 1) {
79            Some(v) => v & !(ALLOC_STEP - 1),
80            None => return None,
81        }
82    };
83    if class <= ALLOC_MAX_CLASS { Some(class) } else { None }
84}
85
86unsafe fn alloc_mmap(size: usize) -> *mut u8 {
87    let pages = (size + PAGE - 1) & !(PAGE - 1);
88    let p = sys_mmap(
89        null_mut(),
90        pages,
91        PROT_READ | PROT_WRITE,
92        MAP_PRIVATE | MAP_ANONYMOUS,
93        -1,
94        0,
95    );
96    if p == MMAP_FAILED { null_mut() } else { p }
97}
98
99unsafe fn alloc_large(size: usize) -> *mut u8 {
100    let total = match size.checked_add(ALLOC_HDR) {
101        Some(v) => v,
102        None => {
103            ERRNO!() = ENOMEM;
104            return null_mut();
105        }
106    };
107    if total > usize::MAX - (PAGE - 1) {
108        ERRNO!() = ENOMEM;
109        return null_mut();
110    }
111    let pages = (total + PAGE - 1) / PAGE;
112    let map_size = pages * PAGE;
113    let base = alloc_mmap(map_size);
114    if base.is_null() {
115        return null_mut();
116    }
117    let block = base as *mut AllocBlock;
118    (*block).next = block;
119    (*block).tag = ALLOC_LARGE | pages;
120    base.add(ALLOC_HDR)
121}
122
123unsafe fn alloc_aligned_impl(alignment: usize, size: usize) -> *mut u8 {
124    if alignment == 0 || !alignment.is_power_of_two() {
125        ERRNO!() = EINVAL;
126        return null_mut();
127    }
128    if alignment <= ALLOC_STEP {
129        return malloc(size) as *mut u8;
130    }
131    let total = match size.checked_add(alignment).and_then(|v| v.checked_add(ALLOC_HDR)) {
132        Some(v) => v,
133        None => {
134            ERRNO!() = ENOMEM;
135            return null_mut();
136        }
137    };
138    if alignment <= PAGE && total <= ALLOC_MAX_CLASS {
139        // Small over-aligned block: carve it out of the size-class heap
140        // instead of paying an mmap/munmap per allocation.
141        let raw = malloc(total) as *mut u8;
142        if raw.is_null() {
143            return null_mut();
144        }
145        // The aligned header lives inside the raw block's user area; the raw
146        // block's own header is ALLOC_HDR bytes below `raw`.
147        let data_addr = (raw as usize + ALLOC_HDR + alignment - 1) & !(alignment - 1);
148        let block = (data_addr - ALLOC_HDR) as *mut AllocBlock;
149        (*block).next = raw as *mut AllocBlock;
150        (*block).tag = ALLOC_OFFSET | size;
151        return data_addr as *mut u8;
152    }
153    if total > usize::MAX - (PAGE - 1) {
154        ERRNO!() = ENOMEM;
155        return null_mut();
156    }
157    let pages = (total + PAGE - 1) / PAGE;
158    let map_size = pages * PAGE;
159    let base = alloc_mmap(map_size);
160    if base.is_null() {
161        return null_mut();
162    }
163    let data_addr = (base as usize + ALLOC_HDR + alignment - 1) & !(alignment - 1);
164    let block = (data_addr - ALLOC_HDR) as *mut AllocBlock;
165    (*block).next = base as *mut AllocBlock;
166    (*block).tag = ALLOC_ALIGNED | pages;
167    data_addr as *mut u8
168}
169
170pub(crate) unsafe fn alloc_usable_size(ptr: *mut u8) -> usize {
171    if ptr.is_null() {
172        return 0;
173    }
174    let block = ptr.sub(ALLOC_HDR) as *mut AllocBlock;
175    let tag = (*block).tag;
176    if tag & ALLOC_OFFSET != 0 {
177        tag & ALLOC_SIZE_MASK
178    } else if tag & ALLOC_ALIGNED != 0 {
179        let base = (*block).next as usize;
180        let pages = tag & ALLOC_PAGES_MASK;
181        pages * PAGE - (ptr as usize - base)
182    } else if tag & ALLOC_LARGE != 0 {
183        let pages = tag & ALLOC_PAGES_MASK;
184        pages * PAGE - ALLOC_HDR
185    } else if tag >= ALLOC_MIN_CLASS && tag <= ALLOC_MAX_CLASS {
186        tag - ALLOC_HDR
187    } else {
188        0
189    }
190}
191
192#[no_mangle]
193pub unsafe extern "C" fn malloc(size: SizeT) -> *mut c_void {
194    let class = match alloc_class_for(size) {
195        Some(c) => c,
196        None => return alloc_large(size) as *mut c_void,
197    };
198    let idx = class / ALLOC_STEP;
199    if class <= ALLOC_TCACHE_MAX {
200        let t = current_thread_fast();
201        if !t.is_null() && core::ptr::read_volatile(&(*t).alloc_busy) == 0 {
202            core::ptr::write_volatile(&mut (*t).alloc_busy, 1);
203            core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
204            let slot = idx - ALLOC_TCACHE_MIN / ALLOC_STEP;
205            debug_assert!(slot < ALLOC_TCACHE_SLOTS);
206            let head = (*t).alloc_cache[slot];
207            if !head.is_null() {
208                (*t).alloc_cache[slot] = (*head).next;
209                core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
210                core::ptr::write_volatile(&mut (*t).alloc_busy, 0);
211                return (head as *mut u8).add(ALLOC_HDR) as *mut c_void;
212            }
213            core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
214            core::ptr::write_volatile(&mut (*t).alloc_busy, 0);
215        }
216    }
217    let shard = idx & (ALLOC_SHARDS - 1);
218
219    alloc_lock(shard);
220    let head = ALLOC_FREE[idx];
221    if !head.is_null() {
222        ALLOC_FREE[idx] = (*head).next;
223        alloc_unlock(shard);
224        return (head as *mut u8).add(ALLOC_HDR) as *mut c_void;
225    }
226
227    // Refill this size class with a chunk of blocks.
228    let chunk_size = if class < 4096 { 65536 } else { class * 2 };
229    let map_size = (chunk_size + PAGE - 1) & !(PAGE - 1);
230    let base = alloc_mmap(map_size);
231    if base.is_null() {
232        alloc_unlock(shard);
233        return null_mut();
234    }
235    let count = map_size / class;
236    let mut i = count;
237    while i > 1 {
238        i -= 1;
239        let block = base.add(i * class) as *mut AllocBlock;
240        (*block).tag = class;
241        (*block).next = ALLOC_FREE[idx];
242        ALLOC_FREE[idx] = block;
243    }
244    let first = base as *mut AllocBlock;
245    (*first).tag = class;
246    alloc_unlock(shard);
247    base.add(ALLOC_HDR) as *mut c_void
248}
249
250#[no_mangle]
251pub unsafe extern "C" fn free(ptr: *mut c_void) {
252    if ptr.is_null() {
253        return;
254    }
255    let block = (ptr as *mut u8).sub(ALLOC_HDR) as *mut AllocBlock;
256    let tag = (*block).tag;
257    if tag & ALLOC_OFFSET != 0 {
258        // Heap-backed over-aligned block: `next` holds the raw malloc base.
259        free((*block).next as *mut c_void);
260        return;
261    }
262    if tag & ALLOC_ALIGNED != 0 {
263        let base = (*block).next as *mut u8;
264        let pages = tag & ALLOC_PAGES_MASK;
265        sys_munmap(base, pages * PAGE);
266        return;
267    }
268    if tag & ALLOC_LARGE != 0 {
269        let pages = tag & ALLOC_PAGES_MASK;
270        sys_munmap(block as *mut u8, pages * PAGE);
271        return;
272    }
273    if tag < ALLOC_MIN_CLASS || tag > ALLOC_MAX_CLASS {
274        return;
275    }
276    let idx = tag / ALLOC_STEP;
277    if tag <= ALLOC_TCACHE_MAX {
278        let t = current_thread_fast();
279        if !t.is_null() && core::ptr::read_volatile(&(*t).alloc_busy) == 0 {
280            core::ptr::write_volatile(&mut (*t).alloc_busy, 1);
281            core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
282            let slot = idx - ALLOC_TCACHE_MIN / ALLOC_STEP;
283            debug_assert!(slot < ALLOC_TCACHE_SLOTS);
284            if (*t).alloc_cache[slot].is_null() {
285                (*block).next = core::ptr::null_mut();
286                (*t).alloc_cache[slot] = block;
287                core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
288                core::ptr::write_volatile(&mut (*t).alloc_busy, 0);
289                return;
290            }
291            core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
292            core::ptr::write_volatile(&mut (*t).alloc_busy, 0);
293        }
294    }
295    let shard = idx & (ALLOC_SHARDS - 1);
296    alloc_lock(shard);
297    (*block).next = ALLOC_FREE[idx];
298    ALLOC_FREE[idx] = block;
299    alloc_unlock(shard);
300}
301
302// Return one thread's cached blocks to the global free lists.  Called when a
303// Thread slot is reused, so the next thread does not inherit them and a dead
304// thread's cache cannot strand memory forever.
305pub(crate) unsafe fn allocator_flush_cache(cache: &mut [*mut AllocBlock; ALLOC_TCACHE_SLOTS]) {
306    let mut slot = 0usize;
307    while slot < ALLOC_TCACHE_SLOTS {
308        let mut block = cache[slot];
309        cache[slot] = null_mut();
310        if block.is_null() {
311            slot += 1;
312            continue;
313        }
314        let class = ALLOC_TCACHE_MIN + slot * ALLOC_STEP;
315        let idx = class / ALLOC_STEP;
316        let shard = idx & (ALLOC_SHARDS - 1);
317        alloc_lock(shard);
318        while !block.is_null() {
319            let next = (*block).next;
320            (*block).next = ALLOC_FREE[idx];
321            ALLOC_FREE[idx] = block;
322            block = next;
323        }
324        alloc_unlock(shard);
325        slot += 1;
326    }
327}
328
329#[no_mangle]
330pub unsafe extern "C" fn calloc(count: SizeT, size: SizeT) -> *mut c_void {
331    let total = match count.checked_mul(size) {
332        Some(v) => v,
333        None => {
334            ERRNO!() = ENOMEM;
335            return null_mut();
336        }
337    };
338    let ptr = malloc(total);
339    if !ptr.is_null() && total != 0 {
340        // Large and dedicated-aligned blocks always come from a fresh
341        // MAP_ANONYMOUS mapping, which the kernel has already zeroed.
342        let block = (ptr as *mut u8).sub(ALLOC_HDR) as *mut AllocBlock;
343        let tag = (*block).tag;
344        if tag & (ALLOC_LARGE | ALLOC_ALIGNED) == 0 {
345            core::ptr::write_bytes(ptr as *mut u8, 0, total);
346        }
347    }
348    ptr
349}
350
351#[no_mangle]
352pub unsafe extern "C" fn realloc(ptr: *mut c_void, new_size: SizeT) -> *mut c_void {
353    if ptr.is_null() {
354        return malloc(new_size);
355    }
356    if new_size == 0 {
357        free(ptr);
358        return null_mut();
359    }
360    let old_size = alloc_usable_size(ptr as *mut u8);
361    if new_size <= old_size {
362        return ptr;
363    }
364    let block = (ptr as *mut u8).sub(ALLOC_HDR) as *mut AllocBlock;
365    let tag = (*block).tag;
366    if tag & (ALLOC_LARGE | ALLOC_ALIGNED | ALLOC_OFFSET) == ALLOC_LARGE {
367        // Grow a dedicated mapping in place.  This avoids copying the whole
368        // block for every small growth (musl uses mremap here too).
369        let old_pages = tag & ALLOC_PAGES_MASK;
370        let total = match new_size.checked_add(ALLOC_HDR) {
371            Some(v) if v <= usize::MAX - (PAGE - 1) => v,
372            _ => {
373                ERRNO!() = ENOMEM;
374                return null_mut();
375            }
376        };
377        let new_pages = (total + PAGE - 1) / PAGE;
378        if new_pages > old_pages {
379            let moved = <Arch as Syscalls>::syscall5(
380                SYS_MREMAP,
381                block as i64,
382                (old_pages * PAGE) as i64,
383                (new_pages * PAGE) as i64,
384                MREMAP_MAYMOVE,
385                0,
386            );
387            if moved >= 0 {
388                let nb = moved as *mut AllocBlock;
389                (*nb).next = nb;
390                (*nb).tag = ALLOC_LARGE | new_pages;
391                return (nb as *mut u8).add(ALLOC_HDR) as *mut c_void;
392            }
393        }
394    }
395    let new_ptr = malloc(new_size);
396    if new_ptr.is_null() {
397        return null_mut();
398    }
399    core::ptr::copy_nonoverlapping(ptr as *const u8, new_ptr as *mut u8, old_size);
400    free(ptr);
401    new_ptr
402}