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
//! Operating system services for reserving, committing and discarding address space.
//!
//! The allocator manages one large mapping that it reserves at start-up. Everything it needs from
//! the OS is a handful of calls on that mapping, and Linux and macOS differ in only a few of them.
//!
//! | Operation       | Linux                             | macOS                              |
//! | --------------- | --------------------------------- | ---------------------------------- |
//! | [`reserve`]     | `mmap` with `MAP_NORESERVE`       | `mmap` with `MAP_NORESERVE`        |
//! | [`advise_huge`] | `madvise(MADV_HUGEPAGE)`          | nothing, there is no THP           |
//! | [`populate`]    | `MADV_POPULATE_WRITE`, else touch | touch every page                   |
//! | [`lock`]        | `mlock`                           | `mlock`                            |
//! | [`discard`]     | `MADV_DONTNEED`, reads as zeros   | `MADV_FREE_REUSABLE`, not zeroed   |
//! | [`reuse`]       | nothing                           | `MADV_FREE_REUSE`                  |
//!
//! A reservation is ordinary read-write anonymous memory that the kernel only backs with physical
//! pages when they are first touched. Reserving tens of gigabytes therefore costs address space and
//! nothing else. Under Miri only the reservation exists and every hint does nothing.

use core::ptr::NonNull;

#[cfg(not(unix))]
compile_error!("bcmalloc supports Linux and macOS only");

/// Reserves `len` bytes of zeroed, lazily committed, read-write memory.
///
/// The mapping is page aligned. Returns `None` if the kernel refuses, for example because the
/// address space or an overcommit limit is exhausted.
pub(crate) fn reserve(len: usize) -> Option<NonNull<u8>> {
    #[allow(unused_mut)]
    let mut flags = libc::MAP_PRIVATE | libc::MAP_ANON;
    // The kernel must not charge the whole reservation against the commit limit.
    #[cfg(not(miri))]
    {
        flags |= libc::MAP_NORESERVE;
    }
    // SAFETY: an anonymous mapping at a kernel-chosen address cannot alias existing memory.
    let ptr = unsafe {
        libc::mmap(core::ptr::null_mut(), len, libc::PROT_READ | libc::PROT_WRITE, flags, -1, 0)
    };
    if ptr == libc::MAP_FAILED { None } else { NonNull::new(ptr.cast()) }
}

/// Returns a reservation to the OS.
///
/// # Safety
///
/// `ptr` and `len` must be exactly the pair returned by and passed to [`reserve`], and nothing
/// may use the memory afterwards.
pub(crate) unsafe fn release(ptr: NonNull<u8>, len: usize) {
    // SAFETY: forwarded from the caller.
    let result = unsafe { libc::munmap(ptr.as_ptr().cast(), len) };
    debug_assert_eq!(result, 0, "munmap failed");
}

/// Asks the kernel to back the range with transparent huge pages where it can.
///
/// # Safety
///
/// The range must lie within a live reservation.
#[cfg_attr(
    not(all(target_os = "linux", not(miri))),
    allow(clippy::missing_const_for_fn, reason = "only Linux makes a system call here")
)]
pub(crate) unsafe fn advise_huge(ptr: NonNull<u8>, len: usize) {
    #[cfg(all(target_os = "linux", not(miri)))]
    // SAFETY: forwarded from the caller, and the advice never changes memory contents.
    unsafe {
        libc::madvise(ptr.as_ptr().cast(), len, libc::MADV_HUGEPAGE);
    }
    #[cfg(not(all(target_os = "linux", not(miri))))]
    let _ = (ptr, len);
}

/// Backs every page of the range with physical memory now instead of on first touch.
///
/// # Safety
///
/// The range must lie within a live reservation that holds nothing the caller needs, because the
/// fallback path overwrites the first byte of every page with zero.
#[cfg(not(miri))]
pub(crate) unsafe fn populate(ptr: NonNull<u8>, len: usize) {
    #[cfg(target_os = "linux")]
    // SAFETY: forwarded from the caller. The kernel rejects the advice before Linux 5.14.
    if unsafe { libc::madvise(ptr.as_ptr().cast(), len, libc::MADV_POPULATE_WRITE) } == 0 {
        return;
    }
    // SAFETY: sysconf has no preconditions.
    let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize;
    for offset in (0..len).step_by(page) {
        // SAFETY: the offset is inside the reservation, which is writable.
        unsafe { ptr.as_ptr().add(offset).write_volatile(0) };
    }
}

