cargo clippy & fmt

This commit is contained in:
Yifan Wu 2022-01-21 14:23:53 -08:00
parent e3601918ba
commit 3a120122ba
29 changed files with 361 additions and 289 deletions

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,14 +40,18 @@ _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
.align 3 .align 3
app_{0}_start: app_{0}_start:
.incbin "{2}{1}" .incbin "{2}{1}"
app_{0}_end:"#, idx, app, TARGET_PATH)?; app_{0}_end:"#,
idx, app, TARGET_PATH
)?;
} }
Ok(()) Ok(())
} }

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,20 +1,22 @@
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 get_app_data(app_id: usize) -> &'static [u8] { pub fn get_app_data(app_id: usize) -> &'static [u8] {
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)
};
assert!(app_id < num_app); assert!(app_id < num_app);
unsafe { unsafe {
core::slice::from_raw_parts( core::slice::from_raw_parts(
app_start[app_id] as *const u8, app_start[app_id] as *const u8,
app_start[app_id + 1] - app_start[app_id] app_start[app_id + 1] - app_start[app_id],
) )
} }
} }

View file

@ -10,16 +10,16 @@ extern crate bitflags;
#[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 mm;
mod sbi;
mod sync;
mod syscall;
mod task; mod task;
mod timer; mod timer;
mod sync; mod trap;
mod mm;
use core::arch::global_asm; use core::arch::global_asm;
@ -32,10 +32,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);
} }
} }

View file

