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 / mem / frame_allocator.rs

355 lines · 11039 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//! Deterministic physical memory and frame allocator primitives for AIENOS.
17
18/// Physical Page Size on AArch64 (4 KiB standard).
19pub const PAGE_SIZE: usize = 4096;
20pub const MAX_BATCH_FRAMES: usize = 160;
21
22/// Fixed-capacity ownership record for a reservation made under one allocator
23/// lock. The addresses are explicit physical frame starts; no Rust layout is
24/// persisted or passed across the firmware handoff.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct FrameBatch {
27 frames: [PhysAddr; MAX_BATCH_FRAMES],
28 count: u16,
29}
30
31impl FrameBatch {
32 pub const fn empty() -> Self {
33 Self {
34 frames: [PhysAddr(0); MAX_BATCH_FRAMES],
35 count: 0,
36 }
37 }
38
39 pub fn as_slice(&self) -> &[PhysAddr] {
40 &self.frames[..usize::from(self.count)]
41 }
42
43 pub const fn len(&self) -> usize {
44 self.count as usize
45 }
46
47 pub const fn is_empty(&self) -> bool {
48 self.count == 0
49 }
50}
51
52/// Physical address wrapper.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
54#[repr(transparent)]
55pub struct PhysAddr(pub usize);
56
57impl PhysAddr {
58 #[inline(always)]
59 pub const fn new(addr: usize) -> Self {
60 Self(addr)
61 }
62
63 #[inline(always)]
64 pub const fn as_usize(self) -> usize {
65 self.0
66 }
67
68 #[inline(always)]
69 pub const fn is_page_aligned(self) -> bool {
70 self.0.is_multiple_of(PAGE_SIZE)
71 }
72
73 #[inline(always)]
74 pub const fn align_up(self) -> Self {
75 Self((self.0 + PAGE_SIZE - 1) & !(PAGE_SIZE - 1))
76 }
77
78 #[inline(always)]
79 pub const fn align_down(self) -> Self {
80 Self(self.0 & !(PAGE_SIZE - 1))
81 }
82
83 #[inline(always)]
84 pub const fn offset(self, bytes: usize) -> Self {
85 Self(self.0 + bytes)
86 }
87}
88
89/// Virtual address wrapper.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
91#[repr(transparent)]
92pub struct VirtAddr(pub usize);
93
94impl VirtAddr {
95 #[inline(always)]
96 pub const fn new(addr: usize) -> Self {
97 Self(addr)
98 }
99
100 #[inline(always)]
101 pub const fn as_usize(self) -> usize {
102 self.0
103 }
104
105 #[inline(always)]
106 pub const fn is_page_aligned(self) -> bool {
107 self.0.is_multiple_of(PAGE_SIZE)
108 }
109}
110
111/// Represents a single physical page frame.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
113pub struct Frame {
114 pub index: usize,
115}
116
117impl Frame {
118 #[inline(always)]
119 pub const fn from_index(index: usize) -> Self {
120 Self { index }
121 }
122
123 #[inline(always)]
124 pub const fn start_address(self, base: PhysAddr) -> PhysAddr {
125 PhysAddr(base.0 + self.index * PAGE_SIZE)
126 }
127}
128
129/// Fixed-size bitmap frame allocator for deterministic bare-metal memory tracking.
130///
131/// `FRAMES` is the total number of managed 4 KiB frames.
132/// `WORDS` = `(FRAMES + 63) / 64`.
133pub struct BitmapFrameAllocator<const WORDS: usize> {
134 base_addr: PhysAddr,
135 total_frames: usize,
136 bitmap: [u64; WORDS],
137 allocated_count: usize,
138}
139
140impl<const WORDS: usize> BitmapFrameAllocator<WORDS> {
141 /// Initialize a new frame allocator for a physical memory region.
142 pub const fn new(base_addr: PhysAddr, total_frames: usize) -> Self {
143 assert!(
144 base_addr.is_page_aligned(),
145 "frame region must be page aligned"
146 );
147 assert!(
148 total_frames / 64 + (!total_frames.is_multiple_of(64)) as usize <= WORDS,
149 "frame region exceeds bitmap capacity"
150 );
151 assert!(
152 total_frames <= (usize::MAX - base_addr.0) / PAGE_SIZE,
153 "frame region overflows physical address space"
154 );
155 Self {
156 base_addr,
157 total_frames,
158 bitmap: [0u64; WORDS],
159 allocated_count: 0,
160 }
161 }
162
163 /// Total managed physical frames.
164 pub const fn total_frames(&self) -> usize {
165 self.total_frames
166 }
167
168 /// Number of allocated frames.
169 pub const fn allocated_count(&self) -> usize {
170 self.allocated_count
171 }
172
173 /// Number of free frames remaining.
174 pub const fn free_count(&self) -> usize {
175 self.total_frames.saturating_sub(self.allocated_count)
176 }
177
178 /// Allocate a single physical frame.
179 pub fn allocate_frame(&mut self) -> Option<PhysAddr> {
180 for (word_idx, word) in self.bitmap.iter_mut().enumerate() {
181 if *word != !0u64 {
182 let bit_idx = word.trailing_ones() as usize;
183 let frame_idx = word_idx * 64 + bit_idx;
184 if frame_idx < self.total_frames {
185 *word |= 1u64 << bit_idx;
186 self.allocated_count += 1;
187 return Some(PhysAddr(self.base_addr.0 + frame_idx * PAGE_SIZE));
188 }
189 }
190 }
191 None
192 }
193
194 /// Free a previously allocated physical frame.
195 pub fn deallocate_frame(&mut self, addr: PhysAddr) -> bool {
196 if !addr.is_page_aligned() || addr.0 < self.base_addr.0 {
197 return false;
198 }
199 let offset = addr.0 - self.base_addr.0;
200 let frame_idx = offset / PAGE_SIZE;
201 if frame_idx >= self.total_frames {
202 return false;
203 }
204
205 let word_idx = frame_idx / 64;
206 let bit_idx = frame_idx % 64;
207
208 if (self.bitmap[word_idx] & (1u64 << bit_idx)) != 0 {
209 self.bitmap[word_idx] &= !(1u64 << bit_idx);
210 self.allocated_count = self.allocated_count.saturating_sub(1);
211 true
212 } else {
213 false
214 }
215 }
216
217 /// Allocate contiguous physical frames.
218 pub fn allocate_contiguous(&mut self, count: usize) -> Option<PhysAddr> {
219 if count == 0 || count > self.free_count() {
220 return None;
221 }
222
223 let mut run_start = 0;
224 let mut current_run = 0;
225
226 for i in 0..self.total_frames {
227 let word_idx = i / 64;
228 let bit_idx = i % 64;
229 let is_set = (self.bitmap[word_idx] & (1u64 << bit_idx)) != 0;
230
231 if !is_set {
232 if current_run == 0 {
233 run_start = i;
234 }
235 current_run += 1;
236 if current_run == count {
237 // Mark run as allocated
238 for f in run_start..run_start + count {
239 let w = f / 64;
240 let b = f % 64;
241 self.bitmap[w] |= 1u64 << b;
242 }
243 self.allocated_count += count;
244 return Some(PhysAddr(self.base_addr.0 + run_start * PAGE_SIZE));
245 }
246 } else {
247 current_run = 0;
248 }
249 }
250
251 None
252 }
253
254 /// Reserve a bounded set of frames atomically from this allocator. On
255 /// exhaustion, every frame acquired by this call is returned before it
256 /// reports failure.
257 pub fn allocate_batch(&mut self, count: usize) -> Option<FrameBatch> {
258 if count == 0 || count > MAX_BATCH_FRAMES || count > self.free_count() {
259 return None;
260 }
261 let mut batch = FrameBatch::empty();
262 for index in 0..count {
263 match self.allocate_frame() {
264 Some(frame) => {
265 batch.frames[index] = frame;
266 batch.count += 1;
267 }
268 None => {
269 self.release_batch(batch);
270 return None;
271 }
272 }
273 }
274 Some(batch)
275 }
276
277 /// Return every frame owned by a prior batch. Invalid/double-freed entries
278 /// cause `false`; valid entries are still returned.
279 pub fn release_batch(&mut self, batch: FrameBatch) -> bool {
280 let mut complete = true;
281 for frame in batch.as_slice() {
282 complete &= self.deallocate_frame(*frame);
283 }
284 complete
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291
292 #[test]
293 fn test_allocator_basic() {
294 let mut alloc = BitmapFrameAllocator::<4>::new(PhysAddr(0x1000_0000), 256);
295 assert_eq!(alloc.total_frames(), 256);
296 assert_eq!(alloc.free_count(), 256);
297
298 let f0 = alloc.allocate_frame().expect("Alloc f0");
299 assert_eq!(f0, PhysAddr(0x1000_0000));
300 assert_eq!(alloc.allocated_count(), 1);
301
302 let f1 = alloc.allocate_frame().expect("Alloc f1");
303 assert_eq!(f1, PhysAddr(0x1000_1000));
304
305 assert!(alloc.deallocate_frame(f0));
306 assert_eq!(alloc.allocated_count(), 1);
307
308 // Re-allocation should pick reused f0
309 let f0_reused = alloc.allocate_frame().expect("Realloc f0");
310 assert_eq!(f0_reused, PhysAddr(0x1000_0000));
311 }
312
313 #[test]
314 fn test_alloc_contiguous() {
315 let mut alloc = BitmapFrameAllocator::<2>::new(PhysAddr(0x2000_0000), 128);
316 let block = alloc.allocate_contiguous(4).expect("Contiguous 4 frames");
317 assert_eq!(block, PhysAddr(0x2000_0000));
318 assert_eq!(alloc.allocated_count(), 4);
319 }
320
321 #[test]
322 fn allocator_rejects_unaligned_deallocation() {
323 let mut alloc = BitmapFrameAllocator::<1>::new(PhysAddr(0x2000_0000), 64);
324 let frame = alloc.allocate_frame().unwrap();
325 assert!(!alloc.deallocate_frame(PhysAddr(frame.0 + 1)));
326 assert_eq!(alloc.allocated_count(), 1);
327 assert!(alloc.deallocate_frame(frame));
328 }
329
330 #[test]
331 fn batch_reservation_is_bounded_and_released_as_a_unit() {
332 let mut alloc = BitmapFrameAllocator::<1>::new(PhysAddr(0x3000_0000), 8);
333 let batch = alloc.allocate_batch(6).unwrap();
334 assert_eq!(batch.len(), 6);
335 assert_eq!(alloc.free_count(), 2);
336 assert!(alloc.release_batch(batch));
337 assert_eq!(alloc.free_count(), 8);
338 assert!(alloc.allocate_batch(MAX_BATCH_FRAMES + 1).is_none());
339 }
340
341 #[test]
342 fn insufficient_batch_reservation_leaves_no_partial_allocations() {
343 let mut alloc = BitmapFrameAllocator::<1>::new(PhysAddr(0x4000_0000), 8);
344 assert!(alloc.allocate_frame().is_some());
345 assert!(alloc.allocate_batch(8).is_none());
346 assert_eq!(alloc.allocated_count(), 1);
347 assert_eq!(alloc.free_count(), 7);
348 }
349
350 #[test]
351 #[should_panic(expected = "frame region exceeds bitmap capacity")]
352 fn allocator_rejects_capacity_overflow() {
353 let _ = BitmapFrameAllocator::<1>::new(PhysAddr(0x2000_0000), 65);
354 }
355}