/// Backs every page of the range with physical memory now. Miri has no paging, so this does
/// nothing.
///
/// # Safety
///
/// Same contract as the non-Miri version.
#[cfg(miri)]
pub(crate) unsafe fn populate(_ptr: NonNull<u8>, _len: usize) {}

/// Pins the range in RAM so it is never swapped out. Returns whether the kernel agreed, which
/// depends on `RLIMIT_MEMLOCK`.
///
/// # Safety
///
/// The range must lie within a live reservation.
pub(crate) unsafe fn lock(ptr: NonNull<u8>, len: usize) -> bool {
    #[cfg(not(miri))]
    {
        // SAFETY: forwarded from the caller.
        unsafe { libc::mlock(ptr.as_ptr().cast(), len) == 0 }
    }
    #[cfg(miri)]
    {
        let _ = (ptr, len);
        false
    }
}

/// Whether pages that [`discard`] gave back read as zeros when next touched.
pub(crate) const DISCARD_ZEROES: bool = cfg!(all(target_os = "linux", not(miri)));

/// Tells the kernel the contents of the range are no longer needed, so it may reclaim the physical
/// pages. The range stays mapped and usable. Reading it afterwards returns zeros on Linux and
/// either the old contents or zeros on macOS. Returns whether the kernel took the advice. It
/// refuses for pages that are locked in memory, which then keep their contents.
///
/// # Safety
///
/// The range must lie within a live reservation, and no live allocation may overlap it.
#[must_use]
pub(crate) unsafe fn discard(ptr: NonNull<u8>, len: usize) -> bool {
    #[cfg(not(miri))]
    {
        #[cfg(target_os = "linux")]
        const ADVICE: libc::c_int = libc::MADV_DONTNEED;
        // The reusable advice takes the pages out of the process's footprint at once, where the
        // plain free advice waits for memory pressure. It must be undone by [`reuse`].
        #[cfg(target_os = "macos")]
        const ADVICE: libc::c_int = libc::MADV_FREE_REUSABLE;
        // SAFETY: forwarded from the caller.
        unsafe { libc::madvise(ptr.as_ptr().cast(), len, ADVICE) == 0 }
    }
    // Miri has no pages to give back, and does not take discarded memory for zeros.
    #[cfg(miri)]
    {
        let _ = (ptr, len);
        true
    }
}

/// Prepares pages that [`discard`] gave back for use again. Linux needs nothing, because the pages
/// come back zeroed on first touch. On macOS this restores the accounting of the pages.
///
/// # Safety
///
/// The range must lie within a live reservation and belong to the caller.
#[cfg_attr(
    not(all(target_os = "macos", not(miri))),
    allow(clippy::missing_const_for_fn, reason = "only macOS makes a system call here")
)]
pub(crate) unsafe fn reuse(ptr: NonNull<u8>, len: usize) {
    #[cfg(all(target_os = "macos", not(miri)))]
    // SAFETY: forwarded from the caller.
    unsafe {
        libc::madvise(ptr.as_ptr().cast(), len, libc::MADV_FREE_REUSE);
    }
    #[cfg(not(all(target_os = "macos", not(miri))))]
    let _ = (ptr, len);
}

/// A monotonic clock in milliseconds, cheap enough to read on the paths that free chunks.
///
/// On aarch64 it reads the architected counter, which takes no system call and ticks at a fixed
/// rate on both supported systems. Elsewhere it asks for the coarse clock where there is one.
pub(crate) fn monotonic_ms() -> u64 {
    #[cfg(all(target_arch = "aarch64", not(miri)))]
    {
        let (ticks, frequency): (u64, u64);
        // SAFETY: both registers are readable from user space and reading them has no effects.
        unsafe {
            core::arch::asm!(
                "mrs {}, cntvct_el0",
                out(reg) ticks,
                options(nomem, nostack, preserves_flags)
            );
            core::arch::asm!(
                "mrs {}, cntfrq_el0",
                out(reg) frequency,
                options(nomem, nostack, preserves_flags)
            );
        }
        ticks / (frequency / 1000).max(1)
    }
    #[cfg(not(all(target_arch = "aarch64", not(miri))))]
    {
        #[cfg(target_os = "linux")]
        const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC_COARSE;
        #[cfg(not(target_os = "linux"))]
        const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC;
        let mut now = libc::timespec { tv_sec: 0, tv_nsec: 0 };
        // SAFETY: the pointer is valid for the call.
        unsafe { libc::clock_gettime(CLOCK, &raw mut now) };
        now.tv_sec as u64 * 1000 + now.tv_nsec as u64 / 1_000_000
    }
}

