移除标准库 #1

Closed
yanguangshaonian wants to merge 81 commits from main into ch1

@ -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"] }

@ -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 := /Users/zhangxinyu/Downloads/qemu-7.0.0/build/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)

@ -0,0 +1,69 @@
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(())
}

@ -0,0 +1,136 @@
use core::arch::asm;
use lazy_static::*;
use riscv::register::mcause::Trap;
use crate::println;
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<AppManager> = 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]
);
}
}
// 把app_idx位置的app 加载到指定的内存APP_BASE_ADDRESS位置
unsafe fn load_app(&self, app_idx: usize){
if app_idx >= self.num_app{
panic!("All applications completed!")
}
// 清空app执行区域的内存
core::slice::from_raw_parts_mut(APP_BASE_ADDRESS as *mut u8, APP_SIZE_LIMIT).fill(0);
// 得到指定app_idx位置的数据(下一个位置的开始 - 需要运行app的开始 = 需要运行app的内存大小
let app_src = core::slice::from_raw_parts(self.app_start_lis[app_idx] as *const u8,
self.app_start_lis[app_idx + 1] - self.app_start_lis[app_idx]);
// 把app的代码 copy到指定的运行的区域
let app_len = app_src.len();
if app_len > APP_SIZE_LIMIT {
panic!("app memory overrun!")
}
core::slice::from_raw_parts_mut(APP_BASE_ADDRESS as *mut u8, app_len)
.copy_from_slice(app_src);
// 刷新cache
asm!("fence.i");
}
}
pub fn init() {
APP_MANAGER.exclusive_access().show_app_info();
}
pub fn run_next_app() -> ! {
// 运行一个新的app
// 把需要执行的指定app, 加载到执行位置APP_BASE_ADDRESS
// app_manager 需要drop 或者在一个作用域中, 因为这个函数不会返回, 后面直接进入用户态了
{
let mut app_manager = APP_MANAGER.exclusive_access();
unsafe{
app_manager.load_app(app_manager.current_app);
println!("------------- run_next_app load app {}", app_manager.current_app);
}
app_manager.current_app += 1;
}
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_BASE_ADDRESS, 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::<TrapContext>()) 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!");
}

@ -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:

@ -0,0 +1,2 @@
pub mod panic;
pub mod console;

@ -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)+)?));
}
}

@ -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();
}

@ -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)
}
}

@ -0,0 +1,50 @@
#![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;
// 汇编脚本引入, 调整内核的内存布局之后, 会跳入到 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);
trap::init();
batch::init();
batch::run_next_app();
}
/// ## 初始化bss段
///
fn init_bss() {
unsafe {
(sbss as usize..ebss as usize).for_each(|p| (p as *mut u8).write_unaligned(0))
}
}

@ -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!")
}

@ -0,0 +1,4 @@
//! Synchronization and interior mutability primitives
mod up;
pub use up::UPSafeCell;

@ -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<T> {
/// inner data
inner: RefCell<T>,
}
unsafe impl<T> Sync for UPSafeCell<T> {}
impl<T> UPSafeCell<T> {
/// 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()
}
}

@ -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!");
}
}
}

@ -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),
}
}

@ -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()
}

@ -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 返回
}
}

@ -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
}

@ -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<TrapContext>
csrrw sp, sscratch, sp # sp sscratch , sscratch, sp USER_STACK()
sret # , sstatus(/) sepc(/ pc)

@ -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

@ -0,0 +1,29 @@
MODE := release
TARGET := riscv64gc-unknown-none-elf
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})
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
CARGO_BUILD_RUSTFLAGS="$(RUST_FLAGS)" \
cargo build --$(MODE) --target=$(TARGET)
# 把每个elf文件去掉无关代码
build: build_elf
@$(foreach elf, $(ELFS), $(OBJCOPY) $(elf) --strip-all -O binary $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.bin, $(elf));)
clean:
rm -rf ./target*

@ -0,0 +1,10 @@
#![no_std]
#![no_main]
use user_lib::*;
#[no_mangle]
fn main() -> i32 {
println!("hello 1");
0
}

@ -0,0 +1,15 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
#[no_mangle]
fn main() -> i32 {
println!("Into Test store_fault, we will insert an invalid store operation...");
println!("Kernel should kill this application!");
unsafe {
core::ptr::null_mut::<u8>().write_volatile(0);
}
0
}

