Compare commits
No commits in common. 'main' and 'ch2' have entirely different histories.
@ -1,14 +0,0 @@
|
||||
[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"] }
|
@ -1,51 +0,0 @@
|
||||
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)
|
||||
|
@ -1,70 +0,0 @@
|
||||
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(())
|
||||
}
|
@ -1,111 +0,0 @@
|
||||
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!");
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
pub const APP_BASE_ADDRESS: usize = 0x80400000; // 载入的app的起始的地址
|
||||
pub const APP_SIZE_LIMIT: usize = 0x20000; // app的最大的二进制文件能够使用的大小
|
@ -1,15 +0,0 @@
|
||||
.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:
|
@ -1,2 +0,0 @@
|
||||
pub mod panic;
|
||||
pub mod console;
|
@ -1,33 +0,0 @@
|
||||
|
||||
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)+)?));
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
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();
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
@ -1,56 +0,0 @@
|
||||
#![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))
|
||||
}
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
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!")
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
//! Synchronization and interior mutability primitives
|
||||
|
||||
mod up;
|
||||
pub use up::UPSafeCell;
|
@ -1,31 +0,0 @@
|
||||
//! 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()
|
||||
}
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
//! 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!");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
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),
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
//! 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()
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
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 返回
|
||||
}
|
||||
}
|
@ -1,66 +0,0 @@
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,12 +0,0 @@
|
||||
[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
|
@ -1,24 +0,0 @@
|
||||
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*
|
@ -1,39 +0,0 @@
|
||||
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
|
@ -1,20 +0,0 @@
|
||||
#![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
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
#![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
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
#![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
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
#![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))
|
||||
};
|
||||
}
|
@ -1,31 +0,0 @@
|
||||
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*)
|
||||
}
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
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]);
|
||||
}
|
||||
|
@ -1,2 +0,0 @@
|
||||
pub mod user_panic;
|
||||
pub mod user_console;
|
@ -1,32 +0,0 @@
|
||||
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)+)?));
|
||||
}
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
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 {
|
||||
|
||||
}
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
[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"] }
|
@ -1,50 +0,0 @@
|
||||
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
|
||||
|
@ -1,70 +0,0 @@
|
||||
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(())
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
//! Constants used in rCore for qemu
|
||||
|
||||
pub const CLOCK_FREQ: usize = 12500000;
|
@ -1,8 +0,0 @@
|
||||
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::*;
|
@ -1,15 +0,0 @@
|
||||
.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:
|
@ -1,2 +0,0 @@
|
||||
pub mod panic;
|
||||
pub mod console;
|
@ -1,33 +0,0 @@
|
||||
|
||||
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)+)?));
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
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();
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
@ -1,95 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
#![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))
|
||||
}
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
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 _);
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
//! Synchronization and interior mutability primitives
|
||||
|
||||
mod up;
|
||||
pub use up::UPSafeCell;
|
@ -1,31 +0,0 @@
|
||||
//! 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()
|
||||
}
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
//! 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!");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
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),
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
//! 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
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
|
||||
|
||||
// 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],
|
||||
}
|
||||
}
|
||||
}
|
@ -1,221 +0,0 @@
|
||||
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();
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
# 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) # 将当前执行的ra和s0~s11寄存器的值保存到当前任务current_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 # 返回到下一个任务的执行点
|
@ -1,11 +0,0 @@
|
||||
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
|
||||
);
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
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,
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
|
||||
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)
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
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 返回
|
||||
}
|
||||
}
|
@ -1,83 +0,0 @@
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,12 +0,0 @@
|
||||
[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
|
@ -1,24 +0,0 @@
|
||||
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*
|
@ -1,39 +0,0 @@
|
||||
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
|
@ -1,28 +0,0 @@
|
||||
#![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
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
#![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
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
#![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
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
#![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
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
#![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
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
#![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))
|
||||
};
|
||||
}
|
@ -1,31 +0,0 @@
|
||||
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*)
|
||||
}
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
use core::arch::asm;
|
||||
|
||||
const SYSCALL_WRITE: usize = 64;
|
||||
const SYSCALL_EXIT: usize = 93;
|
||||
const SYSCALL_YIELD: usize = 124;
|
||||
const SYSCALL_GET_TIME: usize = 169;
|
||||
|
||||
|
||||
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]);
|
||||
}
|
||||
|
||||
pub fn sys_get_time() -> isize {
|
||||
syscall(SYSCALL_GET_TIME, [0, 0, 0])
|
||||
}
|
||||
|
||||
|
@ -1,2 +0,0 @@
|
||||
pub mod user_panic;
|
||||
pub mod user_console;
|
@ -1,32 +0,0 @@
|
||||
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)+)?));
|
||||
}
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
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 {
|
||||
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
[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"] }
|
||||
buddy_system_allocator = "0.6"
|
||||
bitflags = "1.2.1"
|
||||
xmas-elf = "0.7.0"
|
@ -1,50 +0,0 @@
|
||||
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) kill
|
||||
$(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
|
||||
|
@ -1,70 +0,0 @@
|
||||
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}"
|
||||
app_{0}_end:"#,
|
||||
idx, app, TARGET_PATH
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
//! Constants used in rCore for qemu
|
||||
|
||||
pub const CLOCK_FREQ: usize = 12500000;
|
@ -1,25 +0,0 @@
|
||||
pub const MAX_APP_NUM: usize = 10; // 支持最大的用户应用数量
|
||||
pub const KERNEL_HEAP_SIZE: usize = 0x30_0000; // 内核的堆大小 3M
|
||||
pub const PAGE_SIZE_BITS: usize = 0xc; // 页内偏移的位宽(也就是每页的大小)
|
||||
pub const PAGE_SIZE: usize = 0x1000; // 每个页 的字节大小为 4kb
|
||||
pub const MEMORY_END: usize = 0x80800000; // 设置我们当前操作系统最大只能用到 0x80800000-0x80000000大小的内存也就是8M
|
||||
|
||||
pub const USER_STACK_SIZE: usize = 4096 * 2; // 每个应用用户态的栈大小为8kb
|
||||
pub const KERNEL_STACK_SIZE: usize = 4096 * 2; // 每个应用的内核栈
|
||||
|
||||
pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1; // __alltraps对齐到了这里, (内核空间和用户空间这里虚拟地址都用这个)虚拟地址最高页 存放跳板, 跳板那一页, 被映射到 strampoline段(trap) 实际的物理地址, 即陷入时 cpu需要跳转的地址
|
||||
pub const TRAP_CONTEXT: usize = TRAMPOLINE - PAGE_SIZE; // 用户 trap context开始的位置 在 每个用户程序 它本身地址空间 的次高页
|
||||
|
||||
pub use crate::board::*;
|
||||
|
||||
|
||||
|
||||
/// 得到 "用户程序的内核栈" 的在 内核本身地址空间 中的虚拟位置(当然由于恒等映射其实也是实际的物理地址)
|
||||
/// 这个在 跳板的下面的某个位置
|
||||
/// 每个用户除了分配 KERNEL_STACK_SIZE 大小外, 还额外 增加 一个PAGE_SIZE 放在比栈底要高的地址 用来隔离每个用户内核栈
|
||||
pub fn kernel_stack_position(app_id: usize) -> (usize, usize) {
|
||||
let top = TRAMPOLINE - app_id * (KERNEL_STACK_SIZE + PAGE_SIZE);
|
||||
// 栈底只需要 KERNEL_STACK_SIZE 即可,
|
||||
let bottom = top - KERNEL_STACK_SIZE;
|
||||
(bottom, top)
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
.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:
|
@ -1,2 +0,0 @@
|
||||
pub mod panic;
|
||||
pub mod console;
|
@ -1,33 +0,0 @@
|
||||
|
||||
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)+)?));
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
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();
|
||||
}
|
@ -1,53 +0,0 @@
|
||||
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段, 被放在顶部*/
|
||||
. = ALIGN(4K); /*4k对齐*/
|
||||
strampoline = .;
|
||||
/* strampoline 段, 将来会被 memory set 导入, 当做跳板最高页vpn的实际物理帧 ppn*/
|
||||
*(.text.trampoline);
|
||||
*(.text .text.*)
|
||||
}
|
||||
|
||||
. = ALIGN(4K);
|
||||
etext = .;
|
||||
srodata = .;
|
||||
.rodata : {
|
||||
*(.rodata .rodata.*)
|
||||
*(.srodata .srodata.*)
|
||||
}
|
||||
|
||||
. = ALIGN(4K);
|
||||
erodata = .;
|
||||
sdata = .;
|
||||
.data : {
|
||||
*(.data .data.*)
|
||||
*(.sdata .sdata.*)
|
||||
}
|
||||
|
||||
. = ALIGN(4K);
|
||||
edata = .;
|
||||
sbss_with_stack = .;
|
||||
.bss : {
|
||||
*(.bss.stack) /* 全局符号 sbss 和 ebss 分别指向 .bss 段除 .bss.stack 以外的起始和终止地址(.bss.stack是我们在entry.asm中定义的栈) */
|
||||
sbss = .;
|
||||
*(.bss .bss.*)
|
||||
*(.sbss .sbss.*)
|
||||
}
|
||||
|
||||
. = ALIGN(4K);
|
||||
ebss = .;
|
||||
ekernel = .;
|
||||
|
||||
/DISCARD/ : {
|
||||
*(.eh_frame)
|
||||
}
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_app_data(app_id: usize) -> &'static [u8] {
|
||||
extern "C" {
|
||||
fn _num_app();
|
||||
}
|
||||
let num_app_ptr = _num_app as usize as *const usize;
|
||||
let num_app = get_num_app();
|
||||
let app_start = unsafe { core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1) };
|
||||
assert!(app_id < num_app);
|
||||
unsafe {
|
||||
core::slice::from_raw_parts(
|
||||
app_start[app_id] as *const u8,
|
||||
app_start[app_id + 1] - app_start[app_id],
|
||||
)
|
||||
}
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
#![feature(panic_info_message)]
|
||||
#![feature(alloc_error_handler)]
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
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;
|
||||
pub mod mm;
|
||||
|
||||
#[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);
|
||||
|
||||
// 初始化动态内存分配器, 使我们能在内核中使用动态大小数据类型
|
||||
mm::init();
|
||||
trap::init();
|
||||
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))
|
||||
}
|
||||
}
|
@ -1,202 +0,0 @@
|
||||
use crate::config::{PAGE_SIZE, PAGE_SIZE_BITS};
|
||||
use crate::mm::page_table::PageTableEntry;
|
||||
|
||||
const PA_WIDTH_SV39: usize = 56; // 真实物理地址 的字节宽度 44(物理页宽) + 12(4kb的宽度)
|
||||
const VA_WIDTH_SV39: usize = 39; // 虚拟地址的宽度 9 + 9 + 9 + 12
|
||||
const PPN_WIDTH_SV39: usize = PA_WIDTH_SV39 - PAGE_SIZE_BITS; // 物理页 的宽度, 也就是 物理地址宽度-每页宽度=物理页宽度
|
||||
const VPN_WIDTH_SV39: usize = VA_WIDTH_SV39 - PAGE_SIZE_BITS; // 虚拟页的宽度 27
|
||||
|
||||
|
||||
// 物理地址 56bit 44 12
|
||||
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
|
||||
pub struct PhysAddr(pub usize);
|
||||
|
||||
// 虚拟地址 39bit 9 9 9 12
|
||||
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
|
||||
pub struct VirtAddr(pub usize);
|
||||
|
||||
// 物理页 44bit
|
||||
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
|
||||
pub struct PhysPageNum(pub usize);
|
||||
|
||||
// 虚拟页 29bit 布局为 9 9 9
|
||||
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
|
||||
pub struct VirtPageNum(pub usize);
|
||||
|
||||
|
||||
// 把usize 转为真实地址(只保留 PA_WIDTH_SV39 位字节)
|
||||
impl From<usize> for PhysAddr {
|
||||
fn from(v: usize) -> Self {
|
||||
Self(v & ( (1 << PA_WIDTH_SV39) - 1 ))
|
||||
}
|
||||
}
|
||||
|
||||
// 把usize类型的物理页号 转为物理页结构体 (只保留物理页的宽度)
|
||||
impl From<usize> for PhysPageNum {
|
||||
fn from(v: usize) -> Self {
|
||||
Self(v & ( (1 << PPN_WIDTH_SV39) - 1 ))
|
||||
}
|
||||
}
|
||||
|
||||
// 把物理地址转为 usize, 直接返回即可
|
||||
impl From<PhysAddr> for usize {
|
||||
fn from(v: PhysAddr) -> Self {
|
||||
v.0
|
||||
}
|
||||
}
|
||||
|
||||
// 把物理页结构体转为 usize类型的物理页 直接返回即可
|
||||
impl From<PhysPageNum> for usize {
|
||||
fn from(v: PhysPageNum) -> Self {
|
||||
v.0
|
||||
}
|
||||
}
|
||||
|
||||
// 把PhysAddr 转为 PhysPageNum
|
||||
impl From<PhysAddr> for PhysPageNum {
|
||||
fn from(v: PhysAddr) -> Self {
|
||||
assert_eq!(v.page_offset(), 0);
|
||||
v.floor()
|
||||
}
|
||||
}
|
||||
|
||||
// 把物理页转为物理地址(左移页宽即可)
|
||||
impl From<PhysPageNum> for PhysAddr {
|
||||
fn from(v: PhysPageNum) -> Self { Self(v.0 << PAGE_SIZE_BITS) }
|
||||
}
|
||||
|
||||
impl PhysAddr {
|
||||
// 从当前物理地址得到页内偏移(只保留12个bit即可)
|
||||
pub fn page_offset(&self) -> usize {
|
||||
self.0 & (PAGE_SIZE - 1)
|
||||
}
|
||||
|
||||
// 舍去小数位, 把物理地址, 转为 物理页号 向下取整
|
||||
pub fn floor(&self) -> PhysPageNum {
|
||||
PhysPageNum(self.0 / PAGE_SIZE)
|
||||
}
|
||||
|
||||
// 有小数统一 +1, 物理地址转为物理页号 向上取整
|
||||
pub fn ceil(&self) -> PhysPageNum {
|
||||
PhysPageNum((self.0 + PAGE_SIZE - 1) / PAGE_SIZE)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl PhysPageNum {
|
||||
// // 从当前物理页保存的数据中得到所有的 PTE
|
||||
pub fn get_pte_array(&self) -> &'static mut [PageTableEntry] {
|
||||
// 物理页号 转为物理地址
|
||||
let pa: PhysAddr = (*self).into();
|
||||
// 从物理页地址读出一页 512个8字节(4k)的数据
|
||||
unsafe { core::slice::from_raw_parts_mut(pa.0 as *mut PageTableEntry, 512) }
|
||||
}
|
||||
|
||||
// 从当前物理页得到 引用类型的 byte array
|
||||
pub fn get_bytes_array(&self) -> &'static mut [u8] {
|
||||
let pa: PhysAddr = (*self).into();
|
||||
unsafe { core::slice::from_raw_parts_mut(pa.0 as *mut u8, 4096) }
|
||||
}
|
||||
|
||||
// 把物理页转为物理地址之后, 再转为T, 强转
|
||||
pub fn get_mut<T>(&self) -> &'static mut T {
|
||||
let pa: PhysAddr = (*self).into();
|
||||
unsafe { (pa.0 as *mut T).as_mut().unwrap() }
|
||||
}
|
||||
}
|
||||
|
||||
impl VirtAddr{
|
||||
// 舍去小数位, 把虚拟地址转为物理页号 向下取整
|
||||
pub fn floor(&self) -> VirtPageNum {
|
||||
VirtPageNum(self.0 / PAGE_SIZE)
|
||||
}
|
||||
|
||||
// 有小数统一+1 虚拟地址转为虚拟页号 向上取整
|
||||
pub fn ceil(&self) -> VirtPageNum {
|
||||
VirtPageNum((self.0 - 1 + PAGE_SIZE) / PAGE_SIZE)
|
||||
}
|
||||
|
||||
// 虚拟地址得到业内偏移 只保留12个bit即可
|
||||
pub fn page_offset(&self) -> usize {
|
||||
self.0 & (PAGE_SIZE - 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 把usize 转为 虚拟地址, 只保留39位
|
||||
impl From<usize> for VirtAddr {
|
||||
fn from(value: usize) -> Self {
|
||||
Self(value & ((1 << VA_WIDTH_SV39) - 1))
|
||||
}
|
||||
}
|
||||
|
||||
// 把虚拟地址, 转为usize
|
||||
impl From<VirtAddr> for usize {
|
||||
fn from(v: VirtAddr) -> Self {
|
||||
if v.0 >= (1 << (VA_WIDTH_SV39 - 1)) {
|
||||
// 将高位全部设置为1, 虚拟地址就是这样的, 64~39 位, 随着38位变化
|
||||
v.0 | (!((1 << VA_WIDTH_SV39) - 1))
|
||||
} else {
|
||||
v.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 把usize类型的页号 转为 虚拟页号结构体, 只保留27位即可
|
||||
impl From<usize> for VirtPageNum {
|
||||
fn from(v: usize) -> Self {
|
||||
Self(v & ((1 << VPN_WIDTH_SV39) - 1))
|
||||
}
|
||||
}
|
||||
|
||||
// 虚拟地址 转为虚拟页号 向下取整
|
||||
impl From<VirtAddr> for VirtPageNum {
|
||||
fn from(v: VirtAddr) -> Self {
|
||||
assert_eq!(v.page_offset(), 0);
|
||||
v.floor()
|
||||
}
|
||||
}
|
||||
|
||||
// 虚拟页号 转为虚拟地址 左移即可
|
||||
impl From<VirtPageNum> for VirtAddr {
|
||||
fn from(v: VirtPageNum) -> Self {
|
||||
// 左移12位
|
||||
Self(v.0 << PAGE_SIZE_BITS)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl VirtPageNum{
|
||||
// 从虚拟页号中 抽离 9 9 9 的布局
|
||||
pub fn indexes(&self) -> [usize; 3] {
|
||||
let mut vpn = self.0;
|
||||
let mut idx = [0usize; 3];
|
||||
for i in (0..3).rev() {
|
||||
idx[i] = vpn & 511;
|
||||
vpn >>= 9;
|
||||
}
|
||||
idx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 代表一个range类型, 表示一段 虚拟地址 的区间
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct VPNRange {
|
||||
pub l: VirtPageNum,
|
||||
pub r: VirtPageNum
|
||||
}
|
||||
|
||||
impl Iterator for VPNRange {
|
||||
type Item = VirtPageNum;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.l == self.r {
|
||||
None
|
||||
} else {
|
||||
let current_vpn = self.l;
|
||||
self.l = (self.l.0 + 1).into();
|
||||
Some(current_vpn)
|
||||
}
|
||||
}
|
||||
}
|
@ -1,120 +0,0 @@
|
||||
use alloc::vec::Vec;
|
||||
use lazy_static::lazy_static;
|
||||
use crate::mm::address::{PhysPageNum, PhysAddr};
|
||||
use crate::config::MEMORY_END;
|
||||
use crate::println;
|
||||
use crate::sync::UPSafeCell;
|
||||
|
||||
extern "C" {
|
||||
fn ekernel();
|
||||
}
|
||||
|
||||
// 物理页帧的结构体, 他和物理页号不同, 它是管理整个物理页内的数据, 而物理页号被页表管理
|
||||
// 这个结构体只是利用rust drop管理变量的方式
|
||||
// 我们使用这个结构体, 来利用rust变量生命周期, 自动管理该页, 数据清零或者还回物理页帧管理器
|
||||
// 这个结构可以省去(因为他很多时候使用PhysPageNum 也可以完成), 但是为了防止后续课程还有其他地方使用, 就不省了,
|
||||
pub struct FrameTracker {
|
||||
pub ppn: PhysPageNum,
|
||||
}
|
||||
|
||||
impl FrameTracker {
|
||||
pub fn new(ppn: PhysPageNum) -> Self {
|
||||
// 页数据初始化
|
||||
let bytes_array = ppn.get_bytes_array();
|
||||
for i in bytes_array {
|
||||
*i = 0;
|
||||
}
|
||||
Self { ppn }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FrameTracker {
|
||||
// 生命周期结束, 自动把页还给 物理页帧管理器
|
||||
fn drop(&mut self) {
|
||||
frame_dealloc(self.ppn);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 物理页帧管理器, 它管理了 ekernel(操作系统使用的内存结束位置) 到 MEMORY_END(最大的可用的物理内存地址)所有的内存, 这部分内存是给用户用的
|
||||
// current, end 这个区间表示此前从未被分配过的页
|
||||
// recycled 表示之前被分配过, 但是已经被回收可以再利用的页
|
||||
pub struct StackFrameAllocator {
|
||||
current: PhysPageNum,
|
||||
end: PhysPageNum,
|
||||
recycled: Vec<PhysPageNum>,
|
||||
}
|
||||
|
||||
impl StackFrameAllocator {
|
||||
fn from(l: PhysPageNum, r: PhysPageNum) -> Self {
|
||||
Self {
|
||||
current: l,
|
||||
end: r,
|
||||
recycled: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StackFrameAllocator {
|
||||
// 从分配器中, 找到一个空闲页(它可能之前从未分配过, 或者之前被分配但是已经被回收的完好页)
|
||||
fn alloc(&mut self) -> Option<PhysPageNum> {
|
||||
if let Some(ppn) = self.recycled.pop() {
|
||||
Some(ppn)
|
||||
} else if self.current == self.end {
|
||||
None
|
||||
} else {
|
||||
let current_ppn = self.current;
|
||||
let next_ppn = (self.current.0 + 1).into();
|
||||
self.current = next_ppn;
|
||||
Some(current_ppn)
|
||||
}
|
||||
}
|
||||
|
||||
// 回收一个页, 为了防止二次回收, 我们这里直接panic
|
||||
fn dealloc(&mut self, ppn: PhysPageNum) {
|
||||
// 防止被二次回收
|
||||
if ppn >= self.current || self.recycled.iter().any(|&v| v == ppn) {
|
||||
panic!("Frame ppn={:#x} has not been allocated!", ppn.0);
|
||||
}
|
||||
// 校验完毕, 把这个页, 还给管理器
|
||||
self.recycled.push(ppn);
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref FRAME_ALLOCATOR: UPSafeCell<StackFrameAllocator> = unsafe {
|
||||
// 这里我们只要完整的页, 舍去开头和结尾一些碎片
|
||||
UPSafeCell::new(StackFrameAllocator::from(PhysAddr::from(ekernel as usize).ceil(), PhysAddr::from(MEMORY_END).floor()))
|
||||
};
|
||||
}
|
||||
|
||||
/// 分配一个页
|
||||
pub fn frame_alloc() -> Option<FrameTracker> {
|
||||
FRAME_ALLOCATOR
|
||||
.exclusive_access()
|
||||
.alloc()
|
||||
.map(FrameTracker::new)
|
||||
}
|
||||
|
||||
/// 回收指定的页
|
||||
fn frame_dealloc(ppn: PhysPageNum) {
|
||||
FRAME_ALLOCATOR.exclusive_access().dealloc(ppn);
|
||||
}
|
||||
|
||||
|
||||
pub fn frame_allocator_test() {
|
||||
let mut v: Vec<FrameTracker> = Vec::new();
|
||||
for i in 0..5 {
|
||||
let frame = frame_alloc().unwrap();
|
||||
println!("frame_allocator_test {:?}", frame.ppn.0);
|
||||
v.push(frame);
|
||||
}
|
||||
v.clear();
|
||||
for i in 0..5 {
|
||||
let frame = frame_alloc().unwrap();
|
||||
println!("frame_allocator_test {:?}", frame.ppn.0);
|
||||
v.push(frame);
|
||||
}
|
||||
drop(v);
|
||||
println!("frame_allocator_test passed!");
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use alloc::vec;
|
||||
use buddy_system_allocator::LockedHeap;
|
||||
use crate::config::KERNEL_HEAP_SIZE;
|
||||
use crate::println;
|
||||
|
||||
|
||||
// 动态内存分配器
|
||||
#[global_allocator]
|
||||
static HEAP_ALLOCATOR: LockedHeap = LockedHeap::empty();
|
||||
|
||||
// 内存分配失败时, 会调用此错误处理函数
|
||||
|
||||
// 堆的空间
|
||||
static mut HEAP_SPACE: [u8; KERNEL_HEAP_SIZE] = [0; KERNEL_HEAP_SIZE];
|
||||
|
||||
|
||||
// 为内存分配器, 绑定一个空间用来实现动态内存分配
|
||||
pub fn init_heap() {
|
||||
unsafe {
|
||||
HEAP_ALLOCATOR
|
||||
.lock()
|
||||
.init(HEAP_SPACE.as_ptr() as usize, KERNEL_HEAP_SIZE);
|
||||
}
|
||||
// heap_test()
|
||||
}
|
||||
|
||||
pub fn heap_test() {
|
||||
use alloc::boxed::Box;
|
||||
use alloc::vec::Vec;
|
||||
extern "C" {
|
||||
fn sbss();
|
||||
fn ebss();
|
||||
}
|
||||
let bss_range = sbss as usize..ebss as usize;
|
||||
println!("bss_range {:?}", bss_range);
|
||||
|
||||
let a = Box::new(5);
|
||||
println!("a: {:?} ptr: {:p}", a, a.as_ref());
|
||||
let b = Box::new(6);
|
||||
println!("b: {:?} ptr: {:p}", b, b.as_ref());
|
||||
|
||||
|
||||
unsafe {
|
||||
println!("HEAP_SPACE: {:?}", HEAP_SPACE.as_ptr())
|
||||
}
|
||||
|
||||
let mut v = vec![];
|
||||
for i in 0..500{
|
||||
v.push(i);
|
||||
}
|
||||
|
||||
for i in 0..500{
|
||||
v.pop();
|
||||
}
|
||||
|
||||
println!("{:?}", v);
|
||||
|
||||
// 通过输出打印, 发现 a 和b 均被分配在了 HEAP_SPACE 中, 且 HEAP_SPACE 被分配在了 bss段中, 这个段由我们 linker.ld 进行手动布局
|
||||
// 目前整个bss段的大小都是3M, 说明当前bss段中只有这一个 数据
|
||||
}
|
||||
|
||||
#[alloc_error_handler]
|
||||
pub fn handle_alloc_error(layout: core::alloc::Layout) -> ! {
|
||||
panic!("Heap allocation error, layout = {:?}", layout);
|
||||
}
|
@ -1,447 +0,0 @@
|
||||
use alloc::collections::BTreeMap;
|
||||
use alloc::sync::Arc;
|
||||
use alloc::vec::Vec;
|
||||
use core::arch::asm;
|
||||
use bitflags::bitflags;
|
||||
use lazy_static::lazy_static;
|
||||
use riscv::register::satp;
|
||||
use xmas_elf;
|
||||
use crate::sync::UPSafeCell;
|
||||
use crate::config::{MEMORY_END, PAGE_SIZE, TRAMPOLINE, TRAP_CONTEXT, USER_STACK_SIZE};
|
||||
use crate::mm::address::{PhysAddr, PhysPageNum, VirtAddr, VirtPageNum, VPNRange};
|
||||
use crate::mm::frame_allocator::{frame_alloc, FrameTracker};
|
||||
use crate::mm::page_table::{PageTable, PTEFlags};
|
||||
use crate::println;
|
||||
|
||||
// 引入外部符号进来, 下面映射地址空间的逻辑段会用到
|
||||
extern "C" {
|
||||
fn stext();
|
||||
fn etext();
|
||||
fn srodata();
|
||||
fn erodata();
|
||||
fn sdata();
|
||||
fn edata();
|
||||
fn sbss_with_stack();
|
||||
fn ebss();
|
||||
fn ekernel();
|
||||
fn strampoline(); // 这个符号 在linker.ld 中定义
|
||||
}
|
||||
lazy_static! {
|
||||
/// a memory set instance through lazy_static! managing kernel space
|
||||
pub static ref KERNEL_SPACE: Arc<UPSafeCell<MemorySet>> =
|
||||
Arc::new(unsafe { UPSafeCell::new(MemorySet::new_kernel()) });
|
||||
}
|
||||
|
||||
// 某逻辑段的映射方式
|
||||
#[derive(Copy, Clone, PartialEq, Debug)]
|
||||
pub enum MapType {
|
||||
Identical, // 恒等映射
|
||||
Framed, // 逻辑映射
|
||||
}
|
||||
|
||||
|
||||
// 这个段的权限, 它是页表项标志位 PTEFlags 的一个子集, 仅仅保留4个标志位就足够了
|
||||
bitflags! {
|
||||
/// map permission corresponding to that in pte: `R W X U`
|
||||
pub struct MapPermission: u8 {
|
||||
const R = 1 << 1;
|
||||
const W = 1 << 2;
|
||||
const X = 1 << 3;
|
||||
const U = 1 << 4;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 代表一个逻辑段
|
||||
pub struct MapArea {
|
||||
vpn_range: VPNRange, // 逻辑段的虚拟页起始位置 和 结束位置
|
||||
data_frames: BTreeMap<VirtPageNum, FrameTracker>, // 这个逻辑段 虚拟页 对应的具体的物理帧, 这里使用rust 进行管理其物理帧的释放, 自动drop进行还给物理页帧管理器
|
||||
map_type: MapType,
|
||||
map_perm: MapPermission,
|
||||
}
|
||||
|
||||
impl MapArea {
|
||||
// 从虚拟地址起始和结束, 创建一个逻辑段结构体
|
||||
pub fn from(start_va: VirtAddr, end_va: VirtAddr, map_type: MapType, map_perm: MapPermission,) -> Self {
|
||||
// 截取抛弃内存碎片
|
||||
let start_vpn: VirtPageNum = start_va.floor();
|
||||
let end_vpn: VirtPageNum = end_va.ceil();
|
||||
|
||||
Self {
|
||||
vpn_range: VPNRange {l:start_vpn, r: end_vpn},
|
||||
data_frames: BTreeMap::new(),
|
||||
map_type,
|
||||
map_perm,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MapArea {
|
||||
// 把一个虚拟页号 创建一个对应的物理页帧 映射到page_table中, 并把创建的物理页帧生命周期 绑定到 self上
|
||||
pub fn map_one(&mut self, page_table: &mut PageTable, vpn: VirtPageNum) {
|
||||
let ppn: PhysPageNum;
|
||||
match self.map_type {
|
||||
// 恒等映射
|
||||
MapType::Identical => {
|
||||
ppn = PhysPageNum(vpn.0);
|
||||
}
|
||||
MapType::Framed => {
|
||||
// 随便创建一个 物理页帧
|
||||
let frame = frame_alloc().unwrap();
|
||||
ppn = frame.ppn;
|
||||
// 把随便创建的物理页帧, 绑定到data_frames 中被 self管理生命周期
|
||||
self.data_frames.insert(vpn, frame);
|
||||
}
|
||||
}
|
||||
|
||||
// 根据上面创建的物理页帧映射pte 到三级页表中
|
||||
let pte_flags = PTEFlags::from_bits(self.map_perm.bits).unwrap();
|
||||
page_table.map(vpn, ppn, pte_flags);
|
||||
}
|
||||
|
||||
// 取消映射一个vpn, 并把 self管理的 物理页帧的生命周期结束
|
||||
pub fn unmap_one(&mut self, page_table: &mut PageTable, vpn: VirtPageNum) {
|
||||
if self.map_type == MapType::Framed {
|
||||
// 删除映射关系, 自动调用 drop 把vpn对应的ppn还给全局内存管理器
|
||||
self.data_frames.remove(&vpn);
|
||||
}
|
||||
// 物理帧不存在了 把vpn 对应的pte设置为空
|
||||
page_table.unmap(vpn);
|
||||
}
|
||||
|
||||
// 映射 当前逻辑段中的每一个虚拟页, 到页表中
|
||||
pub fn map(&mut self, page_table: &mut PageTable) {
|
||||
|
||||
for vpn in self.vpn_range {
|
||||
self.map_one(page_table, vpn);
|
||||
}
|
||||
}
|
||||
|
||||
// 在页表中取消映射每一个虚拟页
|
||||
pub fn unmap(&mut self, page_table: &mut PageTable) {
|
||||
for vpn in self.vpn_range {
|
||||
self.unmap_one(page_table, vpn);
|
||||
}
|
||||
}
|
||||
|
||||
// 拷贝外部的数据二进制 到当前的逻辑段中 按照页 为单位
|
||||
pub fn copy_data(&mut self, page_table: &mut PageTable, data: &[u8]) {
|
||||
assert_eq!(self.map_type, MapType::Framed);
|
||||
|
||||
let mut start: usize = 0;
|
||||
|
||||
// 当前逻辑段的起始页位置
|
||||
let mut current_vpn = self.vpn_range.l;
|
||||
// 需要拷贝的字节总大小
|
||||
let len = data.len();
|
||||
loop {
|
||||
// 拷贝 每次最大拷贝1个页
|
||||
let src = &data[start..len.min(start + PAGE_SIZE)];
|
||||
|
||||
// 得到逻辑段每个页的起始位置
|
||||
let dst = &mut page_table
|
||||
.get_pte(current_vpn) // 在页表中, 根据逻辑段中的vpn 得到 54bit的pte (44+10)
|
||||
.unwrap()
|
||||
.ppn() // 根据54bit的pte, 得到44bit 的物理页帧的位置
|
||||
.get_bytes_array()[..src.len()]; // 得到物理页帧那一页的起始的地址 44bit<<12
|
||||
dst.copy_from_slice(src);
|
||||
start += PAGE_SIZE;
|
||||
if start >= len {
|
||||
break;
|
||||
}
|
||||
current_vpn = (current_vpn.0 + 1).into();
|
||||
}
|
||||
}
|
||||
// 当前段, 缩小到新的结束位置, 即把new_end后面的页, 都还给物理页帧管理器, 并取消映射(通过unmap_one方法即可)
|
||||
pub fn shrink_to(&mut self, page_table: &mut PageTable, new_end: VirtPageNum) {
|
||||
let tmp_vpn_range = VPNRange{
|
||||
l: new_end,
|
||||
r: self.vpn_range.r,
|
||||
};
|
||||
for vpn in tmp_vpn_range {
|
||||
self.unmap_one(page_table, vpn)
|
||||
}
|
||||
|
||||
// 注意 当前段的区间 也要调整哦new(self.vpn_range.get_start(), new_end);
|
||||
self.vpn_range.r = new_end;
|
||||
}
|
||||
|
||||
|
||||
// 当前段, 把当前结束的位置, 扩展到新的结束的位置
|
||||
pub fn append_to(&mut self, page_table: &mut PageTable, new_end: VirtPageNum) {
|
||||
let tmp_vpn_range = VPNRange{
|
||||
l: self.vpn_range.r,
|
||||
r: new_end,
|
||||
};
|
||||
|
||||
for vpn in tmp_vpn_range {
|
||||
self.map_one(page_table, vpn)
|
||||
}
|
||||
|
||||
self.vpn_range.r = new_end;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 表示一个地址空间, 它是一个页表和 包含所有段信息的页表组成
|
||||
pub struct MemorySet {
|
||||
pub page_table: PageTable,
|
||||
pub areas: Vec<MapArea>,
|
||||
}
|
||||
|
||||
impl MemorySet {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
page_table: PageTable::new(),
|
||||
areas: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_elf(elf_data: &[u8]) -> (Self, usize, usize) {
|
||||
let mut memory_set = Self::new();
|
||||
// map trampoline
|
||||
// 创建一个地址空间
|
||||
memory_set.map_trampoline();
|
||||
// map program headers of elf, with U flag
|
||||
// 分析外部传进来的 elf文件数据
|
||||
let elf = xmas_elf::ElfFile::new(elf_data).unwrap();
|
||||
let elf_header = elf.header;
|
||||
let magic = elf_header.pt1.magic;
|
||||
assert_eq!(magic, [0x7f, 0x45, 0x4c, 0x46], "invalid elf!");
|
||||
let ph_count = elf_header.pt2.ph_count();
|
||||
// 得到所有的段数量
|
||||
let mut max_end_vpn = VirtPageNum(0);
|
||||
// 循环所有的段
|
||||
for i in 0..ph_count {
|
||||
// 得到当前段
|
||||
let ph = elf.program_header(i).unwrap();
|
||||
// 确定有加载的必要
|
||||
if ph.get_type().unwrap() == xmas_elf::program::Type::Load {
|
||||
// 当前段开始位置
|
||||
let start_va: VirtAddr = (ph.virtual_addr() as usize).into();
|
||||
// 当前段结束位置 (开始位置+大小)
|
||||
let end_va: VirtAddr = ((ph.virtual_addr() + ph.mem_size()) as usize).into();
|
||||
|
||||
// 当前段权限
|
||||
let mut map_perm = MapPermission::U;
|
||||
let ph_flags = ph.flags();
|
||||
if ph_flags.is_read() {
|
||||
map_perm |= MapPermission::R;
|
||||
}
|
||||
if ph_flags.is_write() {
|
||||
map_perm |= MapPermission::W;
|
||||
}
|
||||
if ph_flags.is_execute() {
|
||||
map_perm |= MapPermission::X;
|
||||
}
|
||||
// 创建一个 逻辑段
|
||||
let map_area = MapArea::from(start_va, end_va, MapType::Framed, map_perm);
|
||||
// 每次都更新最后的逻辑段的最后结束最大的逻辑地址
|
||||
max_end_vpn = map_area.vpn_range.r;
|
||||
|
||||
// 当前逻辑段, 添加到地址空间, 并copy数据进去
|
||||
memory_set.push(
|
||||
map_area,
|
||||
Some(&elf.input[ph.offset() as usize..(ph.offset() + ph.file_size()) as usize]),
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// map user stack with U flags
|
||||
// 将最后一个最大的逻辑段的结束的页, 转为逻辑地址 左移12位 得到39位的VirtAddr
|
||||
let max_end_va: VirtAddr = max_end_vpn.into();
|
||||
// 根据riscv 的规则, 转成一个 合法的地址 (todo 为什么这里需要转成合法的地址:将高位全部设置为1, 上面的start_va 不转就传?, 而且不直接可以使用end_va 吗? 这里还创建一个max_end_vpn?)
|
||||
let mut user_stack_bottom: usize = max_end_va.into();
|
||||
|
||||
// guard page 放置 一页 保护页隔离用户栈
|
||||
user_stack_bottom += PAGE_SIZE;
|
||||
|
||||
// 保护页之后 再增加 用户栈大小,得到栈底和当前的栈顶
|
||||
// 此时 user_stack_top 距离 max_end_vpn 三个页
|
||||
let user_stack_top = user_stack_bottom + USER_STACK_SIZE;
|
||||
|
||||
// 添加 用户逻辑栈段并映射物理地址页, 到当前的地址空间
|
||||
memory_set.push(
|
||||
MapArea::from(
|
||||
user_stack_bottom.into(),
|
||||
user_stack_top.into(),
|
||||
MapType::Framed,
|
||||
MapPermission::R | MapPermission::W | MapPermission::U,
|
||||
),
|
||||
None,
|
||||
);
|
||||
|
||||
// 用户的堆空间段 只有一个起始位置即可, 因为 user_stack_top上面全是堆的空间(除了最后两页)
|
||||
memory_set.push(
|
||||
MapArea::from(
|
||||
user_stack_top.into(),
|
||||
user_stack_top.into(),
|
||||
MapType::Framed,
|
||||
MapPermission::R | MapPermission::W | MapPermission::U,
|
||||
),
|
||||
None,
|
||||
);
|
||||
|
||||
// 设置 TrapContext为统一的虚拟地址
|
||||
// 将 虚拟地址的 次高页添加到用户空间, 后面会被内核强行找到物理地址并修改为 trap context
|
||||
memory_set.push(
|
||||
MapArea::from(
|
||||
TRAP_CONTEXT.into(),
|
||||
TRAMPOLINE.into(),
|
||||
MapType::Framed,
|
||||
MapPermission::R | MapPermission::W,
|
||||
),
|
||||
None,
|
||||
);
|
||||
|
||||
(
|
||||
memory_set, // 地址空间
|
||||
user_stack_top, // 用户栈底和当前的栈顶, 他在地址空间各个逻辑段的上面, 同时
|
||||
elf.header.pt2.entry_point() as usize, // elf文件的入口地址
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl MemorySet {
|
||||
// 得到当前地址空间的 页表token
|
||||
pub fn token(&self) -> usize {
|
||||
self.page_table.token()
|
||||
}
|
||||
|
||||
// 激活当前地址空间
|
||||
pub fn activate(&self) {
|
||||
// let satp = self.page_table.token();
|
||||
// 得到当前地址空间的 页表 的规定格式
|
||||
let satp = self.token();;
|
||||
unsafe {
|
||||
// 设置satp CSR寄存器为我们
|
||||
satp::write(satp);
|
||||
|
||||
// 刷新快表缓存TLB, 这个指令最简单的作用就是清空旧的快表
|
||||
// 更深层次其实是一个内存屏障
|
||||
asm!("sfence.vma");
|
||||
}
|
||||
}
|
||||
|
||||
// 根据 start va 和end va 创建一个 逻辑段类型为逻辑映射, 插入到 当前地址空间
|
||||
pub fn insert_framed_area(&mut self, start_va: VirtAddr, end_va: VirtAddr, permission: MapPermission) {
|
||||
self.push(MapArea::from(start_va, end_va, MapType::Framed, permission), None);
|
||||
}
|
||||
|
||||
// 把一个 逻辑段, 映射到当前页表中
|
||||
fn push(&mut self, mut map_area: MapArea, data: Option<&[u8]>) {
|
||||
map_area.map(&mut self.page_table);
|
||||
if let Some(data) = data {
|
||||
map_area.copy_data(&mut self.page_table, data);
|
||||
}
|
||||
self.areas.push(map_area);
|
||||
}
|
||||
|
||||
/// 创建跳板, 跳板就是 trap.S中的代码段中.text.trampoline, 由 linker.ld手动布局在代码段
|
||||
/// 内核空间和用户空间,他们都会运行这个函数, 插入同样的代码, 把虚拟地址映射为同样的物理地址, 这里内核空间和用户空间执行这段代码的时候, 每个 虚拟地址对应的物理地址是相同的
|
||||
/// 所以 (内核空间的 TRAMPOLINE+指令offset) == (用户空间的 TRAMPOLINE+offset) == (strampoline + offset)
|
||||
/// (内核的 TRAMPOLINE) 和 (用户的 TRAMPOLINE) 和 strampoline 他们都是相等的
|
||||
/// 在 trap.S 切换用户空间之后, 取值执行, 切换空间之前和切换空间之后, 他们对应的虚拟地址空间是相同的, 且都映射到了同一个物理页帧
|
||||
fn map_trampoline(&mut self) {
|
||||
// 直接插入到 把 linker.ld 中的符号strampoline, 映射到最高的虚拟页, 他的物理页帧是 链接脚本中我们手动内存布局的符号
|
||||
// 如果是用户应用, 这个符号的最下面就是 次高页 即 trap context
|
||||
self.page_table.map(
|
||||
VirtAddr::from(TRAMPOLINE).into(),
|
||||
PhysAddr::from(strampoline as usize).into(),
|
||||
PTEFlags::R | PTEFlags::X,
|
||||
);
|
||||
}
|
||||
|
||||
// 创建一个内核用的地址空间
|
||||
pub fn new_kernel() -> Self {
|
||||
let mut memory_set = Self::new();
|
||||
// 跳板创建
|
||||
memory_set.map_trampoline();
|
||||
// map kernel sections
|
||||
println!(".text [{:#x}, {:#x})", stext as usize, etext as usize);
|
||||
println!(".rodata [{:#x}, {:#x})", srodata as usize, erodata as usize);
|
||||
println!(".data [{:#x}, {:#x})", sdata as usize, edata as usize);
|
||||
println!(
|
||||
".bss [{:#x}, {:#x})",
|
||||
sbss_with_stack as usize, ebss as usize
|
||||
);
|
||||
println!("mapping .text section");
|
||||
memory_set.push(
|
||||
MapArea::from(
|
||||
(stext as usize).into(),
|
||||
(etext as usize).into(),
|
||||
MapType::Identical,
|
||||
MapPermission::R | MapPermission::X,
|
||||
),
|
||||
None,
|
||||
);
|
||||
println!("mapping .rodata section");
|
||||
memory_set.push(
|
||||
MapArea::from(
|
||||
(srodata as usize).into(),
|
||||
(erodata as usize).into(),
|
||||
MapType::Identical,
|
||||
MapPermission::R,
|
||||
),
|
||||
None,
|
||||
);
|
||||
println!("mapping .data section");
|
||||
memory_set.push(
|
||||
MapArea::from(
|
||||
(sdata as usize).into(),
|
||||
(edata as usize).into(),
|
||||
MapType::Identical,
|
||||
MapPermission::R | MapPermission::W,
|
||||
),
|
||||
None,
|
||||
);
|
||||
println!("mapping .bss section");
|
||||
memory_set.push(
|
||||
MapArea::from(
|
||||
(sbss_with_stack as usize).into(),
|
||||
(ebss as usize).into(),
|
||||
MapType::Identical,
|
||||
MapPermission::R | MapPermission::W,
|
||||
),
|
||||
None,
|
||||
);
|
||||
println!("mapping physical memory");
|
||||
memory_set.push(
|
||||
MapArea::from(
|
||||
(ekernel as usize).into(),
|
||||
MEMORY_END.into(),
|
||||
MapType::Identical,
|
||||
MapPermission::R | MapPermission::W,
|
||||
),
|
||||
None,
|
||||
);
|
||||
memory_set
|
||||
}
|
||||
|
||||
|
||||
// 当前地址空间, 缩小 虚拟地址start位置到虚拟地址 new end的位置
|
||||
pub fn shrink_to(&mut self, start: VirtAddr, new_end: VirtAddr) -> bool {
|
||||
// 起始虚拟地址所在的页
|
||||
let start_vpn = start.floor();
|
||||
|
||||
// 找到起始地址所在的段, 传入页表, 把当前段缩小到指定结束位置new_end
|
||||
if let Some(area) = self.areas.iter_mut().find(|area| area.vpn_range.l == start_vpn) {
|
||||
area.shrink_to(&mut self.page_table, new_end.ceil());
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// 增加当前的地址空间 扩展为 start到 新的结束的位置
|
||||
pub fn append_to(&mut self, start: VirtAddr, new_end: VirtAddr) -> bool {
|
||||
// 同上, 找到逻辑段之后, 只不过这里是 扩展
|
||||
if let Some(area) = self.areas.iter_mut().find(|area| area.vpn_range.l == start.floor()) {
|
||||
area.append_to(&mut self.page_table, new_end.ceil());
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
@ -1,59 +0,0 @@
|
||||
use crate::mm::address::VirtAddr;
|
||||
use crate::mm::memory_set::KERNEL_SPACE;
|
||||
use crate::{etext, println, stext};
|
||||
|
||||
pub mod heap_allocator;
|
||||
pub mod address;
|
||||
pub mod frame_allocator;
|
||||
pub mod page_table;
|
||||
pub mod memory_set;
|
||||
|
||||
|
||||
|
||||
pub fn init(){
|
||||
// 开启 内核的内存分配器
|
||||
heap_allocator::init_heap();
|
||||
// 初始化并测试 物理页帧管理器
|
||||
frame_allocator::frame_allocator_test();
|
||||
// 激活内核的地址空间
|
||||
KERNEL_SPACE.exclusive_access().activate();
|
||||
|
||||
remap_test();
|
||||
}
|
||||
|
||||
|
||||
pub fn remap_test() {
|
||||
extern "C" {
|
||||
fn stext();
|
||||
fn etext();
|
||||
fn srodata();
|
||||
fn erodata();
|
||||
fn sdata();
|
||||
fn edata();
|
||||
fn sbss_with_stack();
|
||||
fn ebss();
|
||||
fn ekernel();
|
||||
fn strampoline(); // 这个符号 在linker.ld 中定义
|
||||
}
|
||||
|
||||
let mut kernel_space = KERNEL_SPACE.exclusive_access();
|
||||
let mid_text: VirtAddr = ((stext as usize + etext as usize) / 2).into();
|
||||
let mid_rodata: VirtAddr = ((srodata as usize + erodata as usize) / 2).into();
|
||||
let mid_data: VirtAddr = ((sdata as usize + edata as usize) / 2).into();
|
||||
assert!(!kernel_space
|
||||
.page_table
|
||||
.get_pte(mid_text.floor())
|
||||
.unwrap()
|
||||
.writable(),);
|
||||
assert!(!kernel_space
|
||||
.page_table
|
||||
.get_pte(mid_rodata.floor())
|
||||
.unwrap()
|
||||
.writable(),);
|
||||
assert!(!kernel_space
|
||||
.page_table
|
||||
.get_pte(mid_data.floor())
|
||||
.unwrap()
|
||||
.executable(),);
|
||||
println!("remap_test passed!");
|
||||
}
|
@ -1,218 +0,0 @@
|
||||
use alloc::vec;
|
||||
use alloc::vec::Vec;
|
||||
use bitflags::*;
|
||||
use crate::config::TRAMPOLINE;
|
||||
use crate::mm::address::{PhysPageNum, VirtAddr, VirtPageNum};
|
||||
use crate::mm::frame_allocator::{frame_alloc, FrameTracker};
|
||||
use crate::println;
|
||||
use crate::task::TASK_MANAGER;
|
||||
|
||||
|
||||
bitflags! {
|
||||
pub struct PTEFlags: u8 {
|
||||
const V = 1 << 0; // 仅当位 V 为 1 时,页表项才是合法的
|
||||
const R = 1 << 1; // 可读标志
|
||||
const W = 1 << 2; // 可写标志
|
||||
const X = 1 << 3; // 可执行标志
|
||||
const U = 1 << 4; // 是否允许U级访问
|
||||
const G = 1 << 5; //
|
||||
const A = 1 << 6; // 从上次清零之后, 该页是否被访问过
|
||||
const D = 1 << 7; // 从上次清零之后, 该页是否被修改过
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
#[repr(C)]
|
||||
/// pte结构体
|
||||
///
|
||||
/// 对应的64个字节的布局为
|
||||
///
|
||||
/// 10bit(保留) | 44bit(物理页号) | 10bit(标志位)
|
||||
pub struct PageTableEntry {
|
||||
pub bits: usize,
|
||||
}
|
||||
|
||||
|
||||
impl PageTableEntry {
|
||||
// 从一个物理页号和一个flag 创建出来一个 PTE
|
||||
// 物理也好 左移10位 加上 flag 即可
|
||||
pub fn from(ppn: PhysPageNum, flags: PTEFlags) -> Self {
|
||||
PageTableEntry {
|
||||
bits: ppn.0 << 10 | flags.bits as usize,
|
||||
}
|
||||
}
|
||||
|
||||
// 生成一个全0的PTE, V也是0, 它是不合法的
|
||||
pub fn new() -> Self {
|
||||
PageTableEntry { bits: 0 }
|
||||
}
|
||||
|
||||
// 从PTE中的到 物理页的地址, 右移bit flag的宽度 再只保留44位即可得到 usize类型的物理页号, 随后调用into进行转换
|
||||
pub fn ppn(&self) -> PhysPageNum {
|
||||
(self.bits >> 10 & ((1usize << 44) - 1)).into()
|
||||
}
|
||||
// 从PTE中得到bit flag
|
||||
pub fn flags(&self) -> PTEFlags {
|
||||
PTEFlags::from_bits(self.bits as u8).unwrap()
|
||||
}
|
||||
|
||||
// 判断是否合法, 只保留 V标志的位置, 再判断是否为0
|
||||
pub fn is_valid(&self) -> bool {
|
||||
(self.flags() & PTEFlags::V) != PTEFlags::empty()
|
||||
}
|
||||
// 判断是否可读
|
||||
pub fn readable(&self) -> bool {
|
||||
(self.flags() & PTEFlags::R) != PTEFlags::empty()
|
||||
}
|
||||
// 判断是否可写
|
||||
pub fn writable(&self) -> bool {
|
||||
(self.flags() & PTEFlags::W) != PTEFlags::empty()
|
||||
}
|
||||
// 判断是否可执行
|
||||
pub fn executable(&self) -> bool {
|
||||
(self.flags() & PTEFlags::X) != PTEFlags::empty()
|
||||
}
|
||||
}
|
||||
|
||||
// 页表
|
||||
pub struct PageTable {
|
||||
root_ppn: PhysPageNum,
|
||||
// 这里保存, 保存了 被映射出来的每级页表的物理帧, 页表被删除时, 页表所占用的物理帧 也被rust释放执行drop还给物理页帧管理器, FrameTracker 实现了 Drop trait
|
||||
frames: Vec<FrameTracker>,
|
||||
}
|
||||
|
||||
impl PageTable {
|
||||
// 创建根节点页表
|
||||
pub fn new() -> Self {
|
||||
let frame = frame_alloc().unwrap();
|
||||
PageTable {
|
||||
root_ppn: frame.ppn,
|
||||
frames: vec![frame],
|
||||
}
|
||||
}
|
||||
|
||||
// 从stap寄存器保存的特定格式的token, 转为根节点页表
|
||||
pub fn from_token(satp: usize) -> Self {
|
||||
Self {
|
||||
// 只保留44位 bit, 这44位bit, 就是 页表所在的物理页帧
|
||||
root_ppn: PhysPageNum::from(satp & ((1usize << 44) - 1)),
|
||||
frames: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl PageTable {
|
||||
// 得到该页表被设置到 stap 需要的格式
|
||||
// 注意, 这个只能是根节点才会用得到
|
||||
pub fn token(&self) -> usize {
|
||||
// 8 表示MODE, SV39分页机制开启
|
||||
// 4bit 16bit 44bit 构成页表的 stap CSR的格式要求
|
||||
8usize << 60 | self.root_ppn.0
|
||||
}
|
||||
|
||||
// 寻找 指定页号, 如果不存在中间节点, 则创建出来, 知道找到三级页表的 指定下标 的 pte的指针
|
||||
fn find_pte_create(&mut self, vpn: VirtPageNum) -> Option<&mut PageTableEntry> {
|
||||
let idxs = vpn.indexes();
|
||||
let mut ppn = self.root_ppn;
|
||||
let mut result: Option<&mut PageTableEntry> = None;
|
||||
for (i, idx) in idxs.iter().enumerate() {
|
||||
// 得到一级页表的pte
|
||||
let pte = &mut ppn.get_pte_array()[*idx];
|
||||
// 到达最后一级, 不管有无数据直接 跳出, 返回 三级页表保存的信息 0或者指向 物理页44bit+权限10bit 的数据
|
||||
if i == 2 {
|
||||
result = Some(pte);
|
||||
break;
|
||||
}
|
||||
// 如果没有中间节点
|
||||
if pte.is_valid() == false {
|
||||
let frame = frame_alloc().unwrap();
|
||||
*pte = PageTableEntry::from(frame.ppn, PTEFlags::V);
|
||||
self.frames.push(frame);
|
||||
}
|
||||
ppn = pte.ppn();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
// 和 find_pte_create 差不多, 只不过这个不创建中间节点, 缺中间节点立马就返回
|
||||
fn find_pte(&self, vpn: VirtPageNum) -> Option<&mut PageTableEntry> {
|
||||
let idxs = vpn.indexes();
|
||||
let mut ppn = self.root_ppn;
|
||||
let mut result: Option<&mut PageTableEntry> = None;
|
||||
for (i, idx) in idxs.iter().enumerate() {
|
||||
let pte = &mut ppn.get_pte_array()[*idx];
|
||||
if i == 2 {
|
||||
result = Some(pte);
|
||||
break;
|
||||
}
|
||||
if pte.is_valid() == false {
|
||||
return None;
|
||||
}
|
||||
ppn = pte.ppn();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
// 把虚拟页 映射到页表中, 并创建一个 物理页, 然后把物理页ppn组成pte的格式, copy到 虚拟页对应的页表项内
|
||||
pub fn map(&mut self, vpn: VirtPageNum, ppn: PhysPageNum, flags: PTEFlags) {
|
||||
// 查找vpn 没有中间节点就创建出来
|
||||
let pte = self.find_pte_create(vpn).unwrap();
|
||||
assert!(!pte.is_valid(), "vpn {:?} is mapped before mapping", vpn.0);
|
||||
*pte = PageTableEntry::from(ppn, flags | PTEFlags::V);
|
||||
}
|
||||
|
||||
// 把虚拟页 取消映射(注意, 取消之后, 外部一定要 把该虚拟页对应的物理页帧 还给全局的物理页帧管理器)
|
||||
pub fn unmap(&mut self, vpn: VirtPageNum) {
|
||||
let pte = self.find_pte(vpn).unwrap();
|
||||
assert!(pte.is_valid(), "vpn {:?} is invalid before unmapping", vpn.0);
|
||||
*pte = PageTableEntry::new();
|
||||
}
|
||||
|
||||
// 根据虚拟页号, 找到页表中对应的pte
|
||||
pub fn get_pte(&self, vpn: VirtPageNum) -> Option<PageTableEntry> {
|
||||
self.find_pte(vpn).map(|pte| *pte)
|
||||
}
|
||||
}
|
||||
|
||||
// 根据token得到用户应用的页表, 并根据ptr 和len 在页表中找到指定的数据
|
||||
pub fn translated_byte_buffer(token: usize, ptr: *const u8, len: usize) -> Vec<&'static mut [u8]> {
|
||||
// 根据寄存器token, 得到用户页表
|
||||
let page_table = PageTable::from_token(token);
|
||||
|
||||
// 用户空间指定数据 的 逻辑起始位置
|
||||
let mut start = ptr as usize;
|
||||
// 用户空间指定数据的 逻辑结束位置
|
||||
let end = start + len;
|
||||
|
||||
// 循环 逻辑的起始和结束位置, 根据页表,在物理页中寻找数据
|
||||
// 可能 start 和end 跨了很多页, 需要找到每一页并偏移
|
||||
let mut v = Vec::new();
|
||||
while start < end {
|
||||
// 逻辑起始位置对应实际的物理页帧
|
||||
let start_va = VirtAddr::from(start);
|
||||
let mut vpn = start_va.floor();
|
||||
let ppn = page_table.get_pte(vpn).unwrap().ppn();
|
||||
|
||||
// 当前start页 的结束页 就是下一个逻辑页 start+1 的位置
|
||||
vpn = (vpn.0+1).into();
|
||||
let mut end_va: VirtAddr = vpn.into();
|
||||
|
||||
// 找到 比较小的结束位置
|
||||
end_va = end_va.min(VirtAddr::from(end));
|
||||
|
||||
// 如果 不是最后一页, 就找到当前物理页的所有4096字节 进行拷贝
|
||||
if end_va.page_offset() == 0 {
|
||||
v.push(&mut ppn.get_bytes_array()[start_va.page_offset()..]);
|
||||
} else {
|
||||
// 如果是最后一页 就 拷贝到最后的位置
|
||||
v.push(&mut ppn.get_bytes_array()[start_va.page_offset()..end_va.page_offset()]);
|
||||
}
|
||||
|
||||
// 状态转移, 循环 拷贝下一个虚拟逻辑页
|
||||
start = end_va.into();
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
|
@ -1,45 +0,0 @@
|
||||
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 _);
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
//! Synchronization and interior mutability primitives
|
||||
|
||||
mod up;
|
||||
pub use up::UPSafeCell;
|
@ -1,31 +0,0 @@
|
||||
//! 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()
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
//! File and filesystem-related syscalls
|
||||
|
||||
use crate::mm::page_table::translated_byte_buffer;
|
||||
use crate::print;
|
||||
use crate::task::TASK_MANAGER;
|
||||
|
||||
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 buffers = translated_byte_buffer(TASK_MANAGER.get_current_token(), buf, len);
|
||||
for buffer in buffers {
|
||||
print!("{}", core::str::from_utf8(buffer).unwrap());
|
||||
}
|
||||
len as isize
|
||||
}
|
||||
_ => {
|
||||
panic!("Unsupported fd in sys_write!");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
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::*;
|
||||
use crate::println;
|
||||
|
||||
/// 根据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(),
|
||||
SYSCALL_SBRK => sys_sbrk(args[0] as i32),
|
||||
_ => panic!("Unsupported syscall_id: {}", syscall_id),
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
//! App management syscalls
|
||||
// use crate::batch::run_next_app;
|
||||
use crate::println;
|
||||
use crate::task::{change_program_brk, 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
|
||||
}
|
||||
|
||||
// 根据传入的 size 对当前堆进行扩容和缩小, 返回值为 失败 或者 申请的空间的起始位置
|
||||
pub fn sys_sbrk(size: i32) -> isize {
|
||||
if let Some(old_brk) = change_program_brk(size) {
|
||||
old_brk as isize
|
||||
} else {
|
||||
-1
|
||||
}
|
||||
}
|
@ -1,44 +0,0 @@
|
||||
use crate::trap::trap_return;
|
||||
|
||||
// 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],
|
||||
}
|
||||
}
|
||||
|
||||
/// 根据用户当前内核栈做的栈顶 构造一个 任务上下文, 并把 trap_return 设置为 switch切换 ret的返回地址
|
||||
pub fn goto_trap_return(kstack_ptr: usize) -> Self {
|
||||
Self {
|
||||
ra: trap_return as usize, // 这里是 在内核空间的 函数地址 (当然 task context 只有在内核态才是可见的)
|
||||
sp: kstack_ptr,
|
||||
s: [0; 12],
|
||||
}
|
||||
}
|
||||
}
|
@ -1,235 +0,0 @@
|
||||
use lazy_static::lazy_static;
|
||||
use alloc::vec::Vec;
|
||||
use crate::config::MAX_APP_NUM;
|
||||
use crate::sync::UPSafeCell;
|
||||
use crate::task::task::{TaskControlBlock, TaskStatus};
|
||||
use crate::loader::{get_num_app, get_app_data};
|
||||
use crate::println;
|
||||
use crate::task::context::TaskContext;
|
||||
use crate::task::switch::__switch;
|
||||
use crate::timer::{get_time_ms, get_time_us};
|
||||
use crate::trap::TrapContext;
|
||||
|
||||
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();
|
||||
|
||||
println!("start run app");
|
||||
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
|
||||
}
|
||||
|
||||
// 得到当前正在执行用户应用的 trap context
|
||||
pub fn get_current_trap_cx(&self) -> &'static mut TrapContext {
|
||||
let inner = self.inner.exclusive_access();
|
||||
inner.tasks[inner.current_task_id].get_trap_cx()
|
||||
}
|
||||
|
||||
// 得到当前正在只用的用户应用的 页表
|
||||
pub fn get_current_token(&self) -> usize {
|
||||
let inner = self.inner.exclusive_access();
|
||||
inner.tasks[inner.current_task_id].get_user_token()
|
||||
}
|
||||
|
||||
// 扩张/缩减, 当前应用的地址空间中的堆段, 指定字节的数据
|
||||
pub fn change_current_program_brk(&self, size: i32) -> Option<usize> {
|
||||
let mut inner = self.inner.exclusive_access();
|
||||
let current_task_id = inner.current_task_id;
|
||||
inner.tasks[current_task_id].change_program_brk(size)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 不公开的结构体, 有一个MAX_APP_NUM大小的数组, 用来保存TCB, 和当前任务的的TCB的下标
|
||||
struct TaskManagerInner {
|
||||
tasks: Vec<TaskControlBlock>,
|
||||
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 = {
|
||||
println!("init TASK_MANAGER");
|
||||
let num_app = get_num_app();
|
||||
println!("num_app = {}", num_app);
|
||||
let mut tasks: Vec<TaskControlBlock> = Vec::new();
|
||||
|
||||
for i in 0..num_app {
|
||||
// 得到elf 的二进制数据
|
||||
let app_elf_data = get_app_data(i);
|
||||
// 根据二进制数据创建 TCB
|
||||
let tcb = TaskControlBlock::from(app_elf_data, i);
|
||||
tasks.push(tcb);
|
||||
}
|
||||
TaskManager {
|
||||
num_app,
|
||||
inner: unsafe {
|
||||
UPSafeCell::new(TaskManagerInner {
|
||||
tasks,
|
||||
stop_clock_time: 0,
|
||||
current_task_id: 0, // 从第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();
|
||||
}
|
||||
|
||||
// 扩张/缩减, 当前应用的地址空间中的堆段, 指定字节的数据
|
||||
pub fn change_program_brk(size: i32) -> Option<usize> {
|
||||
TASK_MANAGER.change_current_program_brk(size)
|
||||
}
|
||||
|
||||
// 得到当前运行任务的 trap context 的地址
|
||||
pub fn current_trap_cx() -> &'static mut TrapContext {
|
||||
TASK_MANAGER.get_current_trap_cx()
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue