Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ extern crate psm;
mod backends;

use std::cell::Cell;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

static HUGE_PAGES: AtomicBool = AtomicBool::new(false);
static CACHED_STACKS: AtomicUsize = AtomicUsize::new(0);

pub fn set_huge_pages(enabled: bool) {
HUGE_PAGES.store(enabled, Ordering::Relaxed);
}

pub fn set_cached_stacks(count: usize) {
CACHED_STACKS.store(count, Ordering::Relaxed);
}

/// Grows the call stack if necessary.
///
Expand All @@ -56,10 +68,16 @@ pub fn maybe_grow<R, F: FnOnce() -> R>(red_zone: usize, stack_size: usize, callb
if enough_space {
callback()
} else {
grow(stack_size, callback)
grow_cold(stack_size, callback)
}
}

#[cold]
#[inline(never)]
fn grow_cold<R, F: FnOnce() -> R>(stack_size: usize, callback: F) -> R {
grow(stack_size, callback)
}

/// Always creates a new stack for the passed closure to run on.
/// The closure will still be on the same thread as the caller of `grow`.
/// This will allocate a new stack with at least `stack_size` bytes.
Expand Down
154 changes: 121 additions & 33 deletions src/mmap_stack_restore_guard.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,72 @@
use crate::{get_stack_limit, set_stack_limit};
use crate::{get_stack_limit, set_stack_limit, CACHED_STACKS, HUGE_PAGES};
use std::cell::RefCell;
use std::sync::atomic::Ordering;

pub struct StackRestoreGuard {
mapping: *mut u8,
size_with_guard: usize,
page_size: usize,
mapping: Option<Mapping>,
old_stack_limit: Option<usize>,
}

impl StackRestoreGuard {
pub fn new(requested_size: usize) -> StackRestoreGuard {
let huge_pages = HUGE_PAGES.load(Ordering::Relaxed);
let mapping = take_cached(requested_size, huge_pages)
.unwrap_or_else(|| Mapping::new(requested_size, huge_pages));
StackRestoreGuard {
mapping: Some(mapping),
old_stack_limit: get_stack_limit(),
}
}

// TODO this should return a *mut [u8], but pointer slices only got proper support with Rust 1.79.
pub fn stack_area(&self) -> (*mut u8, usize) {
let mapping = self.mapping.as_ref().unwrap();
(mapping.stack, mapping.stack_size)
}
}

impl Drop for StackRestoreGuard {
fn drop(&mut self) {
if let Some(mapping) = self.mapping.take() {
release(mapping);
}
set_stack_limit(self.old_stack_limit);
}
}

struct Mapping {
mapping: *mut u8,
mapping_size: usize,
stack: *mut u8,
stack_size: usize,
huge_pages: bool,
}