@ -0,0 +1,27 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
const SIZE: usize = 10;
const P: u32 = 3;
const STEP: usize = 100000;
const MOD: u32 = 10007;
#[no_mangle]
fn main() -> i32 {
let mut pow = [0u32; SIZE];
let mut index: usize = 0;
pow[index] = 1;
for i in 1..=STEP {
let last = pow[index];
index = (index + 1) % SIZE;
pow[index] = last * P % MOD;
if i % 10000 == 0 {
println!("{}^{}={}(MOD {})", P, i, pow[index], MOD);
}
}
println!("Test power OK!");
0
}

@ -0,0 +1,17 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use core::arch::asm;
#[no_mangle]
fn main() -> i32 {
println!("Try to execute privileged instruction in U Mode");
println!("Kernel should kill this application!");
unsafe {
asm!("sret");
}
0
}

@ -0,0 +1,17 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use riscv::register::sstatus::{self, SPP};
#[no_mangle]
fn main() -> i32 {
println!("Try to access privileged CSR in U Mode");
println!("Kernel should kill this application!");
unsafe {
sstatus::set_spp(SPP::User);
}
0
}

@ -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))
};
}

@ -0,0 +1,32 @@
OUTPUT_ARCH(riscv)
ENTRY(_start)
/*设置用户程序链接的基础起始位置为0x80400000*/
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*)
}
}

@ -0,0 +1,30 @@
use core::arch::asm;
const SYSCALL_WRITE: usize = 64;
const SYSCALL_EXIT: usize = 93;
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])
}

@ -0,0 +1,2 @@
pub mod user_panic;
pub mod user_console;

@ -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)+)?));
}
}

@ -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 {
}
}

@ -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"] }

@ -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)

@ -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(())
}

@ -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<AppManager> = 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::<TrapContext>()) 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!");
}

@ -0,0 +1,2 @@
pub const APP_BASE_ADDRESS: usize = 0x80400000; // 载入的app的起始的地址
pub const APP_SIZE_LIMIT: usize = 0x20000; // app的最大的二进制文件能够使用的大小

@ -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:

@ -0,0 +1,2 @@
pub mod panic;
pub mod console;

@ -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)+)?));
}
}

@ -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();
}

@ -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)
}
}

@ -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);
}
}

@ -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))
}
}

@ -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!")
}

@ -0,0 +1,4 @@
//! Synchronization and interior mutability primitives
mod up;
pub use up::UPSafeCell;

@ -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<T> {
/// inner data
inner: RefCell<T>,
}
unsafe impl<T> Sync for UPSafeCell<T> {}
impl<T> UPSafeCell<T> {
/// 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()
}
}

@ -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!");
}
}
}

@ -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),
}
}

@ -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()
}

@ -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 返回
}
}

@ -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
}

@ -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<TrapContext>
csrrw sp, sscratch, sp # sp sscratch , sscratch, sp USER_STACK()
sret # , sstatus(/) sepc(/ pc)

@ -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

@ -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*

@ -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

@ -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
}

@ -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
}

@ -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
}

@ -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))
};
}

@ -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*)
}
}

@ -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]);
}

@ -0,0 +1,2 @@
pub mod user_panic;
pub mod user_console;

@ -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)+)?));
}
}

@ -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 {
}
}

@ -0,0 +1,15 @@
[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"] }
sbi-rt = { version = "0.0.2", features = ["legacy"] }

@ -0,0 +1,50 @@
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
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:
pkill -9 qemu

@ -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(())
}

@ -0,0 +1,3 @@
//! Constants used in rCore for qemu
pub const CLOCK_FREQ: usize = 12500000;

@ -0,0 +1,8 @@
pub const APP_BASE_ADDRESS: usize = 0x80400000; // 载入的app的起始的地址
pub const APP_SIZE_LIMIT: usize = 0x20000; // app的最大的二进制文件能够使用的大小
pub const MAX_APP_NUM: usize = 10; // 支持最大的用户应用数量
pub const USER_STACK_SIZE: usize = 4096 * 2; // 栈大小为8kb
pub const KERNEL_STACK_SIZE: usize = 4096 * 2;
pub use crate::board::*;

@ -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:

@ -0,0 +1,2 @@
pub mod panic;
pub mod console;

@ -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)+)?));
}
}

@ -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();
}

@ -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)
}
}

