cargo clippy & fmt

This commit is contained in:
Yifan Wu 2022-01-21 14:21:32 -08:00
parent ddaf5fa5f7
commit fff4669596
25 changed files with 139 additions and 130 deletions

View File

@ -12,4 +12,4 @@ lazy_static = { version = "1.4.0", features = ["spin_no_std"] }
[features] [features]
board_qemu = [] board_qemu = []
board_k210 = [] board_k210 = []

View File

@ -1,5 +1,5 @@
use std::fs::{read_dir, File};
use std::io::{Result, Write}; use std::io::{Result, Write};
use std::fs::{File, read_dir};
fn main() { fn main() {
println!("cargo:rerun-if-changed=../user/src/"); println!("cargo:rerun-if-changed=../user/src/");
@ -22,12 +22,16 @@ fn insert_app_data() -> Result<()> {
.collect(); .collect();
apps.sort(); apps.sort();
writeln!(f, r#" writeln!(
f,
r#"
.align 3 .align 3
.section .data .section .data
.global _num_app .global _num_app
_num_app: _num_app:
.quad {}"#, apps.len())?; .quad {}"#,
apps.len()
)?;
for i in 0..apps.len() { for i in 0..apps.len() {
writeln!(f, r#" .quad app_{}_start"#, i)?; writeln!(f, r#" .quad app_{}_start"#, i)?;
@ -36,13 +40,17 @@ _num_app:
for (idx, app) in apps.iter().enumerate() { for (idx, app) in apps.iter().enumerate() {
println!("app_{}: {}", idx, app); println!("app_{}: {}", idx, app);
writeln!(f, r#" writeln!(
f,
r#"
.section .data .section .data
.global app_{0}_start .global app_{0}_start
.global app_{0}_end .global app_{0}_end
app_{0}_start: app_{0}_start:
.incbin "{2}{1}.bin" .incbin "{2}{1}.bin"
app_{0}_end:"#, idx, app, TARGET_PATH)?; app_{0}_end:"#,
idx, app, TARGET_PATH
)?;
} }
Ok(()) Ok(())
} }

View File

@ -8,4 +8,4 @@ pub const APP_SIZE_LIMIT: usize = 0x20000;
pub const CLOCK_FREQ: usize = 403000000 / 62; pub const CLOCK_FREQ: usize = 403000000 / 62;
#[cfg(feature = "board_qemu")] #[cfg(feature = "board_qemu")]
pub const CLOCK_FREQ: usize = 12500000; pub const CLOCK_FREQ: usize = 12500000;

View File

@ -1,5 +1,5 @@
use core::fmt::{self, Write};
use crate::sbi::console_putchar; use crate::sbi::console_putchar;
use core::fmt::{self, Write};
struct Stdout; struct Stdout;
@ -29,5 +29,3 @@ macro_rules! println {
$crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?));
} }
} }

View File

