Skip to main content

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

1#![cfg_attr(asan, allow(dead_code))]
2
3use super::index_allocator::{SimpleIndexAllocator, SlotId};
4use crate::config::PoolingAllocationConfig;
5use crate::prelude::*;
6use crate::runtime::vm::{HostAlignedByteCount, Mmap, mmap::AlignedLength};
7
8/// Represents a pool of execution stacks (used for the async fiber implementation).
9///
10/// Each index into the pool represents a single execution stack. The maximum number of
11/// stacks is the same as the maximum number of instances.
12///
13/// As stacks grow downwards, each stack starts (lowest address) with a guard page
14/// that can be used to detect stack overflow.
15///
16/// The top of the stack (starting stack pointer) is returned when a stack is allocated
17/// from the pool.
18#[derive(Debug)]
19pub struct StackPool {
20    mapping: Mmap<AlignedLength>,
21    stack_size: HostAlignedByteCount,
22    max_stacks: usize,
23    page_size: HostAlignedByteCount,
24    index_allocator: SimpleIndexAllocator,
25    async_stack_zeroing: bool,
26    async_stack_keep_resident: HostAlignedByteCount,
27}
28
29impl StackPool {
30    #[cfg(test)]
31    pub fn enabled() -> bool {
32        true
33    }
34
35    pub fn new(config: &PoolingAllocationConfig) -> Result<Self> {
36        use rustix::mm::{MprotectFlags, mprotect};
37
38        let page_size = HostAlignedByteCount::host_page_size();
39
40        // Add a page to the stack size for the guard page when using fiber stacks
41        let stack_size = if config.stack_size == 0 {
42            HostAlignedByteCount::ZERO
43        } else {
44            HostAlignedByteCount::new_rounded_up(config.stack_size)
45                .and_then(|size| size.checked_add(HostAlignedByteCount::host_page_size()))
46                .context("stack size exceeds addressable memory")?
47        };
48
49        let max_stacks = usize::try_from(config.limits.total_stacks).unwrap();
50
51        let allocation_size = stack_size
52            .checked_mul(max_stacks)
53            .context("total size of execution stacks exceeds addressable memory")?;
54
55        let mapping = Mmap::accessible_reserved(allocation_size, allocation_size)
56            .context("failed to create stack pool mapping")?;
57
58        // Set up the stack guard pages.
59        if !allocation_size.is_zero() {
60            unsafe {
61                for i in 0..max_stacks {
62                    // Safety: i < max_stacks and we've already checked that
63                    // stack_size * max_stacks is valid.
64                    let offset = stack_size.unchecked_mul(i);
65                    // Make the stack guard page inaccessible.
66                    let bottom_of_stack = mapping.as_ptr().add(offset.byte_count()).cast_mut();
67                    mprotect(
68                        bottom_of_stack.cast(),
69                        page_size.byte_count(),
70                        MprotectFlags::empty(),
71                    )
72                    .context("failed to protect stack guard page")?;
73                }
74            }
75        }
76
77        Ok(Self {
78            mapping,
79            stack_size,
80            max_stacks,
81            page_size,
82            async_stack_zeroing: config.async_stack_zeroing,
83            async_stack_keep_resident: HostAlignedByteCount::new_rounded_up(
84                config.async_stack_keep_resident,
85            )?,
86            index_allocator: SimpleIndexAllocator::new(config.limits.total_stacks)?,
87        })
88    }
89
90    /// Are there zero slots in use right now?
91    pub fn is_empty(&self) -> bool {
92        self.index_allocator.is_empty()
93    }
94
95    /// Allocate a new fiber.
96    pub fn allocate(&self) -> Result<wasmtime_fiber::FiberStack> {
97        if self.stack_size.is_zero() {
98            bail!("pooling allocator not configured to enable fiber stack allocation");
99        }
100
101        let index = self
102            .index_allocator
103            .alloc()
104            .ok_or_else(|| super::PoolConcurrencyLimitError::new(self.max_stacks, "fibers"))?
105            .index();
106
107        assert!(index < self.max_stacks);
108
109        unsafe {
110            // Remove the guard page from the size
111            let size_without_guard = self.stack_size.checked_sub(self.page_size).expect(
112                "self.stack_size is host-page-aligned and is > 0,\
113                 so it must be >= self.page_size",
114            );
115
116            let bottom_of_stack = self
117                .mapping
118                .as_ptr()
119                .add(self.stack_size.unchecked_mul(index).byte_count())
120                .cast_mut();
121
122            let stack = wasmtime_fiber::FiberStack::from_raw_parts(
123                bottom_of_stack,
124                self.page_size.byte_count(),
125                size_without_guard.byte_count(),
126            )?;
127            Ok(stack)
128        }
129    }
130
131    /// Zero the given stack, if we are configured to do so.
132    ///
133    /// This will call the given `decommit` function for each region of memory
134    /// that should be decommitted. It is the caller's responsibility to ensure
135    /// that those decommits happen before this stack is reused.
136    ///
137    /// # Panics
138    ///
139    /// `zero_stack` panics if the passed in `stack` was not created by
140    /// [`Self::allocate`].
141    ///
142    /// # Safety
143    ///
144    /// The stack must no longer be in use, and ready for returning to the pool
145    /// after it is zeroed and decommitted.
146    pub unsafe fn zero_stack(
147        &self,
148        stack: &mut wasmtime_fiber::FiberStack,
149        mut decommit: impl FnMut(*mut u8, usize),
150    ) -> usize {
151        assert!(stack.is_from_raw_parts());
152        assert!(
153            !self.stack_size.is_zero(),
154            "pooling allocator not configured to enable fiber stack allocation \
155             (Self::allocate should have returned an error)"
156        );
157
158        if !self.async_stack_zeroing {
159            return 0;
160        }
161
162        let top = stack
163            .top()
164            .expect("fiber stack not allocated from the pool") as usize;
165
166        let base = self.mapping.as_ptr() as usize;
167        let len = self.mapping.len();
168        assert!(
169            top > base && top <= (base + len),
170            "fiber stack top pointer not in range"
171        );
172
173        // Remove the guard page from the size.
174        let stack_size = self.stack_size.checked_sub(self.page_size).expect(
175            "self.stack_size is host-page-aligned and is > 0,\
176             so it must be >= self.page_size",
177        );
178        let bottom_of_stack = top - stack_size.byte_count();
179        let start_of_stack = bottom_of_stack - self.page_size.byte_count();
180        assert!(start_of_stack >= base && start_of_stack < (base + len));
181        assert!((start_of_stack - base) % self.stack_size.byte_count() == 0);
182
183        // Manually zero the top of the stack to keep the pages resident in
184        // memory and avoid future page faults. Use the system to deallocate
185        // pages past this. This hopefully strikes a reasonable balance between:
186        //
187        // * memset for the whole range is probably expensive
188        // * madvise for the whole range incurs expensive future page faults
189        // * most threads probably don't use most of the stack anyway
190        let size_to_memset = stack_size.min(self.async_stack_keep_resident);
191        let rest = stack_size
192            .checked_sub(size_to_memset)
193            .expect("stack_size >= size_to_memset");
194
195        // SAFETY: this function's own contract requires that the stack is not
196        // in use so it's safe to pave over part of it with zero.
197        unsafe {
198            std::ptr::write_bytes(
199                (bottom_of_stack + rest.byte_count()) as *mut u8,
200                0,
201                size_to_memset.byte_count(),
202            );
203        }
204
205        // Use the system to reset remaining stack pages to zero.
206        decommit(bottom_of_stack as _, rest.byte_count());
207
208        size_to_memset.byte_count()
209    }
210
211    /// Deallocate the previously-allocated fibers produced by `items`.
212    ///
213    /// # Safety
214    ///
215    /// The fibers must have been previously-allocated by this pool, must be
216    /// in an allocated state, and must never be used again.
217    ///
218    /// The caller must have already called `zero_stack` on the fiber stacks
219    /// and flushed any enqueued decommits for these stacks' memories.
220    pub unsafe fn deallocate_many(
221        &self,
222        stacks: impl Iterator<Item = (wasmtime_fiber::FiberStack, usize)>,
223    ) {
224        self.index_allocator.free_many(
225            stacks
226                .map(|(stack, bytes_resident)| (SlotId(self.stack_index(&stack)), bytes_resident)),
227        );
228    }
229
230    fn stack_index(&self, stack: &wasmtime_fiber::FiberStack) -> u32 {
231        assert!(stack.is_from_raw_parts());
232
233        let top = stack
234            .top()
235            .expect("fiber stack not allocated from the pool") as usize;
236
237        let base = self.mapping.as_ptr() as usize;
238        let len = self.mapping.len();
239        assert!(
240            top > base && top <= (base + len),
241            "fiber stack top pointer not in range"
242        );
243
244        // Remove the guard page from the size
245        let stack_size = self.stack_size.byte_count() - self.page_size.byte_count();
246        let bottom_of_stack = top - stack_size;
247        let start_of_stack = bottom_of_stack - self.page_size.byte_count();
248        assert!(start_of_stack >= base && start_of_stack < (base + len));
249        assert!((start_of_stack - base) % self.stack_size.byte_count() == 0);
250
251        let index = (start_of_stack - base) / self.stack_size.byte_count();
252        assert!(index < self.max_stacks);
253        u32::try_from(index).unwrap()
254    }
255
256    pub fn unused_warm_slots(&self) -> u32 {
257        self.index_allocator.unused_warm_slots()
258    }
259
260    pub fn unused_bytes_resident(&self) -> Option<usize> {
261        if self.async_stack_zeroing {
262            Some(self.index_allocator.unused_bytes_resident())
263        } else {
264            None
265        }
266    }
267}
268
269#[cfg(all(test, unix, feature = "async", not(miri), not(asan)))]
270mod tests {
271    use super::*;
272    use crate::config::InstanceLimits;
273
274    #[test]
275    fn test_stack_pool() -> Result<()> {
276        let config = PoolingAllocationConfig {
277            limits: InstanceLimits {
278                total_stacks: 10,
279                ..Default::default()
280            },
281            stack_size: 1,
282            async_stack_zeroing: true,
283            ..PoolingAllocationConfig::default()
284        };
285        let pool = StackPool::new(&config)?;
286
287        let native_page_size = crate::runtime::vm::host_page_size();
288        assert_eq!(pool.stack_size, 2 * native_page_size);
289        assert_eq!(pool.max_stacks, 10);
290        assert_eq!(pool.page_size, native_page_size);
291
292        assert_eq!(pool.index_allocator.testing_freelist(), []);
293
294        let base = pool.mapping.as_ptr() as usize;
295
296        let mut stacks = Vec::new();
297        for i in 0..10 {
298            let stack = pool.allocate().expect("allocation should succeed");
299            assert_eq!(
300                ((stack.top().unwrap() as usize - base) / pool.stack_size.byte_count()) - 1,
301                i
302            );
303            stacks.push(stack);
304        }
305
306        assert_eq!(pool.index_allocator.testing_freelist(), []);
307
308        assert!(pool.allocate().is_err(), "allocation should fail");
309
310        unsafe {
311            pool.deallocate_many(stacks.into_iter().map(|stack| (stack, 0)));
312        }
313
314        assert_eq!(
315            pool.index_allocator.testing_freelist(),
316            [
317                SlotId(0),
318                SlotId(1),
319                SlotId(2),
320                SlotId(3),
321                SlotId(4),
322                SlotId(5),
323                SlotId(6),
324                SlotId(7),
325                SlotId(8),
326                SlotId(9)
327            ],
328        );
329
330        Ok(())
331    }
332}