@ -0,0 +1,95 @@
use core::arch::asm;
use crate::config::*;
use crate::trap::TrapContext;
static KERNEL_STACK: [[u8; KERNEL_STACK_SIZE]; MAX_APP_NUM] = [[0; KERNEL_STACK_SIZE]; MAX_APP_NUM]; // 这一章, 每个用户应用对应一个内核栈 [每个应用自己的内核栈; 总应用数]
static USER_STACK: [[u8; USER_STACK_SIZE]; MAX_APP_NUM] = [[0; USER_STACK_SIZE]; MAX_APP_NUM]; // 这一行每个用户应用对应一个应用栈
extern "C" {
fn _num_app();
}
// 得到用户app的数量
pub 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);
}
}
// 初始化用户应用栈, 并返回用户应用栈在内核栈中的trap_context的地址
// 这个函数根据 app_id得到 USER_STACK的所在的位置, 初始化之后, 再构造 KERNEL_STACK
pub fn init_app_cx(app_id: usize) -> usize {
// 得到 用户栈
unsafe {
// 构造 trap_context
let user_trap_context = {
// 初始化用户栈顶
let user_stack_top = {
let _tmp_stack = USER_STACK.as_ptr() as usize + USER_STACK_SIZE * app_id; // 用户栈开始 + (每个用户栈的大小 * 指定用户栈的索引) 得到栈顶位置,
_tmp_stack + USER_STACK_SIZE // 加上栈大小, 得到新的栈顶位置
};
// 用户应用的开始位置
let user_entry = APP_BASE_ADDRESS + APP_SIZE_LIMIT * app_id;
TrapContext::from(user_entry, user_stack_top)
};
// 把构造的 user_trap_context 放到 KERNEL_STACK指定应用的内核栈中
let kernel_app_stack_ptr = {
// 栈顶位置 + 栈大小 = 栈底
let _tme_stack_low = KERNEL_STACK.as_ptr() as usize + KERNEL_STACK_SIZE * app_id + KERNEL_STACK_SIZE;
// 给TrapContext 分配栈空间, 得到新的栈顶
(_tme_stack_low - core::mem::size_of::<TrapContext>()) as * mut TrapContext
};
// copy 数据到内核栈中
*kernel_app_stack_ptr = user_trap_context;
// 返回内核栈的地址
kernel_app_stack_ptr as usize
}
}

@ -0,0 +1,63 @@
#![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 sync;
pub mod trap;
pub mod syscall;
pub mod loader;
pub mod config;
pub mod task;
pub mod timer;
#[path = "boards/qemu.rs"]
mod board;
// 汇编脚本引入, 调整内核的内存布局之后, 会跳入到 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);
trap::init();
loader::load_app();
trap::enable_timer_interrupt(); // 允许定时器中断
timer::set_next_trigger(); // 在进入用户态之前, 设置一个时钟中断, 防止第一个用户任务死循环
task::run_first_task();
panic!("Disable run here")
}
/// ## 初始化bss段
///
fn init_bss() {
unsafe {
(sbss as usize..ebss as usize).for_each(|p| (p as *mut u8).write_unaligned(0))
}
}

@ -0,0 +1,45 @@
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!")
}
// 设置 mtimecmp 的值
pub fn set_timer(timer: usize) {
sbi_rt::set_timer(timer as _);
}

@ -0,0 +1,4 @@
//! Synchronization and interior mutability primitives
mod up;
pub use up::UPSafeCell;

@ -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<T> {
/// inner data
inner: RefCell<T>,
}
unsafe impl<T> Sync for UPSafeCell<T> {}
impl<T> UPSafeCell<T> {
/// 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()
}
}

@ -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!");
}
}
}

@ -0,0 +1,21 @@
const SYSCALL_WRITE: usize = 64;
const SYSCALL_EXIT: usize = 93;
const SYSCALL_YIELD: usize = 124;
const SYSCALL_GET_TIME: usize = 169;
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),
SYSCALL_YIELD => sys_yield(),
SYSCALL_GET_TIME => sys_get_time(),
_ => panic!("Unsupported syscall_id: {}", syscall_id),
}
}

@ -0,0 +1,21 @@
//! App management syscalls
// use crate::batch::run_next_app;
use crate::println;
use crate::task::{exit_current_and_run_next, suspend_current_and_run_next};
use crate::timer::get_time_ms;
/// 任务退出, 并立即切换任务
pub fn sys_exit(exit_code: i32) -> ! {
println!("[kernel] Application exited with code {}", exit_code);
exit_current_and_run_next();
panic!("Unreachable in sys_exit!");
}
pub fn sys_yield() -> isize {
suspend_current_and_run_next();
0
}
pub fn sys_get_time() -> isize {
get_time_ms() as isize
}