/// How many CPUs are online, or 1 if the system does not say. It reads no files and allocates
/// nothing, so the allocator can ask while it sets itself up.
#[cfg(all(feature = "std", not(loom)))]
pub(crate) fn online_cpus() -> usize {
    // SAFETY: sysconf has no preconditions.
    let cpus = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) };
    usize::try_from(cpus).unwrap_or(1).max(1)
}

/// How many NUMA nodes the machine has, counting from node 0. It is 1 where the system does not
/// say, the list of nodes has gaps, or the platform has no NUMA support to speak of.
#[cfg_attr(
    not(all(target_os = "linux", not(miri))),
    allow(clippy::missing_const_for_fn, reason = "only Linux reads the system here")
)]
pub(crate) fn numa_nodes() -> usize {
    #[cfg(all(target_os = "linux", not(miri)))]
    {
        // The kernel lists online nodes as ranges such as "0-3". Reading the file needs no
        // allocation, which matters because this runs inside the first allocation.
        let mut buffer = [0_u8; 64];
        let path = c"/sys/devices/system/node/online";
        // SAFETY: the path is a valid C string and the buffer is ours.
        let read = unsafe {
            let fd = libc::open(path.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC);
            if fd < 0 {
                return 1;
            }
            let read = libc::read(fd, buffer.as_mut_ptr().cast(), buffer.len());
            libc::close(fd);
            read
        };
        let Ok(read) = usize::try_from(read) else { return 1 };
        parse_node_list(&buffer[..read])
    }
    #[cfg(not(all(target_os = "linux", not(miri))))]
    {
        1
    }
}

/// The node count in a list like "0" or "0-3". Anything else, such as a list with gaps, counts as
/// one node, so that the allocator never binds memory to a node that may not exist.
#[cfg(any(test, all(target_os = "linux", not(miri))))]
fn parse_node_list(list: &[u8]) -> usize {
    let list = list.strip_suffix(b"\n").unwrap_or(list);
    let count = match list {
        b"0" => 1,
        [b'0', b'-', last @ ..]
            if (1..=4).contains(&last.len()) && last.iter().all(u8::is_ascii_digit) =>
        {
            last.iter().fold(0_usize, |n, digit| n * 10 + usize::from(digit - b'0')) + 1
        }
        _ => 1,
    };
    if count > MAX_NODES { 1 } else { count }
}

/// The most NUMA nodes the allocator splits a region between. Machines with more are treated as
/// one node.
#[cfg(any(test, all(target_os = "linux", not(miri))))]
const MAX_NODES: usize = 1024;

/// The NUMA node of the CPU the calling thread runs on, or 0 where the system does not say.
#[cfg_attr(
    not(all(target_os = "linux", not(miri))),
    allow(clippy::missing_const_for_fn, reason = "only Linux asks the system here")
)]
pub(crate) fn current_node() -> usize {
    #[cfg(all(target_os = "linux", not(miri)))]
    {
        let (mut cpu, mut node) = (0_u32, 0_u32);
        // SAFETY: both pointers are valid for the call, and the third argument is unused.
        let result = unsafe {
            libc::syscall(
                libc::SYS_getcpu,
                &raw mut cpu,
                &raw mut node,
                core::ptr::null_mut::<u8>(),
            )
        };
        if result == 0 { node as usize } else { 0 }
    }
    #[cfg(not(all(target_os = "linux", not(miri))))]
    {
        0
    }
}

