Skip to main content

os/
allocator.rs

1/*
2 * ============================================
3 * RISC-V 堆分配器模块
4 * ============================================
5 * 功能:提供内核堆内存分配
6 * 实现:默认使用链表分配器,可复用释放后的空闲区域
7 *
8 * 堆配置:
9 * - 起始地址:0x8040_0000(物理内存中的某个位置)
10 * - 大小:1 MB
11 * ============================================
12 */
13
14// ============================================
15// 堆配置
16// ============================================
17
18/// 堆起始地址(RISC-V 物理内存空间)
19pub const HEAP_START: usize = 0x8040_0000;
20
21/// 堆大小(1 MB)
22pub const HEAP_SIZE: usize = 1024 * 1024;
23
24// ============================================
25// 分配器实现
26// ============================================
27
28pub mod bump;
29#[cfg(feature = "fixed_size_allocator")]
30pub mod fixed_size_block;
31pub mod linked_list;
32
33use linked_list::LinkedListAllocator;
34
35/// 互斥锁包装器
36pub struct Locked<A> {
37    inner: spin::Mutex<A>,
38}
39
40impl<A> Locked<A> {
41    pub const fn new(inner: A) -> Self {
42        Locked {
43            inner: spin::Mutex::new(inner),
44        }
45    }
46
47    pub fn lock(&self) -> spin::MutexGuard<'_, A> {
48        self.inner.lock()
49    }
50}
51
52/// 全局分配器实例。
53///
54/// The heap tests allocate and drop many short-lived values, so the
55/// allocator must recycle freed regions instead of only bumping forward.
56#[global_allocator]
57static ALLOCATOR: Locked<LinkedListAllocator> = Locked::new(LinkedListAllocator::new());
58
59/// 初始化堆分配器
60///
61/// # 功能
62/// - 为堆区域分配物理帧
63/// - 映射堆区域到虚拟地址空间
64/// - 初始化全局分配器
65///
66/// # 参数
67/// - `frame_allocator`: 物理帧分配器
68pub fn init_heap(
69    _frame_allocator: &mut crate::memory::SimpleFrameAllocator,
70) -> Result<(), &'static str> {
71    // Use the linker-defined heap region (1024K reserved in linker-riscv64.ld).
72    // Under OpenSBI identity mapping, these virtual addresses directly map to
73    // the physical RAM reserved by the ELF .heap segment.
74    extern "C" {
75        static heap_start: u8;
76        static heap_end: u8;
77    }
78
79    let start = unsafe { &heap_start as *const u8 as usize };
80    let end = unsafe { &heap_end as *const u8 as usize };
81    let size = end - start;
82
83    unsafe {
84        ALLOCATOR.lock().init(start, size);
85    }
86
87    crate::serial_println!("[ALLOCATOR] Heap initialized");
88    Ok(())
89}
90
91// PTA exercise placeholder — students fill in their sys_malloc() implementation here
92// STUDENT_CODE_HERE
93
94// ============================================
95// 测试
96// ============================================
97
98#[cfg(test)]
99mod tests {
100    use alloc::{boxed::Box, vec::Vec};
101
102    #[test_case]
103    fn test_heap_allocation() {
104        let heap_value = Box::new(41);
105        assert_eq!(*heap_value, 41);
106    }
107
108    #[test_case]
109    fn test_large_vec() {
110        let n = 1000;
111        let mut vec = Vec::new();
112        for i in 0..n {
113            vec.push(i);
114        }
115        assert_eq!(vec.iter().sum::<u64>(), (n - 1) * n / 2);
116    }
117
118    #[test_case]
119    fn test_many_boxes() {
120        for i in 0..10000 {
121            let x = Box::new(i);
122            assert_eq!(*x, i);
123        }
124    }
125}