@ -0,0 +1,35 @@
// TCB的字段 用来保存cpu 在内核切换人物的时候 寄存器还有栈顶的信息, 这个结构体将来会传到 switch.S 中的汇编中
#[derive(Copy, Clone)]
#[repr(C)]
pub struct TaskContext{
ra: usize, // 保存了进行切换完毕之后需要 跳转继续执行的地址
sp: usize, // 当前任务的在内核中的内核栈的栈顶, 这个会被switch 保存与恢复
s: [usize; 12] // 当前任务内核 有必要 保存的寄存器
}
impl TaskContext{
// 初始的内容
pub fn new() -> Self {
Self {
ra: 0,
sp: 0,
s: [0; 12],
}
}
// 从kernel_stack_ptr 创建一个 任务上下文
// 并把任务上下文的返回地址设置为 trap.S的返回符号的地方
pub fn from(kernel_stack_ptr: usize) -> Self{
extern "C" {
fn __restore();
}
Self {
ra: __restore as usize, // 新创建的任务, 在switch ret 之后 直接进入 trap返回函数
sp: kernel_stack_ptr, // 这里设置 应用内核栈的栈顶了, 后面会被switch 恢复, 所以我们在trap.S中 注释mv sp, a0
s: [0; 12],
}
}
}

@ -0,0 +1,221 @@
use lazy_static::lazy_static;
use crate::config::MAX_APP_NUM;
use crate::sync::UPSafeCell;
use crate::task::task::{TaskControlBlock, TaskStatus};
use crate::loader::{get_num_app, init_app_cx};
use crate::println;
use crate::task::context::TaskContext;
use crate::task::switch::__switch;
use crate::timer::{get_time_ms, get_time_us};
mod context;
mod switch;
mod task;
// 公开到外部的一个全局任务管理器的结构体
pub struct TaskManager {
num_app: usize, // app的数量 这个在os运行之后就不会有变化
inner: UPSafeCell<TaskManagerInner>, // 这个内部TaskControlBlock 会随着系统运行发生变化
}
impl TaskManager {
// 即将进入用户态, 把之前使用的内核时间统计
pub fn user_time_start(&self){
let mut inner = self.inner.exclusive_access();
let current_task_id = inner.current_task_id;
let kernel_use_time = inner.refresh_stop_clock();
inner.tasks[current_task_id].kernel_time += kernel_use_time;
}
pub fn kernel_time_start(&self){
let mut inner = self.inner.exclusive_access();
let current_task_id = inner.current_task_id;
let user_use_time = inner.refresh_stop_clock();
inner.tasks[current_task_id].user_time += user_use_time;
}
fn run_first_task(&self){
// 得到下一个需要执行的任务,的上下文 这里我们由于第一次执行, 下一个任务我们指定为0下标的任务即可
let next_task_context_ptr = {
let mut inner = self.inner.exclusive_access();
// 第一次掐表, 开始记录时间
inner.refresh_stop_clock();
let task_0 = &mut inner.tasks[0];
// 修改任务0的状态
task_0.task_status = TaskStatus::Running;
&(task_0.task_cx) as *const TaskContext
};
// 由于第一次切换, 我们current task context 不存在, 所以我们手动创建一个, 在调用switch的时候
// 这里调用switch的状态会被保存在unused 这里, 但是一旦程序开始运行, 就开始在内核栈或者用户栈之间切换, 永远
// 不会走到这里了
let mut unused = TaskContext::new();
unsafe {
__switch(&mut unused as *mut TaskContext, next_task_context_ptr)
}
//
panic!("unreachable in run_first_task!");
}
// 停止当前正在运行的任务
fn mark_current_exit(&self){
let mut inner = self.inner.exclusive_access();
let current_task_id = inner.current_task_id;
let kernel_use_time = inner.refresh_stop_clock();
let current_task = &mut inner.tasks[current_task_id];
current_task.task_status = TaskStatus::Exited;
// 统计内核时间, 并输出这个任务 花费了多少内核时间
current_task.kernel_time += kernel_use_time;
println!("task {:?}, exit, kernel_time: {:?}ms, user_time: {:?}ms", current_task_id, current_task.kernel_time/1000, current_task.user_time/1000);
}
// 挂起当前任务
fn mark_current_suspend(&self){
let mut inner = self.inner.exclusive_access();
let current_task_id = inner.current_task_id;
let kernel_use_time = inner.refresh_stop_clock();
let current_task = &mut inner.tasks[current_task_id];
current_task.task_status = TaskStatus::Ready;
// 统计内核时间(因为内核进入到这里之前肯定是掐表了)
// 挂起任务A之后,这里也掐表了, 切到新的任务B, B开始执行, B在挂起的时候 也会走入到这里掐表, 顺便并得到任务A掐表到现在任务B掐表准备切换任务出去中间的时间
current_task.kernel_time += kernel_use_time;
}
// 运行下一个任务
fn run_next_task(&self){
if let Some(next_task_id) = self.find_next_task() {
// 得到当前任务context ptr 以及 下一个任务context的ptr
let (current_task_ptr,next_task_ptr) = {
let mut inner = self.inner.exclusive_access();
// 当前任务id
let current_task_id = inner.current_task_id;
// 修改current_task_id 为 下一个任务, 因为一旦到switch就是在运行下一个任务了
inner.current_task_id = next_task_id;
// 修改下一个任务的状态
inner.tasks[next_task_id].task_status = TaskStatus::Running;
// 得到current的ptr
let current_task_ptr = &mut inner.tasks[current_task_id].task_cx as *mut TaskContext;
// 得到需要被切换的下一个任务ptr
let next_task_ptr = &inner.tasks[next_task_id].task_cx as *const TaskContext;
(current_task_ptr, next_task_ptr)
};
// 开始伟大的切换!
unsafe {
__switch(current_task_ptr, next_task_ptr);
}
} else {
panic!("All applications completed!");
}
}
// 找到一个除当前任务之外的 是Ready状态的任务的id
fn find_next_task(&self) -> Option<usize>{
let mut inner = self.inner.exclusive_access();
let current = inner.current_task_id;
for task_id in current + 1..current + self.num_app + 1 {
let _tmp_id = task_id % self.num_app;
if inner.tasks[_tmp_id].task_status == TaskStatus::Ready {
return Some(_tmp_id)
}
}
None
}
}
// 不公开的结构体, 有一个MAX_APP_NUM大小的数组, 用来保存TCB, 和当前任务的的TCB的下标
struct TaskManagerInner {
tasks: [TaskControlBlock; MAX_APP_NUM],
current_task_id: usize,
stop_clock_time: usize, // 记录最近一次停表时间
}
impl TaskManagerInner {
fn refresh_stop_clock(&mut self) -> usize {
// 上次停表的时间
let start_time = self.stop_clock_time;
// 当前时间
self.stop_clock_time = get_time_us();
// 返回 当前时间 - 上次停表时间 = 时间间距
self.stop_clock_time - start_time
}
}
lazy_static!{
pub static ref TASK_MANAGER: TaskManager = {
// 得到app的总数
let num_app = get_num_app();
// 初始化内核中的任务列表
let mut tasks = [
TaskControlBlock {
task_cx: TaskContext::new(),
// UnInit 这个tcb 还没用户应用填充加载
task_status: TaskStatus::UnInit,
kernel_time: 0,
user_time: 0,
};
MAX_APP_NUM
];
// 初始化用户的应用对应的 TCB
for app_idx in 0..num_app {
// 初始化用户应用的内核栈
let kernel_app_stack_ptr = init_app_cx(app_idx);
// 从 初始内核栈的栈顶(保存 trap_context的位置) 创建 任务context
let task_context = TaskContext::from(kernel_app_stack_ptr);
// 把内核栈的信息保存到 TCB中
tasks[app_idx].task_cx = task_context;
// 初始为 准备好的状态
tasks[app_idx].task_status = TaskStatus::Ready
};
TaskManager { // 直接返回即可, 所有字段都是sync的, 那这个结构体也是sync
num_app,
inner: unsafe {
UPSafeCell::new(TaskManagerInner {
tasks,
current_task_id: 0,
stop_clock_time: 0
})
}
}
};
}
// 由内核调用, 在main中, 用来 作为执行用户应用的开端
pub fn run_first_task() {
TASK_MANAGER.run_first_task();
}
// 挂起当前任务, 并运行下一个
pub fn suspend_current_and_run_next(){
TASK_MANAGER.mark_current_suspend();
TASK_MANAGER.run_next_task();
}
// 退出当前任务, 并运行下一个
pub fn exit_current_and_run_next(){
TASK_MANAGER.mark_current_exit();
TASK_MANAGER.run_next_task();
}

