interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / budget.rs

432 lines · 13870 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Fixed-capacity resource accounting and watchdog policy for isolated Worlds.
17//!
18//! This module has no hardware dependencies. A caller supplies counter ticks
19//! and performs the actual revocation and restoration around these decisions.
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct ResourceEnvelope {
23 pub cpu_ticks_per_period: u64,
24 pub memory_frames_limit: u64,
25 pub dma_window_bytes_limit: u64,
26 /// Maximum counter ticks from admission until the World deadline.
27 pub max_runtime_ticks: u64,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum ResourceLimit {
32 CpuTicks,
33 MemoryFrames,
34 DmaBytes,
35 RuntimeDeadline,
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum BudgetError {
40 Full,
41 DuplicateWorld,
42 UnknownWorld,
43 Exceeded(ResourceLimit),
44 Quarantined,
45 InvalidRelease,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum WorldState {
50 Active,
51 Quarantined,
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum BudgetMode {
56 Active,
57 Idle,
58 Urgent,
59}
60
61/// Owner-priority scaling for Forge CPU budgets. Urgent is a temporary
62/// elevated allowance and may exceed the admitted base CPU allowance.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub struct BudgetPolicy {
65 mode: BudgetMode,
66}
67
68impl BudgetPolicy {
69 pub const fn new() -> Self {
70 Self {
71 mode: BudgetMode::Active,
72 }
73 }
74
75 pub const fn mode(self) -> BudgetMode {
76 self.mode
77 }
78
79 pub fn set_mode(&mut self, mode: BudgetMode) {
80 self.mode = mode;
81 }
82
83 const fn allowance(self, base: u64) -> u64 {
84 let (whole, remainder, divisor) = match self.mode {
85 BudgetMode::Active => (0, 100, 1000),
86 BudgetMode::Idle => (0, 800, 1000),
87 BudgetMode::Urgent => (1, 500, 1000),
88 };
89 base.saturating_mul(whole)
90 .saturating_add((base / divisor) * remainder)
91 .saturating_add(((base % divisor) * remainder) / divisor)
92 }
93}
94
95impl Default for BudgetPolicy {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102struct WorldBudget {
103 id: u32,
104 envelope: ResourceEnvelope,
105 forge: bool,
106 cpu_used: u64,
107 frames_used: u64,
108 dma_used: u64,
109 /// Counter value when the watchdog was last armed (admit, pet, restore).
110 armed_at: u64,
111 state: WorldState,
112}
113
114/// Resource budgets and per-World watchdogs with caller-chosen fixed capacity.
115pub struct BudgetManager<const WORLDS: usize> {
116 worlds: [Option<WorldBudget>; WORLDS],
117 policy: BudgetPolicy,
118}
119
120impl<const WORLDS: usize> BudgetManager<WORLDS> {
121 pub const fn new() -> Self {
122 Self {
123 worlds: [None; WORLDS],
124 policy: BudgetPolicy::new(),
125 }
126 }
127
128 /// Admit a World. Deadline addition saturates to avoid wrapping a counter.
129 pub fn admit(
130 &mut self,
131 id: u32,
132 envelope: ResourceEnvelope,
133 forge: bool,
134 now: u64,
135 ) -> Result<(), BudgetError> {
136 if self.worlds.iter().flatten().any(|w| w.id == id) {
137 return Err(BudgetError::DuplicateWorld);
138 }
139 let slot = self
140 .worlds
141 .iter()
142 .position(Option::is_none)
143 .ok_or(BudgetError::Full)?;
144 self.worlds[slot] = Some(WorldBudget {
145 id,
146 envelope,
147 forge,
148 cpu_used: 0,
149 frames_used: 0,
150 dma_used: 0,
151 armed_at: now,
152 state: WorldState::Active,
153 });
154 Ok(())
155 }
156
157 /// Remove an explicitly stopped World and free its fixed slot.
158 pub fn remove(&mut self, id: u32) -> Result<(), BudgetError> {
159 let slot = self.slot(id)?;
160 self.worlds[slot] = None;
161 Ok(())
162 }
163
164 /// Start a new CPU accounting period for every active World.
165 pub fn begin_period(&mut self) {
166 for world in self.worlds.iter_mut().flatten() {
167 if world.state == WorldState::Active {
168 world.cpu_used = 0;
169 }
170 }
171 }
172
173 pub fn set_mode(&mut self, mode: BudgetMode) {
174 self.policy.set_mode(mode);
175 }
176 pub const fn mode(&self) -> BudgetMode {
177 self.policy.mode()
178 }
179
180 pub fn cpu_allowance(&self, id: u32) -> Result<u64, BudgetError> {
181 let world = self.world(id)?;
182 Ok(if world.forge {
183 self.policy.allowance(world.envelope.cpu_ticks_per_period)
184 } else {
185 world.envelope.cpu_ticks_per_period
186 })
187 }
188
189 pub fn state(&self, id: u32) -> Result<WorldState, BudgetError> {
190 Ok(self.world(id)?.state)
191 }
192
193 pub fn charge_cpu(&mut self, id: u32, ticks: u64) -> Result<(), BudgetError> {
194 let allowance = self.cpu_allowance(id)?;
195 let world = self.world_mut(id)?;
196 let next = world
197 .cpu_used
198 .checked_add(ticks)
199 .ok_or(BudgetError::Exceeded(ResourceLimit::CpuTicks))?;
200 if next > allowance {
201 return Err(BudgetError::Exceeded(ResourceLimit::CpuTicks));
202 }
203 world.cpu_used = next;
204 Ok(())
205 }
206
207 pub fn charge_frames(&mut self, id: u32, frames: u64) -> Result<(), BudgetError> {
208 let world = self.world_mut(id)?;
209 let next = world
210 .frames_used
211 .checked_add(frames)
212 .ok_or(BudgetError::Exceeded(ResourceLimit::MemoryFrames))?;
213 if next > world.envelope.memory_frames_limit {
214 return Err(BudgetError::Exceeded(ResourceLimit::MemoryFrames));
215 }
216 world.frames_used = next;
217 Ok(())
218 }
219
220 pub fn release_frames(&mut self, id: u32, frames: u64) -> Result<(), BudgetError> {
221 let world = self.world_mut(id)?;
222 if frames > world.frames_used {
223 return Err(BudgetError::InvalidRelease);
224 }
225 world.frames_used -= frames;
226 Ok(())
227 }
228
229 pub fn charge_dma(&mut self, id: u32, bytes: u64) -> Result<(), BudgetError> {
230 let world = self.world_mut(id)?;
231 let next = world
232 .dma_used
233 .checked_add(bytes)
234 .ok_or(BudgetError::Exceeded(ResourceLimit::DmaBytes))?;
235 if next > world.envelope.dma_window_bytes_limit {
236 return Err(BudgetError::Exceeded(ResourceLimit::DmaBytes));
237 }
238 world.dma_used = next;
239 Ok(())
240 }
241
242 /// Pet an active World, extending its watchdog deadline from `now`.
243 pub fn pet(&mut self, id: u32, now: u64) -> Result<(), BudgetError> {
244 let world = self.world_mut(id)?;
245 world.armed_at = now;
246 Ok(())
247 }
248
249 /// Quarantine overdue Worlds and return their IDs. Quarantine is sticky.
250 pub fn check(&mut self, now: u64) -> [Option<u32>; WORLDS] {
251 let mut expired = [None; WORLDS];
252 for (index, entry) in self.worlds.iter_mut().enumerate() {
253 if let Some(world) = entry {
254 // Elapsed time with wrapping arithmetic stays correct across a
255 // counter wrap (a saturating deadline expired early near u64::MAX).
256 if world.state == WorldState::Active
257 && now.wrapping_sub(world.armed_at) >= world.envelope.max_runtime_ticks
258 {
259 world.state = WorldState::Quarantined;
260 expired[index] = Some(world.id);
261 }
262 }
263 }
264 expired
265 }
266
267 /// Explicitly restore a quarantined World from its admitted envelope.
268 /// Call only after the owner/caller restored its last known-good state.
269 pub fn restore(&mut self, id: u32, now: u64) -> Result<(), BudgetError> {
270 let world = self.world_mut_allow_quarantined(id)?;
271 world.cpu_used = 0;
272 world.frames_used = 0;
273 world.dma_used = 0;
274 world.armed_at = now;
275 world.state = WorldState::Active;
276 Ok(())
277 }
278
279 fn slot(&self, id: u32) -> Result<usize, BudgetError> {
280 self.worlds
281 .iter()
282 .position(|w| w.is_some_and(|w| w.id == id))
283 .ok_or(BudgetError::UnknownWorld)
284 }
285 fn world(&self, id: u32) -> Result<&WorldBudget, BudgetError> {
286 self.worlds[self.slot(id)?]
287 .as_ref()
288 .ok_or(BudgetError::UnknownWorld)
289 }
290 fn world_mut_allow_quarantined(&mut self, id: u32) -> Result<&mut WorldBudget, BudgetError> {
291 let slot = self.slot(id)?;
292 self.worlds[slot].as_mut().ok_or(BudgetError::UnknownWorld)
293 }
294 fn world_mut(&mut self, id: u32) -> Result<&mut WorldBudget, BudgetError> {
295 let world = self.world_mut_allow_quarantined(id)?;
296 if world.state == WorldState::Quarantined {
297 return Err(BudgetError::Quarantined);
298 }
299 Ok(world)
300 }
301}
302
303impl<const WORLDS: usize> Default for BudgetManager<WORLDS> {
304 fn default() -> Self {
305 Self::new()
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312
313 fn envelope() -> ResourceEnvelope {
314 ResourceEnvelope {
315 cpu_ticks_per_period: 100,
316 memory_frames_limit: 4,
317 dma_window_bytes_limit: 32,
318 max_runtime_ticks: 10,
319 }
320 }
321 fn manager() -> BudgetManager<2> {
322 let mut manager = BudgetManager::new();
323 manager.admit(7, envelope(), false, 0).unwrap();
324 manager
325 }
326
327 #[test]
328 fn each_resource_limit_is_enforced_independently() {
329 let mut m = manager();
330 assert_eq!(
331 m.charge_cpu(7, 101),
332 Err(BudgetError::Exceeded(ResourceLimit::CpuTicks))
333 );
334 assert_eq!(
335 m.charge_frames(7, 5),
336 Err(BudgetError::Exceeded(ResourceLimit::MemoryFrames))
337 );
338 assert_eq!(
339 m.charge_dma(7, 33),
340 Err(BudgetError::Exceeded(ResourceLimit::DmaBytes))
341 );
342 }
343
344 #[test]
345 fn releasing_frames_restores_headroom() {
346 let mut m = manager();
347 m.charge_frames(7, 4).unwrap();
348 m.release_frames(7, 2).unwrap();
349 m.charge_frames(7, 2).unwrap();
350 assert_eq!(m.release_frames(7, 5), Err(BudgetError::InvalidRelease));
351 }
352
353 #[test]
354 fn watchdog_pet_expiry_and_sticky_quarantine() {
355 let mut m = manager();
356 assert_eq!(m.check(9), [None, None]);
357 m.pet(7, 8).unwrap();
358 assert_eq!(m.check(17), [None, None]);
359 assert_eq!(m.check(18), [Some(7), None]);
360 assert_eq!(m.charge_cpu(7, 1), Err(BudgetError::Quarantined));
361 assert_eq!(m.pet(7, 20), Err(BudgetError::Quarantined));
362 assert_eq!(m.state(7), Ok(WorldState::Quarantined));
363 m.restore(7, 20).unwrap();
364 assert_eq!(m.state(7), Ok(WorldState::Active));
365 }
366
367 #[test]
368 fn explicit_policy_switch_changes_forge_allowance() {
369 let mut m = BudgetManager::<1>::new();
370 m.admit(1, envelope(), true, 0).unwrap();
371 assert_eq!(m.cpu_allowance(1), Ok(10));
372 m.set_mode(BudgetMode::Idle);
373 assert_eq!(m.cpu_allowance(1), Ok(80));
374 m.set_mode(BudgetMode::Urgent);
375 assert_eq!(m.cpu_allowance(1), Ok(150));
376 }
377
378 #[test]
379 fn arithmetic_is_overflow_safe_at_u64_limits() {
380 let mut m = BudgetManager::<1>::new();
381 let max = ResourceEnvelope {
382 cpu_ticks_per_period: u64::MAX,
383 memory_frames_limit: u64::MAX,
384 dma_window_bytes_limit: u64::MAX,
385 max_runtime_ticks: u64::MAX,
386 };
387 m.admit(1, max, false, u64::MAX - 1).unwrap();
388 assert_eq!(m.charge_cpu(1, u64::MAX), Ok(()));
389 assert_eq!(
390 m.charge_cpu(1, 1),
391 Err(BudgetError::Exceeded(ResourceLimit::CpuTicks))
392 );
393 assert_eq!(m.charge_frames(1, u64::MAX), Ok(()));
394 assert_eq!(
395 m.charge_frames(1, 1),
396 Err(BudgetError::Exceeded(ResourceLimit::MemoryFrames))
397 );
398 assert_eq!(m.charge_dma(1, u64::MAX), Ok(()));
399 assert_eq!(
400 m.charge_dma(1, 1),
401 Err(BudgetError::Exceeded(ResourceLimit::DmaBytes))
402 );
403 // One tick of a u64::MAX runtime budget has elapsed: not expired. (The
404 // saturating-deadline draft reported expiry here; that was the wrap bug.)
405 assert_eq!(m.check(u64::MAX), [None]);
406 assert_eq!(m.cpu_allowance(1), Ok(u64::MAX));
407 }
408 #[test]
409 fn watchdog_is_correct_across_counter_wrap() {
410 // Review regression: admitted at u64::MAX - 4 with a 10-tick runtime must
411 // survive until 10 ticks have elapsed, even though the counter wraps.
412 let start = u64::MAX - 4;
413 let mut manager = BudgetManager::<4>::new();
414 let envelope = ResourceEnvelope {
415 max_runtime_ticks: 10,
416 ..envelope()
417 };
418 manager.admit(1, envelope, false, start).unwrap();
419 let expired = |r: [Option<u32>; 4]| r.iter().flatten().count();
420 assert_eq!(expired(manager.check(u64::MAX)), 0, "4 ticks elapsed");
421 assert_eq!(
422 expired(manager.check(start.wrapping_add(9))),
423 0,
424 "9 ticks elapsed"
425 );
426 assert_eq!(
427 expired(manager.check(start.wrapping_add(10))),
428 1,
429 "10 ticks: expired"
430 );
431 }
432}