Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/allen-reflex-kernel/src/heap.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / allen-reflex-kernel / src / heap.rs` 280 lines ยท 9011 bytes Raw Blame History 1 //! Bounded bump heap over ONE region handed over by the kernel (`ck_mm_frames_alloc`). 2 //! 3 //! Allocation moves a cursor; `dealloc` only reclaims the newest block and `realloc` grows the 4 //! newest block in place (otherwise a new block is taken and the old one is not reused). Training 5 //! keeps everything it allocates, so the cursor after training is the trained core's footprint 6 //! plus training garbage. Around each decision the runner takes a [`Mark`] and, once every block 7 //! allocated after it is freed again (`live` back to the mark's value), resets the cursor to it: 8 //! repeated decisions then reuse the same bytes and the region does not grow. 9 //! 10 //! Exhaustion (or a region of length 0, the state before `init` and after close) returns 0; 11 //! the global allocator turns that into a null pointer, Rust's allocation-error path into a 12 //! panic, and the kernel's panic handler stops the run. The heap is NOT a general allocator and 13 //! has no locking: one core, interrupts masked by the caller. 14 //! 15 //! Counters: `peak` is the region high-water mark (what the region must hold for this run); 16 //! `live_peak` is the most bytes live at once (what a reusing allocator would need). 17 18 use core::cell::Cell; 19 20 /// The heap state. All fields are plain cells: single core, no locking. 21 pub struct Bump { 22 base: Cell, 23 end: Cell, 24 next: Cell, 25 last: Cell, // start of the newest block, 0 if none 26 peak: Cell, 27 live: Cell, 28 live_peak: Cell, 29 allocs: Cell, 30 fails: Cell, 31 } 32 33 /// Cursor position to return to after a decision. 34 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 35 pub struct Mark { 36 next: usize, 37 live: usize, 38 } 39 40 /// Snapshot for the report. `#[repr(C)]`: the kernel declares the same struct 41 /// (`native/kernel/core/allen.c`, `struct allen_heap_stats`). 42 #[repr(C)] 43 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] 44 pub struct Stats { 45 /// region bytes 46 pub cap: u64, 47 /// cursor - base now 48 pub used: u64, 49 /// highest cursor - base seen 50 pub peak: u64, 51 /// bytes in blocks not yet freed 52 pub live: u64, 53 /// most bytes live at once 54 pub live_peak: u64, 55 /// successful allocations 56 pub allocs: u64, 57 /// refused allocations (exhausted or no region) 58 pub fails: u64, 59 } 60 61 impl Bump { 62 /// Empty heap: every allocation fails until [`Bump::init`]. 63 pub const fn new() -> Bump { 64 Bump { 65 base: Cell::new(0), 66 end: Cell::new(0), 67 next: Cell::new(0), 68 last: Cell::new(0), 69 peak: Cell::new(0), 70 live: Cell::new(0), 71 live_peak: Cell::new(0), 72 allocs: Cell::new(0), 73 fails: Cell::new(0), 74 } 75 } 76 77 /// Use `[base, base + len)`. `len == 0` (or `base == 0`) closes the heap: every later 78 /// allocation fails. Counters restart. 79 pub fn init(&self, base: usize, len: usize) { 80 let ok = base != 0 && len != 0 && base.checked_add(len).is_some(); 81 self.base.set(if ok { base } else { 0 }); 82 self.end.set(if ok { base + len } else { 0 }); 83 self.next.set(if ok { base } else { 0 }); 84 self.last.set(0); 85 self.peak.set(0); 86 self.live.set(0); 87 self.live_peak.set(0); 88 self.allocs.set(0); 89 self.fails.set(0); 90 } 91 92 fn fail(&self) -> usize { 93 self.fails.set(self.fails.get() + 1); 94 0 95 } 96 97 fn grew(&self, e: usize, add_live: usize) { 98 let used = e - self.base.get(); 99 if used > self.peak.get() { 100 self.peak.set(used); 101 } 102 let live = self.live.get() + add_live; 103 self.live.set(live); 104 if live > self.live_peak.get() { 105 self.live_peak.set(live); 106 } 107 } 108 109 /// Address of a new block, or 0. `align` must be a power of two. 110 pub fn alloc(&self, size: usize, align: usize) -> usize { 111 if self.base.get() == 0 || align == 0 || !align.is_power_of_two() { 112 return self.fail(); 113 } 114 let start = match self.next.get().checked_add(align - 1) { 115 Some(v) => v & !(align - 1), 116 None => return self.fail(), 117 }; 118 match start.checked_add(size) { 119 Some(e) if e <= self.end.get() => { 120 self.next.set(e); 121 self.last.set(start); 122 self.allocs.set(self.allocs.get() + 1); 123 self.grew(e, size); 124 start 125 } 126 _ => self.fail(), 127 } 128 } 129 130 /// Free a block of `size` bytes at `p` (reclaimed only when it is the newest). 131 pub fn dealloc(&self, p: usize, size: usize) { 132 self.live.set(self.live.get().saturating_sub(size)); 133 if p == self.last.get() && p + size == self.next.get() { 134 self.next.set(p); 135 self.last.set(0); 136 } 137 } 138 139 /// Grow or shrink the newest block in place; any other block: 0 (the caller copies). 140 pub fn resize_in_place(&self, p: usize, size: usize, new_size: usize) -> usize { 141 if p == 0 || p != self.last.get() || p + size != self.next.get() { 142 return 0; 143 } 144 match p.checked_add(new_size) { 145 Some(e) if e <= self.end.get() => { 146 self.next.set(e); 147 self.live.set(self.live.get().saturating_sub(size)); 148 self.grew(e, new_size); 149 p 150 } 151 _ => 0, 152 } 153 } 154 155 /// Current cursor and live bytes. 156 pub fn mark(&self) -> Mark { 157 Mark { 158 next: self.next.get(), 159 live: self.live.get(), 160 } 161 } 162 163 /// Return to `m` if every block allocated since it was freed (live bytes equal the mark's); 164 /// otherwise leave the cursor (memory is not reused, nothing is corrupted) and say so. 165 pub fn reset_to(&self, m: Mark) -> bool { 166 if self.base.get() == 0 || self.live.get() != m.live || m.next > self.next.get() { 167 return false; 168 } 169 self.next.set(m.next); 170 self.last.set(0); 171 true 172 } 173 174 /// Start the peak counters again from the current state (one report per mode). 175 pub fn reset_peaks(&self) { 176 if self.base.get() != 0 { 177 self.peak.set(self.next.get() - self.base.get()); 178 } 179 self.live_peak.set(self.live.get()); 180 } 181 182 /// Counters now. 183 pub fn stats(&self) -> Stats { 184 let b = self.base.get(); 185 Stats { 186 cap: (self.end.get() - b) as u64, 187 used: (self.next.get() - b) as u64, 188 peak: self.peak.get() as u64, 189 live: self.live.get() as u64, 190 live_peak: self.live_peak.get() as u64, 191 allocs: self.allocs.get(), 192 fails: self.fails.get(), 193 } 194 } 195 } 196 197 impl Default for Bump { 198 fn default() -> Bump { 199 Bump::new() 200 } 201 } 202 203 #[cfg(test)] 204 mod tests { 205 use super::*; 206 207 fn region(len: usize) -> (Vec, Bump) { 208 let v = vec![0u64; len / 8]; 209 let h = Bump::new(); 210 h.init(v.as_ptr() as usize, len); 211 (v, h) 212 } 213 214 #[test] 215 fn closed_heap_refuses_everything() { 216 let h = Bump::new(); 217 assert_eq!(h.alloc(8, 8), 0); 218 assert_eq!(h.stats().fails, 1); 219 let (_v, h) = region(64); 220 h.init(0, 0); 221 assert_eq!(h.alloc(1, 1), 0); 222 } 223 224 #[test] 225 fn exhaustion_returns_zero_and_counts() { 226 let (_v, h) = region(64); 227 assert_ne!(h.alloc(48, 8), 0); 228 assert_eq!(h.alloc(32, 8), 0); 229 assert_eq!(h.stats().fails, 1); 230 assert_eq!(h.stats().peak, 48); 231 } 232 233 #[test] 234 fn alignment_and_bad_align() { 235 let (_v, h) = region(256); 236 let a = h.alloc(3, 1); 237 let b = h.alloc(8, 64); 238 assert_eq!(b % 64, 0); 239 assert!(b >= a + 3); 240 assert_eq!(h.alloc(8, 3), 0); 241 } 242 243 #[test] 244 fn newest_block_is_reclaimed_and_grown_in_place() { 245 let (_v, h) = region(256); 246 let a = h.alloc(16, 8); 247 assert_eq!(h.resize_in_place(a, 16, 64), a); 248 assert_eq!(h.stats().live, 64); 249 h.dealloc(a, 64); 250 assert_eq!(h.stats().used, 0); 251 assert_eq!(h.stats().live, 0); 252 let b = h.alloc(16, 8); 253 let _c = h.alloc(16, 8); 254 assert_eq!(h.resize_in_place(b, 16, 32), 0, "not the newest block"); 255 } 256 257 #[test] 258 fn mark_reset_reuses_bytes_only_when_all_freed() { 259 let (_v, h) = region(1024); 260 let keep = h.alloc(100, 8); 261 let m = h.mark(); 262 for _ in 0..50 { 263 let x = h.alloc(200, 8); 264 let y = h.alloc(300, 8); 265 h.dealloc(x, 200); 266 h.dealloc(y, 300); 267 assert!(h.reset_to(m)); 268 assert_eq!(h.mark(), m); 269 } 270 assert!(h.stats().peak <= 104 + 200 + 8 + 300); 271 let z = h.alloc(10, 8); 272 assert!( 273 !h.reset_to(m), 274 "a live block after the mark blocks the reset" 275 ); 276 h.dealloc(z, 10); 277 assert!(h.reset_to(m)); 278 assert_ne!(keep, 0); 279 } 280 }