@ -1,10 +1,15 @@
use core::panic::PanicInfo;
use crate::sbi::shutdown; use crate::sbi::shutdown;
use core::panic::PanicInfo;
#[panic_handler] #[panic_handler]
fn panic(info: &PanicInfo) -> ! { fn panic(info: &PanicInfo) -> ! {
if let Some(location) = info.location() { if let Some(location) = info.location() {
println!("[kernel] Panicked at {}:{} {}", location.file(), location.line(), info.message().unwrap()); println!(
"[kernel] Panicked at {}:{} {}",
location.file(),
location.line(),
info.message().unwrap()
);
} else { } else {
println!("[kernel] Panicked: {}", info.message().unwrap()); println!("[kernel] Panicked: {}", info.message().unwrap());
} }

View File

@ -1,5 +1,5 @@
use crate::trap::TrapContext;
use crate::config::*; use crate::config::*;
use crate::trap::TrapContext;
use core::arch::asm; use core::arch::asm;
#[repr(align(4096))] #[repr(align(4096))]
@ -14,15 +14,13 @@ struct UserStack {
data: [u8; USER_STACK_SIZE], data: [u8; USER_STACK_SIZE],
} }
static KERNEL_STACK: [KernelStack; MAX_APP_NUM] = [ static KERNEL_STACK: [KernelStack; MAX_APP_NUM] = [KernelStack {
KernelStack { data: [0; KERNEL_STACK_SIZE], }; data: [0; KERNEL_STACK_SIZE],
MAX_APP_NUM }; MAX_APP_NUM];
];
static USER_STACK: [UserStack; MAX_APP_NUM] = [ static USER_STACK: [UserStack; MAX_APP_NUM] = [UserStack {
UserStack { data: [0; USER_STACK_SIZE], }; data: [0; USER_STACK_SIZE],
MAX_APP_NUM }; MAX_APP_NUM];
];
impl KernelStack { impl KernelStack {
fn get_sp(&self) -> usize { fn get_sp(&self) -> usize {
@ -30,7 +28,9 @@ impl KernelStack {
} }
pub fn push_context(&self, trap_cx: TrapContext) -> usize { pub fn push_context(&self, trap_cx: TrapContext) -> usize {
let trap_cx_ptr = (self.get_sp() - core::mem::size_of::<TrapContext>()) as *mut TrapContext; let trap_cx_ptr = (self.get_sp() - core::mem::size_of::<TrapContext>()) as *mut TrapContext;
unsafe { *trap_cx_ptr = trap_cx; } unsafe {
*trap_cx_ptr = trap_cx;
}
trap_cx_ptr as usize trap_cx_ptr as usize
} }
} }
@ -46,39 +46,41 @@ fn get_base_i(app_id: usize) -> usize {
} }
pub fn get_num_app() -> usize { pub fn get_num_app() -> usize {
extern "C" { fn _num_app(); } extern "C" {
fn _num_app();
}
unsafe { (_num_app as usize as *const usize).read_volatile() } unsafe { (_num_app as usize as *const usize).read_volatile() }
} }
pub fn load_apps() { pub fn load_apps() {
extern "C" { fn _num_app(); } extern "C" {
fn _num_app();
}
let num_app_ptr = _num_app as usize as *const usize; let num_app_ptr = _num_app as usize as *const usize;
let num_app = get_num_app(); let num_app = get_num_app();
let app_start = unsafe { let app_start = unsafe { core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1) };
core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1)
};
// clear i-cache first // clear i-cache first
unsafe { asm!("fence.i"); } unsafe {
asm!("fence.i");
}
// load apps // load apps
for i in 0..num_app { for i in 0..num_app {
let base_i = get_base_i(i); let base_i = get_base_i(i);
// clear region // clear region
(base_i..base_i + APP_SIZE_LIMIT).for_each(|addr| unsafe { (base_i..base_i + APP_SIZE_LIMIT)
(addr as *mut u8).write_volatile(0) .for_each(|addr| unsafe { (addr as *mut u8).write_volatile(0) });
});
// load app from data section to memory // load app from data section to memory
let src = unsafe { let src = unsafe {
core::slice::from_raw_parts(app_start[i] as *const u8, app_start[i + 1] - app_start[i]) core::slice::from_raw_parts(app_start[i] as *const u8, app_start[i + 1] - app_start[i])
}; };
let dst = unsafe { let dst = unsafe { core::slice::from_raw_parts_mut(base_i as *mut u8, src.len()) };
core::slice::from_raw_parts_mut(base_i as *mut u8, src.len())
};
dst.copy_from_slice(src); dst.copy_from_slice(src);
} }
} }
pub fn init_app_cx(app_id: usize) -> usize { pub fn init_app_cx(app_id: usize) -> usize {
KERNEL_STACK[app_id].push_context( KERNEL_STACK[app_id].push_context(TrapContext::app_init_context(
TrapContext::app_init_context(get_base_i(app_id), USER_STACK[app_id].get_sp()), get_base_i(app_id),
) USER_STACK[app_id].get_sp(),
))
} }

View File

@ -6,15 +6,15 @@ use core::arch::global_asm;
#[macro_use] #[macro_use]
mod console; mod console;
mod lang_items;
mod sbi;
mod syscall;
mod trap;
mod loader;
mod config; mod config;
mod lang_items;
mod loader;
mod sbi;
mod sync;
mod syscall;
mod task; mod task;
mod timer; mod timer;
mod sync; mod trap;
global_asm!(include_str!("entry.asm")); global_asm!(include_str!("entry.asm"));
global_asm!(include_str!("link_app.S")); global_asm!(include_str!("link_app.S"));
@ -25,10 +25,8 @@ fn clear_bss() {
fn ebss(); fn ebss();
} }
unsafe { unsafe {
core::slice::from_raw_parts_mut( core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize)
sbss as usize as *mut u8, .fill(0);
ebss as usize - sbss as usize,
).fill(0);
} }
} }
@ -42,4 +40,4 @@ pub fn rust_main() -> ! {
timer::set_next_trigger(); timer::set_next_trigger();
task::run_first_task(); task::run_first_task();
panic!("Unreachable in rust_main!"); panic!("Unreachable in rust_main!");
} }

View File

