wasmtime/runtime/vm/instance/allocator/pooling/
unix_stack_pool.rs1#![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#[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 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 if !allocation_size.is_zero() {
60 unsafe {
61 for i in 0..max_stacks {
62 let offset = stack_size.unchecked_mul(i);
65 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 pub fn is_empty(&self) -> bool {
92 self.index_allocator.is_empty()
93 }
94
95 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 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 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 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 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 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 decommit(bottom_of_stack as _, rest.byte_count());
207
208 size_to_memset.byte_count()
209 }
210
211 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 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}