@ -0,0 +1,43 @@
# os/src/task/switch.S
.altmacro
.macro SAVE_SN n
sd s\n, (\n+2)*8(a0) # s(n)
.endm
.macro LOAD_SN n
ld s\n, (\n+2)*8(a1) # s(n)
.endm
.section .text
.globl __switch
__switch:
# [1]
# __switch(
# current_task_cx_ptr: *mut TaskContext,
# next_task_cx_ptr: *const TaskContext
# )
# [2] current_task_cx_ptr
# save kernel stack of current task
sd sp, 8(a0) # current_task_cx_ptr
# save ra & s0~s11 of current execution
sd ra, 0(a0) # ras0~s11current_task_cx_ptr
.set n, 0
.rept 12
SAVE_SN %n # s0~s11
.set n, n + 1
.endr
# [3] next_task_cx_ptr
# restore ra & s0~s11 of next execution
ld ra, 0(a1) # ra
.set n, 0
.rept 12
LOAD_SN %n # s0~s11
.set n, n + 1
.endr
# restore kernel stack of next task
ld sp, 8(a1) #
# [4]
ret #

@ -0,0 +1,11 @@
use core::arch::global_asm;
global_asm!(include_str!("switch.S")); // 读入switch.S 到当前代码
use super::context::TaskContext;
extern "C" {
// 引入 switch.S 中的切换函数
pub fn __switch(
current_task_cx_ptr: *mut TaskContext,
next_task_cx_ptr: *const TaskContext
);
}