@ -1,5 +1,5 @@
use crate::config::{PAGE_SIZE, PAGE_SIZE_BITS};
use super::PageTableEntry; use super::PageTableEntry;
use crate::config::{PAGE_SIZE, PAGE_SIZE_BITS};
use core::fmt::{self, Debug, Formatter}; use core::fmt::{self, Debug, Formatter};
const PA_WIDTH_SV39: usize = 56; const PA_WIDTH_SV39: usize = 56;
@ -48,35 +48,59 @@ impl Debug for PhysPageNum {
/// usize -> T: usize.into() /// usize -> T: usize.into()
impl From<usize> for PhysAddr { impl From<usize> for PhysAddr {
fn from(v: usize) -> Self { Self(v & ( (1 << PA_WIDTH_SV39) - 1 )) } fn from(v: usize) -> Self {
Self(v & ((1 << PA_WIDTH_SV39) - 1))
}
} }
impl From<usize> for PhysPageNum { impl From<usize> for PhysPageNum {
fn from(v: usize) -> Self { Self(v & ( (1 << PPN_WIDTH_SV39) - 1 )) } fn from(v: usize) -> Self {
Self(v & ((1 << PPN_WIDTH_SV39) - 1))
}
} }
impl From<usize> for VirtAddr { impl From<usize> for VirtAddr {
fn from(v: usize) -> Self { Self(v & ( (1 << VA_WIDTH_SV39) - 1 )) } fn from(v: usize) -> Self {
Self(v & ((1 << VA_WIDTH_SV39) - 1))
}
} }
impl From<usize> for VirtPageNum { impl From<usize> for VirtPageNum {
fn from(v: usize) -> Self { Self(v & ( (1 << VPN_WIDTH_SV39) - 1 )) } fn from(v: usize) -> Self {
Self(v & ((1 << VPN_WIDTH_SV39) - 1))
}
} }
impl From<PhysAddr> for usize { impl From<PhysAddr> for usize {
fn from(v: PhysAddr) -> Self { v.0 } fn from(v: PhysAddr) -> Self {
v.0
}
} }
impl From<PhysPageNum> for usize { impl From<PhysPageNum> for usize {
fn from(v: PhysPageNum) -> Self { v.0 } fn from(v: PhysPageNum) -> Self {
v.0
}
} }
impl From<VirtAddr> for usize { impl From<VirtAddr> for usize {
fn from(v: VirtAddr) -> Self { v.0 } fn from(v: VirtAddr) -> Self {
v.0
}
} }
impl From<VirtPageNum> for usize { impl From<VirtPageNum> for usize {
fn from(v: VirtPageNum) -> Self { v.0 } fn from(v: VirtPageNum) -> Self {
v.0
}
} }
impl VirtAddr { impl VirtAddr {
pub fn floor(&self) -> VirtPageNum { VirtPageNum(self.0 / PAGE_SIZE) } pub fn floor(&self) -> VirtPageNum {
pub fn ceil(&self) -> VirtPageNum { VirtPageNum((self.0 - 1 + PAGE_SIZE) / PAGE_SIZE) } VirtPageNum(self.0 / PAGE_SIZE)
pub fn page_offset(&self) -> usize { self.0 & (PAGE_SIZE - 1) } }
pub fn aligned(&self) -> bool { self.page_offset() == 0 } pub fn ceil(&self) -> VirtPageNum {
VirtPageNum((self.0 - 1 + PAGE_SIZE) / PAGE_SIZE)
}
pub fn page_offset(&self) -> usize {
self.0 & (PAGE_SIZE - 1)
}
pub fn aligned(&self) -> bool {
self.page_offset() == 0
}
} }
impl From<VirtAddr> for VirtPageNum { impl From<VirtAddr> for VirtPageNum {
fn from(v: VirtAddr) -> Self { fn from(v: VirtAddr) -> Self {
@ -85,13 +109,23 @@ impl From<VirtAddr> for VirtPageNum {
} }
} }
impl From<VirtPageNum> for VirtAddr { impl From<VirtPageNum> for VirtAddr {
fn from(v: VirtPageNum) -> Self { Self(v.0 << PAGE_SIZE_BITS) } fn from(v: VirtPageNum) -> Self {
Self(v.0 << PAGE_SIZE_BITS)
}
} }
impl PhysAddr { impl PhysAddr {
pub fn floor(&self) -> PhysPageNum { PhysPageNum(self.0 / PAGE_SIZE) } pub fn floor(&self) -> PhysPageNum {
pub fn ceil(&self) -> PhysPageNum { PhysPageNum((self.0 - 1 + PAGE_SIZE) / PAGE_SIZE) } PhysPageNum(self.0 / PAGE_SIZE)
pub fn page_offset(&self) -> usize { self.0 & (PAGE_SIZE - 1) } }
pub fn aligned(&self) -> bool { self.page_offset() == 0 } pub fn ceil(&self) -> PhysPageNum {
PhysPageNum((self.0 - 1 + PAGE_SIZE) / PAGE_SIZE)
}
pub fn page_offset(&self) -> usize {
self.0 & (PAGE_SIZE - 1)
}
pub fn aligned(&self) -> bool {
self.page_offset() == 0
}
} }
impl From<PhysAddr> for PhysPageNum { impl From<PhysAddr> for PhysPageNum {
fn from(v: PhysAddr) -> Self { fn from(v: PhysAddr) -> Self {
@ -100,7 +134,9 @@ impl From<PhysAddr> for PhysPageNum {
} }
} }
impl From<PhysPageNum> for PhysAddr { impl From<PhysPageNum> for PhysAddr {
fn from(v: PhysPageNum) -> Self { Self(v.0 << PAGE_SIZE_BITS) } fn from(v: PhysPageNum) -> Self {
Self(v.0 << PAGE_SIZE_BITS)
}
} }
impl VirtPageNum { impl VirtPageNum {
@ -118,21 +154,15 @@ impl VirtPageNum {
impl PhysPageNum { impl PhysPageNum {
pub fn get_pte_array(&self) -> &'static mut [PageTableEntry] { pub fn get_pte_array(&self) -> &'static mut [PageTableEntry] {
let pa: PhysAddr = self.clone().into(); let pa: PhysAddr = self.clone().into();
unsafe { unsafe { core::slice::from_raw_parts_mut(pa.0 as *mut PageTableEntry, 512) }
core::slice::from_raw_parts_mut(pa.0 as *mut PageTableEntry, 512)
}
} }
pub fn get_bytes_array(&self) -> &'static mut [u8] { pub fn get_bytes_array(&self) -> &'static mut [u8] {
let pa: PhysAddr = self.clone().into(); let pa: PhysAddr = self.clone().into();
unsafe { unsafe { core::slice::from_raw_parts_mut(pa.0 as *mut u8, 4096) }
core::slice::from_raw_parts_mut(pa.0 as *mut u8, 4096)
}
} }
pub fn get_mut<T>(&self) -> &'static mut T { pub fn get_mut<T>(&self) -> &'static mut T {
let pa: PhysAddr = self.clone().into(); let pa: PhysAddr = self.clone().into();
unsafe { unsafe { (pa.0 as *mut T).as_mut().unwrap() }
(pa.0 as *mut T).as_mut().unwrap()
}
} }
} }
@ -146,41 +176,57 @@ impl StepByOne for VirtPageNum {
} }
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct SimpleRange<T> where pub struct SimpleRange<T>
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, { where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
l: T, l: T,
r: T, r: T,
} }
impl<T> SimpleRange<T> where impl<T> SimpleRange<T>
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, { where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
pub fn new(start: T, end: T) -> Self { pub fn new(start: T, end: T) -> Self {
assert!(start <= end, "start {:?} > end {:?}!", start, end); assert!(start <= end, "start {:?} > end {:?}!", start, end);
Self { l: start, r: end } Self { l: start, r: end }
} }
pub fn get_start(&self) -> T { self.l } pub fn get_start(&self) -> T {
pub fn get_end(&self) -> T { self.r } self.l
}
pub fn get_end(&self) -> T {
self.r
}
} }
impl<T> IntoIterator for SimpleRange<T> where impl<T> IntoIterator for SimpleRange<T>
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, { where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
type Item = T; type Item = T;
type IntoIter = SimpleRangeIterator<T>; type IntoIter = SimpleRangeIterator<T>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
SimpleRangeIterator::new(self.l, self.r) SimpleRangeIterator::new(self.l, self.r)
} }
} }
pub struct SimpleRangeIterator<T> where pub struct SimpleRangeIterator<T>
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, { where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
current: T, current: T,
end: T, end: T,
} }
impl<T> SimpleRangeIterator<T> where impl<T> SimpleRangeIterator<T>
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, { where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
pub fn new(l: T, r: T) -> Self { pub fn new(l: T, r: T) -> Self {
Self { current: l, end: r, } Self { current: l, end: r }
} }
} }
impl<T> Iterator for SimpleRangeIterator<T> where impl<T> Iterator for SimpleRangeIterator<T>
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, { where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
type Item = T; type Item = T;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
if self.current == self.end { if self.current == self.end {

View file

@ -1,9 +1,9 @@
use super::{PhysAddr, PhysPageNum}; use super::{PhysAddr, PhysPageNum};
use alloc::vec::Vec;
use crate::sync::UPSafeCell;
use crate::config::MEMORY_END; use crate::config::MEMORY_END;
use lazy_static::*; use crate::sync::UPSafeCell;
use alloc::vec::Vec;
use core::fmt::{self, Debug, Formatter}; use core::fmt::{self, Debug, Formatter};
use lazy_static::*;
pub struct FrameTracker { pub struct FrameTracker {
pub ppn: PhysPageNum, pub ppn: PhysPageNum,
@ -61,22 +61,17 @@ impl FrameAllocator for StackFrameAllocator {
fn alloc(&mut self) -> Option<PhysPageNum> { fn alloc(&mut self) -> Option<PhysPageNum> {
if let Some(ppn) = self.recycled.pop() { if let Some(ppn) = self.recycled.pop() {
Some(ppn.into()) Some(ppn.into())
} else if self.current == self.end {
None
} else { } else {
if self.current == self.end { self.current += 1;
None Some((self.current - 1).into())
} else {
self.current += 1;
Some((self.current - 1).into())
}
} }
} }
fn dealloc(&mut self, ppn: PhysPageNum) { fn dealloc(&mut self, ppn: PhysPageNum) {
let ppn = ppn.0; let ppn = ppn.0;
// validity check // validity check
if ppn >= self.current || self.recycled if ppn >= self.current || self.recycled.iter().find(|&v| *v == ppn).is_some() {
.iter()
.find(|&v| {*v == ppn})
.is_some() {
panic!("Frame ppn={:#x} has not been allocated!", ppn); panic!("Frame ppn={:#x} has not been allocated!", ppn);
} }
// recycle // recycle
@ -87,18 +82,18 @@ impl FrameAllocator for StackFrameAllocator {
type FrameAllocatorImpl = StackFrameAllocator; type FrameAllocatorImpl = StackFrameAllocator;
lazy_static! { lazy_static! {
pub static ref FRAME_ALLOCATOR: UPSafeCell<FrameAllocatorImpl> = unsafe { pub static ref FRAME_ALLOCATOR: UPSafeCell<FrameAllocatorImpl> =
UPSafeCell::new(FrameAllocatorImpl::new()) unsafe { UPSafeCell::new(FrameAllocatorImpl::new()) };
};
} }
pub fn init_frame_allocator() { pub fn init_frame_allocator() {
extern "C" { extern "C" {
fn ekernel(); fn ekernel();
} }
FRAME_ALLOCATOR FRAME_ALLOCATOR.exclusive_access().init(
.exclusive_access() PhysAddr::from(ekernel as usize).ceil(),
.init(PhysAddr::from(ekernel as usize).ceil(), PhysAddr::from(MEMORY_END).floor()); PhysAddr::from(MEMORY_END).floor(),
);
} }
pub fn frame_alloc() -> Option<FrameTracker> { pub fn frame_alloc() -> Option<FrameTracker> {
@ -109,9 +104,7 @@ pub fn frame_alloc() -> Option<FrameTracker> {
} }
fn frame_dealloc(ppn: PhysPageNum) { fn frame_dealloc(ppn: PhysPageNum) {
FRAME_ALLOCATOR FRAME_ALLOCATOR.exclusive_access().dealloc(ppn);
.exclusive_access()
.dealloc(ppn);
} }
#[allow(unused)] #[allow(unused)]
@ -130,4 +123,4 @@ pub fn frame_allocator_test() {
} }
drop(v); drop(v);
println!("frame_allocator_test passed!"); println!("frame_allocator_test passed!");
} }

View file

@ -1,5 +1,5 @@
use buddy_system_allocator::LockedHeap;
use crate::config::KERNEL_HEAP_SIZE; use crate::config::KERNEL_HEAP_SIZE;
use buddy_system_allocator::LockedHeap;
#[global_allocator] #[global_allocator]
static HEAP_ALLOCATOR: LockedHeap = LockedHeap::empty(); static HEAP_ALLOCATOR: LockedHeap = LockedHeap::empty();

View file

@ -1,21 +1,15 @@
use super::{PageTable, PageTableEntry, PTEFlags}; use super::{frame_alloc, FrameTracker};
use super::{VirtPageNum, VirtAddr, PhysPageNum, PhysAddr}; use super::{PTEFlags, PageTable, PageTableEntry};
use super::{FrameTracker, frame_alloc}; use super::{PhysAddr, PhysPageNum, VirtAddr, VirtPageNum};
use super::{VPNRange, StepByOne}; use super::{StepByOne, VPNRange};
use alloc::collections::BTreeMap; use crate::config::{MEMORY_END, PAGE_SIZE, TRAMPOLINE, TRAP_CONTEXT, USER_STACK_SIZE};
use alloc::vec::Vec;
use riscv::register::satp;
use alloc::sync::Arc;
use lazy_static::*;
use crate::sync::UPSafeCell; use crate::sync::UPSafeCell;
use crate::config::{ use alloc::collections::BTreeMap;
MEMORY_END, use alloc::sync::Arc;
PAGE_SIZE, use alloc::vec::Vec;
TRAMPOLINE,
TRAP_CONTEXT,
USER_STACK_SIZE
};
use core::arch::asm; use core::arch::asm;
use lazy_static::*;
use riscv::register::satp;
extern "C" { extern "C" {
fn stext(); fn stext();
@ -31,9 +25,8 @@ extern "C" {
} }
lazy_static! { lazy_static! {
pub static ref KERNEL_SPACE: Arc<UPSafeCell<MemorySet>> = Arc::new(unsafe { pub static ref KERNEL_SPACE: Arc<UPSafeCell<MemorySet>> =
UPSafeCell::new(MemorySet::new_kernel() Arc::new(unsafe { UPSafeCell::new(MemorySet::new_kernel()) });
)});
} }
pub struct MemorySet { pub struct MemorySet {
@ -52,13 +45,16 @@ impl MemorySet {
self.page_table.token() self.page_table.token()
} }
/// Assume that no conflicts. /// Assume that no conflicts.
pub fn insert_framed_area(&mut self, start_va: VirtAddr, end_va: VirtAddr, permission: MapPermission) { pub fn insert_framed_area(
self.push(MapArea::new( &mut self,
start_va, start_va: VirtAddr,
end_va, end_va: VirtAddr,
MapType::Framed, permission: MapPermission,
permission, ) {
), None); self.push(
MapArea::new(start_va, end_va, MapType::Framed, permission),
None,
);
} }
fn push(&mut self, mut map_area: MapArea, data: Option<&[u8]>) { fn push(&mut self, mut map_area: MapArea, data: Option<&[u8]>) {
map_area.map(&mut self.page_table); map_area.map(&mut self.page_table);
@ -84,42 +80,60 @@ impl MemorySet {
println!(".text [{:#x}, {:#x})", stext as usize, etext as usize); println!(".text [{:#x}, {:#x})", stext as usize, etext as usize);
println!(".rodata [{:#x}, {:#x})", srodata as usize, erodata as usize); println!(".rodata [{:#x}, {:#x})", srodata as usize, erodata as usize);
println!(".data [{:#x}, {:#x})", sdata as usize, edata 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!(
".bss [{:#x}, {:#x})",
sbss_with_stack as usize, ebss as usize
);
println!("mapping .text section"); println!("mapping .text section");
memory_set.push(MapArea::new( memory_set.push(
(stext as usize).into(), MapArea::new(
(etext as usize).into(), (stext as usize).into(),
MapType::Identical, (etext as usize).into(),
MapPermission::R | MapPermission::X, MapType::Identical,
), None); MapPermission::R | MapPermission::X,
),
None,
);
println!("mapping .rodata section"); println!("mapping .rodata section");
memory_set.push(MapArea::new( memory_set.push(
(srodata as usize).into(), MapArea::new(
(erodata as usize).into(), (srodata as usize).into(),
MapType::Identical, (erodata as usize).into(),
MapPermission::R, MapType::Identical,
), None); MapPermission::R,
),
None,
);
println!("mapping .data section"); println!("mapping .data section");
memory_set.push(MapArea::new( memory_set.push(
(sdata as usize).into(), MapArea::new(
(edata as usize).into(), (sdata as usize).into(),
MapType::Identical, (edata as usize).into(),
MapPermission::R | MapPermission::W, MapType::Identical,
), None); MapPermission::R | MapPermission::W,
),
None,
);
println!("mapping .bss section"); println!("mapping .bss section");
memory_set.push(MapArea::new( memory_set.push(
(sbss_with_stack as usize).into(), MapArea::new(
(ebss as usize).into(), (sbss_with_stack as usize).into(),
MapType::Identical, (ebss as usize).into(),
MapPermission::R | MapPermission::W, MapType::Identical,
), None); MapPermission::R | MapPermission::W,
),
None,
);
println!("mapping physical memory"); println!("mapping physical memory");
memory_set.push(MapArea::new( memory_set.push(
(ekernel as usize).into(), MapArea::new(
MEMORY_END.into(), (ekernel as usize).into(),
MapType::Identical, MEMORY_END.into(),
MapPermission::R | MapPermission::W, MapType::Identical,
), None); MapPermission::R | MapPermission::W,
),
None,
);
memory_set memory_set
} }
/// Include sections in elf and trampoline and TrapContext and user stack, /// Include sections in elf and trampoline and TrapContext and user stack,
@ -142,19 +156,20 @@ impl MemorySet {
let end_va: VirtAddr = ((ph.virtual_addr() + ph.mem_size()) as usize).into(); let end_va: VirtAddr = ((ph.virtual_addr() + ph.mem_size()) as usize).into();
let mut map_perm = MapPermission::U; let mut map_perm = MapPermission::U;
let ph_flags = ph.flags(); let ph_flags = ph.flags();
if ph_flags.is_read() { map_perm |= MapPermission::R; } if ph_flags.is_read() {
if ph_flags.is_write() { map_perm |= MapPermission::W; } map_perm |= MapPermission::R;
if ph_flags.is_execute() { map_perm |= MapPermission::X; } }
let map_area = MapArea::new( if ph_flags.is_write() {
start_va, map_perm |= MapPermission::W;
end_va, }
MapType::Framed, if ph_flags.is_execute() {
map_perm, map_perm |= MapPermission::X;
); }
let map_area = MapArea::new(start_va, end_va, MapType::Framed, map_perm);
max_end_vpn = map_area.vpn_range.get_end(); max_end_vpn = map_area.vpn_range.get_end();
memory_set.push( memory_set.push(
map_area, map_area,
Some(&elf.input[ph.offset() as usize..(ph.offset() + ph.file_size()) as usize]) Some(&elf.input[ph.offset() as usize..(ph.offset() + ph.file_size()) as usize]),
); );
} }
} }
@ -164,20 +179,30 @@ impl MemorySet {
// guard page // guard page
user_stack_bottom += PAGE_SIZE; user_stack_bottom += PAGE_SIZE;
let user_stack_top = user_stack_bottom + USER_STACK_SIZE; let user_stack_top = user_stack_bottom + USER_STACK_SIZE;
memory_set.push(MapArea::new( memory_set.push(
user_stack_bottom.into(), MapArea::new(
user_stack_top.into(), user_stack_bottom.into(),
MapType::Framed, user_stack_top.into(),
MapPermission::R | MapPermission::W | MapPermission::U, MapType::Framed,
), None); MapPermission::R | MapPermission::W | MapPermission::U,
),
None,
);
// map TrapContext // map TrapContext
memory_set.push(MapArea::new( memory_set.push(
TRAP_CONTEXT.into(), MapArea::new(
TRAMPOLINE.into(), TRAP_CONTEXT.into(),
MapType::Framed, TRAMPOLINE.into(),
MapPermission::R | MapPermission::W, MapType::Framed,
), None); MapPermission::R | MapPermission::W,
(memory_set, user_stack_top, elf.header.pt2.entry_point() as usize) ),
None,
);
(
memory_set,
user_stack_top,
elf.header.pt2.entry_point() as usize,
)
} }
pub fn activate(&self) { pub fn activate(&self) {
let satp = self.page_table.token(); let satp = self.page_table.token();
@ -203,7 +228,7 @@ impl MapArea {
start_va: VirtAddr, start_va: VirtAddr,
end_va: VirtAddr, end_va: VirtAddr,
map_type: MapType, map_type: MapType,
map_perm: MapPermission map_perm: MapPermission,
) -> Self { ) -> Self {
let start_vpn: VirtPageNum = start_va.floor(); let start_vpn: VirtPageNum = start_va.floor();
let end_vpn: VirtPageNum = end_va.ceil(); let end_vpn: VirtPageNum = end_va.ceil();
@ -296,15 +321,27 @@ pub fn remap_test() {
let mid_rodata: VirtAddr = ((srodata as usize + erodata 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(); let mid_data: VirtAddr = ((sdata as usize + edata as usize) / 2).into();
assert_eq!( assert_eq!(
kernel_space.page_table.translate(mid_text.floor()).unwrap().writable(), kernel_space
.page_table
.translate(mid_text.floor())
.unwrap()
.writable(),
false false
); );
assert_eq!( assert_eq!(
kernel_space.page_table.translate(mid_rodata.floor()).unwrap().writable(), kernel_space
.page_table
.translate(mid_rodata.floor())
.unwrap()
.writable(),
false, false,
); );
assert_eq!( assert_eq!(
kernel_space.page_table.translate(mid_data.floor()).unwrap().executable(), kernel_space
.page_table
.translate(mid_data.floor())
.unwrap()
.executable(),
false, false,
); );
println!("remap_test passed!"); println!("remap_test passed!");

View file

@ -1,16 +1,16 @@
mod heap_allocator;
mod address; mod address;
mod frame_allocator; mod frame_allocator;
mod page_table; mod heap_allocator;
mod memory_set; mod memory_set;
mod page_table;
use page_table::{PageTable, PTEFlags}; pub use address::{PhysAddr, PhysPageNum, VirtAddr, VirtPageNum};
use address::{VPNRange, StepByOne}; use address::{StepByOne, VPNRange};
pub use address::{PhysAddr, VirtAddr, PhysPageNum, VirtPageNum}; pub use frame_allocator::{frame_alloc, FrameTracker};
pub use frame_allocator::{FrameTracker, frame_alloc};
pub use page_table::{PageTableEntry, translated_byte_buffer};
pub use memory_set::{MemorySet, KERNEL_SPACE, MapPermission};
pub use memory_set::remap_test; pub use memory_set::remap_test;
pub use memory_set::{MapPermission, MemorySet, KERNEL_SPACE};
pub use page_table::{translated_byte_buffer, PageTableEntry};
use page_table::{PTEFlags, PageTable};
pub fn init() { pub fn init() {
heap_allocator::init_heap(); heap_allocator::init_heap();

View file

@ -1,6 +1,6 @@
use super::{frame_alloc, PhysPageNum, FrameTracker, VirtPageNum, VirtAddr, StepByOne}; use super::{frame_alloc, FrameTracker, PhysPageNum, StepByOne, VirtAddr, VirtPageNum};
use alloc::vec::Vec;
use alloc::vec; use alloc::vec;
use alloc::vec::Vec;
use bitflags::*; use bitflags::*;
bitflags! { bitflags! {
@ -29,9 +29,7 @@ impl PageTableEntry {
} }
} }
pub fn empty() -> Self { pub fn empty() -> Self {
PageTableEntry { PageTableEntry { bits: 0 }
bits: 0,
}
} }
pub fn ppn(&self) -> PhysPageNum { pub fn ppn(&self) -> PhysPageNum {
(self.bits >> 10 & ((1usize << 44) - 1)).into() (self.bits >> 10 & ((1usize << 44) - 1)).into()
@ -123,8 +121,7 @@ impl PageTable {
*pte = PageTableEntry::empty(); *pte = PageTableEntry::empty();
} }
pub fn translate(&self, vpn: VirtPageNum) -> Option<PageTableEntry> { pub fn translate(&self, vpn: VirtPageNum) -> Option<PageTableEntry> {
self.find_pte(vpn) self.find_pte(vpn).map(|pte| pte.clone())
.map(|pte| {pte.clone()})
} }
pub fn token(&self) -> usize { pub fn token(&self) -> usize {
8usize << 60 | self.root_ppn.0 8usize << 60 | self.root_ppn.0
@ -139,10 +136,7 @@ pub fn translated_byte_buffer(token: usize, ptr: *const u8, len: usize) -> Vec<&
while start < end { while start < end {
let start_va = VirtAddr::from(start); let start_va = VirtAddr::from(start);
let mut vpn = start_va.floor(); let mut vpn = start_va.floor();
let ppn = page_table let ppn = page_table.translate(vpn).unwrap().ppn();
.translate(vpn)
.unwrap()
.ppn();
vpn.step(); vpn.step();
let mut end_va: VirtAddr = vpn.into(); let mut end_va: VirtAddr = vpn.into();
end_va = end_va.min(VirtAddr::from(end)); end_va = end_va.min(VirtAddr::from(end));

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

@ -11,9 +11,9 @@ pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
print!("{}", core::str::from_utf8(buffer).unwrap()); print!("{}", core::str::from_utf8(buffer).unwrap());
} }
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

@ -23,4 +23,3 @@ impl TaskContext {
} }
} }
} }

View file

@ -2,13 +2,13 @@ mod context;
mod switch; mod switch;
mod task; mod task;
use crate::loader::{get_num_app, get_app_data}; use crate::loader::{get_app_data, get_num_app};
use crate::trap::TrapContext;
use crate::sync::UPSafeCell; use crate::sync::UPSafeCell;
use crate::trap::TrapContext;
use alloc::vec::Vec;
use lazy_static::*; use lazy_static::*;
use switch::__switch; use switch::__switch;
use task::{TaskControlBlock, TaskStatus}; use task::{TaskControlBlock, TaskStatus};
use alloc::vec::Vec;
pub use context::TaskContext; pub use context::TaskContext;
@ -29,17 +29,16 @@ lazy_static! {
println!("num_app = {}", num_app); println!("num_app = {}", num_app);
let mut tasks: Vec<TaskControlBlock> = Vec::new(); let mut tasks: Vec<TaskControlBlock> = Vec::new();
for i in 0..num_app { for i in 0..num_app {
tasks.push(TaskControlBlock::new( tasks.push(TaskControlBlock::new(get_app_data(i), i));
get_app_data(i),
i,
));
} }
TaskManager { TaskManager {
num_app, num_app,
inner: unsafe { UPSafeCell::new(TaskManagerInner { inner: unsafe {
tasks, UPSafeCell::new(TaskManagerInner {
current_task: 0, tasks,
})}, current_task: 0,
})
},
} }
}; };
} }
@ -54,10 +53,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 _, next_task_cx_ptr);
&mut _unused as *mut _,
next_task_cx_ptr,
);
} }
panic!("unreachable in run_first_task!"); panic!("unreachable in run_first_task!");
} }
@ -79,9 +75,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 get_current_token(&self) -> usize { fn get_current_token(&self) -> usize {
@ -105,10 +99,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 {
@ -149,4 +140,4 @@ pub fn current_user_token() -> usize {
pub fn current_trap_cx() -> &'static mut TrapContext { pub fn current_trap_cx() -> &'static mut TrapContext {
TASK_MANAGER.get_current_trap_cx() TASK_MANAGER.get_current_trap_cx()
} }

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

@ -1,7 +1,7 @@
use crate::mm::{MemorySet, MapPermission, PhysPageNum, KERNEL_SPACE, VirtAddr};
use crate::trap::{TrapContext, trap_handler};
use crate::config::{TRAP_CONTEXT, kernel_stack_position};
use super::TaskContext; use super::TaskContext;
use crate::config::{kernel_stack_position, TRAP_CONTEXT};
use crate::mm::{MapPermission, MemorySet, PhysPageNum, VirtAddr, KERNEL_SPACE};
use crate::trap::{trap_handler, TrapContext};
pub struct TaskControlBlock { pub struct TaskControlBlock {
pub task_status: TaskStatus, pub task_status: TaskStatus,
@ -28,13 +28,11 @@ impl TaskControlBlock {
let task_status = TaskStatus::Ready; let task_status = TaskStatus::Ready;
// map a kernel-stack in kernel space // map a kernel-stack in kernel space
let (kernel_stack_bottom, kernel_stack_top) = kernel_stack_position(app_id); let (kernel_stack_bottom, kernel_stack_top) = kernel_stack_position(app_id);
KERNEL_SPACE KERNEL_SPACE.exclusive_access().insert_framed_area(
.exclusive_access() kernel_stack_bottom.into(),
.insert_framed_area( kernel_stack_top.into(),
kernel_stack_bottom.into(), MapPermission::R | MapPermission::W,
kernel_stack_top.into(), );
MapPermission::R | MapPermission::W,
);
let task_control_block = Self { let task_control_block = Self {
task_status, task_status,
task_cx: TaskContext::goto_trap_return(kernel_stack_top), task_cx: TaskContext::goto_trap_return(kernel_stack_top),
@ -60,4 +58,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;
@ -15,4 +15,4 @@ pub fn get_time_ms() -> usize {
pub fn set_next_trigger() { pub fn set_next_trigger() {
set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC); set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC);
} }

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 {
@ -11,7 +11,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( pub fn app_init_context(
entry: usize, entry: usize,
sp: usize, sp: usize,

View file

@ -1,27 +1,17 @@
mod context; mod context;
use riscv::register::{ use crate::config::{TRAMPOLINE, TRAP_CONTEXT};
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, current_trap_cx, current_user_token, exit_current_and_run_next, suspend_current_and_run_next,
suspend_current_and_run_next,
current_user_token,
current_trap_cx,
}; };
use crate::timer::set_next_trigger; use crate::timer::set_next_trigger;
use crate::config::{TRAP_CONTEXT, TRAMPOLINE}; use core::arch::{asm, global_asm};
use core::arch::{global_asm, 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"));
@ -42,7 +32,9 @@ fn set_user_trap_entry() {
} }
pub fn enable_timer_interrupt() { pub fn enable_timer_interrupt() {
unsafe { sie::set_stimer(); } unsafe {
sie::set_stimer();
}
} }
#[no_mangle] #[no_mangle]
@ -56,8 +48,7 @@ pub fn trap_handler() -> ! {
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();
} }
@ -70,7 +61,11 @@ pub fn trap_handler() -> ! {
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
);
} }
} }
trap_return(); trap_return();
@ -103,4 +98,4 @@ pub fn trap_from_kernel() -> ! {
panic!("a trap from kernel!"); panic!("a trap from kernel!");
} }
pub use context::{TrapContext}; pub use context::TrapContext;

View file

@ -26,4 +26,4 @@ unsafe 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"]
@ -20,10 +20,17 @@ fn main() -> i32 {
panic!("Cannot find main!"); panic!("Cannot find main!");
} }
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()
}