diff --git a/src/lib.rs b/src/lib.rs index 3f78fc5..b91d076 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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. /// @@ -56,10 +68,16 @@ pub fn maybe_grow 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>(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. diff --git a/src/mmap_stack_restore_guard.rs b/src/mmap_stack_restore_guard.rs index 2c9f8c3..f7f0d8f 100644 --- a/src/mmap_stack_restore_guard.rs +++ b/src/mmap_stack_restore_guard.rs @@ -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, old_stack_limit: Option, } 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 @@ -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, @@ -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> = const { RefCell::new(Vec::new()) }; +} + +fn take_cached(requested_size: usize, huge_pages: bool) -> Option { + 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 { + static SIZE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + 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::().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 { + None +} + fn page_size() -> usize { // FIXME: consider caching the page size. unsafe { libc::sysconf(libc::_SC_PAGE_SIZE) as usize } diff --git a/tests/cache.rs b/tests/cache.rs new file mode 100644 index 0000000..0846c87 --- /dev/null +++ b/tests/cache.rs @@ -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 { + 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(); +} diff --git a/tests/huge_pages.rs b/tests/huge_pages.rs new file mode 100644 index 0000000..e29fc56 --- /dev/null +++ b/tests/huge_pages.rs @@ -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::().unwrap(), + Err(_) => return, + }; + stacker::set_huge_pages(true); + thread::spawn(move || { + stacker::grow(64 * 1024, || { + assert!(stacker::remaining_stack().unwrap() > size / 2); + }); + }) + .join() + .unwrap(); +}