Skip to main content

wasmtime/runtime/vm/instance/allocator/pooling/
memory_pool.rs

1//! Implements a memory pool using a single allocated memory slab.
2//!
3//! The pooling instance allocator maps one large slab of memory in advance and
4//! allocates WebAssembly memories from this slab--a [`MemoryPool`]. Each
5//! WebAssembly memory is allocated in its own slot (see uses of `index` and
6//! [`SlotId`] in this module):
7//!
8//! ```text
9//! ┌──────┬──────┬──────┬──────┬──────┐
10//! │Slot 0│Slot 1│Slot 2│Slot 3│......│
11//! └──────┴──────┴──────┴──────┴──────┘
12//! ```
13//!
14//! Diving deeper, we note that a [`MemoryPool`] protects Wasmtime from
15//! out-of-bounds memory accesses by inserting inaccessible guard regions
16//! between memory slots. These guard regions are configured to raise a signal
17//! if they are accessed--a WebAssembly out-of-bounds (OOB) memory access. The
18//! [`MemoryPool`] documentation has a more detailed chart but one can think of
19//! memory slots being laid out like the following:
20//!
21//! ```text
22//! ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
23//! │Guard│Mem 0│Guard│Mem 1│Guard│Mem 2│.....│Guard│
24//! └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
25//! ```
26//!
27//! But we can be more efficient about guard regions: with memory protection
28//! keys (MPK) enabled, the interleaved guard regions can be smaller. If we
29//! surround a memory with memories from other instances and each instance is
30//! protected by different protection keys, the guard region can be smaller AND
31//! the pool will still raise a signal on an OOB access. This complicates how we
32//! lay out memory slots: we must store memories from the same instance in the
33//! same "stripe". Each stripe is protected by a different protection key.
34//!
35//! This concept, dubbed [ColorGuard] in the original paper, relies on careful
36//! calculation of the memory sizes to prevent any "overlapping access" (see
37//! [`calculate`]): there are limited protection keys available (15) so the next
38//! memory using the same key must be at least as far away as the guard region
39//! we would insert otherwise. This ends up looking like the following, where a
40//! store for instance 0 (`I0`) "stripes" two memories (`M0` and `M1`) with the
41//! same protection key 1 and far enough apart to signal an OOB access:
42//!
43//! ```text
44//! ┌─────┬─────┬─────┬─────┬────────────────┬─────┬─────┬─────┐
45//! │.....│I0:M1│.....│.....│.<enough slots>.│I0:M2│.....│.....│
46//! ├─────┼─────┼─────┼─────┼────────────────┼─────┼─────┼─────┤
47//! │.....│key 1│key 2│key 3│..<more keys>...│key 1│key 2│.....│
48//! └─────┴─────┴─────┴─────┴────────────────┴─────┴─────┴─────┘
49//! ```
50//!
51//! [ColorGuard]: https://plas2022.github.io/files/pdf/SegueColorGuard.pdf
52
53use super::{
54    MemoryAllocationIndex,
55    index_allocator::{MemoryInModule, ModuleAffinityIndexAllocator, SlotId},
56};
57use crate::config::InstanceLimits;
58use crate::config::PoolingAllocationConfig;
59use crate::prelude::*;
60use crate::runtime::vm::{
61    CompiledModuleId, InstanceAllocationRequest, Memory, MemoryImageSlot, Mmap, MmapOffset,
62    mmap::AlignedLength,
63};
64use crate::vm::sys::vm::{decommit_pages, iovec};
65use crate::{
66    Enabled,
67    runtime::vm::mpk::{self, ProtectionKey, ProtectionMask},
68    vm::HostAlignedByteCount,
69};
70use std::mem;
71use std::sync::atomic::{AtomicUsize, Ordering};
72use std::sync::{Arc, Mutex};
73use wasmtime_environ::{DefinedMemoryIndex, MemoryKind, MemoryTunables, Module, Tunables};
74
75/// A set of allocator slots.
76///
77/// The allocated slots can be split by striping them: e.g., with two stripe
78/// colors 0 and 1, we would allocate all even slots using stripe 0 and all odd
79/// slots using stripe 1.
80///
81/// This is helpful for the use of protection keys: (a) if a request comes to
82/// allocate multiple instances, we can allocate them all from the same stripe
83/// and (b) if a store wants to allocate more from the same stripe it can.
84#[derive(Debug)]
85struct Stripe {
86    allocator: ModuleAffinityIndexAllocator,
87    pkey: Option<ProtectionKey>,
88}
89
90/// Represents a pool of WebAssembly linear memories.
91///
92/// A linear memory is divided into accessible pages and guard pages. A memory
93/// pool contains linear memories: each memory occupies a slot in an
94/// allocated slab (i.e., `mapping`):
95///
96/// ```text
97///          layout.max_memory_bytes                 layout.slot_bytes
98///                    |                                   |
99///              ◄─────┴────►                  ◄───────────┴──────────►
100/// ┌───────────┬────────────┬───────────┐     ┌───────────┬───────────┬───────────┐
101/// | PROT_NONE |            | PROT_NONE | ... |           | PROT_NONE | PROT_NONE |
102/// └───────────┴────────────┴───────────┘     └───────────┴───────────┴───────────┘
103/// |           |◄──────────────────┬─────────────────────────────────► ◄────┬────►
104/// |           |                   |                                        |
105/// mapping     |            `layout.num_slots` memories         layout.post_slab_guard_size
106///             |
107///   layout.pre_slab_guard_size
108/// ```
109#[derive(Debug)]
110pub struct MemoryPool {
111    mapping: Arc<Mmap<AlignedLength>>,
112    /// This memory pool is stripe-aware. If using  memory protection keys, this
113    /// will contain one stripe per available key; otherwise, a single stripe
114    /// with an empty key.
115    stripes: Vec<Stripe>,
116
117    /// If using a copy-on-write allocation scheme, the slot management. We
118    /// dynamically transfer ownership of a slot to a Memory when in use.
119    image_slots: Vec<Mutex<ImageSlot>>,
120
121    /// A description of the various memory sizes used in allocating the
122    /// `mapping` slab.
123    layout: SlabLayout,
124
125    /// The maximum number of memories that a single core module instance may
126    /// use.
127    ///
128    /// NB: this is needed for validation but does not affect the pool's size.
129    memories_per_instance: usize,
130
131    /// How much linear memory, in bytes, to keep resident after resetting for
132    /// use with the next instance. This much memory will be `memset` to zero
133    /// when a linear memory is deallocated.
134    ///
135    /// Memory exceeding this amount in the wasm linear memory will be released
136    /// with `madvise` back to the kernel.
137    ///
138    /// Only applicable on Linux.
139    pub(super) keep_resident: HostAlignedByteCount,
140
141    /// Keep track of protection keys handed out to initialized stores; this
142    /// allows us to round-robin the assignment of stores to stripes.
143    next_available_pkey: AtomicUsize,
144}
145
146/// The state of memory for each slot in this pool.
147#[derive(Debug)]
148enum ImageSlot {
149    /// This slot is guaranteed to be entirely unmapped.
150    ///
151    /// This is the initial state of all slots.
152    Unmapped,
153
154    /// The state of this slot is unknown.
155    ///
156    /// This encompasses a number of situations such as:
157    ///
158    /// * The slot is currently in use.
159    /// * The slot was attempted to be in use, but allocation failed.
160    /// * The slot was used but not deallocated properly.
161    ///
162    /// All of these situations are lumped into this one variant indicating
163    /// that, at a base level, no knowledge is known about this slot. Using a
164    /// slot in this state first requires resetting all memory in this slot by
165    /// mapping anonymous memory on top of the entire slot.
166    Unknown,
167
168    /// This slot was previously used and `MemoryImageSlot` maintains the state
169    /// about what this slot was last configured as.
170    ///
171    /// Future use of this slot will use `MemoryImageSlot` to continue to
172    /// re-instantiate and reuse images and such. This state is entered after
173    /// and allocated slot is successfully deallocated.
174    PreviouslyUsed(MemoryImageSlot),
175}
176
177impl MemoryPool {
178    /// Create a new `MemoryPool`.
179    pub fn new(config: &PoolingAllocationConfig, tunables: &Tunables) -> Result<Self> {
180        if u64::try_from(config.limits.max_memory_size).unwrap() > tunables.memory_reservation {
181            bail!(
182                "maximum memory size of {:#x} bytes exceeds the configured \
183                 memory reservation of {:#x} bytes",
184                config.limits.max_memory_size,
185                tunables.memory_reservation
186            );
187        }
188        let pkeys = match config.memory_protection_keys {
189            Enabled::Auto => {
190                if mpk::is_supported() {
191                    mpk::keys(config.max_memory_protection_keys)
192                } else {
193                    &[]
194                }
195            }
196            Enabled::Yes => {
197                if mpk::is_supported() {
198                    mpk::keys(config.max_memory_protection_keys)
199                } else {
200                    bail!("mpk is disabled on this system")
201                }
202            }
203            Enabled::No => &[],
204        };
205
206        // This is a tricky bit of global state: when creating a memory pool
207        // that uses memory protection keys, we ensure here that any host code
208        // will have access to all keys (i.e., stripes). It's only when we enter
209        // the WebAssembly guest code (see `StoreInner::call_hook`) that we
210        // enforce which keys/stripes can be accessed. Be forewarned about the
211        // assumptions here:
212        // - we expect this "allow all" configuration to reset the default
213        //   process state (only allow key 0) _before_ any memories are accessed
214        // - and we expect no other code (e.g., host-side code) to modify this
215        //   global MPK configuration
216        if !pkeys.is_empty() {
217            mpk::allow(ProtectionMask::all());
218        }
219
220        // Create a slab layout and allocate it as a completely inaccessible
221        // region to start--`PROT_NONE`.
222        let constraints = SlabConstraints::new(&config.limits, tunables, pkeys.len())?;
223        let layout = calculate(&constraints)?;
224        log::debug!(
225            "creating memory pool: {constraints:?} -> {layout:?} (total: {})",
226            layout.total_slab_bytes()?
227        );
228        let mut mapping =
229            Mmap::accessible_reserved(HostAlignedByteCount::ZERO, layout.total_slab_bytes()?)
230                .context("failed to create memory pool mapping")?;
231
232        // Then, stripe the memory with the available protection keys. This is
233        // unnecessary if there is only one stripe color.
234        if layout.num_stripes >= 2 {
235            let mut cursor = layout.pre_slab_guard_bytes;
236            let pkeys = &pkeys[..layout.num_stripes];
237            for i in 0..constraints.num_slots {
238                let pkey = &pkeys[i % pkeys.len()];
239                let region = unsafe {
240                    mapping.slice_mut(
241                        cursor.byte_count()..cursor.byte_count() + layout.slot_bytes.byte_count(),
242                    )
243                };
244                pkey.protect(region)?;
245                cursor = cursor
246                    .checked_add(layout.slot_bytes)
247                    .context("cursor + slot_bytes overflows")?;
248            }
249            debug_assert_eq!(
250                cursor
251                    .checked_add(layout.post_slab_guard_bytes)
252                    .context("cursor + post_slab_guard_bytes overflows")?,
253                layout.total_slab_bytes()?
254            );
255        }
256
257        let image_slots: Vec<_> = std::iter::repeat_with(|| Mutex::new(ImageSlot::Unmapped))
258            .take(constraints.num_slots)
259            .collect();
260
261        let create_stripe = |i| {
262            let num_slots = constraints.num_slots / layout.num_stripes
263                + usize::from(constraints.num_slots % layout.num_stripes > i);
264            let allocator = ModuleAffinityIndexAllocator::new(
265                num_slots.try_into().unwrap(),
266                config.max_unused_warm_slots,
267            )?;
268            Ok(Stripe {
269                allocator,
270                pkey: pkeys.get(i).cloned(),
271            })
272        };
273
274        debug_assert!(layout.num_stripes > 0);
275        let stripes: Vec<_> = (0..layout.num_stripes)
276            .map(create_stripe)
277            .collect::<Result<_, OutOfMemory>>()?;
278
279        let pool = Self {
280            stripes,
281            mapping: Arc::new(mapping),
282            image_slots,
283            layout,
284            memories_per_instance: usize::try_from(config.limits.max_memories_per_module).unwrap(),
285            keep_resident: HostAlignedByteCount::new_rounded_up(
286                config.linear_memory_keep_resident,
287            )?,
288            next_available_pkey: AtomicUsize::new(0),
289        };
290
291        Ok(pool)
292    }
293
294    /// Return a protection key that stores can use for requesting new
295    pub fn next_available_pkey(&self) -> Option<ProtectionKey> {
296        let index = self.next_available_pkey.fetch_add(1, Ordering::SeqCst) % self.stripes.len();
297        debug_assert!(
298            self.stripes.len() < 2 || self.stripes[index].pkey.is_some(),
299            "if we are using stripes, we cannot have an empty protection key"
300        );
301        self.stripes[index].pkey
302    }
303
304    /// Validate whether this memory pool supports the given module.
305    pub fn validate_memories(&self, module: &Module) -> Result<()> {
306        let memories = module.num_defined_memories();
307        if memories > self.memories_per_instance {
308            bail!(
309                "defined memories count of {} exceeds the per-instance limit of {}",
310                memories,
311                self.memories_per_instance,
312            );
313        }
314
315        for (i, memory) in module.memories.iter().skip(module.num_imported_memories) {
316            self.validate_memory(memory).with_context(|| {
317                format!(
318                    "memory index {} is unsupported in this pooling allocator configuration",
319                    i.as_u32()
320                )
321            })?;
322        }
323        Ok(())
324    }
325
326    /// Validate one memory for this pool.
327    pub fn validate_memory(&self, memory: &wasmtime_environ::Memory) -> Result<()> {
328        let min = memory.minimum_byte_size().with_context(|| {
329            format!("memory has a minimum byte size that cannot be represented in a u64",)
330        })?;
331        if min > u64::try_from(self.layout.max_memory_bytes.byte_count()).unwrap() {
332            bail!(
333                "memory has a minimum byte size of {} which exceeds the limit of {} bytes",
334                min,
335                self.layout.max_memory_bytes,
336            );
337        }
338        if memory.shared {
339            // FIXME(#4244): since the pooling allocator owns the memory
340            // allocation (which is torn down with the instance), that
341            // can't be used with shared memory where threads or the host
342            // might persist the memory beyond the lifetime of the instance
343            // itself.
344            bail!("memory is shared which is not supported in the pooling allocator");
345        }
346        Ok(())
347    }
348
349    /// Are zero slots in use right now?
350    pub fn is_empty(&self) -> bool {
351        self.stripes.iter().all(|s| s.allocator.is_empty())
352    }
353
354    /// Allocate a single memory for the given instance allocation request.
355    pub async fn allocate(
356        &self,
357        request: &mut InstanceAllocationRequest<'_, '_>,
358        ty: &wasmtime_environ::Memory,
359        memory_index: Option<DefinedMemoryIndex>,
360    ) -> Result<(MemoryAllocationIndex, Memory)> {
361        let tunables = request.store.engine().tunables();
362        let memory_tunables = MemoryTunables::new(tunables, MemoryKind::LinearMemory);
363        let stripe_index = if let Some(pkey) = request.store.get_pkey() {
364            pkey.as_stripe()
365        } else {
366            debug_assert!(self.stripes.len() < 2);
367            0
368        };
369
370        let striped_allocation_index = self.stripes[stripe_index]
371            .allocator
372            .alloc(memory_index.and_then(|mem_idx| {
373                request
374                    .runtime_info
375                    .unique_id()
376                    .map(|id| MemoryInModule(id, mem_idx))
377            }))
378            .map(|slot| StripedAllocationIndex(u32::try_from(slot.index()).unwrap()))
379            .ok_or_else(|| {
380                super::PoolConcurrencyLimitError::new(
381                    self.stripes[stripe_index].allocator.len(),
382                    format!("memory stripe {stripe_index}"),
383                )
384            })?;
385        let mut guard = DeallocateIndexGuard {
386            pool: self,
387            stripe_index,
388            striped_allocation_index,
389            active: true,
390        };
391
392        let allocation_index =
393            striped_allocation_index.as_unstriped_slot_index(stripe_index, self.stripes.len());
394
395        // Double-check that the runtime requirements of the memory are
396        // satisfied by the configuration of this pooling allocator. This
397        // should be returned as an error through `validate_memory_plans`
398        // but double-check here to be sure.
399        assert!(
400            memory_tunables.reservation() + memory_tunables.guard_size()
401                <= u64::try_from(self.layout.bytes_to_next_stripe_slot().byte_count()).unwrap()
402        );
403
404        let base = self.get_base(allocation_index);
405        let base_capacity = self.layout.max_memory_bytes;
406
407        let mut slot = self.take_memory_image_slot(allocation_index)?;
408        let image = match memory_index {
409            Some(memory_index) => request.runtime_info.memory_image(memory_index)?,
410            None => None,
411        };
412        let initial_size = ty
413            .minimum_byte_size()
414            .expect("min size checked in validation");
415
416        // If instantiation fails, we can propagate the error
417        // upward and drop the slot. This will cause the Drop
418        // handler to attempt to map the range with PROT_NONE
419        // memory, to reserve the space while releasing any
420        // stale mappings. The next use of this slot will then
421        // create a new slot that will try to map over
422        // this, returning errors as well if the mapping
423        // errors persist. The unmap-on-drop is best effort;
424        // if it fails, then we can still soundly continue
425        // using the rest of the pool and allowing the rest of
426        // the process to continue, because we never perform a
427        // mmap that would leave an open space for someone
428        // else to come in and map something.
429        let initial_size = usize::try_from(initial_size).unwrap();
430        slot.instantiate(initial_size, image, ty, &memory_tunables)?;
431
432        let memory = Memory::new_static(
433            ty,
434            &memory_tunables,
435            base,
436            base_capacity.byte_count(),
437            slot,
438            request.limiter.as_deref_mut(),
439        )
440        .await?;
441        guard.active = false;
442        return Ok((allocation_index, memory));
443
444        struct DeallocateIndexGuard<'a> {
445            pool: &'a MemoryPool,
446            stripe_index: usize,
447            striped_allocation_index: StripedAllocationIndex,
448            active: bool,
449        }
450
451        impl Drop for DeallocateIndexGuard<'_> {
452            fn drop(&mut self) {
453                if !self.active {
454                    return;
455                }
456                self.pool.stripes[self.stripe_index]
457                    .allocator
458                    .free(SlotId(self.striped_allocation_index.0), 0);
459            }
460        }
461    }
462
463    /// Deallocate a previously-allocated memory.
464    ///
465    /// If `image` is `None` then the state of this memory's slot is left
466    /// unknown. Otherwise `image` is used to retain information about the state
467    /// of this slot.
468    ///
469    /// # Safety
470    ///
471    /// The memory must have been previously allocated from this pool and
472    /// assigned the given index, must currently be in an allocated state, and
473    /// must never be used again.
474    ///
475    /// The caller must have already called `clear_and_remain_ready` on the
476    /// memory's image and flushed any enqueued decommits for this memory. Note
477    /// that if `image` is `None` then this is not required.
478    pub unsafe fn deallocate(
479        &self,
480        allocation_index: MemoryAllocationIndex,
481        image: Option<MemoryImageSlot>,
482        bytes_resident: usize,
483    ) {
484        let (stripe_index, slot_id) = self.return_slot(allocation_index, image);
485        self.stripes[stripe_index]
486            .allocator
487            .free(slot_id, bytes_resident);
488    }
489
490    /// Same as [`Self::deallocate`], but for many memories at once, returning
491    /// slot indices to each stripe's index allocator under a single lock
492    /// acquisition per stripe.
493    ///
494    /// # Safety
495    ///
496    /// Same as [`Self::deallocate`].
497    pub unsafe fn deallocate_many(
498        &self,
499        items: impl Iterator<Item = (MemoryAllocationIndex, Option<MemoryImageSlot>, usize)>,
500    ) {
501        let mut per_stripe: smallvec::SmallVec<[smallvec::SmallVec<[(SlotId, usize); 8]>; 16]> = (0
502            ..self.stripes.len())
503            .map(|_| Default::default())
504            .collect();
505        for (allocation_index, image, bytes_resident) in items {
506            let (stripe_index, slot_id) = self.return_slot(allocation_index, image);
507            per_stripe[stripe_index].push((slot_id, bytes_resident));
508        }
509        for (stripe, items) in self.stripes.iter().zip(per_stripe) {
510            if !items.is_empty() {
511                stripe.allocator.free_many(items);
512            }
513        }
514    }
515
516    /// Return `allocation_index`'s image slot to the pool and translate the
517    /// index to its stripe and stripe-local slot id, on behalf of
518    /// [`Self::deallocate`] and [`Self::deallocate_many`].
519    fn return_slot(
520        &self,
521        allocation_index: MemoryAllocationIndex,
522        image: Option<MemoryImageSlot>,
523    ) -> (usize, SlotId) {
524        self.return_memory_image_slot(allocation_index, image);
525        let (stripe_index, striped_allocation_index) =
526            StripedAllocationIndex::from_unstriped_slot_index(allocation_index, self.stripes.len());
527        (stripe_index, SlotId(striped_allocation_index.0))
528    }
529
530    /// Purging everything related to `module`.
531    pub fn purge_module(&self, module: CompiledModuleId) {
532        // This primarily means clearing out all of its memory images present in
533        // the virtual address space. Go through the index allocator for slots
534        // affine to `module` and reset them, freeing up the index when we're
535        // done.
536        //
537        // Note that this is only called when the specified `module` won't be
538        // allocated further (the module is being dropped) so this shouldn't hit
539        // any sort of infinite loop since this should be the final operation
540        // working with `module`.
541        //
542        // TODO: We are given a module id, but key affinity by pair of module id
543        // and defined memory index. We are missing any defined memory index or
544        // count of how many memories the module defines here. Therefore, we
545        // probe up to the maximum number of memories per instance. This is fine
546        // because that maximum is generally relatively small. If this method
547        // somehow ever gets hot because of unnecessary probing, we should
548        // either pass in the actual number of defined memories for the given
549        // module to this method, or keep a side table of all slots that are
550        // associated with a module (not just module and memory). The latter
551        // would require care to make sure that its maintenance wouldn't be too
552        // expensive for normal allocation/free operations.
553        for (stripe_index, stripe) in self.stripes.iter().enumerate() {
554            for i in 0..self.memories_per_instance {
555                use wasmtime_environ::EntityRef;
556                let memory_index = DefinedMemoryIndex::new(i);
557                while let Some(id) = stripe
558                    .allocator
559                    .alloc_affine_and_clear_affinity(module, memory_index)
560                {
561                    // Attempt to acquire the `MemoryImageSlot` state for this
562                    // slot, and then if we have that try to remove the image,
563                    // and then if all that succeeds put the slot back in.
564                    //
565                    // If anything fails then the slot will be in an "unknown"
566                    // state which means that on next use it'll be remapped with
567                    // anonymous memory.
568                    let index = StripedAllocationIndex(id.0)
569                        .as_unstriped_slot_index(stripe_index, self.stripes.len());
570                    if let Ok(mut slot) = self.take_memory_image_slot(index) {
571                        if slot.remove_image().is_ok() {
572                            self.return_memory_image_slot(index, Some(slot));
573                        }
574                    }
575
576                    stripe.allocator.free(id, 0);
577                }
578            }
579        }
580    }
581
582    /// Releases the memory this pool is keeping resident for unused-but-warm
583    /// slots.
584    ///
585    /// Useful when the embedder knows that load has decreased and wishes to
586    /// reduce resident memory usage at the cost of some instantiation time at
587    /// the next instantiation.
588    ///
589    /// Returns the number of bytes freed.
590    ///
591    /// Slots are taken out of the free lists before their memory is released
592    /// and returned afterwards, so nothing can allocate a slot while it is
593    /// being decommitted, the same order `DecommitQueue::flush` uses.
594    pub fn release_resident_unused_memory(&self) -> usize {
595        let mut released = 0;
596        for (stripe_index, stripe) in self.stripes.iter().enumerate() {
597            let taken = stripe.allocator.take_resident_warm_slots();
598            if taken.is_empty() {
599                continue;
600            }
601
602            let mut iov = Vec::with_capacity(taken.len());
603            for (id, bytes_resident) in &taken {
604                if *bytes_resident == 0 {
605                    continue;
606                }
607                let index = StripedAllocationIndex(id.0)
608                    .as_unstriped_slot_index(stripe_index, self.stripes.len());
609                iov.push(iovec {
610                    iov_base: self.get_base(index).as_mut_ptr().cast(),
611                    iov_len: self.layout.max_memory_bytes.byte_count(),
612                });
613            }
614
615            // SAFETY: every region here belongs to a slot this loop has taken
616            // out of the free list, so it is not in use and cannot be handed
617            // out until it is freed below.
618            let decommitted = unsafe { decommit_pages(&iov) }.is_ok();
619
620            // A failed decommit leaves the pages resident with the contents
621            // they had, which is a correct state: the slots go back reporting
622            // the same bytes as before and nothing but the reclaim is lost.
623            for (id, bytes_resident) in taken {
624                if decommitted {
625                    released += bytes_resident;
626                    stripe.allocator.free(id, 0);
627                } else {
628                    stripe.allocator.free(id, bytes_resident);
629                }
630            }
631        }
632        released
633    }
634
635    fn get_base(&self, allocation_index: MemoryAllocationIndex) -> MmapOffset {
636        assert!(allocation_index.index() < self.layout.num_slots);
637        let offset = self
638            .layout
639            .slot_bytes
640            .checked_mul(allocation_index.index())
641            .and_then(|c| c.checked_add(self.layout.pre_slab_guard_bytes))
642            .expect("slot_bytes * index + pre_slab_guard_bytes overflows");
643        self.mapping.offset(offset).expect("offset is in bounds")
644    }
645
646    /// Return the protection key that this slot's memory was striped with when
647    /// the pool was created, if any.
648    ///
649    /// This mirrors the striping performed in `new`: memory is only colored
650    /// when there are at least two stripes, and slot `i` is colored with the
651    /// `i % num_stripes`th key.
652    fn pkey_for_slot(&self, allocation_index: MemoryAllocationIndex) -> Option<ProtectionKey> {
653        if self.stripes.len() < 2 {
654            return None;
655        }
656        self.stripes[allocation_index.index() % self.stripes.len()].pkey
657    }
658
659    /// Take ownership of the given image slot.
660    ///
661    /// This method is used when a `MemoryAllocationIndex` has been allocated
662    /// and the state of the slot needs to be acquired. This will lazily
663    /// allocate a `MemoryImageSlot` which describes the current (and possibly
664    /// prior) state of the slot.
665    ///
666    /// During deallocation this structure is passed back to
667    /// `return_memory_image_slot`.
668    ///
669    /// Note that this is a fallible method because using a slot might require
670    /// resetting the memory that was previously there. This reset operation
671    /// is a fallible operation that may not succeed. If it fails then this
672    /// slot cannot be used at this time.
673    fn take_memory_image_slot(
674        &self,
675        allocation_index: MemoryAllocationIndex,
676    ) -> Result<MemoryImageSlot> {
677        let (maybe_slot, needs_reset) = {
678            let mut slot = self.image_slots[allocation_index.index()].lock().unwrap();
679            match mem::replace(&mut *slot, ImageSlot::Unknown) {
680                ImageSlot::Unmapped => (None, false),
681                ImageSlot::Unknown => (None, true),
682                ImageSlot::PreviouslyUsed(state) => (Some(state), false),
683            }
684        };
685        let mut slot = maybe_slot.unwrap_or_else(|| {
686            MemoryImageSlot::create(
687                self.get_base(allocation_index),
688                HostAlignedByteCount::ZERO,
689                self.layout.max_memory_bytes.byte_count(),
690                self.pkey_for_slot(allocation_index),
691            )
692        });
693
694        // For `Unknown` slots it means that `slot` is brand new and isn't
695        // actually tracking the state of the previous slot, so reset it
696        // entirely with anonymous memory to wipe the slate clean and start
697        // from zero. This should only happen if allocation of the previous
698        // slot failed, for example.
699        if needs_reset {
700            slot.reset_with_anon_memory()?;
701        }
702        Ok(slot)
703    }
704
705    /// Return ownership of the given image slot.
706    ///
707    /// If `slot` is not provided then it's reset with `Unknown` meaning a
708    /// future allocation will need to pave over it to use it.
709    fn return_memory_image_slot(
710        &self,
711        allocation_index: MemoryAllocationIndex,
712        slot: Option<MemoryImageSlot>,
713    ) {
714        let prev = mem::replace(
715            &mut *self.image_slots[allocation_index.index()].lock().unwrap(),
716            match slot {
717                Some(slot) => {
718                    assert!(!slot.is_dirty());
719                    ImageSlot::PreviouslyUsed(slot)
720                }
721                None => ImageSlot::Unknown,
722            },
723        );
724        assert!(matches!(prev, ImageSlot::Unknown));
725    }
726
727    pub fn unused_warm_slots(&self) -> u32 {
728        self.stripes
729            .iter()
730            .map(|i| i.allocator.unused_warm_slots())
731            .sum()
732    }
733
734    pub fn unused_bytes_resident(&self) -> usize {
735        self.stripes
736            .iter()
737            .map(|i| i.allocator.unused_bytes_resident())
738            .sum()
739    }
740}
741
742/// The index of a memory allocation within an `InstanceAllocator`.
743#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
744pub struct StripedAllocationIndex(u32);
745
746impl StripedAllocationIndex {
747    fn from_unstriped_slot_index(
748        index: MemoryAllocationIndex,
749        num_stripes: usize,
750    ) -> (usize, Self) {
751        let stripe_index = index.index() % num_stripes;
752        let num_stripes: u32 = num_stripes.try_into().unwrap();
753        let index_within_stripe = Self(index.0 / num_stripes);
754        (stripe_index, index_within_stripe)
755    }
756
757    fn as_unstriped_slot_index(self, stripe: usize, num_stripes: usize) -> MemoryAllocationIndex {
758        let num_stripes: u32 = num_stripes.try_into().unwrap();
759        let stripe: u32 = stripe.try_into().unwrap();
760        MemoryAllocationIndex(self.0 * num_stripes + stripe)
761    }
762}
763
764#[derive(Clone, Debug)]
765struct SlabConstraints {
766    /// Essentially, the `static_memory_bound`: this is an assumption that the
767    /// runtime and JIT compiler make about how much space will be guarded
768    /// between slots.
769    expected_slot_bytes: HostAlignedByteCount,
770    /// The maximum size of any memory in the pool. Always a non-zero multiple
771    /// of the page size.
772    max_memory_bytes: HostAlignedByteCount,
773    num_slots: usize,
774    num_pkeys_available: usize,
775    guard_bytes: HostAlignedByteCount,
776    guard_before_slots: bool,
777}
778
779impl SlabConstraints {
780    fn new(
781        limits: &InstanceLimits,
782        tunables: &Tunables,
783        num_pkeys_available: usize,
784    ) -> Result<Self> {
785        // `memory_reservation` is the configured number of bytes for a
786        // static memory slot (see `Config::memory_reservation`); even
787        // if the memory never grows to this size (e.g., it has a lower memory
788        // maximum), codegen will assume that this unused memory is mapped
789        // `PROT_NONE`. Typically `memory_reservation` is 4GiB which helps
790        // elide most bounds checks. `MemoryPool` must respect this bound,
791        // though not explicitly: if we can achieve the same effect via
792        // MPK-protected stripes, the slot size can be lower than the
793        // `memory_reservation`.
794        let expected_slot_bytes =
795            HostAlignedByteCount::new_rounded_up_u64(tunables.memory_reservation)
796                .context("memory reservation is too large")?;
797
798        // Page-align the maximum size of memory since that's the granularity that
799        // permissions are going to be controlled at.
800        let max_memory_bytes = HostAlignedByteCount::new_rounded_up(limits.max_memory_size)
801            .context("maximum size of memory is too large")?;
802
803        let guard_bytes = HostAlignedByteCount::new_rounded_up_u64(tunables.memory_guard_size)
804            .context("guard region is too large")?;
805
806        let num_slots = usize::try_from(limits.total_memories).context("too many memories")?;
807
808        let constraints = SlabConstraints {
809            max_memory_bytes,
810            num_slots,
811            expected_slot_bytes,
812            num_pkeys_available,
813            guard_bytes,
814            guard_before_slots: tunables.guard_before_linear_memory,
815        };
816        Ok(constraints)
817    }
818}
819
820#[derive(Debug)]
821struct SlabLayout {
822    /// The total number of slots available in the memory pool slab.
823    num_slots: usize,
824    /// The size of each slot in the memory pool; this contains the maximum
825    /// memory size (i.e., from WebAssembly or Wasmtime configuration) plus any
826    /// guard region after the memory to catch OOB access. On these guard
827    /// regions, note that:
828    /// - users can configure how aggressively (or not) to elide bounds checks
829    ///   via `Config::memory_guard_size` (see also:
830    ///   `memory_and_guard_size`)
831    /// - memory protection keys can compress the size of the guard region by
832    ///   placing slots from a different key (i.e., a stripe) in the guard
833    ///   region; this means the slot itself can be smaller and we can allocate
834    ///   more of them.
835    slot_bytes: HostAlignedByteCount,
836    /// The maximum size that can become accessible, in bytes, for each linear
837    /// memory. Guaranteed to be a whole number of Wasm pages.
838    max_memory_bytes: HostAlignedByteCount,
839    /// If necessary, the number of bytes to reserve as a guard region at the
840    /// beginning of the slab.
841    pre_slab_guard_bytes: HostAlignedByteCount,
842    /// Like `pre_slab_guard_bytes`, but at the end of the slab.
843    post_slab_guard_bytes: HostAlignedByteCount,
844    /// The number of stripes needed in the slab layout.
845    num_stripes: usize,
846}
847
848impl SlabLayout {
849    /// Return the total size of the slab, using the final layout (where `n =
850    /// num_slots`):
851    ///
852    /// ```text
853    /// ┌────────────────────┬──────┬──────┬───┬──────┬─────────────────────┐
854    /// │pre_slab_guard_bytes│slot 1│slot 2│...│slot n│post_slab_guard_bytes│
855    /// └────────────────────┴──────┴──────┴───┴──────┴─────────────────────┘
856    /// ```
857    fn total_slab_bytes(&self) -> Result<HostAlignedByteCount> {
858        self.slot_bytes
859            .checked_mul(self.num_slots)
860            .and_then(|c| c.checked_add(self.pre_slab_guard_bytes))
861            .and_then(|c| c.checked_add(self.post_slab_guard_bytes))
862            .context("total size of memory reservation exceeds addressable memory")
863    }
864
865    /// Returns the number of Wasm bytes from the beginning of one slot to the
866    /// next slot in the same stripe--this is the striped equivalent of
867    /// `static_memory_bound`. Recall that between slots of the same stripe we
868    /// will see a slot from every other stripe.
869    ///
870    /// For example, in a 3-stripe pool, this function measures the distance
871    /// from the beginning of slot 1 to slot 4, which are of the same stripe:
872    ///
873    /// ```text
874    ///  ◄────────────────────►
875    /// ┌────────┬──────┬──────┬────────┬───┐
876    /// │*slot 1*│slot 2│slot 3│*slot 4*│...|
877    /// └────────┴──────┴──────┴────────┴───┘
878    /// ```
879    fn bytes_to_next_stripe_slot(&self) -> HostAlignedByteCount {
880        self.slot_bytes
881            .checked_mul(self.num_stripes)
882            .expect("constructor checks that self.slot_bytes * self.num_stripes is in bounds")
883    }
884}
885
886fn calculate(constraints: &SlabConstraints) -> Result<SlabLayout> {
887    let SlabConstraints {
888        max_memory_bytes,
889        num_slots,
890        expected_slot_bytes,
891        num_pkeys_available,
892        guard_bytes,
893        guard_before_slots,
894    } = *constraints;
895
896    // If the user specifies a guard region, we always need to allocate a
897    // `PROT_NONE` region for it before any memory slots. Recall that we can
898    // avoid bounds checks for loads and stores with immediates up to
899    // `guard_bytes`, but we rely on Wasmtime to emit bounds checks for any
900    // accesses greater than this.
901    let pre_slab_guard_bytes = if guard_before_slots {
902        guard_bytes
903    } else {
904        HostAlignedByteCount::ZERO
905    };
906
907    // To calculate the slot size, we start with the default configured size and
908    // attempt to chip away at this via MPK protection. Note here how we begin
909    // to define a slot as "all of the memory and guard region."
910    let faulting_region_bytes = expected_slot_bytes
911        .max(max_memory_bytes)
912        .checked_add(guard_bytes)
913        .context("faulting region is too large")?;
914
915    let (num_stripes, slot_bytes) = if guard_bytes == 0 || max_memory_bytes == 0 || num_slots == 0 {
916        // In the uncommon case where the memory/guard regions are empty or we don't need any slots , we
917        // will not need any stripes: we just lay out the slots back-to-back
918        // using a single stripe.
919        (1, faulting_region_bytes.byte_count())
920    } else if num_pkeys_available < 2 {
921        // If we do not have enough protection keys to stripe the memory, we do
922        // the same. We can't elide any of the guard bytes because we aren't
923        // overlapping guard regions with other stripes...
924        (1, faulting_region_bytes.byte_count())
925    } else {
926        // ...but if we can create at least two stripes, we can use another
927        // stripe (i.e., a different pkey) as this slot's guard region--this
928        // reduces the guard bytes each slot has to allocate. We must make
929        // sure, though, that if the size of that other stripe(s) does not
930        // fully cover `guard_bytes`, we keep those around to prevent OOB
931        // access.
932
933        // We first calculate the number of stripes we need: we want to
934        // minimize this so that there is less chance of a single store
935        // running out of slots with its stripe--we need at least two,
936        // though. But this is not just an optimization; we need to handle
937        // the case when there are fewer slots than stripes. E.g., if our
938        // pool is configured with only three slots (`num_memory_slots =
939        // 3`), we will run into failures if we attempt to set up more than
940        // three stripes.
941        let needed_num_stripes = faulting_region_bytes
942            .checked_div(max_memory_bytes)
943            .expect("if condition above implies max_memory_bytes is non-zero")
944            + usize::from(
945                faulting_region_bytes
946                    .checked_rem(max_memory_bytes)
947                    .expect("if condition above implies max_memory_bytes is non-zero")
948                    != 0,
949            );
950        assert!(needed_num_stripes > 0);
951        let num_stripes = num_pkeys_available.min(needed_num_stripes).min(num_slots);
952
953        // Next, we try to reduce the slot size by "overlapping" the stripes: we
954        // can make slot `n` smaller since we know that slot `n+1` and following
955        // are in different stripes and will look just like `PROT_NONE` memory.
956        // Recall that codegen expects a guarantee that at least
957        // `faulting_region_bytes` will catch OOB accesses via segfaults.
958        let needed_slot_bytes = faulting_region_bytes
959            .byte_count()
960            .checked_div(num_stripes)
961            .unwrap_or(faulting_region_bytes.byte_count())
962            .max(max_memory_bytes.byte_count());
963        assert!(needed_slot_bytes >= max_memory_bytes.byte_count());
964
965        (num_stripes, needed_slot_bytes)
966    };
967
968    // The page-aligned slot size; equivalent to `memory_and_guard_size`.
969    let slot_bytes =
970        HostAlignedByteCount::new_rounded_up(slot_bytes).context("slot size is too large")?;
971
972    // We may need another guard region (like `pre_slab_guard_bytes`) at the end
973    // of our slab to maintain our `faulting_region_bytes` guarantee. We could
974    // be conservative and just create it as large as `faulting_region_bytes`,
975    // but because we know that the last slot's `slot_bytes` make up the first
976    // part of that region, we reduce the final guard region by that much.
977    let post_slab_guard_bytes = faulting_region_bytes.saturating_sub(slot_bytes);
978
979    // Check that we haven't exceeded the slab we can calculate given the limits
980    // of `usize`.
981    let layout = SlabLayout {
982        num_slots,
983        slot_bytes,
984        max_memory_bytes,
985        pre_slab_guard_bytes,
986        post_slab_guard_bytes,
987        num_stripes,
988    };
989    match layout.total_slab_bytes() {
990        Ok(_) => Ok(layout),
991        Err(e) => Err(e),
992    }
993}
994
995#[cfg(test)]
996mod tests {
997    use super::*;
998    use proptest::prelude::*;
999
1000    const WASM_PAGE_SIZE: u32 = wasmtime_environ::Memory::DEFAULT_PAGE_SIZE;
1001
1002    #[cfg(target_pointer_width = "64")]
1003    #[test]
1004    fn test_memory_pool() -> Result<()> {
1005        let pool = MemoryPool::new(
1006            &PoolingAllocationConfig {
1007                limits: InstanceLimits {
1008                    total_memories: 5,
1009                    max_tables_per_module: 0,
1010                    max_memories_per_module: 3,
1011                    table_elements: 0,
1012                    max_memory_size: WASM_PAGE_SIZE as usize,
1013                    ..Default::default()
1014                },
1015                ..Default::default()
1016            },
1017            &Tunables {
1018                memory_reservation: WASM_PAGE_SIZE as u64,
1019                memory_guard_size: 0,
1020                ..Tunables::default_host()
1021            },
1022        )?;
1023
1024        assert_eq!(pool.layout.slot_bytes, WASM_PAGE_SIZE as usize);
1025        assert_eq!(pool.layout.num_slots, 5);
1026        assert_eq!(pool.layout.max_memory_bytes, WASM_PAGE_SIZE as usize);
1027
1028        let base = pool.mapping.as_ptr() as usize;
1029
1030        for i in 0..5 {
1031            let index = MemoryAllocationIndex(i);
1032            let ptr = pool.get_base(index).as_mut_ptr();
1033            assert_eq!(
1034                ptr as usize - base,
1035                i as usize * pool.layout.slot_bytes.byte_count()
1036            );
1037        }
1038
1039        Ok(())
1040    }
1041
1042    #[test]
1043    #[cfg_attr(miri, ignore)]
1044    fn test_pooling_allocator_striping() {
1045        if !mpk::is_supported() {
1046            println!("skipping `test_pooling_allocator_striping` test; mpk is not supported");
1047            return;
1048        }
1049
1050        // Force the use of MPK.
1051        let config = PoolingAllocationConfig {
1052            memory_protection_keys: Enabled::Yes,
1053            ..PoolingAllocationConfig::default()
1054        };
1055        let pool = MemoryPool::new(&config, &Tunables::default_host()).unwrap();
1056        assert!(pool.stripes.len() >= 2);
1057
1058        let max_memory_slots = config.limits.total_memories;
1059        dbg!(pool.stripes[0].allocator.num_empty_slots());
1060        dbg!(pool.stripes[1].allocator.num_empty_slots());
1061        let available_memory_slots: usize = pool
1062            .stripes
1063            .iter()
1064            .map(|s| s.allocator.num_empty_slots())
1065            .sum();
1066        assert_eq!(
1067            max_memory_slots,
1068            u32::try_from(available_memory_slots).unwrap()
1069        );
1070    }
1071
1072    #[test]
1073    fn check_known_layout_calculations() {
1074        for num_pkeys_available in 0..16 {
1075            for num_memory_slots in [0, 1, 10, 64] {
1076                for expected_slot_bytes in [0, 1 << 30 /* 1GB */, 4 << 30 /* 4GB */] {
1077                    let expected_slot_bytes =
1078                        HostAlignedByteCount::new(expected_slot_bytes).unwrap();
1079                    for max_memory_bytes in
1080                        [0, 1 * WASM_PAGE_SIZE as usize, 10 * WASM_PAGE_SIZE as usize]
1081                    {
1082                        // Note new rather than new_rounded_up here -- for now,
1083                        // WASM_PAGE_SIZE is 64KiB, which is a multiple of the
1084                        // host page size on all platforms.
1085                        let max_memory_bytes = HostAlignedByteCount::new(max_memory_bytes).unwrap();
1086                        for guard_bytes in [0, 2 << 30 /* 2GB */] {
1087                            let guard_bytes = HostAlignedByteCount::new(guard_bytes).unwrap();
1088                            for guard_before_slots in [true, false] {
1089                                let constraints = SlabConstraints {
1090                                    max_memory_bytes,
1091                                    num_slots: num_memory_slots,
1092                                    expected_slot_bytes,
1093                                    num_pkeys_available,
1094                                    guard_bytes,
1095                                    guard_before_slots,
1096                                };
1097                                match calculate(&constraints) {
1098                                    Ok(layout) => {
1099                                        assert_slab_layout_invariants(constraints, layout)
1100                                    }
1101                                    Err(e) => {
1102                                        // Only allow failure on 32-bit
1103                                        // platforms where the calculation
1104                                        // exceeded the size of the address
1105                                        // space
1106                                        assert!(
1107                                            cfg!(target_pointer_width = "32")
1108                                                && e.to_string()
1109                                                    .contains("exceeds addressable memory"),
1110                                            "bad error: {e:?}"
1111                                        );
1112                                    }
1113                                }
1114                            }
1115                        }
1116                    }
1117                }
1118            }
1119        }
1120    }
1121
1122    proptest! {
1123        #[test]
1124        #[cfg_attr(miri, ignore)]
1125        fn check_random_layout_calculations(c in constraints()) {
1126            if let Ok(l) = calculate(&c) {
1127                assert_slab_layout_invariants(c, l);
1128            }
1129        }
1130    }
1131
1132    fn constraints() -> impl Strategy<Value = SlabConstraints> {
1133        (
1134            any::<HostAlignedByteCount>(),
1135            any::<usize>(),
1136            any::<HostAlignedByteCount>(),
1137            any::<usize>(),
1138            any::<HostAlignedByteCount>(),
1139            any::<bool>(),
1140        )
1141            .prop_map(
1142                |(
1143                    max_memory_bytes,
1144                    num_memory_slots,
1145                    expected_slot_bytes,
1146                    num_pkeys_available,
1147                    guard_bytes,
1148                    guard_before_slots,
1149                )| {
1150                    SlabConstraints {
1151                        max_memory_bytes,
1152                        num_slots: num_memory_slots,
1153                        expected_slot_bytes,
1154                        num_pkeys_available,
1155                        guard_bytes,
1156                        guard_before_slots,
1157                    }
1158                },
1159            )
1160    }
1161
1162    fn assert_slab_layout_invariants(c: SlabConstraints, s: SlabLayout) {
1163        // Check that all the sizes add up.
1164        assert_eq!(
1165            s.total_slab_bytes().unwrap(),
1166            s.pre_slab_guard_bytes
1167                .checked_add(s.slot_bytes.checked_mul(c.num_slots).unwrap())
1168                .and_then(|c| c.checked_add(s.post_slab_guard_bytes))
1169                .unwrap(),
1170            "the slab size does not add up: {c:?} => {s:?}"
1171        );
1172        assert!(
1173            s.slot_bytes >= s.max_memory_bytes,
1174            "slot is not big enough: {c:?} => {s:?}"
1175        );
1176
1177        // The HostAlignedByteCount newtype wrapper ensures that the various
1178        // byte values are page-aligned.
1179
1180        // Check that we use no more or less stripes than needed.
1181        assert!(s.num_stripes >= 1, "not enough stripes: {c:?} => {s:?}");
1182        if c.num_pkeys_available == 0 || c.num_slots == 0 {
1183            assert_eq!(
1184                s.num_stripes, 1,
1185                "expected at least one stripe: {c:?} => {s:?}"
1186            );
1187        } else {
1188            assert!(
1189                s.num_stripes <= c.num_pkeys_available,
1190                "layout has more stripes than available pkeys: {c:?} => {s:?}"
1191            );
1192            assert!(
1193                s.num_stripes <= c.num_slots,
1194                "layout has more stripes than memory slots: {c:?} => {s:?}"
1195            );
1196        }
1197
1198        // Check that we use the minimum number of stripes/protection keys.
1199        // - if the next MPK-protected slot is bigger or the same as the
1200        //   required guard region, we only need two stripes
1201        // - if the next slot is smaller than the guard region, we only need
1202        //   enough stripes to add up to at least that guard region size.
1203        if c.num_pkeys_available > 1 && !c.max_memory_bytes.is_zero() {
1204            assert!(
1205                s.num_stripes <= (c.guard_bytes.checked_div(c.max_memory_bytes).unwrap() + 2),
1206                "calculated more stripes than needed: {c:?} => {s:?}"
1207            );
1208        }
1209
1210        // Check that the memory-striping will not allow OOB access.
1211        // - we may have reduced the slot size from `expected_slot_bytes` to
1212        //   `slot_bytes` assuming MPK striping; we check that our guaranteed
1213        //   "faulting region" is respected
1214        // - the last slot won't have MPK striping after it; we check that the
1215        //   `post_slab_guard_bytes` accounts for this
1216        assert!(
1217            s.bytes_to_next_stripe_slot()
1218                >= c.expected_slot_bytes
1219                    .max(c.max_memory_bytes)
1220                    .checked_add(c.guard_bytes)
1221                    .unwrap(),
1222            "faulting region not large enough: {c:?} => {s:?}"
1223        );
1224        assert!(
1225            s.slot_bytes.checked_add(s.post_slab_guard_bytes).unwrap() >= c.expected_slot_bytes,
1226            "last slot may allow OOB access: {c:?} => {s:?}"
1227        );
1228    }
1229}