diff --git a/ch3/os/Cargo.toml b/ch3/os/Cargo.toml new file mode 100644 index 0000000..dd3234d --- /dev/null +++ b/ch3/os/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "os" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +# 设置release模式下保存调试信息 +[profile.release] +debug=true + +[dependencies] +riscv = { git = "https://github.com/rcore-os/riscv", features = ["inline-asm"] } +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } \ No newline at end of file diff --git a/ch3/os/Makefile b/ch3/os/Makefile new file mode 100644 index 0000000..0c03143 --- /dev/null +++ b/ch3/os/Makefile @@ -0,0 +1,51 @@ +TARGET := riscv64gc-unknown-none-elf +KERNEL_ENTRY := 0x80200000 +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin +SYMBOL_MAP := target/system.map +QEMU_CMD_PATH := ../../tools/qemu-system-riscv64 +QEMU_PID = $(shell ps aux | grep "[q]emu-system' | awk '{print $$2}") +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +RUST_FLAGS := -Clink-arg=-Tsrc/linker.ld # 使用我们自己的链接脚本 +RUST_FLAGS += -Cforce-frame-pointers=yes # 强制编译器生成帧指针 +RUST_FLAGS:=$(strip ${RUST_FLAGS}) + +# 编译elf文件 +build_elf: clean + CARGO_BUILD_RUSTFLAGS="$(RUST_FLAGS)" \ + cargo build --$(MODE) --target=$(TARGET) + +# 导出一个符号表, 供我们查看 +$(SYMBOL_MAP):build_elf + nm $(KERNEL_ELF) | sort > $(SYMBOL_MAP) + +# 丢弃内核可执行elf文件中的元数据得到内核镜像 +$(KERNEL_BIN): build_elf + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + + +debug:build_elf $(KERNEL_BIN) $(SYMBOL_MAP) + $(QEMU_CMD_PATH) \ + -machine virt \ + -display none \ + -daemonize \ + -bios ../../bootloader/rustsbi-qemu.bin \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY) \ + -s -S + +run:build_elf $(KERNEL_BIN) $(SYMBOL_MAP) kill + $(QEMU_CMD_PATH) \ + -machine virt \ + -nographic \ + -bios ../../bootloader/rustsbi-qemu.bin \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY) + +clean: + rm -rf ./target* && rm -rf ./src/link_app.S + +kill: + -kill -9 $(QEMU_PID) + diff --git a/ch3/os/build.rs b/ch3/os/build.rs new file mode 100644 index 0000000..0d4cdb2 --- /dev/null +++ b/ch3/os/build.rs @@ -0,0 +1,70 @@ +use std::fs::{read_dir, File}; +use std::io::{Result, Write}; + +fn main() { + // 主要功能是把用户的应用程序加载到内核中 + println!("cargo:rerun-if-changed=../user/src/"); + println!("cargo:rerun-if-changed={}", TARGET_PATH); + insert_app_data().unwrap(); +} + +static TARGET_PATH: &str = "../user/target/riscv64gc-unknown-none-elf/release/"; + +fn insert_app_data() -> Result<()> { + let mut f = File::create("src/link_app.S").unwrap(); + let mut apps: Vec<_> = read_dir("../user/src/bin") + .unwrap() + .into_iter() + .map(|dir_entry| { + let mut name_with_ext = dir_entry.unwrap().file_name().into_string().unwrap(); + name_with_ext.drain(name_with_ext.find('.').unwrap()..name_with_ext.len()); + name_with_ext + }) + .collect(); + apps.sort(); + + + /// + /// .align 3 表示接下来的数据或代码 使用2^3 8字节对齐 + /// .section .data 下面属于data段 + /// .global _num_app 定义一个全局符号 _num_app + /// _num_app: _num_app的位置的数据 + /// .quad 5 用来当做matedata 8字节的整数 表示有5个元素 + /// .quad app_0_start 依次存储每个app的开始的位置 + /// .quad app_1_start + /// .quad app_2_start + /// .quad app_3_start + /// .quad app_4_start + /// .quad app_4_end + writeln!( + f, + r#" + .align 3 + .section .data + .global _num_app +_num_app: + .quad {}"#, + apps.len() + )?; + + for i in 0..apps.len() { + writeln!(f, r#" .quad app_{}_start"#, i)?; + } + writeln!(f, r#" .quad app_{}_end"#, apps.len() - 1)?; + + for (idx, app) in apps.iter().enumerate() { + println!("app_{}: {}", idx, app); + writeln!( + f, + r#" + .section .data + .global app_{0}_start + .global app_{0}_end +app_{0}_start: + .incbin "{2}{1}.bin" +app_{0}_end:"#, + idx, app, TARGET_PATH + )?; + } + Ok(()) +} diff --git a/ch3/os/src/batch.rs b/ch3/os/src/batch.rs new file mode 100644 index 0000000..a42c9e9 --- /dev/null +++ b/ch3/os/src/batch.rs @@ -0,0 +1,111 @@ +use core::arch::asm; +use lazy_static::*; +use riscv::register::mcause::Trap; +use crate::println; +use crate::sbi::shutdown; +use crate::sync::UPSafeCell; +use crate::trap::TrapContext; + +const USER_STACK_SIZE: usize = 4096 * 2; // 栈大小为8kb +const KERNEL_STACK_SIZE: usize = 4096 * 2; + +const MAX_APP_NUM: usize = 16; // 系统最大支持的运行程序数量 + +const APP_BASE_ADDRESS: usize = 0x80400000; // 载入的app的起始的地址 +const APP_SIZE_LIMIT: usize = 0x20000; // app的最大的二进制文件能够使用的大小 + +// 在此之后 应用使用UserStack, 而内核使用KernelStack, entry.asm设置的64k启动栈不再被使用(首次运行run_next_app时被接管了 mv sp, a0) +// KERNEL_STACK 保存的是 Trap Context + +static KERNEL_STACK: [u8; KERNEL_STACK_SIZE] = [0; KERNEL_STACK_SIZE]; +static USER_STACK: [u8; USER_STACK_SIZE] = [0; USER_STACK_SIZE]; + +lazy_static! { + static ref APP_MANAGER: UPSafeCell = unsafe { + UPSafeCell::new({ + extern "C" { + fn _num_app(); + } + let num_app_ptr = _num_app as usize as *const usize; + let num_app = num_app_ptr.read_volatile(); // 用户app的总数量 + + let mut app_start_lis: [usize; MAX_APP_NUM + 1] = [0; MAX_APP_NUM + 1]; // 创建一个数组, 用来保存每个app的起始位置 + + // 得到每个app的起始地址 + let mut app_start_lis: [usize; MAX_APP_NUM + 1] = [0; MAX_APP_NUM + 1]; + let app_start_raw: &[usize] = + core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1); + app_start_lis[..=num_app].copy_from_slice(app_start_raw); + + AppManager{ + num_app, + current_app: 0, + app_start_lis + } + }) + }; +} + +// 由build.rs 生成的link_app.S, 根据里面的信息生成的结构体 +struct AppManager { + num_app: usize, // 用户app数量 + current_app: usize, // 当前需要执行的第几个app + app_start_lis: [usize; MAX_APP_NUM + 1], // 保存了每个app的起始位置, 后面会跳到这里, +1 是因为end的位置也占了一个usize, 需要知道end的位置 +} + +impl AppManager{ + fn show_app_info(&self){ + println!("[kernel] num_app = {}", self.num_app); + for i in 0..self.num_app { + println!( + "[kernel] app_{} ({:#x}, {:#x})", + i, + self.app_start_lis[i], + self.app_start_lis[i + 1] + ); + } + } +} + + +pub fn init() { + APP_MANAGER.exclusive_access().show_app_info(); +} + +pub fn run_next_app() -> ! { + // 得到下一个需要运行的app的入口地址 + let mut app_manager = APP_MANAGER.exclusive_access(); + let current_app = app_manager.current_app; + if current_app >= app_manager.num_app { + shutdown(); + } + let app_entry_ptr = app_manager.app_start_lis[current_app]; + println!("------------- run_next_app load app {}, {:x}", current_app, app_entry_ptr); + app_manager.current_app += 1; + drop(app_manager); + + + extern "C" { + fn __restore(trap_context_ptr: usize); + } + + unsafe { + // 得到用户栈的栈顶 + let user_stack_top = USER_STACK.as_ptr() as usize + USER_STACK_SIZE; + // 得到用户trap的上下文以及寄存器状态 + let user_trap_context = TrapContext::app_init_context(app_entry_ptr, user_stack_top); + + // 把用户trap copy到内核栈 + let kernel_stack_top = KERNEL_STACK.as_ptr() as usize + KERNEL_STACK_SIZE; // 现在栈顶和栈底都在一个内存位置 + // 为trap context 分配栈空间 + let kernel_trap_context_ptr = (kernel_stack_top - core::mem::size_of::()) as * mut TrapContext; + + unsafe { + // 把user_trap_context copy到内核栈顶 + *kernel_trap_context_ptr = user_trap_context; + // 返回现在的内核栈顶 + __restore(kernel_trap_context_ptr as *const _ as usize); + } + } + panic!("Unreachable in batch::run_current_app!"); +} diff --git a/ch3/os/src/config.rs b/ch3/os/src/config.rs new file mode 100644 index 0000000..23e601c --- /dev/null +++ b/ch3/os/src/config.rs @@ -0,0 +1,2 @@ +pub const APP_BASE_ADDRESS: usize = 0x80400000; // 载入的app的起始的地址 +pub const APP_SIZE_LIMIT: usize = 0x20000; // app的最大的二进制文件能够使用的大小 \ No newline at end of file diff --git a/ch3/os/src/entry.asm b/ch3/os/src/entry.asm new file mode 100644 index 0000000..f790219 --- /dev/null +++ b/ch3/os/src/entry.asm @@ -0,0 +1,15 @@ +.section .text.entry +.globl _start // 声明_start是全局符号 +_start: + la sp, boot_stack_top_bound + call rust_main + + + +// 声明栈空间 后续 .bss.stack 会被link脚本链接到 .bss段 + .section .bss.stack + .globl boot_stack_lower_bound // 栈低地址公开为全局符号 + .globl boot_stack_top_bound // 栈高地址公开为全局符号 +boot_stack_lower_bound: + .space 4096 * 16 +boot_stack_top_bound: diff --git a/ch3/os/src/lang_items.rs b/ch3/os/src/lang_items.rs new file mode 100644 index 0000000..53e74c5 --- /dev/null +++ b/ch3/os/src/lang_items.rs @@ -0,0 +1,2 @@ +pub mod panic; +pub mod console; \ No newline at end of file diff --git a/ch3/os/src/lang_items/console.rs b/ch3/os/src/lang_items/console.rs new file mode 100644 index 0000000..e4330a1 --- /dev/null +++ b/ch3/os/src/lang_items/console.rs @@ -0,0 +1,33 @@ + +use crate::sbi::console_put_char; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout{ + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_put_char(c as usize); + } + Ok(()) + } +} + +// 用函数包装一下, 表示传进来的参数满足Arguments trait, 然后供宏调用 +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] // 导入这个文件即可使用这些宏 +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} diff --git a/ch3/os/src/lang_items/panic.rs b/ch3/os/src/lang_items/panic.rs new file mode 100644 index 0000000..2e893c2 --- /dev/null +++ b/ch3/os/src/lang_items/panic.rs @@ -0,0 +1,18 @@ +use core::panic::PanicInfo; +use crate::println; +use crate::sbi::shutdown; + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println!( + "Panicked at {}:{} {}", + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println!("Panicked: {}", info.message().unwrap()); + } + shutdown(); +} \ No newline at end of file diff --git a/ch3/os/src/linker.ld b/ch3/os/src/linker.ld new file mode 100644 index 0000000..099fd87 --- /dev/null +++ b/ch3/os/src/linker.ld @@ -0,0 +1,48 @@ +OUTPUT_ARCH(riscv) /* 目标平台 */ +ENTRY(_start) /* 设置程序入口点为entry.asm中定义的全局符号 */ +BASE_ADDRESS = 0x80200000; /* 一个常量, 我们的kernel将来加载到这个物理地址 */ + +SECTIONS +{ + . = BASE_ADDRESS; /* 我们对 . 进行赋值, 调整接下来的段的开始位置放在我们定义的常量出 */ +/* skernel = .;*/ + + stext = .; /* .text段的开始位置 */ + .text : { /* 表示生成一个为 .text的段, 花括号内按照防止顺序表示将输入文件中的哪些段放在 当前.text段中 */ + *(.text.entry) /* entry.asm中, 我们自己定义的.text.entry段, 被放在顶部*/ + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + .bss : { + *(.bss.stack) /* 全局符号 sbss 和 ebss 分别指向 .bss 段除 .bss.stack 以外的起始和终止地址(.bss.stack是我们在entry.asm中定义的栈) */ + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/ch3/os/src/loader.rs b/ch3/os/src/loader.rs new file mode 100644 index 0000000..2fa5b83 --- /dev/null +++ b/ch3/os/src/loader.rs @@ -0,0 +1,54 @@ +use core::arch::asm; + +use crate::config::*; + +extern "C" { + fn _num_app(); +} + +// 得到用户app的数量 +fn get_num_app() -> usize{ + unsafe{ + (_num_app as usize as *const usize).read_volatile() + } +} + +// 把把 app一次性都加载到内存, 并分配二进制空间 +pub fn load_app() { + // 得到符号位 + let num_app_ptr = _num_app as usize as *const usize; + + // 得到 符号开始的前8个字节, 这里保存的app的数量 + let num_app = get_num_app(); + + // 得到 app数组的起始位置 num_app_ptr.add(1)跳过上方的 metadata, num_app+1 是确保切免得长度足够, 因为后面还有一个符号在linker.ld中 .quad app_2_end 表示结束的内存地址 + let app_start = unsafe { + core::slice::from_raw_parts(num_app_ptr.add(1), num_app+1) + }; + + // 清除缓存 + unsafe { asm!("fence.i"); } + + // 加载app + for app_id in 0..num_app { + // 得到每个app的起始位置 + let base_ptr = APP_BASE_ADDRESS + app_id * APP_SIZE_LIMIT; + + // 清理这个应用可以占用的内存(好像可以不用做吧? 下面直接dst.copy_from_slice全部覆盖了) + (base_ptr..base_ptr + APP_SIZE_LIMIT).for_each(|addr| unsafe { + (addr as *mut u8).write_volatile(0) + }); + + // 加载 app_start 处二进制数据到内存里 + let src = unsafe { + let app_size = app_start[app_id + 1] - app_start[app_id]; // 下一个app的起始位置, 减去当前的起始位置就是app的大小 + core::slice::from_raw_parts(app_start[app_id] as *const u8, app_size) + }; + + // 得到app占用的内存, 后面需要把app 二进制数据加载到这里 + let dst = unsafe { + core::slice::from_raw_parts_mut(base_ptr as *mut u8, src.len()) + }; + dst.copy_from_slice(src); + } +} \ No newline at end of file diff --git a/ch3/os/src/main.rs b/ch3/os/src/main.rs new file mode 100644 index 0000000..bb76f3f --- /dev/null +++ b/ch3/os/src/main.rs @@ -0,0 +1,56 @@ +#![feature(panic_info_message)] +#![no_std] +#![no_main] + +use core::arch::global_asm; +use sbi::{console_put_char, shutdown}; +use lang_items::console; + +pub mod lang_items; +pub mod sbi; +pub mod batch; +pub mod sync; +pub mod trap; +pub mod syscall; +pub mod loader; +pub mod config; + +// 汇编脚本引入, 调整内核的内存布局之后, 会跳入到 rust_main中执行 +global_asm!(include_str!("entry.asm")); + +// 引入用户的二进制文件 +global_asm!(include_str!("link_app.S")); + +extern "C" { + fn stext(); + fn etext(); + fn sbss(); + fn ebss(); + fn boot_stack_top_bound(); + fn boot_stack_lower_bound(); +} + +#[no_mangle] +pub fn rust_main(){ + init_bss(); + + println!("stext: {:#x}, etext: {:#x}", stext as usize, etext as usize); + println!("sbss: {:#x}, ebss: {:#x}", sbss as usize, ebss as usize); + println!("boot_stack_top_bound: {:#x}, boot_stack_lower_bound: {:#x}", boot_stack_top_bound as usize, boot_stack_lower_bound as usize); + + loader::load_app(); + trap::init(); + batch::init(); + batch::run_next_app(); + loop { + + } +} + +/// ## 初始化bss段 +/// +fn init_bss() { + unsafe { + (sbss as usize..ebss as usize).for_each(|p| (p as *mut u8).write_unaligned(0)) + } +} diff --git a/ch3/os/src/sbi.rs b/ch3/os/src/sbi.rs new file mode 100644 index 0000000..e954239 --- /dev/null +++ b/ch3/os/src/sbi.rs @@ -0,0 +1,40 @@ +use core::arch::asm; + +// legacy extensions: ignore fid +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_CLEAR_IPI: usize = 3; +const SBI_SEND_IPI: usize = 4; +const SBI_REMOTE_FENCE_I: usize = 5; +const SBI_REMOTE_SFENCE_VMA: usize = 6; +const SBI_REMOTE_SFENCE_VMA_ASID: usize = 7; + +// system reset extension +const SRST_EXTENSION: usize = 0x53525354; +const SBI_SHUTDOWN: usize = 0; + +#[inline(always)] +fn sbi_call(eid: usize, fid: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x16") fid, + in("x17") eid, + ); + } + ret +} + +pub fn console_put_char(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, 0, c, 0, 0); +} + +pub fn shutdown() -> ! { + sbi_call(SRST_EXTENSION, SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!") +} \ No newline at end of file diff --git a/ch3/os/src/sync/mod.rs b/ch3/os/src/sync/mod.rs new file mode 100644 index 0000000..1ccdd2e --- /dev/null +++ b/ch3/os/src/sync/mod.rs @@ -0,0 +1,4 @@ +//! Synchronization and interior mutability primitives + +mod up; +pub use up::UPSafeCell; diff --git a/ch3/os/src/sync/up.rs b/ch3/os/src/sync/up.rs new file mode 100644 index 0000000..e8ba20c --- /dev/null +++ b/ch3/os/src/sync/up.rs @@ -0,0 +1,31 @@ +//! Uniprocessor interior mutability primitives + +use core::cell::{RefCell, RefMut}; + +/// Wrap a static data structure inside it so that we are +/// able to access it without any `unsafe`. +/// +/// We should only use it in uniprocessor. +/// +/// In order to get mutable reference of inner data, call +/// `exclusive_access`. +pub struct UPSafeCell { + /// inner data + inner: RefCell, +} + +unsafe impl Sync for UPSafeCell {} + +impl UPSafeCell { + /// User is responsible to guarantee that inner struct is only used in + /// uniprocessor. + pub unsafe fn new(value: T) -> Self { + Self { + inner: RefCell::new(value), + } + } + /// Exclusive access inner data in UPSafeCell. Panic if the data has been borrowed. + pub fn exclusive_access(&self) -> RefMut<'_, T> { + self.inner.borrow_mut() + } +} diff --git a/ch3/os/src/syscall/fs.rs b/ch3/os/src/syscall/fs.rs new file mode 100644 index 0000000..eeb9aeb --- /dev/null +++ b/ch3/os/src/syscall/fs.rs @@ -0,0 +1,20 @@ +//! File and filesystem-related syscalls + +use crate::print; + +const FD_STDOUT: usize = 1; + +/// write buf of length `len` to a file with `fd` +pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize { + match fd { + FD_STDOUT => { + let slice = unsafe { core::slice::from_raw_parts(buf, len) }; + let str = core::str::from_utf8(slice).unwrap(); + print!("{}", str); + len as isize + } + _ => { + panic!("Unsupported fd in sys_write!"); + } + } +} diff --git a/ch3/os/src/syscall/mod.rs b/ch3/os/src/syscall/mod.rs new file mode 100644 index 0000000..0f9f63c --- /dev/null +++ b/ch3/os/src/syscall/mod.rs @@ -0,0 +1,17 @@ +const SYSCALL_WRITE: usize = 64; +const SYSCALL_EXIT: usize = 93; + +mod fs; +mod process; + +use fs::*; +use process::*; + +/// 根据syscall_id 进行分发 +pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize { + match syscall_id { + SYSCALL_WRITE => sys_write(args[0], args[1] as *const u8, args[2]), + SYSCALL_EXIT => sys_exit(args[0] as i32), + _ => panic!("Unsupported syscall_id: {}", syscall_id), + } +} \ No newline at end of file diff --git a/ch3/os/src/syscall/process.rs b/ch3/os/src/syscall/process.rs new file mode 100644 index 0000000..6dbed6d --- /dev/null +++ b/ch3/os/src/syscall/process.rs @@ -0,0 +1,9 @@ +//! App management syscalls +use crate::batch::run_next_app; +use crate::println; + +/// 任务退出, 并立即切换任务 +pub fn sys_exit(exit_code: i32) -> ! { + println!("[kernel] Application exited with code {}", exit_code); + run_next_app() +} diff --git a/ch3/os/src/trap/context.rs b/ch3/os/src/trap/context.rs new file mode 100644 index 0000000..7ed956d --- /dev/null +++ b/ch3/os/src/trap/context.rs @@ -0,0 +1,40 @@ +use riscv::register::sstatus::{self, Sstatus, SPP}; + +/// Trap Context +#[repr(C)] +pub struct TrapContext { + /// 保存了 [0..31] 号寄存器, 其中0/2/4 号寄存器我们不保存, 2有特殊用途 + /// > 其中 [17] 号寄存器保存的是系统调用号 + /// + /// > [10]/[11]/[12] 寄存器保存了系统调用时的3个参数 + /// + /// > [2] 号寄存器因为我们有特殊用途所以也跳过保存, (保存了用户栈)保存了用户 USER_STACK 的 栈顶 + /// + /// > [0] 被硬编码为了0, 不会有变化, 不需要做任何处理 + /// + /// > [4] 除非特殊用途使用它, 一般我们也用不到, 不需要做任何处理 + pub x: [usize; 32], + /// CSR sstatus 保存的是在trap发生之前, cpu处在哪一个特权级 + pub sstatus: Sstatus, + /// CSR sepc 保存的是用户态ecall时 所在的那一行的代码 + pub sepc: usize, +} + +impl TrapContext { + /// 把用户栈的栈顶 保存到 [2] + pub fn set_sp(&mut self, sp: usize) { + self.x[2] = sp; + } + /// init app context + pub fn app_init_context(entry: usize, sp: usize) -> Self { + let mut sstatus = sstatus::read(); // 读取CSR sstatus + sstatus.set_spp(SPP::User); // 设置特权级为用户模式 + let mut cx = Self { + x: [0; 32], + sstatus, + sepc: entry, // 设置代码执行的开头, 将来条入到这里执行 + }; + cx.set_sp(sp); // 设置用户栈的栈顶 + cx // 返回, 外面会恢复完 x[0; 32] 之后最后 sret 根据entry和sstatus 返回 + } +} diff --git a/ch3/os/src/trap/mod.rs b/ch3/os/src/trap/mod.rs new file mode 100644 index 0000000..79418b8 --- /dev/null +++ b/ch3/os/src/trap/mod.rs @@ -0,0 +1,66 @@ +mod context; + +use core::arch::global_asm; +use riscv::register::{ + mtvec::TrapMode, + scause::{self, Exception, Trap}, + stval, stvec, +}; +pub use context::TrapContext; +use crate::batch::run_next_app; +use crate::println; +use crate::syscall::syscall; + + + +// 引入陷入保存寄存器需要的汇编代码 +global_asm!(include_str!("trap.S")); + +/// 初始化stvec 寄存器, 这个寄存器保存陷入时, 入口函数的地址 +pub fn init() { + extern "C" { + fn __alltraps(); + } + unsafe { + stvec::write(__alltraps as usize, TrapMode::Direct); + } +} + + +// 这个函数是 trap.S 中__alltraps 保存完所有寄存器在内核栈 之后会进入到这里 +#[no_mangle] +pub fn trap_handler(trap_context: &mut TrapContext) -> &mut TrapContext { + let scause = scause::read(); // trap 发生的原因 + let stval = stval::read(); // trap的附加信息 + + // 根据发生的原因判断是那种类别 + match scause.cause() { + // 用户态发出的系统调用 + Trap::Exception(Exception::UserEnvCall) => { + trap_context.sepc += 4; // +4 是因为我们需要返回 ecall指令的下一个指令 + trap_context.x[10] = syscall(trap_context.x[17], [trap_context.x[10], trap_context.x[11], trap_context.x[12]]) as usize; + } + // 访问不允许的内存 + Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StorePageFault) => { + println!("[kernel] PageFault in application, kernel killed it."); + run_next_app(); + } + // 非法指令 + Trap::Exception(Exception::IllegalInstruction) => { + println!("[kernel] IllegalInstruction in application, kernel killed it."); + run_next_app(); + } + // 未知错误 + _ => { + panic!( + "Unsupported trap {:?}, stval = {:#x}!", + scause.cause(), + stval + ); + } + } + trap_context +} + + + diff --git a/ch3/os/src/trap/trap.S b/ch3/os/src/trap/trap.S new file mode 100644 index 0000000..be27631 --- /dev/null +++ b/ch3/os/src/trap/trap.S @@ -0,0 +1,73 @@ +# trap进入处理函数的入口__alltraps, 以及第一次进入时的出口__restore + +.altmacro +.macro SAVE_GP n + sd x\n, \n*8(sp) # 将寄存器 x_n 的值保存到栈空间中 +.endm +.macro LOAD_GP n + ld x\n, \n*8(sp) # 从栈空间中加载寄存器 x_n 的值 +.endm +.section .text # 进入 .text 段 +.globl __alltraps # 声明全局符号 __alltraps +.globl __restore # 声明全局符号 __restore +.align 2 # 对齐到 2^2 = 4 字节 + +__alltraps: # __alltraps 符号的实现 + csrrw sp, sscratch, sp # 交换 sp 和 sscratch 寄存器的值 + # 现在 sp 指向内核栈,sscratch 指向用户栈 + # 在内核栈上分配一个 TrapContext + addi sp, sp, -34*8 # 分配 34*8 字节的空间 + # 保存通用寄存器 + sd x1, 1*8(sp) # 保存寄存器 x1 的值 (这一步是为了跳过x0寄存器, 方便下面循环) + # 跳过 sp(x2),后面会再次保存 + sd x3, 3*8(sp) # 保存寄存器 x3 的值 (这一步是为了跳过x4寄存器, 方便下面循环) + # 跳过 tp(x4),应用程序不使用该寄存器 + # 保存 x5~x31 + .set n, 5 # 定义变量 n 的初始值为 5 + .rept 27 # 循环 27 次 + SAVE_GP %n # 保存寄存器 x_n 的值到栈空间中 + .set n, n+1 # 将 n 加 1 + .endr # 结束指令块 + # 我们可以自由使用 t0/t1/t2,因为它们已保存在内核栈上 + csrr t0, sstatus # 读取 sstatus 寄存器的值 + csrr t1, sepc # 读取 sepc 寄存器的值 + sd t0, 32*8(sp) # 保存 sstatus 寄存器的值到栈空间中 + sd t1, 33*8(sp) # 保存 sepc 寄存器的值到栈空间中 + # 从 sscratch 中读取用户栈,并将其保存到内核栈中 + csrr t2, sscratch # 读取 sscratch 寄存器的值 + sd t2, 2*8(sp) # 保存用户栈的地址到内核栈 trap context中 + # 设置 trap_handler(cx: &mut TrapContext) 的输入参数 + mv a0, sp # 将 TrapContext 的地址赋值给 a0 + call trap_handler # 调用 trap_handler 分发函数 + +__restore: # __restore 符号的实现 + # case1: 开始运行应用程序 + # case2: 从处理完中断后返回 U 级别 + mv sp, a0 # 将 a0 中保存的内核栈地址赋值给 sp 这个首次进入是在内核进入首次进入sp 这里会被修改为KERNEL_STACK_SIZE, 被接管 + + # 恢复 sstatus/sepc + ld t0, 32*8(sp) # 从栈空间中读取 sstatus 寄存器的值 + ld t1, 33*8(sp) # 从栈空间中读取 sepc 寄存器的值 + ld t2, 2*8(sp) # 从栈空间中读取用户栈的栈顶地址 + csrw sstatus, t0 # 恢复 sstatus 寄存器的值 + csrw sepc, t1 # 恢复 sepc 寄存器的值 + csrw sscratch, t2 # 将栈指针 用户栈 的值 临时保存到 sscratch 寄存器中 + # 现在 sp 指向内核栈,sscratch 指向用户栈 + + # 恢复通用寄存器,除了 sp/tp 以外的寄存器 + # 跳过x0 + ld x1, 1*8(sp) # 从栈空间中读取寄存器 x1 的值 + # 跳过x2 + ld x3, 3*8(sp) # 从栈空间中读取寄存器 x3 的值 + # 循环恢复 + .set n, 5 # 定义变量 n 的初始值为 5 + .rept 27 # 循环 27 次 + LOAD_GP %n # 从栈空间中加载寄存器 x_n 的值 + .set n, n+1 # 将 n 加 1 + .endr # 结束指令块 + + # 现在 sp 指向内核栈,sscratch 指向用户栈, 释放内核栈中的中的 TrapContext, 陷入已经执行完成, 即将返回用户态 不需要这个上下文了 + addi sp, sp, 34*8 # 释放 sizeof + + csrrw sp, sscratch, sp # 交换 sp内核栈 和 sscratch用户栈 寄存器的值, 交换之后sscratch保存的是内核栈顶, sp是用户栈 USER_STACK(栈底) 的栈顶 + sret # 返回指令, 根据sstatus(陷入/异常之前的特权级) 和 sepc(陷入/异常 之前的pc)返回 \ No newline at end of file diff --git a/ch3/user/Cargo.toml b/ch3/user/Cargo.toml new file mode 100644 index 0000000..5e47670 --- /dev/null +++ b/ch3/user/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "user_lib" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +riscv = { git = "https://github.com/rcore-os/riscv", features = ["inline-asm"] } + +[profile.release] +debug = true diff --git a/ch3/user/Makefile b/ch3/user/Makefile new file mode 100644 index 0000000..367e9f2 --- /dev/null +++ b/ch3/user/Makefile @@ -0,0 +1,24 @@ +MODE := release +TARGET := riscv64gc-unknown-none-elf +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +APP_DIR := src/bin +TARGET_DIR := target/$(TARGET)/$(MODE) +APPS := $(wildcard $(APP_DIR)/*.rs) +ELFS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%, $(APPS)) +BINS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%.bin, $(APPS)) + + +# 编译elf文件 +build_elf: clean + @python3 build.py + + +# 把每个elf文件去掉无关代码 +build: build_elf + @$(foreach elf, $(ELFS), $(OBJCOPY) $(elf) --strip-all -O binary $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.bin, $(elf));) + + +clean: + rm -rf ./target* \ No newline at end of file diff --git a/ch3/user/build.py b/ch3/user/build.py new file mode 100644 index 0000000..08661bd --- /dev/null +++ b/ch3/user/build.py @@ -0,0 +1,39 @@ +import os + +base_address = 0x80400000 # 第一个应用的起始地址 +step = 0x20000 # 每个应用的大小 +linker = "src/linker.ld" # 自定义链接脚本 + +RUST_FLAGS = f"-Clink-arg=-T{linker} " # 使用我们自己的链接脚本 +RUST_FLAGS += "-Cforce-frame-pointers=yes " # 强制编译器生成帧指针 +TARGET = "riscv64gc-unknown-none-elf" + +app_id = 0 +apps: list[str] = os.listdir("src/bin") +apps.sort() +for app_file in apps: + app_name = app_file.split(".")[0] + + lines = [] # 修改了base_address linker.ld + lines_before = [] # 最原本的linker.ld的文本, 最下面会恢复 + + # 读出原本文件 + with open(linker, "r") as f: + for line in f.readlines(): + lines_before.append(line) # 保存原本的文本 + line = line.replace(hex(base_address), hex(base_address+step*app_id)) # 替换的文本 + lines.append(line) + with open(linker, "w+") as f: + f.writelines(lines) + + # 逐个编译 + cmd = f"CARGO_BUILD_RUSTFLAGS='{RUST_FLAGS}' cargo build --bin {app_name} --release --target={TARGET}" + print(cmd) + os.system(cmd) + + print(f"[build.py] application {app_name} start with address {hex(base_address+step*app_id)}") + + # 恢复 + with open(linker, "w+") as f: + f.writelines(lines_before) + app_id += 1 \ No newline at end of file diff --git a/ch3/user/src/bin/00write_a.rs b/ch3/user/src/bin/00write_a.rs new file mode 100644 index 0000000..67088ed --- /dev/null +++ b/ch3/user/src/bin/00write_a.rs @@ -0,0 +1,20 @@ +#![no_std] +#![no_main] + +use user_lib::{syscall::*, *}; + +const WIDTH: usize = 10; +const HEIGHT: usize = 5; + +#[no_mangle] +fn main() -> i32 { + for i in 0..HEIGHT { + for _ in 0..WIDTH { + print!("A"); + } + println!(" [{}/{}]", i + 1, HEIGHT); + // sys_yield(); + } + println!("Test write_a OK!"); + 0 +} diff --git a/ch3/user/src/bin/01write_b.rs b/ch3/user/src/bin/01write_b.rs new file mode 100644 index 0000000..1ae798f --- /dev/null +++ b/ch3/user/src/bin/01write_b.rs @@ -0,0 +1,20 @@ +#![no_std] +#![no_main] + +use user_lib::{syscall::*, *}; + +const WIDTH: usize = 10; +const HEIGHT: usize = 2; + +#[no_mangle] +fn main() -> i32 { + for i in 0..HEIGHT { + for _ in 0..WIDTH { + print!("B"); + } + println!(" [{}/{}]", i + 1, HEIGHT); + // sys_yield(); + } + println!("Test write_b OK!"); + 0 +} diff --git a/ch3/user/src/bin/02write_c.rs b/ch3/user/src/bin/02write_c.rs new file mode 100644 index 0000000..f9c8f71 --- /dev/null +++ b/ch3/user/src/bin/02write_c.rs @@ -0,0 +1,20 @@ +#![no_std] +#![no_main] + +use user_lib::{syscall::*, *}; + +const WIDTH: usize = 10; +const HEIGHT: usize = 3; + +#[no_mangle] +fn main() -> i32 { + for i in 0..HEIGHT { + for _ in 0..WIDTH { + print!("C"); + } + println!(" [{}/{}]", i + 1, HEIGHT); + // sys_yield(); + } + println!("Test write_c OK!"); + 0 +} diff --git a/ch3/user/src/lib.rs b/ch3/user/src/lib.rs new file mode 100644 index 0000000..23b813a --- /dev/null +++ b/ch3/user/src/lib.rs @@ -0,0 +1,38 @@ +#![no_std] +#![feature(linkage)] // 开启弱链接特性 +#![feature(panic_info_message)] + + +pub mod user_lang_items; +pub use user_lang_items::*; + +pub mod syscall; +use syscall::{sys_exit}; + +extern "C" { + fn start_bss(); + fn end_bss(); +} + + +// 只要使用这个包, 那么这里就会作为bin程序的开始 +#[no_mangle] +#[link_section = ".text.entry"] // 链接到指定的段 +pub extern "C" fn _start() -> ! { + clear_bss(); + sys_exit(main()); // 这里执行的main程序是我们 bin文件夹里面的main, 而不是下面的, 下面的main程序只有在bin程序没有main函数的时候才会链接 + // 正常是不会走到这一步的, 因为上面已经退出了程序 + panic!("unreachable after sys_exit!"); +} + +#[linkage = "weak"] // 设置我们默认的main函数, 弱链接 +#[no_mangle] +fn main() -> i32 { + panic!("Cannot find main!"); +} + +fn clear_bss() { + unsafe { + (start_bss as usize..end_bss as usize).for_each(|p| (p as *mut u8).write_unaligned(0)) + }; +} diff --git a/ch3/user/src/linker.ld b/ch3/user/src/linker.ld new file mode 100644 index 0000000..9d48923 --- /dev/null +++ b/ch3/user/src/linker.ld @@ -0,0 +1,31 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) + +BASE_ADDRESS = 0x80400000; + +SECTIONS +{ + . = BASE_ADDRESS; + .text : { + *(.text.entry) + *(.text .text.*) + } + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + .bss : { + start_bss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + end_bss = .; + } + /DISCARD/ : { + *(.eh_frame) + *(.debug*) + } +} \ No newline at end of file diff --git a/ch3/user/src/syscall.rs b/ch3/user/src/syscall.rs new file mode 100644 index 0000000..0c9f3e1 --- /dev/null +++ b/ch3/user/src/syscall.rs @@ -0,0 +1,35 @@ +use core::arch::asm; + +const SYSCALL_WRITE: usize = 64; +const SYSCALL_EXIT: usize = 93; +const SYSCALL_YIELD: usize = 124; + + +fn syscall(id: usize, args: [usize; 3]) -> isize { + let mut ret: isize; + unsafe { + // a0寄存器同时作为输入参数和输出参数, {in_var} => {out_var} + asm!( + "ecall", + inlateout("x10") args[0] => ret, + in("x11") args[1], + in("x12") args[2], + in("x17") id + ); + } + ret +} + + +pub fn sys_write(fd: usize, buffer: &[u8]) -> isize { + syscall(SYSCALL_WRITE, [fd, buffer.as_ptr() as usize, buffer.len()]) +} + +pub fn sys_exit(exit_code: i32) -> isize { + syscall(SYSCALL_EXIT, [exit_code as usize, 0, 0]) +} + +pub fn sys_yield() { + syscall(SYSCALL_YIELD, [0, 0, 0]); +} + diff --git a/ch3/user/src/user_lang_items.rs b/ch3/user/src/user_lang_items.rs new file mode 100644 index 0000000..fb50fe9 --- /dev/null +++ b/ch3/user/src/user_lang_items.rs @@ -0,0 +1,2 @@ +pub mod user_panic; +pub mod user_console; \ No newline at end of file diff --git a/ch3/user/src/user_lang_items/user_console.rs b/ch3/user/src/user_lang_items/user_console.rs new file mode 100644 index 0000000..39f3daf --- /dev/null +++ b/ch3/user/src/user_lang_items/user_console.rs @@ -0,0 +1,32 @@ +use core::fmt::{Arguments, Write, Result}; +use crate::syscall::sys_write; + +struct Stdout; + +const STDOUT: usize = 1; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> Result { + sys_write(STDOUT, s.as_bytes()); + Ok(()) + } +} + +pub fn print(args: Arguments) { + Stdout.write_fmt(args).unwrap(); +} + + +#[macro_export] +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::user_console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::user_console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} \ No newline at end of file diff --git a/ch3/user/src/user_lang_items/user_panic.rs b/ch3/user/src/user_lang_items/user_panic.rs new file mode 100644 index 0000000..e38650e --- /dev/null +++ b/ch3/user/src/user_lang_items/user_panic.rs @@ -0,0 +1,19 @@ +use core::panic::PanicInfo; +use crate::println; + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println!( + "Panicked at {}:{} {}", + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println!("Panicked: {}", info.message().unwrap()); + } + loop { + + } +} \ No newline at end of file