Skip to main content

os/
lib.rs

1/*
2 * ============================================
3 * RISC-V 操作系统库入口
4 * ============================================
5 * 功能:提供操作系统的核心功能库
6 * 架构:RISC-V 64
7 *
8 * 主要模块:
9 * - 串口输出(serial)
10 * - 控制台(console)
11 * - 中断处理(interrupts)
12 * - 内存管理(memory)
13 * - 堆分配器(allocator)
14 * - 异步任务(task)
15 * ============================================
16 */
17
18#![no_std]
19#![cfg_attr(test, no_main)]
20#![feature(custom_test_frameworks)]
21#![test_runner(crate::test_runner)]
22#![reexport_test_harness_main = "test_main"]
23
24#[cfg(test)]
25use core::arch::global_asm;
26use core::panic::PanicInfo;
27
28// ============================================
29// 模块声明
30// ============================================
31
32pub mod allocator; // 堆分配器
33pub mod block; // 块设备驱动(VirtIO)
34pub mod console; // 控制台输出
35pub mod errno; // POSIX 错误码
36pub mod event_log; // 内核事件日志(可视化)
37pub mod fs; // 文件系统(第七章)
38pub mod grading; // 自动化判题系统
39pub mod interrupts; // 中断和异常处理
40pub mod mem_utils; // 内存内联函数 (memcpy/memset/memcmp/memmove)
41pub mod memory; // 内存管理
42pub mod process; // 进程管理(第六章)
43pub mod serial; // 串口驱动
44pub mod shell; // Shell (G6)
45pub mod syscall; // 系统调用
46pub mod task; // 异步任务系统
47
48// ============================================
49// 外部 crate
50// ============================================
51
52extern crate alloc; // 启用 alloc crate(堆分配)
53
54// ============================================
55// 测试框架
56// ============================================
57
58/// 测试特征
59pub trait Testable {
60    fn run(&self) -> ();
61}
62
63impl<T> Testable for T
64where
65    T: Fn(),
66{
67    fn run(&self) {
68        serial_print!("{}...\t", core::any::type_name::<T>());
69        self();
70        serial_println!("[ok]");
71    }
72}
73
74/// 测试运行器
75pub fn test_runner(tests: &[&dyn Testable]) {
76    serial_println!("Running {} tests", tests.len());
77    for test in tests {
78        test.run();
79    }
80    exit_qemu(QemuExitCode::Success);
81}
82
83/// 测试 panic 处理
84pub fn test_panic_handler(info: &PanicInfo) -> ! {
85    serial_println!("[failed]\n");
86    serial_println!("Error: {}\n", info);
87    exit_qemu(QemuExitCode::Failed);
88    hlt_loop();
89}
90
91// ============================================
92// QEMU 退出码
93// ============================================
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96#[repr(u32)]
97pub enum QemuExitCode {
98    Success = 0x10,
99    Failed = 0x11,
100}
101
102/// 退出 QEMU
103///
104/// # 说明
105/// 在 RISC-V QEMU 中,我们使用 SBI 的 shutdown 调用
106pub fn exit_qemu(exit_code: QemuExitCode) {
107    let reason: usize = match exit_code {
108        QemuExitCode::Success => 0,
109        QemuExitCode::Failed => 1,
110    };
111    serial_println!("[QEMU] Exiting with code {:?}", exit_code);
112
113    // Prefer the SBI System Reset extension so test failures carry a failure
114    // reason. Fall back to the legacy shutdown call for older firmware.
115    unsafe {
116        core::arch::asm!(
117            "li a7, 0x53525354", // SBI_EXT_SRST
118            "li a6, 0",          // system_reset
119            "li a0, 0",          // shutdown
120            "mv a1, {reason}",   // no reason / system failure
121            "ecall",
122            "li a7, 8",          // legacy SBI shutdown
123            "li a6, 0",
124            "li a0, 0",
125            "mv a1, {reason}",
126            "ecall",
127            "2:",
128            "wfi",
129            "j 2b",
130            reason = in(reg) reason,
131            options(noreturn)
132        );
133    }
134}
135
136// ============================================
137// 初始化函数
138// ============================================
139
140/// 初始化操作系统
141///
142/// # 功能
143/// - 初始化 trap 向量
144/// - 保持全局中断关闭,直到调度器完成内核栈/任务上下文切换准备
145pub fn init() {
146    serial_println!("[INIT] Initializing RISC-V OS");
147
148    // 初始化中断系统
149    interrupts::init_idt();
150
151    serial_println!("[INIT] Initialization complete");
152}
153
154/// 无限循环(使用 wfi 指令节能)
155///
156/// # 说明
157/// RISC-V 的 wfi (Wait For Interrupt) 指令
158/// 让 CPU 进入低功耗状态,直到中断到来
159pub fn hlt_loop() -> ! {
160    loop {
161        riscv::asm::wfi();
162    }
163}
164
165// ============================================
166// Panic 处理(仅测试模式)
167// ============================================
168
169/// Panic 处理器(测试模式)
170#[cfg(test)]
171#[panic_handler]
172fn panic(info: &PanicInfo) -> ! {
173    test_panic_handler(info)
174}
175
176// ============================================
177// 测试入口点
178// ============================================
179
180#[cfg(test)]
181global_asm!(
182    ".section .text.entry",
183    ".globl _start",
184    "_start:",
185    "   la sp, stack_end",
186    "   la t0, bss_start",
187    "   la t1, bss_end",
188    "1:",
189    "   bgeu t0, t1, 2f",
190    "   sd zero, (t0)",
191    "   addi t0, t0, 8",
192    "   j 1b",
193    "2:",
194    "   call test_kernel_main",
195    "3:",
196    "   wfi",
197    "   j 3b",
198);
199
200#[cfg(test)]
201#[no_mangle]
202pub extern "C" fn test_kernel_main() -> ! {
203    init();
204    init_test_heap();
205    test_main();
206    hlt_loop();
207}
208
209#[cfg(test)]
210fn init_test_heap() {
211    extern "C" {
212        static kernel_end: u8;
213    }
214
215    let kernel_end_addr = unsafe { &kernel_end as *const u8 as usize };
216    let mut memory_manager = memory::init(kernel_end_addr);
217    allocator::init_heap(&mut memory_manager.frame_allocator).expect("heap initialization failed");
218}