A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Shard pools for memories, tables, and stacks to reduce/eliminate lock contention (#13840)
Till Schneidereit90ae123dc4f1
diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rsindex 61ff0669ac..cfc225bb51 100644--- a/crates/wasmtime/src/config.rs+++ b/crates/wasmtime/src/config.rs@@ -4052,6 +4052,12 @@ impl PoolingAllocationConfig {/// aren't prepared to immediately flush them, and so we may go over this/// target size occasionally.///+ /// Note additionally that the queue of not-yet-decommitted entities is+ /// sharded to reduce lock contention: one shard per available CPU, capped+ /// at 16. Each shard batches up to this many decommits independently,+ /// meaning that up to `min(available_parallelism, 16) * (batch_size - 1)`+ /// decommits may be queued and not yet flushed at any given time.+ ////// A batch size of one effectively disables batching.////// Defaults to `1`.diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling.rsindex ef350f978b..b6f0ba589f 100644--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling.rs+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling.rs@@ -78,6 +78,60 @@ use crate::runtime::vm::{GcHeap, GcRuntime};#[cfg(feature = "gc")]use gc_heap_pool::GcHeapPool;+/// Pad a value out to a full cache line (or two, on aarch64 prefetch+/// granularity) so neighboring shards don't false-share.+#[repr(align(128))]+#[derive(Debug)]+struct CachePadded<T>(T);++/// Identifier of one shard of the pooling allocator's sharded data+/// structures (the decommit queues and each pool's index allocator).+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub(crate) struct ShardId(u32);++impl ShardId {+ pub(crate) fn from_index(index: usize) -> ShardId {+ ShardId(u32::try_from(index).unwrap())+ }++ pub(crate) fn index(self) -> usize {+ usize::try_from(self.0).unwrap()+ }+}++/// The number of shards used for the pooling allocator's sharded data+/// structures: one per available CPU, capped to 16.+///+/// The cap bounds worst-case probing when pools run near-full, the+/// dilution of per-shard warm-slot budgets, and per-shard memory+/// overhead, while still being enough shards to make lock collisions+/// rare given the very short critical sections involved.+pub(crate) fn default_shard_count() -> u32 {+ let n = std::thread::available_parallelism()+ .map(|n| n.get())+ .unwrap_or(1)+ .min(16);+ u32::try_from(n).unwrap()+}++/// Pick this thread's shard (used for both the sharded decommit queue and+/// the sharded index allocators): assigned round-robin at first use per+/// thread, cached in a thread-local.+pub(crate) fn thread_shard(nshards: usize) -> ShardId {+ static NEXT_SHARD: AtomicUsize = AtomicUsize::new(0);+ std::thread_local! {+ static SHARD: usize = NEXT_SHARD.fetch_add(1, Ordering::Relaxed);+ }+ ShardId::from_index(SHARD.with(|s| *s) % nshards)+}++/// Enumerate all shard ids for a sharded structure with `nshards` shards,+/// starting with the current thread's home shard and wrapping around.+pub(crate) fn shard_ids_from_home(nshards: usize) -> impl Iterator<Item = ShardId> {+ let home = thread_shard(nshards).index();+ (0..nshards).map(move |i| ShardId::from_index((home + i) % nshards))+}+#[cfg(feature = "async")]use stack_pool::StackPool;@@ -148,7 +202,12 @@ pub struct PoolingInstanceAllocator {live_core_instances: AtomicU64,live_component_instances: AtomicU64,- decommit_queue: Mutex<DecommitQueue>,+ /// Sharded to avoid a single global mutex on every deallocation when+ /// decommit batching is enabled: each thread appends to its own shard+ /// (assigned round-robin at first use) and flushes that shard when it+ /// reaches the configured batch size. Slot-exhaustion paths flush all+ /// shards.+ decommit_queues: Box<[CachePadded<Mutex<DecommitQueue>>]>,memories: MemoryPool,live_memories: AtomicUsize,@@ -183,8 +242,7 @@ impl Drop for PoolingInstanceAllocator {// entities get returned to their associated sub-pools and we can// differentiate between a leaking slot and an enqueued-for-decommit// slot.- let queue = self.decommit_queue.lock().unwrap();- self.flush_decommit_queue(queue);+ self.flush_all_decommit_queues();debug_assert_eq!(self.live_component_instances.load(Ordering::Acquire), 0);debug_assert_eq!(self.live_core_instances.load(Ordering::Acquire), 0);@@ -214,7 +272,9 @@ impl PoolingInstanceAllocator {Ok(Self {live_component_instances: AtomicU64::new(0),live_core_instances: AtomicU64::new(0),- decommit_queue: Mutex::new(DecommitQueue::default()),+ decommit_queues: (0..default_shard_count())+ .map(|_| CachePadded(Mutex::new(DecommitQueue::default())))+ .try_collect::<Box<[_]>, OutOfMemory>()?,memories: MemoryPool::new(config, tunables)?,live_memories: AtomicUsize::new(0),tables: TablePool::new(config)?,@@ -340,6 +400,17 @@ impl PoolingInstanceAllocator {)}+ /// Returns the decommit-queue shard for `shard`.+ fn decommit_queue(&self, shard: ShardId) -> &Mutex<DecommitQueue> {+ &self.decommit_queues[shard.index()].0+ }++ /// Enumerate all decommit-queue shard ids, starting with the current+ /// thread's home shard.+ fn decommit_shard_ids(&self) -> impl Iterator<Item = ShardId> {+ shard_ids_from_home(self.decommit_queues.len())+ }+fn flush_decommit_queue(&self, mut locked_queue: MutexGuard<'_, DecommitQueue>) -> bool {// Take the queue out of the mutex and drop the lock, to minimize// contention.@@ -348,21 +419,45 @@ impl PoolingInstanceAllocator {queue.flush(self)}+ /// Flush every shard of the decommit queue, e.g. on allocator drop.+ /// Returns whether any slot was returned to any pool.+ fn flush_all_decommit_queues(&self) -> bool {+ let mut any = false;+ for shard in self.decommit_shard_ids() {+ let queue = self.decommit_queue(shard).lock().unwrap();+ any |= self.flush_decommit_queue(queue);+ }+ any+ }+/// Execute `f` and if it returns `Err(PoolConcurrencyLimitError)`, then try/// flushing the decommit queue. If flushing the queue freed up slots, then/// try running `f` again.+ ///+ /// Queue shards are flushed one at a time, retrying `f` after each flush+ /// that returned slots to a pool, rather than eagerly flushing all+ /// shards: one flushed shard is often enough to satisfy the allocation,+ /// and this avoids acquiring every shard's lock (at the cost of raising+ /// the chances that another thread steals the freshly-flushed slots+ /// before we get a chance to grab one, in which case we keep flushing).+ ///+ /// Note that [`Self::flush_decommit_queue`] takes the shard's queue out+ /// of its mutex and drops the lock immediately, so no queue lock is held+ /// while decommitting or while `f` runs.#[cfg(feature = "async")]fn with_flush_and_retry<T>(&self, mut f: impl FnMut() -> Result<T>) -> Result<T> {- f().or_else(|e| {- if e.is::<PoolConcurrencyLimitError>() {- let queue = self.decommit_queue.lock().unwrap();- if self.flush_decommit_queue(queue) {- return f();- }+ let mut result = f();+ for shard in self.decommit_shard_ids() {+ match &result {+ Err(e) if e.is::<PoolConcurrencyLimitError>() => {}+ _ => break,}-- Err(e)- })+ let queue = self.decommit_queue(shard).lock().unwrap();+ if self.flush_decommit_queue(queue) {+ result = f();+ }+ }+ result}fn merge_or_flush(&self, mut local_queue: DecommitQueue) {@@ -384,14 +479,14 @@ impl PoolingInstanceAllocator {// If we enqueued some regions for decommit, but did not reach our// batch size, so we don't want to flush it yet, then merge the- // local queue into the shared queue.+ // local queue into this thread's shard of the shared queue.n => {debug_assert!(n < self.config.decommit_batch_size);- let mut shared_queue = self.decommit_queue.lock().unwrap();+ let shard = thread_shard(self.decommit_queues.len());+ let mut shared_queue = self.decommit_queue(shard).lock().unwrap();shared_queue.append(&mut local_queue);- // And if the shared queue now has at least as many regions- // enqueued for decommit as our batch size, then we can flush- // it.+ // And if this shard now has at least as many regions enqueued+ // for decommit as our batch size, then we can flush it.if shared_queue.raw_len() >= self.config.decommit_batch_size {self.flush_decommit_queue(shared_queue);}@@ -541,15 +636,21 @@ unsafe impl InstanceAllocator for PoolingInstanceAllocator {// `with_flush_and_retry` but adapted for async closures instead of only// sync closures. Right now that won't compile though so this is the// manually expanded version of the method.- let e = match self.memories.allocate(request, ty, memory_index).await {+ let mut e = match self.memories.allocate(request, ty, memory_index).await {Ok(result) => return Ok(result),Err(e) => e,};- if e.is::<PoolConcurrencyLimitError>() {- let queue = self.decommit_queue.lock().unwrap();+ for shard in self.decommit_shard_ids() {+ if !e.is::<PoolConcurrencyLimitError>() {+ break;+ }+ let queue = self.decommit_queue(shard).lock().unwrap();if self.flush_decommit_queue(queue) {- return self.memories.allocate(request, ty, memory_index).await;+ match self.memories.allocate(request, ty, memory_index).await {+ Ok(result) => return Ok(result),+ Err(err) => e = err,+ }}}@@ -630,15 +731,21 @@ unsafe impl InstanceAllocator for PoolingInstanceAllocator {async {// FIXME: see `allocate_memory` above for comments about duplication// with `with_flush_and_retry`.- let e = match self.tables.allocate(request, ty).await {+ let mut e = match self.tables.allocate(request, ty).await {Ok(result) => return Ok(result),Err(e) => e,};- if e.is::<PoolConcurrencyLimitError>() {- let queue = self.decommit_queue.lock().unwrap();+ for shard in self.decommit_shard_ids() {+ if !e.is::<PoolConcurrencyLimitError>() {+ break;+ }+ let queue = self.decommit_queue(shard).lock().unwrap();if self.flush_decommit_queue(queue) {- return self.tables.allocate(request, ty).await;+ match self.tables.allocate(request, ty).await {+ Ok(result) => return Ok(result),+ Err(err) => e = err,+ }}}diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/decommit_queue.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/decommit_queue.rsindex 8c27a79815..f324631731 100644--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/decommit_queue.rs+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/decommit_queue.rs@@ -172,46 +172,60 @@ impl DecommitQueue {// Second, restore the various entities to their associated pools' free// lists. This is safe, and they are ready for reuse, now that their- // memory regions have been decommitted.+ // memory regions have been decommitted. Each pool's slots are returned+ // in batch so its index-allocator lock is only acquired once per+ // flush.let mut deallocated_any = false;- for (allocation_index, image, bytes_resident) in self.memories {+ if !self.memories.is_empty() {deallocated_any = true;- // Note that for memory images the images are all dropped here and- // ignored if any decommits failed. This signifies how the state of the- // slot is unknown and needs to be paved over in the future. Also note- // that `bytes_resident` is probably too low, but there's no other- // precise way to know, so it's left here as-is and it'll get reset when- // the slot is reused.- let image = if decommit_succeeded {- Some(image)- } else {- None- };unsafe {- pool.memories- .deallocate(allocation_index, image, bytes_resident);+ pool.memories.deallocate_many(self.memories.into_iter().map(+ |(allocation_index, image, bytes_resident)| {+ // Note that for memory images the images are all dropped+ // here and ignored if any decommits failed. This signifies+ // how the state of the slot is unknown and needs to be+ // paved over in the future. Also note that+ // `bytes_resident` is probably too low, but there's no+ // other precise way to know, so it's left here as-is and+ // it'll get reset when the slot is reused.+ let image = if decommit_succeeded {+ Some(image)+ } else {+ None+ };+ (allocation_index, image, bytes_resident)+ },+ ));}}- for (allocation_index, mut table, bytes_resident) in self.tables {+ if !self.tables.is_empty() {deallocated_any = true;- // Like with memories, if any decommit failed then we need to- // ensure that tables are still in a defined state. Unlike memories- // which track this via images tables are always assumed to be- // all-null on returning to the allocator. If the OS couldn't do it- // then manually do it ourselves here.- if !decommit_succeeded {- table.manually_memset_zeros();- }unsafe {- pool.tables- .deallocate(allocation_index, table, bytes_resident);+ pool.tables.deallocate_many(self.tables.into_iter().map(+ |(allocation_index, mut table, bytes_resident)| {+ // Like with memories, if any decommit failed then we need+ // to ensure that tables are still in a defined state.+ // Unlike memories which track this via images tables are+ // always assumed to be all-null on returning to the+ // allocator. If the OS couldn't do it then manually do it+ // ourselves here.+ if !decommit_succeeded {+ table.manually_memset_zeros();+ }+ (allocation_index, table, bytes_resident)+ },+ ));}}#[cfg(feature = "async")]- for (stack, bytes_resident) in self.stacks {+ if !self.stacks.is_empty() {deallocated_any = true;unsafe {- pool.stacks.deallocate(stack.0, bytes_resident);+ pool.stacks.deallocate_many(+ self.stacks+ .into_iter()+ .map(|(stack, bytes_resident)| (stack.0, bytes_resident)),+ );}}diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/gc_heap_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/gc_heap_pool.rsindex 2a5e47e7f7..20fc1c4a0b 100644--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/gc_heap_pool.rs+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/gc_heap_pool.rs@@ -79,7 +79,7 @@ impl GcHeapPool {"pooling allocator requires memory_may_move == gc_heap_may_move");- let index_allocator = SimpleIndexAllocator::new(config.limits.total_gc_heaps);+ let index_allocator = SimpleIndexAllocator::new(config.limits.total_gc_heaps)?;let max_gc_heaps = usize::try_from(config.limits.total_gc_heaps).unwrap();// Each individual GC heap in the pool is lazily allocated. See thediff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/generic_stack_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/generic_stack_pool.rsindex 0a990d7308..32db660173 100644--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/generic_stack_pool.rs+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/generic_stack_pool.rs@@ -94,6 +94,18 @@ impl StackPool {let _ = stack;}+ /// Safety: see the unix implementation.+ pub unsafe fn deallocate_many(+ &self,+ stacks: impl Iterator<Item = (wasmtime_fiber::FiberStack, usize)>,+ ) {+ for (stack, bytes_resident) in stacks {+ unsafe {+ self.deallocate(stack, bytes_resident);+ }+ }+ }+pub fn unused_warm_slots(&self) -> u32 {0}diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/index_allocator.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/index_allocator.rsindex 41957ee624..80610a2bd7 100644--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/index_allocator.rs+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/index_allocator.rs@@ -1,5 +1,6 @@//! Index/slot allocator policies for the pooling allocator.+use super::ShardId;use crate::hash_map::{Entry, HashMap};use crate::prelude::*;use crate::runtime::vm::CompiledModuleId;@@ -27,8 +28,10 @@ impl SlotId {pub struct SimpleIndexAllocator(ModuleAffinityIndexAllocator);impl SimpleIndexAllocator {- pub fn new(capacity: u32) -> Self {- SimpleIndexAllocator(ModuleAffinityIndexAllocator::new(capacity, 0))+ pub fn new(capacity: u32) -> Result<Self, OutOfMemory> {+ Ok(SimpleIndexAllocator(ModuleAffinityIndexAllocator::new(+ capacity, 0,+ )?))}pub fn is_empty(&self) -> bool {@@ -48,6 +51,12 @@ impl SimpleIndexAllocator {self.0.free(index, bytes_resident);}+ /// Same as [`Self::free`], but frees many slots under a single lock+ /// acquisition.+ pub(crate) fn free_many(&self, items: impl IntoIterator<Item = (SlotId, usize)>) {+ self.0.free_many(items);+ }+/// Returns the number of previously-used slots in this allocator which are/// not currently in use.///@@ -79,7 +88,23 @@ pub struct MemoryInModule(pub CompiledModuleId, pub DefinedMemoryIndex);/// An index allocator that has configurable affinity between slots and modules/// so that slots are often reused for the same module again.#[derive(Debug)]-pub struct ModuleAffinityIndexAllocator(Mutex<Inner>);+pub struct ModuleAffinityIndexAllocator {+ /// The slot space is partitioned into shards, each protected by its own+ /// mutex, to avoid contention on a single lock when many threads+ /// allocate and free slots concurrently. Each shard owns a contiguous+ /// range of `slots_per_shard` slot indices and manages them with local+ /// indices; translation to global `SlotId`s happens at this type's+ /// public boundary.+ ///+ /// Threads have a "home" shard (the same thread-local, round-robin+ /// assignment used for the sharded decommit queue) which they try+ /// first for allocation, falling back to probing the other shards, so+ /// in steady state each thread allocates and frees from its own shard+ /// without cross-thread lock traffic. Pool exhaustion is only reported+ /// after all shards have been consulted.+ shards: Box<[super::CachePadded<Mutex<Inner>>]>,+ slots_per_shard: u32,+}#[derive(Debug)]struct Inner {@@ -184,33 +209,144 @@ enum AllocMode {AnySlot,}+/// The division of an allocator's slot space and unused-warm-slot budget+/// into shards.+#[derive(Debug, PartialEq, Eq)]+struct ShardLayout {+ /// Number of slots in each shard except possibly the last, which may be+ /// smaller when `requested_shards` doesn't evenly divide the capacity.+ slots_per_shard: u32,+ /// Per-shard `(capacity, max_unused_warm_slots)`.+ shards: Box<[(u32, u32)]>,+}++impl ShardLayout {+ fn new(+ capacity: u32,+ max_unused_warm_slots: u32,+ requested_shards: u32,+ ) -> Result<ShardLayout, OutOfMemory> {+ // N.B. we limit the pool sharding (via `default_shard_count`, whose+ // cap `requested_shards` reflects) regardless of CPU count to+ // balance reduced lock-contention with the downsides of slot+ // sharding. In particular, on many-core systems, scaling with the+ // number of cores can lead to:+ // - very small shards, increasing the likelihood of running out of+ // slots in a shard and falling off the fast path.+ // - warm-slot budget dilution, where `max_unused_warm_slots` is low+ // enough that many shards don't get warm slots at all.+ // - affinity dilution, where some threads may have slots with the+ // right instance type affinity available, but the thread handling+ // the request doesn't, so the slower instantiation path has to be+ // taken.+ //+ // Additionally, we don't shard at all for small pools, as the+ // downsides of sharding are too pronounced.+ let nshards = if capacity >= 128 {+ requested_shards.max(1)+ } else {+ 1+ };+ let slots_per_shard = capacity.div_ceil(nshards).max(1);+ let nshards = capacity.div_ceil(slots_per_shard).max(1);++ let shards = (0..nshards)+ .map(|i| {+ let base = i * slots_per_shard;+ let shard_capacity = capacity.saturating_sub(base).min(slots_per_shard);+ // Distribute the unused-warm budget across shards,+ // spreading the remainder over the leading shards.+ let shard_warm = max_unused_warm_slots / nshards+ + u32::from(i < max_unused_warm_slots % nshards);+ (shard_capacity, shard_warm)+ })+ .try_collect()?;++ Ok(ShardLayout {+ slots_per_shard,+ shards,+ })+ }+}+impl ModuleAffinityIndexAllocator {/// Create the default state for this strategy.- pub fn new(capacity: u32, max_unused_warm_slots: u32) -> Self {- ModuleAffinityIndexAllocator(Mutex::new(Inner {- last_cold: 0,+ pub fn new(capacity: u32, max_unused_warm_slots: u32) -> Result<Self, OutOfMemory> {+ Self::new_with_shard_count(+ capacity,max_unused_warm_slots,- unused_warm_slots: 0,- module_affine: HashMap::new(),- slot_state: (0..capacity).map(|_| SlotState::UnusedCold).collect(),- warm: List::default(),- unused_bytes_resident: 0,- }))+ super::default_shard_count(),+ )+ }++ /// Same as [`Self::new`], but with an explicit shard count (which is+ /// capped as described in [`ShardLayout::new`]).+ fn new_with_shard_count(+ capacity: u32,+ max_unused_warm_slots: u32,+ requested_shards: u32,+ ) -> Result<Self, OutOfMemory> {+ let layout = ShardLayout::new(capacity, max_unused_warm_slots, requested_shards)?;+ let shards = layout+ .shards+ .iter()+ .map(|&(shard_capacity, shard_warm)| {+ super::CachePadded(Mutex::new(Inner {+ last_cold: 0,+ max_unused_warm_slots: shard_warm,+ unused_warm_slots: 0,+ module_affine: HashMap::new(),+ slot_state: (0..shard_capacity).map(|_| SlotState::UnusedCold).collect(),+ warm: List::default(),+ unused_bytes_resident: 0,+ }))+ })+ .try_collect()?;++ Ok(ModuleAffinityIndexAllocator {+ shards,+ slots_per_shard: layout.slots_per_shard,+ })+ }++ /// Translate a shard-local slot index to a global `SlotId`.+ fn global_id(&self, shard: ShardId, local: SlotId) -> SlotId {+ SlotId(u32::try_from(shard.index()).unwrap() * self.slots_per_shard + local.0)+ }++ /// Translate a global `SlotId` to its shard and shard-local index.+ fn shard_of(&self, global: SlotId) -> (ShardId, SlotId) {+ let shard = ShardId::from_index((global.0 / self.slots_per_shard) as usize);+ (shard, SlotId(global.0 % self.slots_per_shard))+ }++ /// Returns the [`Inner`] state of the given shard.+ fn shard(&self, shard: ShardId) -> &Mutex<Inner> {+ &self.shards[shard.index()].0+ }++ /// Enumerate all shard ids of this allocator.+ fn shard_ids(&self) -> impl Iterator<Item = ShardId> + use<> {+ (0..self.shards.len()).map(ShardId::from_index)}/// How many slots can this allocator allocate?pub fn len(&self) -> usize {- let inner = self.0.lock().unwrap();- inner.slot_state.len()+ self.shards+ .iter()+ .map(|s| s.0.lock().unwrap().slot_state.len())+ .sum()}/// Are zero slots in use right now?pub fn is_empty(&self) -> bool {- let inner = self.0.lock().unwrap();- !inner- .slot_state- .iter()- .any(|s| matches!(s, SlotState::Used(_)))+ self.shards.iter().all(|s| {+ !s.0.lock()+ .unwrap()+ .slot_state+ .iter()+ .any(|state| matches!(state, SlotState::Used(_)))+ })}/// Allocate a new index from this allocator optionally using `id` as an@@ -218,7 +354,16 @@ impl ModuleAffinityIndexAllocator {////// Returns `None` if no more slots are available.pub fn alloc(&self, for_memory: Option<MemoryInModule>) -> Option<SlotId> {- self._alloc(for_memory, AllocMode::AnySlot)+ // Start at this thread's home shard and probe the others only if+ // it's fully allocated. In steady state this means each thread+ // stays on its own shard.+ for shard in super::shard_ids_from_home(self.shards.len()) {+ let mut inner = self.shard(shard).lock().unwrap();+ if let Some(local) = Self::alloc_within(&mut inner, for_memory, AllocMode::AnySlot) {+ return Some(self.global_id(shard, local));+ }+ }+ None}/// Attempts to allocate a guaranteed-affine slot to the module `id`@@ -233,16 +378,26 @@ impl ModuleAffinityIndexAllocator {module_id: CompiledModuleId,memory_index: DefinedMemoryIndex,) -> Option<SlotId> {- self._alloc(- Some(MemoryInModule(module_id, memory_index)),- AllocMode::ForceAffineAndClear,- )+ // Affine slots for this module may live in any shard, so consult+ // them all. This is a module-teardown path, not a hot path.+ for shard in self.shard_ids() {+ let mut inner = self.shard(shard).lock().unwrap();+ if let Some(local) = Self::alloc_within(+ &mut inner,+ Some(MemoryInModule(module_id, memory_index)),+ AllocMode::ForceAffineAndClear,+ ) {+ return Some(self.global_id(shard, local));+ }+ }+ None}- fn _alloc(&self, for_memory: Option<MemoryInModule>, mode: AllocMode) -> Option<SlotId> {- let mut inner = self.0.lock().unwrap();- let inner = &mut *inner;-+ fn alloc_within(+ inner: &mut Inner,+ for_memory: Option<MemoryInModule>,+ mode: AllocMode,+ ) -> Option<SlotId> {// As a first-pass always attempt an affine allocation. This will// succeed if any slots are considered affine to `module_id` (if it's// specified). Failing that something else is attempted to be chosen.@@ -300,8 +455,33 @@ impl ModuleAffinityIndexAllocator {}pub(crate) fn free(&self, index: SlotId, bytes_resident: usize) {- let mut inner = self.0.lock().unwrap();- let inner = &mut *inner;+ let (shard, local) = self.shard_of(index);+ let mut inner = self.shard(shard).lock().unwrap();+ Self::free_locked(&mut inner, local, bytes_resident);+ }++ /// Same as [`Self::free`], but frees many slots under a single lock+ /// acquisition per shard to reduce contention when a decommit-queue+ /// flush returns a whole batch of slots at once.+ pub(crate) fn free_many(&self, items: impl IntoIterator<Item = (SlotId, usize)>) {+ let mut per_shard: smallvec::SmallVec<[smallvec::SmallVec<[(SlotId, usize); 8]>; 16]> =+ (0..self.shards.len()).map(|_| Default::default()).collect();+ for (index, bytes_resident) in items {+ let (shard, local) = self.shard_of(index);+ per_shard[shard.index()].push((local, bytes_resident));+ }+ for (shard, items) in per_shard.into_iter().enumerate() {+ if items.is_empty() {+ continue;+ }+ let mut inner = self.shard(ShardId::from_index(shard)).lock().unwrap();+ for (local, bytes_resident) in items {+ Self::free_locked(&mut inner, local, bytes_resident);+ }+ }+ }++ fn free_locked(inner: &mut Inner, index: SlotId, bytes_resident: usize) {let module_memory = match inner.slot_state[index.index()] {SlotState::Used(module_memory) => module_memory,_ => unreachable!(),@@ -345,19 +525,29 @@ impl ModuleAffinityIndexAllocator {/// Return the number of empty slots available in this allocator.#[cfg(test)]pub fn num_empty_slots(&self) -> usize {- let inner = self.0.lock().unwrap();- let total_slots = inner.slot_state.len();- (total_slots - inner.last_cold as usize) + inner.unused_warm_slots as usize+ self.shards+ .iter()+ .map(|s| {+ let inner = s.0.lock().unwrap();+ let total_slots = inner.slot_state.len();+ (total_slots - inner.last_cold as usize) + inner.unused_warm_slots as usize+ })+ .sum()}/// For testing only, we want to be able to assert what is on the single/// freelist, for the policies that keep just one.#[cfg(test)]pub(crate) fn testing_freelist(&self) -> Vec<SlotId> {- let inner = self.0.lock().unwrap();- inner- .warm- .iter(&inner.slot_state, |s| &s.unused_list_link)+ self.shard_ids()+ .flat_map(|shard| {+ let inner = self.shard(shard).lock().unwrap();+ inner+ .warm+ .iter(&inner.slot_state, |s| &s.unused_list_link)+ .map(|local| self.global_id(shard, local))+ .collect::<Vec<_>>()+ }).collect()}@@ -365,8 +555,16 @@ impl ModuleAffinityIndexAllocator {/// with affinity for that module.#[cfg(test)]pub(crate) fn testing_module_affinity_list(&self) -> Vec<MemoryInModule> {- let inner = self.0.lock().unwrap();- inner.module_affine.keys().copied().collect()+ let mut ret = Vec::new();+ for s in self.shards.iter() {+ let inner = s.0.lock().unwrap();+ for key in inner.module_affine.keys() {+ if !ret.contains(key) {+ ret.push(*key);+ }+ }+ }+ ret}/// Returns the number of previously-used slots in this allocator which are@@ -375,7 +573,10 @@ impl ModuleAffinityIndexAllocator {/// Note that this acquires a `Mutex` for synchronization at this time to/// read the internal counter information.pub fn unused_warm_slots(&self) -> u32 {- self.0.lock().unwrap().unused_warm_slots+ self.shards+ .iter()+ .map(|s| s.0.lock().unwrap().unused_warm_slots)+ .sum()}/// Returns the number of bytes that are resident in previously-used slots@@ -384,7 +585,10 @@ impl ModuleAffinityIndexAllocator {/// Note that this acquires a `Mutex` for synchronization at this time to/// read the internal counter information.pub fn unused_bytes_resident(&self) -> usize {- self.0.lock().unwrap().unused_bytes_resident+ self.shards+ .iter()+ .map(|s| s.0.lock().unwrap().unused_bytes_resident)+ .sum()}}@@ -541,7 +745,7 @@ mod test {#[test]fn test_next_available_allocation_strategy() {for size in 0..20 {- let state = ModuleAffinityIndexAllocator::new(size, 0);+ let state = ModuleAffinityIndexAllocator::new(size, 0).unwrap();assert_eq!(state.num_empty_slots(), usize::try_from(size).unwrap());for i in 0..size {assert_eq!(state.num_empty_slots(), usize::try_from(size - i).unwrap());@@ -555,7 +759,7 @@ mod test {fn test_affinity_allocation_strategy() {let id1 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));let id2 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));- let state = ModuleAffinityIndexAllocator::new(100, 100);+ let state = ModuleAffinityIndexAllocator::new(100, 100).unwrap();let index1 = state.alloc(Some(id1)).unwrap();assert_eq!(index1.index(), 0);@@ -613,7 +817,7 @@ mod test {let memory_index = DefinedMemoryIndex::new(0);for max_unused_warm_slots in [0, 1, 2] {- let state = ModuleAffinityIndexAllocator::new(100, max_unused_warm_slots);+ let state = ModuleAffinityIndexAllocator::new(100, max_unused_warm_slots).unwrap();let index1 = state.alloc(Some(MemoryInModule(id, memory_index))).unwrap();let index2 = state.alloc(Some(MemoryInModule(id, memory_index))).unwrap();@@ -645,7 +849,13 @@ mod test {}).take(10).collect::<Vec<_>>();- let state = ModuleAffinityIndexAllocator::new(1000, 1000);+ // Pin the allocator to a single shard: with multiple shards a+ // thread's alloc probing finds any free slot in its home shard+ // before consulting the shard holding the affine slot, making the+ // hit-rate statistics below depend on the host's CPU count.+ // Sharded allocation is covered by the proptests at the bottom of+ // this module.+ let state = ModuleAffinityIndexAllocator::new_with_shard_count(1000, 1000, 1).unwrap();let mut allocated: Vec<SlotId> = vec![];let mut last_id = vec![None; 1000];@@ -687,7 +897,7 @@ mod test {let id1 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));let id2 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));let id3 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));- let state = ModuleAffinityIndexAllocator::new(10, 2);+ let state = ModuleAffinityIndexAllocator::new(10, 2).unwrap();// Set some slot affinitiesassert_eq!(state.alloc(Some(id1)), Some(SlotId(0)));@@ -756,7 +966,7 @@ mod test {#[test]fn test_freelist() {- let allocator = SimpleIndexAllocator::new(10);+ let allocator = SimpleIndexAllocator::new(10).unwrap();assert_eq!(allocator.testing_freelist(), []);let a = allocator.alloc().unwrap();assert_eq!(allocator.testing_freelist(), []);@@ -771,4 +981,90 @@ mod test {allocator.free(a, 0);assert_eq!(allocator.testing_freelist(), [b, a]);}++ #[test]+ // proptest reads the current directory for its persistence file, which+ // miri doesn't support with isolation enabled.+ #[cfg_attr(miri, ignore)]+ fn shard_layout_is_exhaustive_and_exact() {+ use proptest::prelude::*;++ proptest!(|(+ capacity in 0u32..100_000,+ max_unused_warm_slots in 0u32..10_000,+ requested_shards in 1u32..64,+ )| {+ let layout = ShardLayout::new(capacity, max_unused_warm_slots, requested_shards)+ .unwrap();++ // Shard capacities partition the whole slot space, and the+ // warm-slot budgets sum to the configured total, no matter how+ // unevenly the capacity divides.+ prop_assert_eq!(+ layout.shards.iter().map(|(c, _)| *c).sum::<u32>(),+ capacity+ );+ prop_assert_eq!(+ layout.shards.iter().map(|(_, w)| *w).sum::<u32>(),+ max_unused_warm_slots+ );++ // Every shard except possibly the last is exactly+ // `slots_per_shard` large, which the global<->local `SlotId`+ // translation relies on.+ let (last, rest) = layout.shards.split_last().unwrap();+ for (c, _) in rest {+ prop_assert_eq!(*c, layout.slots_per_shard);+ }+ prop_assert!(last.0 <= layout.slots_per_shard);++ // The requested shard count is an upper bound, and small pools+ // are never sharded.+ prop_assert!(layout.shards.len() <= requested_shards as usize);+ if capacity < 128 {+ prop_assert_eq!(layout.shards.len(), 1);+ }+ });+ }++ #[test]+ // proptest reads the current directory for its persistence file, which+ // miri doesn't support with isolation enabled.+ #[cfg_attr(miri, ignore)]+ fn sharded_alloc_is_exhaustive_and_unique() {+ use proptest::prelude::*;++ proptest!(|(+ capacity in 0u32..2048,+ max_unused_warm_slots in 0u32..100,+ requested_shards in 1u32..64,+ )| {+ let allocator = ModuleAffinityIndexAllocator::new_with_shard_count(+ capacity,+ max_unused_warm_slots,+ requested_shards,+ )+ .unwrap();++ // Regardless of shard layout, we can allocate exactly+ // `capacity` slots, all distinct and in-bounds, ...+ let mut ids = Vec::new();+ let mut seen = std::collections::HashSet::new();+ for _ in 0..capacity {+ let id = allocator.alloc(None).unwrap();+ prop_assert!(id.0 < capacity);+ prop_assert!(seen.insert(id.0));+ ids.push(id);+ }+ // ... after which the pool reports exhaustion, ...+ prop_assert!(allocator.alloc(None).is_none());++ // ... and freeing everything makes it all allocatable again.+ allocator.free_many(ids.into_iter().map(|id| (id, 0)));+ for _ in 0..capacity {+ prop_assert!(allocator.alloc(None).is_some());+ }+ prop_assert!(allocator.alloc(None).is_none());+ });+ }}diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/memory_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/memory_pool.rsindex 305f032992..1dc57b1232 100644--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/memory_pool.rs+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/memory_pool.rs@@ -263,15 +263,17 @@ impl MemoryPool {let allocator = ModuleAffinityIndexAllocator::new(num_slots.try_into().unwrap(),config.max_unused_warm_slots,- );- Stripe {+ )?;+ Ok(Stripe {allocator,pkey: pkeys.get(i).cloned(),- }+ })};debug_assert!(layout.num_stripes > 0);- let stripes: Vec<_> = (0..layout.num_stripes).map(create_stripe).collect();+ let stripes: Vec<_> = (0..layout.num_stripes)+ .map(create_stripe)+ .collect::<Result<_, OutOfMemory>>()?;let pool = Self {stripes,@@ -478,13 +480,50 @@ impl MemoryPool {image: Option<MemoryImageSlot>,bytes_resident: usize,) {- self.return_memory_image_slot(allocation_index, image);+ let (stripe_index, slot_id) = self.return_slot(allocation_index, image);+ self.stripes[stripe_index]+ .allocator+ .free(slot_id, bytes_resident);+ }+ /// Same as [`Self::deallocate`], but for many memories at once, returning+ /// slot indices to each stripe's index allocator under a single lock+ /// acquisition per stripe.+ ///+ /// # Safety+ ///+ /// Same as [`Self::deallocate`].+ pub unsafe fn deallocate_many(+ &self,+ items: impl Iterator<Item = (MemoryAllocationIndex, Option<MemoryImageSlot>, usize)>,+ ) {+ let mut per_stripe: smallvec::SmallVec<[smallvec::SmallVec<[(SlotId, usize); 8]>; 16]> = (0+ ..self.stripes.len())+ .map(|_| Default::default())+ .collect();+ for (allocation_index, image, bytes_resident) in items {+ let (stripe_index, slot_id) = self.return_slot(allocation_index, image);+ per_stripe[stripe_index].push((slot_id, bytes_resident));+ }+ for (stripe, items) in self.stripes.iter().zip(per_stripe) {+ if !items.is_empty() {+ stripe.allocator.free_many(items);+ }+ }+ }++ /// Return `allocation_index`'s image slot to the pool and translate the+ /// index to its stripe and stripe-local slot id, on behalf of+ /// [`Self::deallocate`] and [`Self::deallocate_many`].+ fn return_slot(+ &self,+ allocation_index: MemoryAllocationIndex,+ image: Option<MemoryImageSlot>,+ ) -> (usize, SlotId) {+ self.return_memory_image_slot(allocation_index, image);let (stripe_index, striped_allocation_index) =StripedAllocationIndex::from_unstriped_slot_index(allocation_index, self.stripes.len());- self.stripes[stripe_index]- .allocator- .free(SlotId(striped_allocation_index.0), bytes_resident);+ (stripe_index, SlotId(striped_allocation_index.0))}/// Purging everything related to `module`.diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/table_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/table_pool.rsindex 1d10026ee9..6f060cb10a 100644--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/table_pool.rs+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/table_pool.rs@@ -48,7 +48,7 @@ impl TablePool {let keep_resident = HostAlignedByteCount::new_rounded_up(config.table_keep_resident)?;Ok(Self {- index_allocator: SimpleIndexAllocator::new(config.limits.total_tables),+ index_allocator: SimpleIndexAllocator::new(config.limits.total_tables)?,mapping,table_size,max_total_tables,@@ -186,26 +186,26 @@ impl TablePool {}}- /// Deallocate a previously-allocated table.+ /// Deallocate the previously-allocated tables produced by `items`.////// # Safety///- /// The table must have been previously-allocated by this pool and assigned- /// the given allocation index, it must currently be allocated, and it must- /// never be used again.+ /// The tables must have been previously-allocated by this pool and assigned+ /// their given allocation indices, they must currently be allocated, and+ /// they must never be used again.////// The caller must have already called `reset_table_pages_to_zero` on the- /// memory and flushed any enqueued decommits for this table's memory.- pub unsafe fn deallocate(+ /// memories and flushed any enqueued decommits for these tables' memories.+ pub unsafe fn deallocate_many(&self,- allocation_index: TableAllocationIndex,- table: Table,- bytes_resident: usize,+ items: impl Iterator<Item = (TableAllocationIndex, Table, usize)>,) {- assert!(table.is_static());- drop(table);self.index_allocator- .free(SlotId(allocation_index.0), bytes_resident);+ .free_many(items.map(|(allocation_index, table, bytes_resident)| {+ assert!(table.is_static());+ drop(table);+ (SlotId(allocation_index.0), bytes_resident)+ }));}/// Reset the given table's memory to zero.diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/unix_stack_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/unix_stack_pool.rsindex fa1718f26e..2f779e2ab2 100644--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/unix_stack_pool.rs+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/unix_stack_pool.rs@@ -83,7 +83,7 @@ impl StackPool {async_stack_keep_resident: HostAlignedByteCount::new_rounded_up(config.async_stack_keep_resident,)?,- index_allocator: SimpleIndexAllocator::new(config.limits.total_stacks),+ index_allocator: SimpleIndexAllocator::new(config.limits.total_stacks)?,})}@@ -208,16 +208,26 @@ impl StackPool {size_to_memset.byte_count()}- /// Deallocate a previously-allocated fiber.+ /// Deallocate the previously-allocated fibers produced by `items`.////// # Safety///- /// The fiber must have been allocated by this pool, must be in an allocated- /// state, and must never be used again.+ /// The fibers must have been previously-allocated by this pool, must be+ /// in an allocated state, and must never be used again.///- /// The caller must have already called `zero_stack` on the fiber stack and- /// flushed any enqueued decommits for this stack's memory.- pub unsafe fn deallocate(&self, stack: wasmtime_fiber::FiberStack, bytes_resident: usize) {+ /// The caller must have already called `zero_stack` on the fiber stacks+ /// and flushed any enqueued decommits for these stacks' memories.+ pub unsafe fn deallocate_many(+ &self,+ stacks: impl Iterator<Item = (wasmtime_fiber::FiberStack, usize)>,+ ) {+ self.index_allocator.free_many(+ stacks+ .map(|(stack, bytes_resident)| (SlotId(self.stack_index(&stack)), bytes_resident)),+ );+ }++ fn stack_index(&self, stack: &wasmtime_fiber::FiberStack) -> u32 {assert!(stack.is_from_raw_parts());let top = stack@@ -240,9 +250,7 @@ impl StackPool {let index = (start_of_stack - base) / self.stack_size.byte_count();assert!(index < self.max_stacks);- let index = u32::try_from(index).unwrap();-- self.index_allocator.free(SlotId(index), bytes_resident);+ u32::try_from(index).unwrap()}pub fn unused_warm_slots(&self) -> u32 {@@ -299,10 +307,8 @@ mod tests {assert!(pool.allocate().is_err(), "allocation should fail");- for stack in stacks {- unsafe {- pool.deallocate(stack, 0);- }+ unsafe {+ pool.deallocate_many(stacks.into_iter().map(|stack| (stack, 0)));}assert_eq!(