impl Mapping {
fn new(requested_size: usize, huge_pages: bool) -> Mapping {
// For maximum portability we want to produce a stack that is aligned to a page and has
// a size that’s a multiple of page size. It is natural to use mmap to allocate
// these pages. Furthermore, we want to allocate two extras pages for the stack guard.
// To achieve that we do our calculations in number of pages and convert to bytes last.
let page_size = page_size();
let requested_pages = requested_size
.checked_add(page_size - 1)
let align = if huge_pages {
huge_page_size().unwrap_or(page_size)
} else {
page_size
};
let stack_size = std::cmp::max(1, requested_size)
.checked_add(align - 1)
.expect("unreasonably large stack requested")
/ page_size;
let page_count_with_guard = std::cmp::max(1, requested_pages) + 2;
let size_with_guard = page_count_with_guard
.checked_mul(page_size)
/ align
* align;
let mapping_size = stack_size
.checked_add(page_size + align)
.expect("unreasonably large stack requested");

unsafe {
let new_stack = libc::mmap(
std::ptr::null_mut(),
size_with_guard,
mapping_size,
libc::PROT_NONE,
libc::MAP_PRIVATE | libc::MAP_ANON,
-1, // Some implementations assert fd = -1 if MAP_ANON is specified
Expand All @@ -38,25 +78,29 @@ impl StackRestoreGuard {
"mmap failed to allocate stack: {}",
std::io::Error::last_os_error()
);
let guard = StackRestoreGuard {
mapping: new_stack as *mut u8,
page_size,
size_with_guard,
old_stack_limit: get_stack_limit(),
let mapping = new_stack as *mut u8;
let base = mapping as usize + page_size;
let above_guard_page = mapping.add((base + align - 1) / align * align - mapping as usize);
let mapping = Mapping {
mapping,
mapping_size,
stack: above_guard_page,
stack_size,
huge_pages,
};
let above_guard_page = above_guard_page as *mut libc::c_void;
// We leave two guard pages without read/write access in our allocation.
// There is one guard page below the stack and another above it.
let above_guard_page = new_stack.add(page_size);
#[cfg(not(target_os = "openbsd"))]
let result = libc::mprotect(
above_guard_page,
size_with_guard - 2 * page_size,
stack_size,
libc::PROT_READ | libc::PROT_WRITE,
);
#[cfg(target_os = "openbsd")]
let result = if libc::mmap(
above_guard_page,
size_with_guard - 2 * page_size,
stack_size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_FIXED | libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_STACK,
-1,
Expand All @@ -73,32 +117,76 @@ impl StackRestoreGuard {
"mprotect/mmap failed: {}",
std::io::Error::last_os_error()
);
guard
}
}

// TODO this should return a *mut [u8], but pointer slices only got proper support with Rust 1.79.
pub fn stack_area(&self) -> (*mut u8, usize) {
unsafe {
(
self.mapping.add(self.page_size),
self.size_with_guard - 2 * self.page_size,
)
#[cfg(any(target_os = "linux", target_os = "android"))]
if huge_pages {
libc::madvise(above_guard_page, stack_size, libc::MADV_HUGEPAGE);
}
mapping
}
}
}

impl Drop for StackRestoreGuard {
impl Drop for Mapping {
fn drop(&mut self) {
unsafe {
// FIXME: check the error code and decide what to do with it.
// Perhaps a debug_assertion?
libc::munmap(self.mapping as *mut std::ffi::c_void, self.size_with_guard);
libc::munmap(self.mapping as *mut std::ffi::c_void, self.mapping_size);
}
set_stack_limit(self.old_stack_limit);
}
}

thread_local! {
static CACHE: RefCell<Vec<Mapping>> = const { RefCell::new(Vec::new()) };
}

fn take_cached(requested_size: usize, huge_pages: bool) -> Option<Mapping> {
CACHE
.try_with(|cache| {
let mut cache = cache.borrow_mut();
let index = cache
.iter()
.rposition(|m| m.huge_pages == huge_pages && m.stack_size >= requested_size)?;
Some(cache.swap_remove(index))
})
.ok()
.flatten()
}

fn release(mapping: Mapping) {
let limit = CACHED_STACKS.load(Ordering::Relaxed);
if limit == 0 {
return;
}
let _ = CACHE.try_with(move |cache| {
let mut cache = cache.borrow_mut();
if cache.len() < limit {
cache.push(mapping);
}
});
}

#[cfg(any(target_os = "linux", target_os = "android"))]
fn huge_page_size() -> Option<usize> {
static SIZE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might switch to OnceLock

match SIZE.load(Ordering::Relaxed) {
0 => {}
usize::MAX => return None,
size => return Some(size),
}
let size = std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size")
.ok()
.and_then(|s| s.trim().parse::<usize>().ok())
.filter(|s| s.is_power_of_two());
SIZE.store(size.unwrap_or(usize::MAX), Ordering::Relaxed);
size
}

#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn huge_page_size() -> Option<usize> {
None
}

fn page_size() -> usize {
// FIXME: consider caching the page size.
unsafe { libc::sysconf(libc::_SC_PAGE_SIZE) as usize }
Expand Down
32 changes: 32 additions & 0 deletions tests/cache.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#![cfg(not(any(target_arch = "wasm32", windows, miri)))]

extern crate stacker;

use std::thread;

#[inline(never)]
fn deep_marker() -> *mut u8 {

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty sure that's UB according to Rust, but but given that this library already operates on stack, I think this may be legal? Will drop this test if not

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...Or, maybe I should just rewrite it to use rust_psm_stack_pointer(), at least that resolves the question of what happens if let local happens to be allocated in heap, which rustc never does right now

let local = 0u8;
let bottom = (&local as *const u8 as usize - stacker::remaining_stack().unwrap()) & !4095;
(bottom + 64) as *mut u8
}

#[test]
fn cached_stack_is_reused() {
stacker::set_cached_stacks(1);
thread::spawn(|| {
let written = stacker::grow(1024 * 1024, || {
let marker = deep_marker();
unsafe { marker.write_volatile(0xab) };
marker as usize
});
let (read, value) = stacker::grow(1024 * 1024, || {
let marker = deep_marker();
(marker as usize, unsafe { marker.read_volatile() })
});
assert_eq!(written, read);
assert_eq!(value, 0xab);
})
.join()
.unwrap();
}
22 changes: 22 additions & 0 deletions tests/huge_pages.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#![cfg(all(target_os = "linux", not(miri)))]

extern crate stacker;

use std::thread;

#[test]
fn huge_page_stack_is_rounded_up() {
let size = match std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size")
{
Ok(size) => size.trim().parse::<usize>().unwrap(),
Err(_) => return,
};
stacker::set_huge_pages(true);
thread::spawn(move || {
stacker::grow(64 * 1024, || {
assert!(stacker::remaining_stack().unwrap() > size / 2);
});
})
.join()
.unwrap();
}
Loading