@ -43,4 +43,3 @@ pub fn shutdown() -> ! {
sbi_call(SBI_SHUTDOWN, 0, 0, 0); sbi_call(SBI_SHUTDOWN, 0, 0, 0);
panic!("It should shutdown!"); panic!("It should shutdown!");
} }

View File

@ -1,3 +1,3 @@
mod up; mod up;
pub use up::UPSafeCell; pub use up::UPSafeCell;

View File

@ -18,10 +18,12 @@ impl<T> UPSafeCell<T> {
/// User is responsible to guarantee that inner struct is only used in /// User is responsible to guarantee that inner struct is only used in
/// uniprocessor. /// uniprocessor.
pub unsafe fn new(value: T) -> Self { pub unsafe fn new(value: T) -> Self {
Self { inner: RefCell::new(value) } Self {
inner: RefCell::new(value),
}
} }
/// Panic if the data has been borrowed. /// Panic if the data has been borrowed.
pub fn exclusive_access(&self) -> RefMut<'_, T> { pub fn exclusive_access(&self) -> RefMut<'_, T> {
self.inner.borrow_mut() self.inner.borrow_mut()
} }
} }

View File

@ -7,9 +7,9 @@ pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
let str = core::str::from_utf8(slice).unwrap(); let str = core::str::from_utf8(slice).unwrap();
print!("{}", str); print!("{}", str);
len as isize len as isize
}, }
_ => { _ => {
panic!("Unsupported fd in sys_write!"); panic!("Unsupported fd in sys_write!");
} }
} }
} }

View File

@ -18,4 +18,3 @@ pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize {
_ => panic!("Unsupported syscall_id: {}", syscall_id), _ => panic!("Unsupported syscall_id: {}", syscall_id),
} }
} }

View File

@ -1,7 +1,4 @@
use crate::task::{ use crate::task::{exit_current_and_run_next, suspend_current_and_run_next};
suspend_current_and_run_next,
exit_current_and_run_next,
};
use crate::timer::get_time_ms; use crate::timer::get_time_ms;
pub fn sys_exit(exit_code: i32) -> ! { pub fn sys_exit(exit_code: i32) -> ! {
@ -17,4 +14,4 @@ pub fn sys_yield() -> isize {
pub fn sys_get_time() -> isize { pub fn sys_get_time() -> isize {
get_time_ms() as isize get_time_ms() as isize
} }

View File

@ -15,7 +15,9 @@ impl TaskContext {
} }
} }
pub fn goto_restore(kstack_ptr: usize) -> Self { pub fn goto_restore(kstack_ptr: usize) -> Self {
extern "C" { fn __restore(); } extern "C" {
fn __restore();
}
Self { Self {
ra: __restore as usize, ra: __restore as usize,
sp: kstack_ptr, sp: kstack_ptr,
@ -23,4 +25,3 @@ impl TaskContext {
} }
} }
} }

View File

