Skip to main content

vthread_stack/
pool.rs

1//! Bounded carrier-local stack cache.
2
3#[cfg(feature = "runtime-evidence")]
4use std::collections::BTreeSet;
5use std::io;
6
7use crate::MappedStack;
8
9/// Operational counters for a stack pool.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub struct StackPoolSnapshot {
12    /// Stacks currently retained for reuse.
13    pub cached: usize,
14    /// Fresh stack mappings created.
15    pub allocated: u64,
16    /// Cached stacks handed out again.
17    pub reused: u64,
18    /// Completed stacks accepted into the cache.
19    pub retained: u64,
20    /// Completed stacks dropped because the cache was full.
21    pub discarded: u64,
22}
23
24/// A bounded cache of guard-page-backed stacks.
25///
26/// Every mapping the pool allocates is stamped with a pool-local identity that survives
27/// cache reuse and is retired once the mapping leaves the pool for good.
28pub struct StackPool {
29    stack_size: usize,
30    max_cached: usize,
31    stacks: Vec<MappedStack>,
32    next_identity: u64,
33    #[cfg(feature = "runtime-evidence")]
34    live: BTreeSet<u64>,
35    snapshot: StackPoolSnapshot,
36}
37
38impl StackPool {
39    /// Creates an empty pool.
40    pub fn new(stack_size: usize, max_cached: usize) -> Self {
41        Self {
42            stack_size,
43            max_cached,
44            stacks: Vec::new(),
45            next_identity: 1,
46            #[cfg(feature = "runtime-evidence")]
47            live: BTreeSet::new(),
48            snapshot: StackPoolSnapshot::default(),
49        }
50    }
51
52    /// Acquires a cached stack or allocates a new one.
53    pub fn acquire(&mut self) -> io::Result<MappedStack> {
54        if let Some(stack) = self.reuse() {
55            return Ok(stack);
56        }
57        self.allocate()
58    }
59
60    /// Acquires a stack together with its stable pool-local mapping identity.
61    #[cfg(feature = "runtime-evidence")]
62    pub fn acquire_identified(&mut self) -> io::Result<(u64, MappedStack)> {
63        let stack = self.acquire()?;
64        Ok((stack.identity(), stack))
65    }
66
67    /// Returns a completed stack to the bounded cache.
68    pub fn release(&mut self, stack: MappedStack) {
69        #[cfg(feature = "runtime-evidence")]
70        {
71            let identity = stack.identity();
72            self.release_identified(identity, stack);
73        }
74        #[cfg(not(feature = "runtime-evidence"))]
75        self.retain(stack);
76    }
77
78    /// Returns an identified mapping and reports whether the bounded cache retained it.
79    ///
80    /// A mapping whose stamp differs from `identity`, or that this pool never issued or
81    /// has already retired, is dropped instead of cached.
82    #[cfg(feature = "runtime-evidence")]
83    pub fn release_identified(&mut self, identity: u64, stack: MappedStack) -> bool {
84        let actual = stack.identity();
85        if actual != identity || !self.live.contains(&actual) {
86            self.snapshot.discarded += 1;
87            self.retire(actual);
88            drop(stack);
89            return false;
90        }
91        if self.retain(stack) {
92            true
93        } else {
94            self.retire(identity);
95            false
96        }
97    }
98
99    /// Retires metadata after its active mapping was discarded outside the cache.
100    #[cfg(feature = "runtime-evidence")]
101    pub fn retire(&mut self, identity: u64) -> bool {
102        self.live.remove(&identity)
103    }
104
105    /// Returns the current counters.
106    pub fn snapshot(&self) -> StackPoolSnapshot {
107        self.snapshot
108    }
109
110    fn reuse(&mut self) -> Option<MappedStack> {
111        let stack = self.stacks.pop()?;
112        self.snapshot.cached = self.stacks.len();
113        self.snapshot.reused += 1;
114        Some(stack)
115    }
116
117    fn allocate(&mut self) -> io::Result<MappedStack> {
118        let identity = self.next_identity;
119        let next = identity
120            .checked_add(1)
121            .ok_or_else(|| io::Error::other("stack mapping identity exhausted"))?;
122        let stack = MappedStack::new(self.stack_size, identity)?;
123        self.next_identity = next;
124        #[cfg(feature = "runtime-evidence")]
125        self.live.insert(identity);
126        self.snapshot.allocated += 1;
127        Ok(stack)
128    }
129
130    fn retain(&mut self, stack: MappedStack) -> bool {
131        if self.stacks.len() < self.max_cached {
132            self.stacks.push(stack);
133            self.snapshot.retained += 1;
134            self.snapshot.cached = self.stacks.len();
135            true
136        } else {
137            self.snapshot.discarded += 1;
138            false
139        }
140    }
141}
142
143#[cfg(test)]
144#[path = "pool_test.rs"]
145mod pool_test;