ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
/*
 * ============================================
 * RISC-V 堆分配器模块
 * ============================================
 * 功能:提供内核堆内存分配
 * 实现:默认使用链表分配器,可复用释放后的空闲区域
 *
 * 堆配置:
 * - 起始地址:0x8040_0000(物理内存中的某个位置)
 * - 大小:1 MB
 * ============================================
 */

// ============================================
// 堆配置
// ============================================

/// 堆起始地址(RISC-V 物理内存空间)
pub const HEAP_START: usize = 0x8040_0000;

/// 堆大小(1 MB)
pub const HEAP_SIZE: usize = 1024 * 1024;

// ============================================
// 分配器实现
// ============================================

pub mod bump;
#[cfg(feature = "fixed_size_allocator")]
pub mod fixed_size_block;
pub mod linked_list;

use linked_list::LinkedListAllocator;

/// 互斥锁包装器
pub struct Locked<A> {
    inner: spin::Mutex<A>,
}

impl<A> Locked<A> {
    pub const fn new(inner: A) -> Self {
        Locked {
            inner: spin::Mutex::new(inner),
        }
    }

    pub fn lock(&self) -> spin::MutexGuard<'_, A> {
        self.inner.lock()
    }
}

/// 全局分配器实例。
///
/// The heap tests allocate and drop many short-lived values, so the
/// allocator must recycle freed regions instead of only bumping forward.
#[global_allocator]
static ALLOCATOR: Locked<LinkedListAllocator> = Locked::new(LinkedListAllocator::new());

/// 初始化堆分配器
///
/// # 功能
/// - 为堆区域分配物理帧
/// - 映射堆区域到虚拟地址空间
/// - 初始化全局分配器
///
/// # 参数
/// - `frame_allocator`: 物理帧分配器
pub fn init_heap(
    _frame_allocator: &mut crate::memory::SimpleFrameAllocator,
) -> Result<(), &'static str> {
    // Use the linker-defined heap region (1024K reserved in linker-riscv64.ld).
    // Under OpenSBI identity mapping, these virtual addresses directly map to
    // the physical RAM reserved by the ELF .heap segment.
    extern "C" {
        static heap_start: u8;
        static heap_end: u8;
    }

    let start = unsafe { &heap_start as *const u8 as usize };
    let end = unsafe { &heap_end as *const u8 as usize };
    let size = end - start;

    unsafe {
        ALLOCATOR.lock().init(start, size);
    }

    crate::serial_println!("[ALLOCATOR] Heap initialized");
    Ok(())
}

// PTA exercise placeholder — students fill in their sys_malloc() implementation here
// STUDENT_CODE_HERE

// ============================================
// 测试
// ============================================

#[cfg(test)]
mod tests {
    use alloc::{boxed::Box, vec::Vec};

    #[test_case]
    fn test_heap_allocation() {
        let heap_value = Box::new(41);
        assert_eq!(*heap_value, 41);
    }

    #[test_case]
    fn test_large_vec() {
        let n = 1000;
        let mut vec = Vec::new();
        for i in 0..n {
            vec.push(i);
        }
        assert_eq!(vec.iter().sum::<u64>(), (n - 1) * n / 2);
    }

    #[test_case]
    fn test_many_boxes() {
        for i in 0..10000 {
            let x = Box::new(i);
            assert_eq!(*x, i);
        }
    }
}