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

View File

@ -8,4 +8,4 @@ pub const APP_SIZE_LIMIT: usize = 0x20000;
pub const CLOCK_FREQ: usize = 403000000 / 62;
#[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 core::fmt::{self, Write};
struct Stdout;
@ -29,5 +29,3 @@ macro_rules! println {
$crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?));
}
}

View File

@ -1,10 +1,15 @@
use core::panic::PanicInfo;
use crate::sbi::shutdown;
use core::panic::PanicInfo;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
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 {
println!("[kernel] Panicked: {}", info.message().unwrap());
}

View File

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

View File

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

View File

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

View File

@ -1,3 +1,3 @@
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
/// uniprocessor.
pub unsafe fn new(value: T) -> Self {
Self { inner: RefCell::new(value) }
Self {
inner: RefCell::new(value),
}
}
/// Panic if the data has been borrowed.
pub fn exclusive_access(&self) -> RefMut<'_, T> {
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();
print!("{}", str);
len as isize
},
}
_ => {
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),
}
}

View File

@ -1,7 +1,4 @@
use crate::task::{
suspend_current_and_run_next,
exit_current_and_run_next,
};
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) -> ! {
@ -17,4 +14,4 @@ pub fn sys_yield() -> isize {
pub fn sys_get_time() -> isize {
get_time_ms() as isize
}
}

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
use riscv::register::time;
use crate::sbi::set_timer;
use crate::config::CLOCK_FREQ;
use crate::sbi::set_timer;
use riscv::register::time;
const TICKS_PER_SEC: usize = 100;
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)]
pub struct TrapContext {
@ -8,7 +8,9 @@ pub struct 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 {
let mut sstatus = sstatus::read();
sstatus.set_spp(SPP::User);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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