Skip to main content

os/allocator/
bump.rs

1pub struct BumpAllocator {
2    heap_start: usize,
3    heap_end: usize,
4    next: usize,
5    allocations: usize,
6}
7
8impl BumpAllocator {
9    pub const fn new() -> Self {
10        BumpAllocator {
11            heap_start: 0,
12            heap_end: 0,
13            next: 0,
14            allocations: 0,
15        }
16    }
17    /// # Safety
18    ///
19    /// The caller must provide an unused, valid heap region that remains
20    /// exclusively owned by this allocator for the lifetime of the kernel.
21    pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
22        self.heap_start = heap_start;
23        self.heap_end = heap_start + heap_size;
24        self.next = self.heap_start;
25        // DEBUG — verify init was called
26        crate::serial_println!(
27            "[BUMP] init called: start={:#x} size={:#x} end={:#x}",
28            heap_start,
29            heap_size,
30            self.heap_end
31        );
32    }
33}
34
35impl Default for BumpAllocator {
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41use super::Locked;
42use alloc::alloc::{GlobalAlloc, Layout};
43use core::ptr;
44
45unsafe impl GlobalAlloc for Locked<BumpAllocator> {
46    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
47        let mut bump = self.lock();
48
49        let alloc_start = align_up(bump.next, layout.align());
50        let alloc_end = match alloc_start.checked_add(layout.size()) {
51            Some(end) => end,
52            None => return ptr::null_mut(),
53        };
54
55        if alloc_end > bump.heap_end {
56            // DEBUG — 打印分配器状态
57            crate::serial_println!("[BUMP] OOM: next={:#x} end={:#x} size={} align={} alloc_start={:#x} alloc_end={:#x}",
58                bump.next, bump.heap_end, layout.size(), layout.align(), alloc_start, alloc_end);
59            ptr::null_mut()
60        } else {
61            bump.next = alloc_end;
62            bump.allocations += 1;
63            alloc_start as *mut u8
64        }
65    }
66
67    unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
68        let mut bump = self.lock();
69
70        bump.allocations -= 1;
71        // BumpAllocator never reuses freed memory — next pointer stays put
72    }
73}
74
75fn align_up(addr: usize, align: usize) -> usize {
76    (addr + align - 1) & !(align - 1)
77}