ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
/*
 * ============================================
 * RISC-V 操作系统库入口
 * ============================================
 * 功能:提供操作系统的核心功能库
 * 架构:RISC-V 64
 *
 * 主要模块:
 * - 串口输出(serial)
 * - 控制台(console)
 * - 中断处理(interrupts)
 * - 内存管理(memory)
 * - 堆分配器(allocator)
 * - 异步任务(task)
 * ============================================
 */

#![no_std]
#![cfg_attr(test, no_main)]
#![feature(custom_test_frameworks)]
#![test_runner(crate::test_runner)]
#![reexport_test_harness_main = "test_main"]

#[cfg(test)]
use core::arch::global_asm;
use core::panic::PanicInfo;

// ============================================
// 模块声明
// ============================================

pub mod allocator; // 堆分配器
pub mod block; // 块设备驱动(VirtIO)
pub mod console; // 控制台输出
pub mod errno; // POSIX 错误码
pub mod event_log; // 内核事件日志(可视化)
pub mod fs; // 文件系统(第七章)
pub mod grading; // 自动化判题系统
pub mod interrupts; // 中断和异常处理
pub mod mem_utils; // 内存内联函数 (memcpy/memset/memcmp/memmove)
pub mod memory; // 内存管理
pub mod process; // 进程管理(第六章)
pub mod serial; // 串口驱动
pub mod shell; // Shell (G6)
pub mod syscall; // 系统调用
pub mod task; // 异步任务系统

// ============================================
// 外部 crate
// ============================================

extern crate alloc; // 启用 alloc crate(堆分配)

// ============================================
// 测试框架
// ============================================

/// 测试特征
pub trait Testable {
    fn run(&self) -> ();
}

impl<T> Testable for T
where
    T: Fn(),
{
    fn run(&self) {
        serial_print!("{}...\t", core::any::type_name::<T>());
        self();
        serial_println!("[ok]");
    }
}

/// 测试运行器
pub fn test_runner(tests: &[&dyn Testable]) {
    serial_println!("Running {} tests", tests.len());
    for test in tests {
        test.run();
    }
    exit_qemu(QemuExitCode::Success);
}

/// 测试 panic 处理
pub fn test_panic_handler(info: &PanicInfo) -> ! {
    serial_println!("[failed]\n");
    serial_println!("Error: {}\n", info);
    exit_qemu(QemuExitCode::Failed);
    hlt_loop();
}

// ============================================
// QEMU 退出码
// ============================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum QemuExitCode {
    Success = 0x10,
    Failed = 0x11,
}

/// 退出 QEMU
///
/// # 说明
/// 在 RISC-V QEMU 中,我们使用 SBI 的 shutdown 调用
pub fn exit_qemu(exit_code: QemuExitCode) {
    let reason: usize = match exit_code {
        QemuExitCode::Success => 0,
        QemuExitCode::Failed => 1,
    };
    serial_println!("[QEMU] Exiting with code {:?}", exit_code);

    // Prefer the SBI System Reset extension so test failures carry a failure
    // reason. Fall back to the legacy shutdown call for older firmware.
    unsafe {
        core::arch::asm!(
            "li a7, 0x53525354", // SBI_EXT_SRST
            "li a6, 0",          // system_reset
            "li a0, 0",          // shutdown
            "mv a1, {reason}",   // no reason / system failure
            "ecall",
            "li a7, 8",          // legacy SBI shutdown
            "li a6, 0",
            "li a0, 0",
            "mv a1, {reason}",
            "ecall",
            "2:",
            "wfi",
            "j 2b",
            reason = in(reg) reason,
            options(noreturn)
        );
    }
}

// ============================================
// 初始化函数
// ============================================

/// 初始化操作系统
///
/// # 功能
/// - 初始化 trap 向量
/// - 保持全局中断关闭,直到调度器完成内核栈/任务上下文切换准备
pub fn init() {
    serial_println!("[INIT] Initializing RISC-V OS");

    // 初始化中断系统
    interrupts::init_idt();

    serial_println!("[INIT] Initialization complete");
}

/// 无限循环(使用 wfi 指令节能)
///
/// # 说明
/// RISC-V 的 wfi (Wait For Interrupt) 指令
/// 让 CPU 进入低功耗状态,直到中断到来
pub fn hlt_loop() -> ! {
    loop {
        riscv::asm::wfi();
    }
}

// ============================================
// Panic 处理(仅测试模式)
// ============================================

/// Panic 处理器(测试模式)
#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    test_panic_handler(info)
}

// ============================================
// 测试入口点
// ============================================

#[cfg(test)]
global_asm!(
    ".section .text.entry",
    ".globl _start",
    "_start:",
    "   la sp, stack_end",
    "   la t0, bss_start",
    "   la t1, bss_end",
    "1:",
    "   bgeu t0, t1, 2f",
    "   sd zero, (t0)",
    "   addi t0, t0, 8",
    "   j 1b",
    "2:",
    "   call test_kernel_main",
    "3:",
    "   wfi",
    "   j 3b",
);

#[cfg(test)]
#[no_mangle]
pub extern "C" fn test_kernel_main() -> ! {
    init();
    init_test_heap();
    test_main();
    hlt_loop();
}

#[cfg(test)]
fn init_test_heap() {
    extern "C" {
        static kernel_end: u8;
    }

    let kernel_end_addr = unsafe { &kernel_end as *const u8 as usize };
    let mut memory_manager = memory::init(kernel_end_addr);
    allocator::init_heap(&mut memory_manager.frame_allocator).expect("heap initialization failed");
}