use core::ptr::NonNull;
#[cfg(not(unix))]
compile_error!("bcmalloc supports Linux and macOS only");
pub(crate) fn reserve(len: usize) -> Option<NonNull<u8>> {
#[allow(unused_mut)]
let mut flags = libc::MAP_PRIVATE | libc::MAP_ANON;
#[cfg(not(miri))]
{
flags |= libc::MAP_NORESERVE;
}
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()) }
}
pub(crate) unsafe fn release(ptr: NonNull<u8>, len: usize) {
let result = unsafe { libc::munmap(ptr.as_ptr().cast(), len) };
debug_assert_eq!(result, 0, "munmap failed");
}
#[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)))]
unsafe {
libc::madvise(ptr.as_ptr().cast(), len, libc::MADV_HUGEPAGE);
}
#[cfg(not(all(target_os = "linux", not(miri))))]
let _ = (ptr, len);
}
#[cfg(not(miri))]
pub(crate) unsafe fn populate(ptr: NonNull<u8>, len: usize) {
#[cfg(target_os = "linux")]
if unsafe { libc::madvise(ptr.as_ptr().cast(), len, libc::MADV_POPULATE_WRITE) } == 0 {
return;
}
let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize;
for offset in (0..len).step_by(page) {
unsafe { ptr.as_ptr().add(offset).write_volatile(0) };
}
}
#[cfg(miri)]
pub(crate) unsafe fn populate(_ptr: NonNull<u8>, _len: usize) {}
pub(crate) unsafe fn lock(ptr: NonNull<u8>, len: usize) -> bool {
#[cfg(not(miri))]
{
unsafe { libc::mlock(ptr.as_ptr().cast(), len) == 0 }
}
#[cfg(miri)]
{
let _ = (ptr, len);
false
}
}
pub(crate) const DISCARD_ZEROES: bool = cfg!(all(target_os = "linux", not(miri)));
#[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;
#[cfg(target_os = "macos")]
const ADVICE: libc::c_int = libc::MADV_FREE_REUSABLE;
unsafe { libc::madvise(ptr.as_ptr().cast(), len, ADVICE) == 0 }
}
#[cfg(miri)]
{
let _ = (ptr, len);
true
}
}
#[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)))]
unsafe {
libc::madvise(ptr.as_ptr().cast(), len, libc::MADV_FREE_REUSE);
}
#[cfg(not(all(target_os = "macos", not(miri))))]
let _ = (ptr, len);
}
pub(crate) fn monotonic_ms() -> u64 {
#[cfg(all(target_arch = "aarch64", not(miri)))]
{
let (ticks, frequency): (u64, u64);
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 };
unsafe { libc::clock_gettime(CLOCK, &raw mut now) };
now.tv_sec as u64 * 1000 + now.tv_nsec as u64 / 1_000_000
}
}
#[cfg(all(feature = "std", not(loom)))]
pub(crate) fn online_cpus() -> usize {
let cpus = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) };
usize::try_from(cpus).unwrap_or(1).max(1)
}
#[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)))]
{
let mut buffer = [0_u8; 64];
let path = c"/sys/devices/system/node/online";
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
}
}
#[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 }
}
#[cfg(any(test, all(target_os = "linux", not(miri))))]
const MAX_NODES: usize = 1024;
#[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);
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
}
}
#[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)))]
{
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);
unsafe {
libc::syscall(
libc::SYS_mbind,
ptr.as_ptr(),
len,
MPOL_PREFERRED,
mask.as_ptr(),
(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();
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();
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();
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();
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}");
}
}