@ -4,10 +4,10 @@ mod task;
use crate::config::MAX_APP_NUM; use crate::config::MAX_APP_NUM;
use crate::loader::{get_num_app, init_app_cx}; use crate::loader::{get_num_app, init_app_cx};
use crate::sync::UPSafeCell;
use lazy_static::*; use lazy_static::*;
use switch::__switch; use switch::__switch;
use task::{TaskControlBlock, TaskStatus}; use task::{TaskControlBlock, TaskStatus};
use crate::sync::UPSafeCell;
pub use context::TaskContext; pub use context::TaskContext;
@ -24,23 +24,22 @@ struct TaskManagerInner {
lazy_static! { lazy_static! {
pub static ref TASK_MANAGER: TaskManager = { pub static ref TASK_MANAGER: TaskManager = {
let num_app = get_num_app(); let num_app = get_num_app();
let mut tasks = [ let mut tasks = [TaskControlBlock {
TaskControlBlock { task_cx: TaskContext::zero_init(),
task_cx: TaskContext::zero_init(), task_status: TaskStatus::UnInit,
task_status: TaskStatus::UnInit }; MAX_APP_NUM];
};
MAX_APP_NUM
];
for i in 0..num_app { for i in 0..num_app {
tasks[i].task_cx = TaskContext::goto_restore(init_app_cx(i)); tasks[i].task_cx = TaskContext::goto_restore(init_app_cx(i));
tasks[i].task_status = TaskStatus::Ready; tasks[i].task_status = TaskStatus::Ready;
} }
TaskManager { TaskManager {
num_app, num_app,
inner: unsafe { UPSafeCell::new(TaskManagerInner { inner: unsafe {
tasks, UPSafeCell::new(TaskManagerInner {
current_task: 0, tasks,
})}, current_task: 0,
})
},
} }
}; };
} }
@ -55,10 +54,7 @@ impl TaskManager {
let mut _unused = TaskContext::zero_init(); let mut _unused = TaskContext::zero_init();
// before this, we should drop local variables that must be dropped manually // before this, we should drop local variables that must be dropped manually
unsafe { unsafe {
__switch( __switch(&mut _unused as *mut TaskContext, next_task_cx_ptr);
&mut _unused as *mut TaskContext,
next_task_cx_ptr,
);
} }
panic!("unreachable in run_first_task!"); panic!("unreachable in run_first_task!");
} }
@ -80,9 +76,7 @@ impl TaskManager {
let current = inner.current_task; let current = inner.current_task;
(current + 1..current + self.num_app + 1) (current + 1..current + self.num_app + 1)
.map(|id| id % self.num_app) .map(|id| id % self.num_app)
.find(|id| { .find(|id| inner.tasks[*id].task_status == TaskStatus::Ready)
inner.tasks[*id].task_status == TaskStatus::Ready
})
} }
fn run_next_task(&self) { fn run_next_task(&self) {
@ -96,10 +90,7 @@ impl TaskManager {
drop(inner); drop(inner);
// before this, we should drop local variables that must be dropped manually // before this, we should drop local variables that must be dropped manually
unsafe { unsafe {
__switch( __switch(current_task_cx_ptr, next_task_cx_ptr);
current_task_cx_ptr,
next_task_cx_ptr,
);
} }
// go back to user mode // go back to user mode
} else { } else {
@ -132,4 +123,4 @@ pub fn suspend_current_and_run_next() {
pub fn exit_current_and_run_next() { pub fn exit_current_and_run_next() {
mark_current_exited(); mark_current_exited();
run_next_task(); run_next_task();
} }

View File

@ -4,8 +4,5 @@ use core::arch::global_asm;
global_asm!(include_str!("switch.S")); global_asm!(include_str!("switch.S"));
extern "C" { extern "C" {
pub fn __switch( pub fn __switch(current_task_cx_ptr: *mut TaskContext, next_task_cx_ptr: *const TaskContext);
current_task_cx_ptr: *mut TaskContext,
next_task_cx_ptr: *const TaskContext
);
} }

View File

@ -12,4 +12,4 @@ pub enum TaskStatus {
Ready, Ready,
Running, Running,
Exited, Exited,
} }

View File

@ -1,6 +1,6 @@
use riscv::register::time;
use crate::sbi::set_timer;
use crate::config::CLOCK_FREQ; use crate::config::CLOCK_FREQ;
use crate::sbi::set_timer;
use riscv::register::time;
const TICKS_PER_SEC: usize = 100; const TICKS_PER_SEC: usize = 100;
const MSEC_PER_SEC: usize = 1000; const MSEC_PER_SEC: usize = 1000;

View File

@ -1,4 +1,4 @@
use riscv::register::sstatus::{Sstatus, self, SPP}; use riscv::register::sstatus::{self, Sstatus, SPP};
#[repr(C)] #[repr(C)]
pub struct TrapContext { pub struct TrapContext {
@ -8,7 +8,9 @@ pub struct TrapContext {
} }
impl TrapContext { impl TrapContext {
pub fn set_sp(&mut self, sp: usize) { self.x[2] = sp; } pub fn set_sp(&mut self, sp: usize) {
self.x[2] = sp;
}
pub fn app_init_context(entry: usize, sp: usize) -> Self { pub fn app_init_context(entry: usize, sp: usize) -> Self {
let mut sstatus = sstatus::read(); let mut sstatus = sstatus::read();
sstatus.set_spp(SPP::User); sstatus.set_spp(SPP::User);

View File

@ -1,36 +1,30 @@
mod context; mod context;
use riscv::register::{
mtvec::TrapMode,
stvec,
scause::{
self,
Trap,
Exception,
Interrupt,
},
stval,
sie,
};
use crate::syscall::syscall; use crate::syscall::syscall;
use crate::task::{ use crate::task::{exit_current_and_run_next, suspend_current_and_run_next};
exit_current_and_run_next,
suspend_current_and_run_next,
};
use crate::timer::set_next_trigger; use crate::timer::set_next_trigger;
use core::arch::global_asm; use core::arch::global_asm;
use riscv::register::{
mtvec::TrapMode,
scause::{self, Exception, Interrupt, Trap},
sie, stval, stvec,
};
global_asm!(include_str!("trap.S")); global_asm!(include_str!("trap.S"));
pub fn init() { pub fn init() {
extern "C" { fn __alltraps(); } extern "C" {
fn __alltraps();
}
unsafe { unsafe {
stvec::write(__alltraps as usize, TrapMode::Direct); stvec::write(__alltraps as usize, TrapMode::Direct);
} }
} }
pub fn enable_timer_interrupt() { pub fn enable_timer_interrupt() {
unsafe { sie::set_stimer(); } unsafe {
sie::set_stimer();
}
} }
#[no_mangle] #[no_mangle]
@ -42,8 +36,7 @@ pub fn trap_handler(cx: &mut TrapContext) -> &mut TrapContext {
cx.sepc += 4; cx.sepc += 4;
cx.x[10] = syscall(cx.x[17], [cx.x[10], cx.x[11], cx.x[12]]) as usize; cx.x[10] = syscall(cx.x[17], [cx.x[10], cx.x[11], cx.x[12]]) as usize;
} }
Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StorePageFault) => {
Trap::Exception(Exception::StorePageFault) => {
println!("[kernel] PageFault in application, bad addr = {:#x}, bad instruction = {:#x}, kernel killed it.", stval, cx.sepc); println!("[kernel] PageFault in application, bad addr = {:#x}, bad instruction = {:#x}, kernel killed it.", stval, cx.sepc);
exit_current_and_run_next(); exit_current_and_run_next();
} }
@ -56,7 +49,11 @@ pub fn trap_handler(cx: &mut TrapContext) -> &mut TrapContext {
suspend_current_and_run_next(); suspend_current_and_run_next();
} }
_ => { _ => {
panic!("Unsupported trap {:?}, stval = {:#x}!", scause.cause(), stval); panic!(
"Unsupported trap {:?}, stval = {:#x}!",
scause.cause(),
stval
);
} }
} }
cx cx

View File

@ -25,4 +25,4 @@ fn main() -> i32 {
println!("{}^{} = {}(MOD {})", p, iter, s[cur], m); println!("{}^{} = {}(MOD {})", p, iter, s[cur], m);
println!("Test power_3 OK!"); println!("Test power_3 OK!");
0 0
} }

View File

@ -15,4 +15,4 @@ fn main() -> i32 {
} }
println!("Test sleep OK!"); println!("Test sleep OK!");
0 0
} }