@ -0,0 +1,20 @@
use crate::task::context::{TaskContext};
// TCB的字段, 用来保存任务的状态
#[derive(Copy, Clone, PartialEq)]
pub enum TaskStatus {
UnInit, // 未初始化
Ready, // 准备运行
Running, // 正在运行
Exited, // 已退出
}
// 一个任务的主体, 用来保存或者控制一个任务所有需要的东西
#[derive(Copy, Clone)]
pub struct TaskControlBlock {
pub user_time: usize, // 用户态程序用的时间
pub kernel_time: usize, // 内核态程序所用的时间
pub task_status: TaskStatus,
pub task_cx: TaskContext,
}

@ -0,0 +1,29 @@
use riscv::register::time;
use crate::config::CLOCK_FREQ;
use crate::sbi::set_timer;
const TICKS_PER_SEC: usize = 100;
const MICRO_PER_SEC: usize = 1_000_000;
const MSEC_PER_SEC: usize = 1_000;
//
pub fn get_time() -> usize {
time::read()
}
// 读取mtime的值, 然后使用 (当前每秒的频率 / TICKS_PER_SEC 100) = 得到 10ms的数值的增量, 相加得到下一个下10ms 后mtime应该属于的值
// 并设置mtimecmp, 这样在10ms后就会发出一个S特权的时钟中断
pub fn set_next_trigger() {
set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC);
}
// 以微秒为单位, 返回当前计数器经过的微秒
// 当前 (计时器的值的总数 / 频率) = 计时器中经过了多少秒, (计时器的值的总数 / 频率) * 1_000_000 得到微秒(1秒有1_000_000微秒)
pub fn get_time_us() -> usize {
time::read() / (CLOCK_FREQ / MICRO_PER_SEC)
}
pub fn get_time_ms() -> usize {
time::read() / (CLOCK_FREQ / MSEC_PER_SEC)
}

@ -0,0 +1,41 @@
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;
}
// 根据entry和sp构造一个 trap_context
pub fn from(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 返回
}
}