/// Asks the kernel to back the range with memory of `node` where it can, and elsewhere when that
/// node is out of memory.
///
/// # Safety
///
/// The range must lie within a live reservation.
#[cfg_attr(
    not(all(target_os = "linux", not(miri))),
    allow(clippy::missing_const_for_fn, reason = "only Linux makes a system call here")
)]
pub(crate) unsafe fn prefer_node(ptr: NonNull<u8>, len: usize, node: usize) {
    #[cfg(all(target_os = "linux", not(miri)))]
    {
        /// The memory policy that prefers one node and falls back to the others.
        const MPOL_PREFERRED: libc::c_long = 1;
        let mut mask = [0_u64; MAX_NODES / 64];
        if node >= MAX_NODES {
            return;
        }
        mask[node / 64] = 1 << (node % 64);
        // SAFETY: the range is inside a reservation, and the mask outlives the call.
        unsafe {
            libc::syscall(
                libc::SYS_mbind,
                ptr.as_ptr(),
                len,
                MPOL_PREFERRED,
                mask.as_ptr(),
                // The kernel reads one bit fewer than this.
                (MAX_NODES + 1) as libc::c_ulong,
                0 as libc::c_uint,
            );
        }
    }
    #[cfg(not(all(target_os = "linux", not(miri))))]
    let _ = (ptr, len, node);
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn node_lists_are_parsed_conservatively() {
        assert_eq!(parse_node_list(b"0\n"), 1);
        assert_eq!(parse_node_list(b"0-3\n"), 4);
        assert_eq!(parse_node_list(b"0-15"), 16);
        assert_eq!(parse_node_list(b"0,2-3\n"), 1, "a list with gaps binds nothing");
        assert_eq!(parse_node_list(b""), 1);
        assert_eq!(parse_node_list(b"0-4095\n"), 1, "more nodes than the masks hold");
        assert_eq!(parse_node_list(b"0-99999999999999999999"), 1);
        assert!(numa_nodes() >= 1);
        assert!(current_node() < 1024);
    }

    const LEN: usize = 1 << 20;

    fn reservation() -> NonNull<u8> {
        reserve(LEN).expect("a 1 MiB reservation always succeeds")
    }

    #[test]
    fn reservations_are_zeroed_and_writable() {
        let ptr = reservation();
        // SAFETY: the offsets are inside the live reservation.
        unsafe {
            assert_eq!(ptr.as_ptr().read(), 0);
            assert_eq!(ptr.as_ptr().add(LEN - 1).read(), 0);
            ptr.as_ptr().add(LEN / 2).write(7);
            assert_eq!(ptr.as_ptr().add(LEN / 2).read(), 7);
            release(ptr, LEN);
        }
    }

    #[test]
    fn populate_and_hints_leave_the_reservation_usable() {
        let ptr = reservation();
        // SAFETY: the range is a live, empty reservation.
        unsafe {
            advise_huge(ptr, LEN);
            populate(ptr, LEN);
            ptr.as_ptr().write(1);
            assert_eq!(ptr.as_ptr().read(), 1);
            release(ptr, LEN);
        }
    }

    #[test]
    #[cfg(all(target_os = "linux", not(miri)))]
    fn discard_zero_fills_on_linux() {
        let ptr = reservation();
        // SAFETY: the range is a live reservation with no other users.
        unsafe {
            ptr.as_ptr().write(9);
            assert!(discard(ptr, LEN));
            assert_eq!(ptr.as_ptr().read(), 0);
            release(ptr, LEN);
        }
    }

    #[test]
    #[cfg(not(miri))]
    fn discard_keeps_the_range_writable() {
        let ptr = reservation();
        // SAFETY: the range is a live reservation with no other users.
        unsafe {
            ptr.as_ptr().write(9);
            assert!(discard(ptr, LEN));
            ptr.as_ptr().write(3);
            assert_eq!(ptr.as_ptr().read(), 3);
            release(ptr, LEN);
        }
    }

    #[test]
    #[cfg(not(miri))]
    fn the_clock_never_runs_backwards_and_keeps_real_time() {
        let before = monotonic_ms();
        std::thread::sleep(std::time::Duration::from_millis(30));
        let after = monotonic_ms();
        assert!(after >= before + 25 && after <= before + 1000, "{before} then {after}");
    }
}