View File

@ -1,5 +1,5 @@
use core::fmt::{self, Write};
use super::write; use super::write;
use core::fmt::{self, Write};
struct Stdout; struct Stdout;
@ -28,4 +28,4 @@ macro_rules! println {
($fmt: literal $(, $($arg: tt)+)?) => { ($fmt: literal $(, $($arg: tt)+)?) => {
$crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?));
} }
} }

View File

@ -2,9 +2,14 @@
fn panic_handler(panic_info: &core::panic::PanicInfo) -> ! { fn panic_handler(panic_info: &core::panic::PanicInfo) -> ! {
let err = panic_info.message().unwrap(); let err = panic_info.message().unwrap();
if let Some(location) = panic_info.location() { if let Some(location) = panic_info.location() {
println!("Panicked at {}:{}, {}", location.file(), location.line(), err); println!(
"Panicked at {}:{}, {}",
location.file(),
location.line(),
err
);
} else { } else {
println!("Panicked: {}", err); println!("Panicked: {}", err);
} }
loop {} loop {}
} }

View File

@ -4,8 +4,8 @@
#[macro_use] #[macro_use]
pub mod console; pub mod console;
mod syscall;
mod lang_items; mod lang_items;
mod syscall;
#[no_mangle] #[no_mangle]
#[link_section = ".text.entry"] #[link_section = ".text.entry"]
@ -26,14 +26,22 @@ fn clear_bss() {
fn start_bss(); fn start_bss();
fn end_bss(); fn end_bss();
} }
(start_bss as usize..end_bss as usize).for_each(|addr| { (start_bss as usize..end_bss as usize).for_each(|addr| unsafe {
unsafe { (addr as *mut u8).write_volatile(0); } (addr as *mut u8).write_volatile(0);
}); });
} }
use syscall::*; use syscall::*;
pub fn write(fd: usize, buf: &[u8]) -> isize { sys_write(fd, buf) } pub fn write(fd: usize, buf: &[u8]) -> isize {
pub fn exit(exit_code: i32) -> isize { sys_exit(exit_code) } sys_write(fd, buf)
pub fn yield_() -> isize { sys_yield() } }
pub fn get_time() -> isize { sys_get_time() } pub fn exit(exit_code: i32) -> isize {
sys_exit(exit_code)
}
pub fn yield_() -> isize {
sys_yield()
}
pub fn get_time() -> isize {
sys_get_time()
}