@ -0,0 +1,83 @@
mod context;
use core::arch::global_asm;
use riscv::register::{mtvec::TrapMode, scause::{self, Exception, Trap}, sie, stval, stvec};
use riscv::register::scause::Interrupt;
pub use context::TrapContext;
use crate::println;
use crate::syscall::syscall;
use crate::task::{exit_current_and_run_next, suspend_current_and_run_next, TASK_MANAGER};
use crate::timer::set_next_trigger;
// 引入陷入保存寄存器需要的汇编代码
global_asm!(include_str!("trap.S"));
/// 初始化stvec 寄存器, 这个寄存器保存陷入时, 入口函数的地址
pub fn init() {
extern "C" {
fn __alltraps();
}
unsafe {
stvec::write(__alltraps as usize, TrapMode::Direct);
}
}
// 设置riscv 允许定时器中断
pub fn enable_timer_interrupt() {
unsafe {
sie::set_stimer();
}
}
// 这个函数是 trap.S 中__alltraps 保存完所有寄存器在内核栈 之后会进入到这里
#[no_mangle]
pub fn trap_handler(trap_context: &mut TrapContext) -> &mut TrapContext {
// 进入到了内核态, 需要把之前的用户消耗时间统计在用户时间上
TASK_MANAGER.kernel_time_start();
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.");
exit_current_and_run_next();
}
// 非法指令
Trap::Exception(Exception::IllegalInstruction) => {
println!("[kernel] IllegalInstruction in application, kernel killed it.");
exit_current_and_run_next();
}
Trap::Interrupt(Interrupt::SupervisorTimer) => {
// 发生时钟中断之后, 继续设置下一个时钟中断的发起时间
set_next_trigger();
// 暂停当前任务, 切换新的任务
suspend_current_and_run_next();
}
// 未知错误
_ => {
panic!(
"Unsupported trap {:?}, stval = {:#x}!",
scause.cause(),
stval
);
}
}
// 即将进入用户态, 把内核使用的时间统计在内核时间上
TASK_MANAGER.user_time_start();
trap_context
}

@ -0,0 +1,75 @@
# 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
# , switch
# 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<TrapContext>
csrrw sp, sscratch, sp # sp sscratch , sscratch, sp USER_STACK()
sret # , sstatus(/) sepc(/ pc)

@ -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

@ -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*

@ -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

@ -0,0 +1,28 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
const LEN: usize = 100;
#[no_mangle]
fn main() -> i32 {
let p = 3u64;
let m = 998244353u64;
let iter: usize = 20000000;
let mut s = [0u64; LEN];
let mut cur = 0usize;
s[cur] = 1;
for i in 1..=iter {
let next = if cur + 1 == LEN { 0 } else { cur + 1 };
s[next] = s[cur] * p % m;
cur = next;
if i % 1000000 == 0 {
println!("power_3 [{}/{}]", i, iter);
}
}
println!("{}^{} = {}(MOD {})", p, iter, s[cur], m);
println!("Test power_3 OK!");
0
}

@ -0,0 +1,28 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
const LEN: usize = 100;
#[no_mangle]
fn main() -> i32 {
let p = 5u64;
let m = 998244353u64;
let iter: usize = 14000000;
let mut s = [0u64; LEN];
let mut cur = 0usize;
s[cur] = 1;
for i in 1..=iter {
let next = if cur + 1 == LEN { 0 } else { cur + 1 };
s[next] = s[cur] * p % m;
cur = next;
if i % 1000000 == 0 {
println!("power_5 [{}/{}]", i, iter);
}
}
println!("{}^{} = {}(MOD {})", p, iter, s[cur], m);
println!("Test power_5 OK!");
0
}

@ -0,0 +1,28 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
const LEN: usize = 100;
#[no_mangle]
fn main() -> i32 {
let p = 7u64;
let m = 998244353u64;
let iter: usize = 16000000;
let mut s = [0u64; LEN];
let mut cur = 0usize;
s[cur] = 1;
for i in 1..=iter {
let next = if cur + 1 == LEN { 0 } else { cur + 1 };
s[next] = s[cur] * p % m;
cur = next;
if i % 1000000 == 0 {
println!("power_7 [{}/{}]", i, iter);
}
}
println!("{}^{} = {}(MOD {})", p, iter, s[cur], m);
println!("Test power_7 OK!");
0
}

@ -0,0 +1,18 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use user_lib::syscall::{sys_get_time, sys_yield};
#[no_mangle]
fn main() -> i32 {
let current_timer = sys_get_time();
let wait_for = current_timer + 3000;
while sys_get_time() < wait_for {
// sys_yield(); loop太快,防止每次切换时间小于1ms, 这里注释, 但是还是不对, 模拟器的时间不准,cpu频率不对, 这个用户应用统计的怎么都不够3000ms
}
println!("Test sleep OK!");
0
}

@ -0,0 +1,18 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use user_lib::syscall::{sys_get_time, sys_yield};
#[no_mangle]
fn main() -> i32 {
let current_timer = sys_get_time();
let wait_for = current_timer + 3000;
loop {
}
println!("Test sleep OK!");
0
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save