use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicUsize, Ordering};
static THRESHOLD: AtomicUsize = AtomicUsize::new(0);
static DIR: AtomicI32 = AtomicI32::new(-1);
static LOG: AtomicBool = AtomicBool::new(false);
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
static COUNT: AtomicUsize = AtomicUsize::new(0);
static LARGEST: AtomicUsize = AtomicUsize::new(0);
#[cfg(not(target_os = "linux"))]
static NAMES: AtomicUsize = AtomicUsize::new(0);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpillStats {
pub threshold: usize,
pub count: usize,
pub largest: usize,
pub live: usize,
pub peak: usize,
}
pub fn stats() -> SpillStats {
SpillStats {
threshold: THRESHOLD.load(Ordering::Acquire),
count: COUNT.load(Ordering::Relaxed),
largest: LARGEST.load(Ordering::Relaxed),
live: LIVE.load(Ordering::Relaxed),
peak: PEAK.load(Ordering::Relaxed),
}
}
const PAGE: usize = 4096;
const DEFAULT_THRESHOLD: usize = 64 << 20;
pub struct SpillAlloc;
#[cold]
fn configure() -> usize {
let dir = unsafe { libc::getenv(c"PYRUCAST_SPILL_DIR".as_ptr()) };
if dir.is_null() {
THRESHOLD.store(usize::MAX, Ordering::Relaxed);
return usize::MAX;
}
let fd = unsafe { libc::open(dir, libc::O_DIRECTORY | libc::O_RDONLY | libc::O_CLOEXEC) };
if fd < 0 {
die(b"pyrucast: PYRUCAST_SPILL_DIR cannot be opened as a directory\n");
}
let min = unsafe { libc::getenv(c"PYRUCAST_SPILL_MIN".as_ptr()) };
let threshold = if min.is_null() {
DEFAULT_THRESHOLD
} else {
parse_bytes(unsafe { std::ffi::CStr::from_ptr(min) }.to_bytes())
};
LOG.store(
!unsafe { libc::getenv(c"PYRUCAST_SPILL_LOG".as_ptr()) }.is_null(),
Ordering::Relaxed,
);
if DIR
.compare_exchange(-1, fd, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
unsafe { libc::close(fd) };
}
THRESHOLD.store(threshold, Ordering::Release);
threshold
}
fn parse_bytes(digits: &[u8]) -> usize {
if digits.is_empty() {
die(b"pyrucast: PYRUCAST_SPILL_MIN must be a byte count\n");
}
digits.iter().fold(0usize, |n, &d| {
if !d.is_ascii_digit() {
die(b"pyrucast: PYRUCAST_SPILL_MIN must be a byte count\n");
}
n.saturating_mul(10).saturating_add((d - b'0') as usize)
})
}
fn die(message: &[u8]) -> ! {
unsafe { libc::write(2, message.as_ptr().cast(), message.len()) };
std::process::abort()
}
#[inline]
fn spilled(layout: Layout) -> bool {
let t = THRESHOLD.load(Ordering::Acquire);
layout.size() >= t && {
let t = if t == 0 { configure() } else { t };
layout.size() >= t && layout.align() <= PAGE
}
}
#[cold]
unsafe fn temporary_file(dir: i32, size: usize) -> i32 {
unsafe {
#[cfg(target_os = "linux")]
let fd = libc::openat(
dir,
c".".as_ptr(),
libc::O_TMPFILE | libc::O_RDWR | libc::O_CLOEXEC,
0o600,
);
#[cfg(not(target_os = "linux"))]
let fd = {
let mut name = [0u8; 48];
let mut n = 0;
let (mut a, mut b) = ([0u8; 20], [0u8; 20]);
for part in [
&b"pyrucast-spill-"[..],
decimal(libc::getpid() as usize, &mut a),
b"-",
decimal(NAMES.fetch_add(1, Ordering::Relaxed), &mut b),
b"\0",
] {
name[n..n + part.len()].copy_from_slice(part);
n += part.len();
}
let fd = libc::openat(
dir,
name.as_ptr().cast(),
libc::O_CREAT | libc::O_EXCL | libc::O_RDWR | libc::O_CLOEXEC,
0o600,
);
if fd >= 0 {
libc::unlinkat(dir, name.as_ptr().cast(), 0);
}
fd
};
if fd < 0 {
return -1;
}
#[cfg(target_os = "linux")]
let reserved = libc::fallocate(fd, 0, 0, size as libc::off_t) == 0;
#[cfg(not(target_os = "linux"))]
let reserved = libc::ftruncate(fd, size as libc::off_t) == 0;
if !reserved {
libc::close(fd);
return -1;
}
fd
}
}
#[cold]
fn map(size: usize) -> *mut u8 {
let dir = DIR.load(Ordering::Relaxed);
unsafe {
let fd = temporary_file(dir, size);
if fd < 0 {
return std::ptr::null_mut();
}
let p = libc::mmap(
std::ptr::null_mut(),
size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED,
fd,
0,
);
libc::close(fd);
if p == libc::MAP_FAILED {
return std::ptr::null_mut();
}
let live = LIVE.fetch_add(size, Ordering::Relaxed) + size;
PEAK.fetch_max(live, Ordering::Relaxed);
LARGEST.fetch_max(size, Ordering::Relaxed);
COUNT.fetch_add(1, Ordering::Relaxed);
log(b'+', size, live);
p.cast()
}
}
#[cold]
fn unmap(ptr: *mut u8, size: usize) {
unsafe { libc::munmap(ptr.cast(), size) };
let live = LIVE.fetch_sub(size, Ordering::Relaxed) - size;
log(b'-', size, live);
}
fn log(sign: u8, size: usize, live: usize) {
if !LOG.load(Ordering::Relaxed) {
return;
}
let mut line = [0u8; 96];
let mut n = 0;
let (mut a, mut b) = ([0u8; 24], [0u8; 24]);
for part in [
&b"pyrucast spill: "[..],
&[sign],
size_in_units(size, &mut a),
b", ",
size_in_units(live, &mut b),
b" mapped\n",
] {
line[n..n + part.len()].copy_from_slice(part);
n += part.len();
}
unsafe { libc::write(2, line.as_ptr().cast(), n) };
}
fn size_in_units(b: usize, buf: &mut [u8; 24]) -> &[u8] {
const UNITS: [&[u8]; 5] = [b" B", b" kB", b" MB", b" GB", b" TB"];
let (mut v, mut u) = (b, 0);
while v >= 1024 && u + 1 < UNITS.len() {
v /= 1024;
u += 1;
}
let mut n = 0;
let mut digits = [0u8; 20];
let mut put = |part: &[u8], buf: &mut [u8; 24]| {
buf[n..n + part.len()].copy_from_slice(part);
n += part.len();
};
put(decimal(v, &mut digits), buf);
if u > 0 {
let tenths = (b / (1usize << (10 * (u - 1))) % 1024) * 10 / 1024;
put(b".", buf);
put(decimal(tenths, &mut digits), buf);
}
put(UNITS[u], buf);
&buf[..n]
}
fn decimal(mut v: usize, buf: &mut [u8; 20]) -> &[u8] {
let mut i = buf.len();
loop {
i -= 1;
buf[i] = b'0' + (v % 10) as u8;
v /= 10;
if v == 0 {
return &buf[i..];
}
}
}
unsafe impl GlobalAlloc for SpillAlloc {
#[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if spilled(layout) {
map(layout.size())
} else {
unsafe { System.alloc(layout) }
}
}
#[inline]
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
if spilled(layout) {
map(layout.size())
} else {
unsafe { System.alloc_zeroed(layout) }
}
}
#[inline]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
if spilled(layout) {
unmap(ptr, layout.size());
} else {
unsafe { System.dealloc(ptr, layout) }
}
}
#[inline]
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let new_layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) };
if !spilled(layout) && !spilled(new_layout) {
return unsafe { System.realloc(ptr, layout, new_size) };
}
let new = unsafe { self.alloc(new_layout) };
if !new.is_null() {
unsafe {
std::ptr::copy_nonoverlapping(ptr, new, layout.size().min(new_size));
self.dealloc(ptr, layout);
}
}
new
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn byte_counts_parse_as_decimal() {
assert_eq!(parse_bytes(b"4096"), 4096);
assert_eq!(parse_bytes(b"67108864"), DEFAULT_THRESHOLD);
}
#[test]
fn sizes_carry_their_unit_and_one_decimal() {
let mut buf = [0u8; 24];
assert_eq!(size_in_units(512, &mut buf), b"512 B");
assert_eq!(size_in_units(1024, &mut buf), b"1.0 kB");
assert_eq!(size_in_units(64 << 20, &mut buf), b"64.0 MB");
assert_eq!(size_in_units(5_604_776_272, &mut buf), b"5.2 GB");
}
#[test]
fn decimals_are_written_without_allocating() {
let mut buf = [0u8; 20];
assert_eq!(decimal(0, &mut buf), b"0");
assert_eq!(decimal(1_073_741_824, &mut buf), b"1073741824");
assert_eq!(decimal(usize::MAX, &mut buf), b"18446744073709551615");
}
}