diff --git a/patches/std-nife/overlay/std/src/sys/alloc/nife/mod.rs b/patches/std-nife/overlay/std/src/sys/alloc/nife/mod.rs index e487368a5..dccd751d5 100644 --- a/patches/std-nife/overlay/std/src/sys/alloc/nife/mod.rs +++ b/patches/std-nife/overlay/std/src/sys/alloc/nife/mod.rs @@ -132,9 +132,89 @@ fn class_layout(class: usize) -> Layout { unsafe { Layout::from_size_align_unchecked(class_bytes(class), GRID) } } +/// MEASUREMENT ONLY (the scratch patch of milestone 561 (a per-CPU allocator is what the +/// current-CPU page was for), `notes/std/allocation.md`): which allocator this build is. 0 is the +/// one lock, 1 a cache per thread (what ships), 2 a cache per CPU id read from the current-CPU +/// page, each behind its own spinlock taken on every operation, and 3 is 2 with the CPU read +/// removed (every thread uses list 0). +const VARIANT: u8 = 1; + +/// One CPU's list for variants 2 and 3, a cache line of its own so neighbors do not share one. +#[repr(align(64))] +struct CpuList { + locked: crate::sync::atomic::AtomicBool, + cache: crate::cell::UnsafeCell, +} + +// SAFETY: `cache` is touched only holding `locked`. +unsafe impl Sync for CpuList {} + +static CPU_LISTS: [CpuList; crate::sys::pal::nife::currentcpuproto::CPU_ID_BOUND] = [const { + CpuList { + locked: crate::sync::atomic::AtomicBool::new(false), + cache: crate::cell::UnsafeCell::new(Cache::new()), + } +}; crate::sys::pal::nife::currentcpuproto::CPU_ID_BOUND]; + +/// The list this thread should use, for variants 2 and 3; `None` before threads exist. +#[inline] +fn cpu_list() -> Option<&'static CpuList> { + let page = tls::current_cpu_page_for_allocation(); + if page == 0 { + return None; + } + let i = if VARIANT == 2 { + // SAFETY: the thread's own current-CPU page, mapped for its life. + let cpu = unsafe { crate::sys::pal::nife::currentcpuproto::CurrentCpuPage::new(page) }.cpu(); + cpu.unwrap_or(0) % crate::sys::pal::nife::currentcpuproto::CPU_ID_BOUND + } else { + 0 + }; + Some(&CPU_LISTS[i]) +} + +/// Variants 2 and 3: `f` on the thread's CPU's cache, holding that list's lock. +#[inline] +fn with_cpu_list(f: impl FnOnce(&mut Cache) -> R) -> Option { + use crate::sync::atomic::Ordering; + let list = cpu_list()?; + let mut contended = false; + while list + .locked + .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_err() + { + contended = true; + crate::hint::spin_loop(); + } + // SAFETY: holding the list's lock. + let r = f(unsafe { &mut *list.cache.get() }); + list.locked.store(false, Ordering::Release); + if INSTRUMENT { + OPS.fetch_add(1, Ordering::Relaxed); + if contended { + CONTENDED.fetch_add(1, Ordering::Relaxed); + } + if VARIANT == 2 && cpu_list().is_some_and(|after| !core::ptr::eq(after, list)) { + STALE.fetch_add(1, Ordering::Relaxed); + } + } + Some(r) +} + +/// MEASUREMENT ONLY: count list operations, those whose first acquire failed, and (variant 2) +/// those after which the thread's CPU id named another list, that is, whose id went stale. +const INSTRUMENT: bool = false; +static OPS: crate::sync::atomic::AtomicU64 = crate::sync::atomic::AtomicU64::new(0); +static CONTENDED: crate::sync::atomic::AtomicU64 = crate::sync::atomic::AtomicU64::new(0); +static STALE: crate::sync::atomic::AtomicU64 = crate::sync::atomic::AtomicU64::new(0); + /// The calling thread's cache, when a request of this shape may use it. #[inline] fn cache_for(layout: Layout) -> Option<(&'static mut Cache, usize)> { + if VARIANT != 1 { + return None; + } let c = class(layout.size(), layout.align())?; let cache = tls::allocation_cache(); // SAFETY: the calling thread's own cache, which nothing else touches (`tls::allocation_cache`), @@ -144,6 +224,16 @@ fn cache_for(layout: Layout) -> Option<(&'static mut Cache, usize)> { #[inline] pub unsafe fn alloc(layout: Layout) -> *mut u8 { + if VARIANT >= 2 { + if let Some(c) = class(layout.size(), layout.align()) { + if let Some(p) = with_cpu_list(|cache| match cache.take(c) { + Some(p) => p.as_ptr(), + None => refill_and_take(cache, c), + }) { + return p; + } + } + } if let Some((cache, c)) = cache_for(layout) { if let Some(p) = cache.take(c) { return p.as_ptr(); @@ -170,6 +260,16 @@ fn refill_and_take(cache: &mut Cache, c: usize) -> *mut u8 { /// **A thread's end**: give every block its cache holds back to the heap under one acquisition. /// The caller has already closed the cache, so nothing refills it after this. pub(crate) fn spill_thread_cache(cache: &mut Cache) { + if INSTRUMENT { + use crate::sync::atomic::Ordering::Relaxed; + let ops = OPS.swap(0, Relaxed); + let (contended, stale) = (CONTENDED.swap(0, Relaxed), STALE.swap(0, Relaxed)); + if ops >= 10_000 { + use crate::io::Write; + let mut err = crate::sys::stdio::Stderr::new(); + let _ = writeln!(err, "lists ops {ops} contended {contended} stale {stale}"); + } + } let mut g = lock(); let inner = g.inner(); // SAFETY: every cached block of class `c` is the heap's and was cached under `class_layout(c)`. @@ -192,6 +292,26 @@ pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) { let Some(p) = NonNull::new(ptr) else { return; }; + if VARIANT >= 2 { + if let Some(c) = class(layout.size(), layout.align()) { + let done = with_cpu_list(|cache| { + // SAFETY: as the per-thread `put` below. + if let Err(p) = unsafe { cache.put(c, p) } { + { + let mut g = lock(); + let inner = g.inner(); + // SAFETY: as `spill_thread_cache`. + cache.spill(c, |b| unsafe { inner.heap.dealloc(b, class_layout(c)) }); + } + // SAFETY: the spill made room. + let _ = unsafe { cache.put(c, p) }; + } + }); + if done.is_some() { + return; + } + } + } if let Some((cache, c)) = cache_for(layout) { // SAFETY: `p` came from `alloc(layout)`, so it is `class_bytes(c)` grid-aligned bytes // of the heap's (a cached block is fungible within its class), and it is ours now. diff --git a/patches/std-nife/overlay/std/src/sys/thread_local/key/nife.rs b/patches/std-nife/overlay/std/src/sys/thread_local/key/nife.rs index 4c6387833..d6abc763c 100644 --- a/patches/std-nife/overlay/std/src/sys/thread_local/key/nife.rs +++ b/patches/std-nife/overlay/std/src/sys/thread_local/key/nife.rs @@ -190,6 +190,18 @@ pub fn allocation_cache() -> *mut Cache { unsafe { if (*b).cache_closed { ptr::null_mut() } else { &raw mut (*b).cache } } } +/// MEASUREMENT ONLY (milestone 561's scratch patch): the calling thread's current-CPU page, the one +/// §269 (how threads share a process: the seven thread forks) fork 6 gives each thread, or 0 before +/// the main thread's block exists. +#[inline] +pub fn current_cpu_page_for_allocation() -> u64 { + if !MAIN_READY.load(Relaxed) { + return 0; + } + // SAFETY: with the flag set, every thread's pointer names its own live block. + unsafe { (*thread_pointer()).cpu_page } +} + /// This thread's allowance: how many cores its process may use (§269 fork 7). pub fn allowance() -> Option> { // SAFETY: a block's page is the one the kernel maps read-only for this thread.