cargo clippy & fmt

This commit is contained in:
Yifan Wu 2022-01-21 14:56:19 -08:00
parent 8917eb7acc
commit b96db03e48
62 changed files with 887 additions and 938 deletions

View File

@ -1,12 +1,9 @@
use easy_fs::{ use clap::{App, Arg};
BlockDevice, use easy_fs::{BlockDevice, EasyFileSystem};
EasyFileSystem, use std::fs::{read_dir, File, OpenOptions};
}; use std::io::{Read, Seek, SeekFrom, Write};
use std::fs::{File, OpenOptions, read_dir};
use std::io::{Read, Write, Seek, SeekFrom};
use std::sync::Mutex;
use std::sync::Arc; use std::sync::Arc;
use clap::{Arg, App}; use std::sync::Mutex;
const BLOCK_SZ: usize = 512; const BLOCK_SZ: usize = 512;
@ -34,17 +31,19 @@ fn main() {
fn easy_fs_pack() -> std::io::Result<()> { fn easy_fs_pack() -> std::io::Result<()> {
let matches = App::new("EasyFileSystem packer") let matches = App::new("EasyFileSystem packer")
.arg(Arg::with_name("source") .arg(
.short("s") Arg::with_name("source")
.long("source") .short("s")
.takes_value(true) .long("source")
.help("Executable source dir(with backslash)") .takes_value(true)
.help("Executable source dir(with backslash)"),
) )
.arg(Arg::with_name("target") .arg(
.short("t") Arg::with_name("target")
.long("target") .short("t")
.takes_value(true) .long("target")
.help("Executable target dir(with backslash)") .takes_value(true)
.help("Executable target dir(with backslash)"),
) )
.get_matches(); .get_matches();
let src_path = matches.value_of("source").unwrap(); let src_path = matches.value_of("source").unwrap();
@ -60,11 +59,7 @@ fn easy_fs_pack() -> std::io::Result<()> {
f f
}))); })));
// 16MiB, at most 4095 files // 16MiB, at most 4095 files
let efs = EasyFileSystem::create( let efs = EasyFileSystem::create(block_file, 16 * 2048, 1);
block_file.clone(),
16 * 2048,
1,
);
let root_inode = Arc::new(EasyFileSystem::root_inode(&efs)); let root_inode = Arc::new(EasyFileSystem::root_inode(&efs));
let apps: Vec<_> = read_dir(src_path) let apps: Vec<_> = read_dir(src_path)
.unwrap() .unwrap()
@ -103,11 +98,7 @@ fn efs_test() -> std::io::Result<()> {
f.set_len(8192 * 512).unwrap(); f.set_len(8192 * 512).unwrap();
f f
}))); })));
EasyFileSystem::create( EasyFileSystem::create(block_file.clone(), 4096, 1);
block_file.clone(),
4096,
1,
);
let efs = EasyFileSystem::open(block_file.clone()); let efs = EasyFileSystem::open(block_file.clone());
let root_inode = EasyFileSystem::root_inode(&efs); let root_inode = EasyFileSystem::root_inode(&efs);
root_inode.create("filea"); root_inode.create("filea");
@ -121,17 +112,11 @@ fn efs_test() -> std::io::Result<()> {
//let mut buffer = [0u8; 512]; //let mut buffer = [0u8; 512];
let mut buffer = [0u8; 233]; let mut buffer = [0u8; 233];
let len = filea.read_at(0, &mut buffer); let len = filea.read_at(0, &mut buffer);
assert_eq!( assert_eq!(greet_str, core::str::from_utf8(&buffer[..len]).unwrap(),);
greet_str,
core::str::from_utf8(&buffer[..len]).unwrap(),
);
let mut random_str_test = |len: usize| { let mut random_str_test = |len: usize| {
filea.clear(); filea.clear();
assert_eq!( assert_eq!(filea.read_at(0, &mut buffer), 0,);
filea.read_at(0, &mut buffer),
0,
);
let mut str = String::new(); let mut str = String::new();
use rand; use rand;
// random digit // random digit
@ -148,9 +133,7 @@ fn efs_test() -> std::io::Result<()> {
break; break;
} }
offset += len; offset += len;
read_str.push_str( read_str.push_str(core::str::from_utf8(&read_buffer[..len]).unwrap());
core::str::from_utf8(&read_buffer[..len]).unwrap()
);
} }
assert_eq!(str, read_str); assert_eq!(str, read_str);
}; };

View File

@ -1,9 +1,5 @@
use super::{get_block_cache, BlockDevice, BLOCK_SZ};
use alloc::sync::Arc; use alloc::sync::Arc;
use super::{
BlockDevice,
BLOCK_SZ,
get_block_cache,
};
type BitmapBlock = [u64; 64]; type BitmapBlock = [u64; 64];
@ -17,7 +13,7 @@ pub struct Bitmap {
/// Return (block_pos, bits64_pos, inner_pos) /// Return (block_pos, bits64_pos, inner_pos)
fn decomposition(mut bit: usize) -> (usize, usize, usize) { fn decomposition(mut bit: usize) -> (usize, usize, usize) {
let block_pos = bit / BLOCK_BITS; let block_pos = bit / BLOCK_BITS;
bit = bit % BLOCK_BITS; bit %= BLOCK_BITS;
(block_pos, bit / 64, bit % 64) (block_pos, bit / 64, bit % 64)
} }
@ -34,14 +30,15 @@ impl Bitmap {
let pos = get_block_cache( let pos = get_block_cache(
block_id + self.start_block_id as usize, block_id + self.start_block_id as usize,
Arc::clone(block_device), Arc::clone(block_device),
).lock().modify(0, |bitmap_block: &mut BitmapBlock| { )
.lock()
.modify(0, |bitmap_block: &mut BitmapBlock| {
if let Some((bits64_pos, inner_pos)) = bitmap_block if let Some((bits64_pos, inner_pos)) = bitmap_block
.iter() .iter()
.enumerate() .enumerate()
.find(|(_, bits64)| **bits64 != u64::MAX) .find(|(_, bits64)| **bits64 != u64::MAX)
.map(|(bits64_pos, bits64)| { .map(|(bits64_pos, bits64)| (bits64_pos, bits64.trailing_ones() as usize))
(bits64_pos, bits64.trailing_ones() as usize) {
}) {
// modify cache // modify cache
bitmap_block[bits64_pos] |= 1u64 << inner_pos; bitmap_block[bits64_pos] |= 1u64 << inner_pos;
Some(block_id * BLOCK_BITS + bits64_pos * 64 + inner_pos as usize) Some(block_id * BLOCK_BITS + bits64_pos * 64 + inner_pos as usize)
@ -58,13 +55,12 @@ impl Bitmap {
pub fn dealloc(&self, block_device: &Arc<dyn BlockDevice>, bit: usize) { pub fn dealloc(&self, block_device: &Arc<dyn BlockDevice>, bit: usize) {
let (block_pos, bits64_pos, inner_pos) = decomposition(bit); let (block_pos, bits64_pos, inner_pos) = decomposition(bit);
get_block_cache( get_block_cache(block_pos + self.start_block_id, Arc::clone(block_device))
block_pos + self.start_block_id, .lock()
Arc::clone(block_device) .modify(0, |bitmap_block: &mut BitmapBlock| {
).lock().modify(0, |bitmap_block: &mut BitmapBlock| { assert!(bitmap_block[bits64_pos] & (1u64 << inner_pos) > 0);
assert!(bitmap_block[bits64_pos] & (1u64 << inner_pos) > 0); bitmap_block[bits64_pos] -= 1u64 << inner_pos;
bitmap_block[bits64_pos] -= 1u64 << inner_pos; });
});
} }
pub fn maximum(&self) -> usize { pub fn maximum(&self) -> usize {

View File

@ -1,7 +1,4 @@
use super::{ use super::{BlockDevice, BLOCK_SZ};
BLOCK_SZ,
BlockDevice,
};
use alloc::collections::VecDeque; use alloc::collections::VecDeque;
use alloc::sync::Arc; use alloc::sync::Arc;
use lazy_static::*; use lazy_static::*;
@ -16,10 +13,7 @@ pub struct BlockCache {
impl BlockCache { impl BlockCache {
/// Load a new BlockCache from disk. /// Load a new BlockCache from disk.
pub fn new( pub fn new(block_id: usize, block_device: Arc<dyn BlockDevice>) -> Self {
block_id: usize,
block_device: Arc<dyn BlockDevice>
) -> Self {
let mut cache = [0u8; BLOCK_SZ]; let mut cache = [0u8; BLOCK_SZ];
block_device.read_block(block_id, &mut cache); block_device.read_block(block_id, &mut cache);
Self { Self {
@ -34,14 +28,20 @@ impl BlockCache {
&self.cache[offset] as *const _ as usize &self.cache[offset] as *const _ as usize
} }
pub fn get_ref<T>(&self, offset: usize) -> &T where T: Sized { pub fn get_ref<T>(&self, offset: usize) -> &T
where
T: Sized,
{
let type_size = core::mem::size_of::<T>(); let type_size = core::mem::size_of::<T>();
assert!(offset + type_size <= BLOCK_SZ); assert!(offset + type_size <= BLOCK_SZ);
let addr = self.addr_of_offset(offset); let addr = self.addr_of_offset(offset);
unsafe { &*(addr as *const T) } unsafe { &*(addr as *const T) }
} }
pub fn get_mut<T>(&mut self, offset: usize) -> &mut T where T: Sized { pub fn get_mut<T>(&mut self, offset: usize) -> &mut T
where
T: Sized,
{
let type_size = core::mem::size_of::<T>(); let type_size = core::mem::size_of::<T>();
assert!(offset + type_size <= BLOCK_SZ); assert!(offset + type_size <= BLOCK_SZ);
self.modified = true; self.modified = true;
@ -53,7 +53,7 @@ impl BlockCache {
f(self.get_ref(offset)) f(self.get_ref(offset))
} }
pub fn modify<T, V>(&mut self, offset:usize, f: impl FnOnce(&mut T) -> V) -> V { pub fn modify<T, V>(&mut self, offset: usize, f: impl FnOnce(&mut T) -> V) -> V {
f(self.get_mut(offset)) f(self.get_mut(offset))
} }
@ -79,7 +79,9 @@ pub struct BlockCacheManager {
impl BlockCacheManager { impl BlockCacheManager {
pub fn new() -> Self { pub fn new() -> Self {
Self { queue: VecDeque::new() } Self {
queue: VecDeque::new(),
}
} }
pub fn get_block_cache( pub fn get_block_cache(
@ -87,27 +89,28 @@ impl BlockCacheManager {
block_id: usize, block_id: usize,
block_device: Arc<dyn BlockDevice>, block_device: Arc<dyn BlockDevice>,
) -> Arc<Mutex<BlockCache>> { ) -> Arc<Mutex<BlockCache>> {
if let Some(pair) = self.queue if let Some(pair) = self.queue.iter().find(|pair| pair.0 == block_id) {
.iter() Arc::clone(&pair.1)
.find(|pair| pair.0 == block_id) {
Arc::clone(&pair.1)
} else { } else {
// substitute // substitute
if self.queue.len() == BLOCK_CACHE_SIZE { if self.queue.len() == BLOCK_CACHE_SIZE {
// from front to tail // from front to tail
if let Some((idx, _)) = self.queue if let Some((idx, _)) = self
.queue
.iter() .iter()
.enumerate() .enumerate()
.find(|(_, pair)| Arc::strong_count(&pair.1) == 1) { .find(|(_, pair)| Arc::strong_count(&pair.1) == 1)
{
self.queue.drain(idx..=idx); self.queue.drain(idx..=idx);
} else { } else {
panic!("Run out of BlockCache!"); panic!("Run out of BlockCache!");
} }
} }
// load block into mem and push back // load block into mem and push back
let block_cache = Arc::new(Mutex::new( let block_cache = Arc::new(Mutex::new(BlockCache::new(
BlockCache::new(block_id, Arc::clone(&block_device)) block_id,
)); Arc::clone(&block_device),
)));
self.queue.push_back((block_id, Arc::clone(&block_cache))); self.queue.push_back((block_id, Arc::clone(&block_cache)));
block_cache block_cache
} }
@ -115,16 +118,17 @@ impl BlockCacheManager {
} }
lazy_static! { lazy_static! {
pub static ref BLOCK_CACHE_MANAGER: Mutex<BlockCacheManager> = Mutex::new( pub static ref BLOCK_CACHE_MANAGER: Mutex<BlockCacheManager> =
BlockCacheManager::new() Mutex::new(BlockCacheManager::new());
);
} }
pub fn get_block_cache( pub fn get_block_cache(
block_id: usize, block_id: usize,
block_device: Arc<dyn BlockDevice> block_device: Arc<dyn BlockDevice>,
) -> Arc<Mutex<BlockCache>> { ) -> Arc<Mutex<BlockCache>> {
BLOCK_CACHE_MANAGER.lock().get_block_cache(block_id, block_device) BLOCK_CACHE_MANAGER
.lock()
.get_block_cache(block_id, block_device)
} }
pub fn block_cache_sync_all() { pub fn block_cache_sync_all() {

View File

@ -1,6 +1,6 @@
use core::any::Any; use core::any::Any;
pub trait BlockDevice : Send + Sync + Any { pub trait BlockDevice: Send + Sync + Any {
fn read_block(&self, block_id: usize, buf: &mut [u8]); fn read_block(&self, block_id: usize, buf: &mut [u8]);
fn write_block(&self, block_id: usize, buf: &[u8]); fn write_block(&self, block_id: usize, buf: &[u8]);
} }

View File

@ -1,16 +1,10 @@
use alloc::sync::Arc;
use spin::Mutex;
use super::{ use super::{
BlockDevice, block_cache_sync_all, get_block_cache, Bitmap, BlockDevice, DiskInode, DiskInodeType, Inode,
Bitmap,
SuperBlock, SuperBlock,
DiskInode,
DiskInodeType,
Inode,
get_block_cache,
block_cache_sync_all,
}; };
use crate::BLOCK_SZ; use crate::BLOCK_SZ;
use alloc::sync::Arc;
use spin::Mutex;
pub struct EasyFileSystem { pub struct EasyFileSystem {
pub block_device: Arc<dyn BlockDevice>, pub block_device: Arc<dyn BlockDevice>,
@ -50,39 +44,36 @@ impl EasyFileSystem {
}; };
// clear all blocks // clear all blocks
for i in 0..total_blocks { for i in 0..total_blocks {
get_block_cache( get_block_cache(i as usize, Arc::clone(&block_device))
i as usize, .lock()
Arc::clone(&block_device) .modify(0, |data_block: &mut DataBlock| {
) for byte in data_block.iter_mut() {
.lock() *byte = 0;
.modify(0, |data_block: &mut DataBlock| { }
for byte in data_block.iter_mut() { *byte = 0; } });
});
} }
// initialize SuperBlock // initialize SuperBlock
get_block_cache(0, Arc::clone(&block_device)) get_block_cache(0, Arc::clone(&block_device)).lock().modify(
.lock() 0,
.modify(0, |super_block: &mut SuperBlock| { |super_block: &mut SuperBlock| {
super_block.initialize( super_block.initialize(
total_blocks, total_blocks,
inode_bitmap_blocks, inode_bitmap_blocks,
inode_area_blocks, inode_area_blocks,
data_bitmap_blocks, data_bitmap_blocks,
data_area_blocks, data_area_blocks,
); );
}); },
);
// write back immediately // write back immediately
// create a inode for root node "/" // create a inode for root node "/"
assert_eq!(efs.alloc_inode(), 0); assert_eq!(efs.alloc_inode(), 0);
let (root_inode_block_id, root_inode_offset) = efs.get_disk_inode_pos(0); let (root_inode_block_id, root_inode_offset) = efs.get_disk_inode_pos(0);
get_block_cache( get_block_cache(root_inode_block_id as usize, Arc::clone(&block_device))
root_inode_block_id as usize, .lock()
Arc::clone(&block_device) .modify(root_inode_offset, |disk_inode: &mut DiskInode| {
) disk_inode.initialize(DiskInodeType::Directory);
.lock() });
.modify(root_inode_offset, |disk_inode: &mut DiskInode| {
disk_inode.initialize(DiskInodeType::Directory);
});
block_cache_sync_all(); block_cache_sync_all();
Arc::new(Mutex::new(efs)) Arc::new(Mutex::new(efs))
} }
@ -97,10 +88,7 @@ impl EasyFileSystem {
super_block.inode_bitmap_blocks + super_block.inode_area_blocks; super_block.inode_bitmap_blocks + super_block.inode_area_blocks;
let efs = Self { let efs = Self {
block_device, block_device,
inode_bitmap: Bitmap::new( inode_bitmap: Bitmap::new(1, super_block.inode_bitmap_blocks as usize),
1,
super_block.inode_bitmap_blocks as usize
),
data_bitmap: Bitmap::new( data_bitmap: Bitmap::new(
(1 + inode_total_blocks) as usize, (1 + inode_total_blocks) as usize,
super_block.data_bitmap_blocks as usize, super_block.data_bitmap_blocks as usize,
@ -117,19 +105,17 @@ impl EasyFileSystem {
// acquire efs lock temporarily // acquire efs lock temporarily
let (block_id, block_offset) = efs.lock().get_disk_inode_pos(0); let (block_id, block_offset) = efs.lock().get_disk_inode_pos(0);
// release efs lock // release efs lock
Inode::new( Inode::new(block_id, block_offset, Arc::clone(efs), block_device)
block_id,
block_offset,
Arc::clone(efs),
block_device,
)
} }
pub fn get_disk_inode_pos(&self, inode_id: u32) -> (u32, usize) { pub fn get_disk_inode_pos(&self, inode_id: u32) -> (u32, usize) {
let inode_size = core::mem::size_of::<DiskInode>(); let inode_size = core::mem::size_of::<DiskInode>();
let inodes_per_block = (BLOCK_SZ / inode_size) as u32; let inodes_per_block = (BLOCK_SZ / inode_size) as u32;
let block_id = self.inode_area_start_block + inode_id / inodes_per_block; let block_id = self.inode_area_start_block + inode_id / inodes_per_block;
(block_id, (inode_id % inodes_per_block) as usize * inode_size) (
block_id,
(inode_id % inodes_per_block) as usize * inode_size,
)
} }
pub fn get_data_block_id(&self, data_block_id: u32) -> u32 { pub fn get_data_block_id(&self, data_block_id: u32) -> u32 {
@ -146,18 +132,16 @@ impl EasyFileSystem {
} }
pub fn dealloc_data(&mut self, block_id: u32) { pub fn dealloc_data(&mut self, block_id: u32) {
get_block_cache( get_block_cache(block_id as usize, Arc::clone(&self.block_device))
block_id as usize, .lock()
Arc::clone(&self.block_device) .modify(0, |data_block: &mut DataBlock| {
) data_block.iter_mut().for_each(|p| {
.lock() *p = 0;
.modify(0, |data_block: &mut DataBlock| { })
data_block.iter_mut().for_each(|p| { *p = 0; }) });
});
self.data_bitmap.dealloc( self.data_bitmap.dealloc(
&self.block_device, &self.block_device,
(block_id - self.data_area_start_block) as usize (block_id - self.data_area_start_block) as usize,
) )
} }
} }

View File

@ -1,11 +1,7 @@
use core::fmt::{Debug, Formatter, Result}; use super::{get_block_cache, BlockDevice, BLOCK_SZ};
use super::{
BLOCK_SZ,
BlockDevice,
get_block_cache,
};
use alloc::sync::Arc; use alloc::sync::Arc;
use alloc::vec::Vec; use alloc::vec::Vec;
use core::fmt::{Debug, Formatter, Result};
const EFS_MAGIC: u32 = 0x3b800001; const EFS_MAGIC: u32 = 0x3b800001;
const INODE_DIRECT_COUNT: usize = 28; const INODE_DIRECT_COUNT: usize = 28;
@ -115,7 +111,8 @@ impl DiskInode {
if data_blocks > INDIRECT1_BOUND { if data_blocks > INDIRECT1_BOUND {
total += 1; total += 1;
// sub indirect1 // sub indirect1
total += (data_blocks - INDIRECT1_BOUND + INODE_INDIRECT1_COUNT - 1) / INODE_INDIRECT1_COUNT; total +=
(data_blocks - INDIRECT1_BOUND + INODE_INDIRECT1_COUNT - 1) / INODE_INDIRECT1_COUNT;
} }
total as u32 total as u32
} }
@ -135,22 +132,16 @@ impl DiskInode {
}) })
} else { } else {
let last = inner_id - INDIRECT1_BOUND; let last = inner_id - INDIRECT1_BOUND;
let indirect1 = get_block_cache( let indirect1 = get_block_cache(self.indirect2 as usize, Arc::clone(block_device))
self.indirect2 as usize, .lock()
Arc::clone(block_device) .read(0, |indirect2: &IndirectBlock| {
) indirect2[last / INODE_INDIRECT1_COUNT]
.lock() });
.read(0, |indirect2: &IndirectBlock| { get_block_cache(indirect1 as usize, Arc::clone(block_device))
indirect2[last / INODE_INDIRECT1_COUNT] .lock()
}); .read(0, |indirect1: &IndirectBlock| {
get_block_cache( indirect1[last % INODE_INDIRECT1_COUNT]
indirect1 as usize, })
Arc::clone(block_device)
)
.lock()
.read(0, |indirect1: &IndirectBlock| {
indirect1[last % INODE_INDIRECT1_COUNT]
})
} }
} }
pub fn increase_size( pub fn increase_size(
@ -169,7 +160,7 @@ impl DiskInode {
current_blocks += 1; current_blocks += 1;
} }
// alloc indirect1 // alloc indirect1
if total_blocks > INODE_DIRECT_COUNT as u32{ if total_blocks > INODE_DIRECT_COUNT as u32 {
if current_blocks == INODE_DIRECT_COUNT as u32 { if current_blocks == INODE_DIRECT_COUNT as u32 {
self.indirect1 = new_blocks.next().unwrap(); self.indirect1 = new_blocks.next().unwrap();
} }
@ -179,17 +170,14 @@ impl DiskInode {
return; return;
} }
// fill indirect1 // fill indirect1
get_block_cache( get_block_cache(self.indirect1 as usize, Arc::clone(block_device))
self.indirect1 as usize, .lock()
Arc::clone(block_device) .modify(0, |indirect1: &mut IndirectBlock| {
) while current_blocks < total_blocks.min(INODE_INDIRECT1_COUNT as u32) {
.lock() indirect1[current_blocks as usize] = new_blocks.next().unwrap();
.modify(0, |indirect1: &mut IndirectBlock| { current_blocks += 1;
while current_blocks < total_blocks.min(INODE_INDIRECT1_COUNT as u32) { }
indirect1[current_blocks as usize] = new_blocks.next().unwrap(); });
current_blocks += 1;
}
});
// alloc indirect2 // alloc indirect2
if total_blocks > INODE_INDIRECT1_COUNT as u32 { if total_blocks > INODE_INDIRECT1_COUNT as u32 {
if current_blocks == INODE_INDIRECT1_COUNT as u32 { if current_blocks == INODE_INDIRECT1_COUNT as u32 {
@ -206,33 +194,27 @@ impl DiskInode {
let a1 = total_blocks as usize / INODE_INDIRECT1_COUNT; let a1 = total_blocks as usize / INODE_INDIRECT1_COUNT;
let b1 = total_blocks as usize % INODE_INDIRECT1_COUNT; let b1 = total_blocks as usize % INODE_INDIRECT1_COUNT;
// alloc low-level indirect1 // alloc low-level indirect1
get_block_cache( get_block_cache(self.indirect2 as usize, Arc::clone(block_device))
self.indirect2 as usize, .lock()
Arc::clone(block_device) .modify(0, |indirect2: &mut IndirectBlock| {
) while (a0 < a1) || (a0 == a1 && b0 < b1) {
.lock() if b0 == 0 {
.modify(0, |indirect2: &mut IndirectBlock| { indirect2[a0] = new_blocks.next().unwrap();
while (a0 < a1) || (a0 == a1 && b0 < b1) { }
if b0 == 0 { // fill current
indirect2[a0] = new_blocks.next().unwrap(); get_block_cache(indirect2[a0] as usize, Arc::clone(block_device))
.lock()
.modify(0, |indirect1: &mut IndirectBlock| {
indirect1[b0] = new_blocks.next().unwrap();
});
// move to next
b0 += 1;
if b0 == INODE_INDIRECT1_COUNT {
b0 = 0;
a0 += 1;
}
} }
// fill current });
get_block_cache(
indirect2[a0] as usize,
Arc::clone(block_device)
)
.lock()
.modify(0, |indirect1: &mut IndirectBlock| {
indirect1[b0] = new_blocks.next().unwrap();
});
// move to next
b0 += 1;
if b0 == INODE_INDIRECT1_COUNT {
b0 = 0;
a0 += 1;
}
}
});
} }
/// Clear size to zero and return blocks that should be deallocated. /// Clear size to zero and return blocks that should be deallocated.
@ -258,18 +240,15 @@ impl DiskInode {
return v; return v;
} }
// indirect1 // indirect1
get_block_cache( get_block_cache(self.indirect1 as usize, Arc::clone(block_device))
self.indirect1 as usize, .lock()
Arc::clone(block_device), .modify(0, |indirect1: &mut IndirectBlock| {
) while current_blocks < data_blocks.min(INODE_INDIRECT1_COUNT) {
.lock() v.push(indirect1[current_blocks]);
.modify(0, |indirect1: &mut IndirectBlock| { //indirect1[current_blocks] = 0;
while current_blocks < data_blocks.min(INODE_INDIRECT1_COUNT) { current_blocks += 1;
v.push(indirect1[current_blocks]); }
//indirect1[current_blocks] = 0; });
current_blocks += 1;
}
});
self.indirect1 = 0; self.indirect1 = 0;
// indirect2 block // indirect2 block
if data_blocks > INODE_INDIRECT1_COUNT { if data_blocks > INODE_INDIRECT1_COUNT {
@ -282,45 +261,33 @@ impl DiskInode {
assert!(data_blocks <= INODE_INDIRECT2_COUNT); assert!(data_blocks <= INODE_INDIRECT2_COUNT);
let a1 = data_blocks / INODE_INDIRECT1_COUNT; let a1 = data_blocks / INODE_INDIRECT1_COUNT;
let b1 = data_blocks % INODE_INDIRECT1_COUNT; let b1 = data_blocks % INODE_INDIRECT1_COUNT;
get_block_cache( get_block_cache(self.indirect2 as usize, Arc::clone(block_device))
self.indirect2 as usize, .lock()
Arc::clone(block_device), .modify(0, |indirect2: &mut IndirectBlock| {
) // full indirect1 blocks
.lock() for entry in indirect2.iter_mut().take(a1) {
.modify(0, |indirect2: &mut IndirectBlock| { v.push(*entry);
// full indirect1 blocks get_block_cache(*entry as usize, Arc::clone(block_device))
for i in 0..a1 { .lock()
v.push(indirect2[i]); .modify(0, |indirect1: &mut IndirectBlock| {
get_block_cache( for entry in indirect1.iter() {
indirect2[i] as usize, v.push(*entry);
Arc::clone(block_device), }
) });
.lock() }
.modify(0, |indirect1: &mut IndirectBlock| { // last indirect1 block
for j in 0..INODE_INDIRECT1_COUNT { if b1 > 0 {
v.push(indirect1[j]); v.push(indirect2[a1]);
//indirect1[j] = 0; get_block_cache(indirect2[a1] as usize, Arc::clone(block_device))
} .lock()
}); .modify(0, |indirect1: &mut IndirectBlock| {
//indirect2[i] = 0; for entry in indirect1.iter().take(b1) {
} v.push(*entry);
// last indirect1 block }
if b1 > 0 { });
v.push(indirect2[a1]); //indirect2[a1] = 0;
get_block_cache( }
indirect2[a1] as usize, });
Arc::clone(block_device),
)
.lock()
.modify(0, |indirect1: &mut IndirectBlock| {
for j in 0..b1 {
v.push(indirect1[j]);
//indirect1[j] = 0;
}
});
//indirect2[a1] = 0;
}
});
self.indirect2 = 0; self.indirect2 = 0;
v v
} }
@ -355,7 +322,9 @@ impl DiskInode {
}); });
read_size += block_read_size; read_size += block_read_size;
// move to next block // move to next block
if end_current_block == end { break; } if end_current_block == end {
break;
}
start_block += 1; start_block += 1;
start = end_current_block; start = end_current_block;
} }
@ -381,7 +350,7 @@ impl DiskInode {
let block_write_size = end_current_block - start; let block_write_size = end_current_block - start;
get_block_cache( get_block_cache(
self.get_block_id(start_block as u32, block_device) as usize, self.get_block_id(start_block as u32, block_device) as usize,
Arc::clone(block_device) Arc::clone(block_device),
) )
.lock() .lock()
.modify(0, |data_block: &mut DataBlock| { .modify(0, |data_block: &mut DataBlock| {
@ -391,7 +360,9 @@ impl DiskInode {
}); });
write_size += block_write_size; write_size += block_write_size;
// move to next block // move to next block
if end_current_block == end { break; } if end_current_block == end {
break;
}
start_block += 1; start_block += 1;
start = end_current_block; start = end_current_block;
} }
@ -423,20 +394,10 @@ impl DirEntry {
} }
} }
pub fn as_bytes(&self) -> &[u8] { pub fn as_bytes(&self) -> &[u8] {
unsafe { unsafe { core::slice::from_raw_parts(self as *const _ as usize as *const u8, DIRENT_SZ) }
core::slice::from_raw_parts(
self as *const _ as usize as *const u8,
DIRENT_SZ,
)
}
} }
pub fn as_bytes_mut(&mut self) -> &mut [u8] { pub fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe { unsafe { core::slice::from_raw_parts_mut(self as *mut _ as usize as *mut u8, DIRENT_SZ) }
core::slice::from_raw_parts_mut(
self as *mut _ as usize as *mut u8,
DIRENT_SZ,
)
}
} }
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
let len = (0usize..).find(|i| self.name[*i] == 0).unwrap(); let len = (0usize..).find(|i| self.name[*i] == 0).unwrap();

View File

@ -2,17 +2,17 @@
extern crate alloc; extern crate alloc;
mod block_dev;
mod layout;
mod efs;
mod bitmap; mod bitmap;
mod vfs;
mod block_cache; mod block_cache;
mod block_dev;
mod efs;
mod layout;
mod vfs;
pub const BLOCK_SZ: usize = 512; pub const BLOCK_SZ: usize = 512;
use bitmap::Bitmap;
use block_cache::{block_cache_sync_all, get_block_cache};
pub use block_dev::BlockDevice; pub use block_dev::BlockDevice;
pub use efs::EasyFileSystem; pub use efs::EasyFileSystem;
pub use vfs::Inode;
use layout::*; use layout::*;
use bitmap::Bitmap; pub use vfs::Inode;
use block_cache::{get_block_cache, block_cache_sync_all};

View File

@ -1,15 +1,9 @@
use super::{ use super::{
BlockDevice, block_cache_sync_all, get_block_cache, BlockDevice, DirEntry, DiskInode, DiskInodeType,
DiskInode, EasyFileSystem, DIRENT_SZ,
DiskInodeType,
DirEntry,
EasyFileSystem,
DIRENT_SZ,
get_block_cache,
block_cache_sync_all,
}; };
use alloc::sync::Arc;
use alloc::string::String; use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec; use alloc::vec::Vec;
use spin::{Mutex, MutexGuard}; use spin::{Mutex, MutexGuard};
@ -37,35 +31,25 @@ impl Inode {
} }
fn read_disk_inode<V>(&self, f: impl FnOnce(&DiskInode) -> V) -> V { fn read_disk_inode<V>(&self, f: impl FnOnce(&DiskInode) -> V) -> V {
get_block_cache( get_block_cache(self.block_id, Arc::clone(&self.block_device))
self.block_id, .lock()
Arc::clone(&self.block_device) .read(self.block_offset, f)
).lock().read(self.block_offset, f)
} }
fn modify_disk_inode<V>(&self, f: impl FnOnce(&mut DiskInode) -> V) -> V { fn modify_disk_inode<V>(&self, f: impl FnOnce(&mut DiskInode) -> V) -> V {
get_block_cache( get_block_cache(self.block_id, Arc::clone(&self.block_device))
self.block_id, .lock()
Arc::clone(&self.block_device) .modify(self.block_offset, f)
).lock().modify(self.block_offset, f)
} }
fn find_inode_id( fn find_inode_id(&self, name: &str, disk_inode: &DiskInode) -> Option<u32> {
&self,
name: &str,
disk_inode: &DiskInode,
) -> Option<u32> {
// assert it is a directory // assert it is a directory
assert!(disk_inode.is_dir()); assert!(disk_inode.is_dir());
let file_count = (disk_inode.size as usize) / DIRENT_SZ; let file_count = (disk_inode.size as usize) / DIRENT_SZ;
let mut dirent = DirEntry::empty(); let mut dirent = DirEntry::empty();
for i in 0..file_count { for i in 0..file_count {
assert_eq!( assert_eq!(
disk_inode.read_at( disk_inode.read_at(DIRENT_SZ * i, dirent.as_bytes_mut(), &self.block_device,),
DIRENT_SZ * i,
dirent.as_bytes_mut(),
&self.block_device,
),
DIRENT_SZ, DIRENT_SZ,
); );
if dirent.name() == name { if dirent.name() == name {
@ -78,8 +62,7 @@ impl Inode {
pub fn find(&self, name: &str) -> Option<Arc<Inode>> { pub fn find(&self, name: &str) -> Option<Arc<Inode>> {
let fs = self.fs.lock(); let fs = self.fs.lock();
self.read_disk_inode(|disk_inode| { self.read_disk_inode(|disk_inode| {
self.find_inode_id(name, disk_inode) self.find_inode_id(name, disk_inode).map(|inode_id| {
.map(|inode_id| {
let (block_id, block_offset) = fs.get_disk_inode_pos(inode_id); let (block_id, block_offset) = fs.get_disk_inode_pos(inode_id);
Arc::new(Self::new( Arc::new(Self::new(
block_id, block_id,
@ -110,26 +93,25 @@ impl Inode {
pub fn create(&self, name: &str) -> Option<Arc<Inode>> { pub fn create(&self, name: &str) -> Option<Arc<Inode>> {
let mut fs = self.fs.lock(); let mut fs = self.fs.lock();
if self.modify_disk_inode(|root_inode| { let op = |root_inode: &DiskInode| {
// assert it is a directory // assert it is a directory
assert!(root_inode.is_dir()); assert!(root_inode.is_dir());
// has the file been created? // has the file been created?
self.find_inode_id(name, root_inode) self.find_inode_id(name, root_inode)
}).is_some() { };
if self.read_disk_inode(op).is_some() {
return None; return None;
} }
// create a new file // create a new file
// alloc a inode with an indirect block // alloc a inode with an indirect block
let new_inode_id = fs.alloc_inode(); let new_inode_id = fs.alloc_inode();
// initialize inode // initialize inode
let (new_inode_block_id, new_inode_block_offset) let (new_inode_block_id, new_inode_block_offset) = fs.get_disk_inode_pos(new_inode_id);
= fs.get_disk_inode_pos(new_inode_id); get_block_cache(new_inode_block_id as usize, Arc::clone(&self.block_device))
get_block_cache( .lock()
new_inode_block_id as usize, .modify(new_inode_block_offset, |new_inode: &mut DiskInode| {
Arc::clone(&self.block_device) new_inode.initialize(DiskInodeType::File);
).lock().modify(new_inode_block_offset, |new_inode: &mut DiskInode| { });
new_inode.initialize(DiskInodeType::File);
});
self.modify_disk_inode(|root_inode| { self.modify_disk_inode(|root_inode| {
// append file in the dirent // append file in the dirent
let file_count = (root_inode.size as usize) / DIRENT_SZ; let file_count = (root_inode.size as usize) / DIRENT_SZ;
@ -165,11 +147,7 @@ impl Inode {
for i in 0..file_count { for i in 0..file_count {
let mut dirent = DirEntry::empty(); let mut dirent = DirEntry::empty();
assert_eq!( assert_eq!(
disk_inode.read_at( disk_inode.read_at(i * DIRENT_SZ, dirent.as_bytes_mut(), &self.block_device,),
i * DIRENT_SZ,
dirent.as_bytes_mut(),
&self.block_device,
),
DIRENT_SZ, DIRENT_SZ,
); );
v.push(String::from(dirent.name())); v.push(String::from(dirent.name()));
@ -180,9 +158,7 @@ impl Inode {
pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> usize { pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> usize {
let _fs = self.fs.lock(); let _fs = self.fs.lock();
self.read_disk_inode(|disk_inode| { self.read_disk_inode(|disk_inode| disk_inode.read_at(offset, buf, &self.block_device))
disk_inode.read_at(offset, buf, &self.block_device)
})
} }
pub fn write_at(&self, offset: usize, buf: &[u8]) -> usize { pub fn write_at(&self, offset: usize, buf: &[u8]) -> usize {

View File

@ -17,26 +17,24 @@ pub const CLOCK_FREQ: usize = 403000000 / 62;
pub const CLOCK_FREQ: usize = 12500000; pub const CLOCK_FREQ: usize = 12500000;
#[cfg(feature = "board_qemu")] #[cfg(feature = "board_qemu")]
pub const MMIO: &[(usize, usize)] = &[ pub const MMIO: &[(usize, usize)] = &[(0x10001000, 0x1000)];
(0x10001000, 0x1000),
];
#[cfg(feature = "board_k210")] #[cfg(feature = "board_k210")]
pub const MMIO: &[(usize, usize)] = &[ pub const MMIO: &[(usize, usize)] = &[
// we don't need clint in S priv when running // we don't need clint in S priv when running
// we only need claim/complete for target0 after initializing // we only need claim/complete for target0 after initializing
(0x0C00_0000, 0x3000), /* PLIC */ (0x0C00_0000, 0x3000), /* PLIC */
(0x0C20_0000, 0x1000), /* PLIC */ (0x0C20_0000, 0x1000), /* PLIC */
(0x3800_0000, 0x1000), /* UARTHS */ (0x3800_0000, 0x1000), /* UARTHS */
(0x3800_1000, 0x1000), /* GPIOHS */ (0x3800_1000, 0x1000), /* GPIOHS */
(0x5020_0000, 0x1000), /* GPIO */ (0x5020_0000, 0x1000), /* GPIO */
(0x5024_0000, 0x1000), /* SPI_SLAVE */ (0x5024_0000, 0x1000), /* SPI_SLAVE */
(0x502B_0000, 0x1000), /* FPIOA */ (0x502B_0000, 0x1000), /* FPIOA */
(0x502D_0000, 0x1000), /* TIMER0 */ (0x502D_0000, 0x1000), /* TIMER0 */
(0x502E_0000, 0x1000), /* TIMER1 */ (0x502E_0000, 0x1000), /* TIMER1 */
(0x502F_0000, 0x1000), /* TIMER2 */ (0x502F_0000, 0x1000), /* TIMER2 */
(0x5044_0000, 0x1000), /* SYSCTL */ (0x5044_0000, 0x1000), /* SYSCTL */
(0x5200_0000, 0x1000), /* SPI0 */ (0x5200_0000, 0x1000), /* SPI0 */
(0x5300_0000, 0x1000), /* SPI1 */ (0x5300_0000, 0x1000), /* SPI1 */
(0x5400_0000, 0x1000), /* SPI2 */ (0x5400_0000, 0x1000), /* SPI2 */
]; ];

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,9 +1,9 @@
mod virtio_blk;
mod sdcard; mod sdcard;
mod virtio_blk;
use lazy_static::*;
use alloc::sync::Arc; use alloc::sync::Arc;
use easy_fs::BlockDevice; use easy_fs::BlockDevice;
use lazy_static::*;
#[cfg(feature = "board_qemu")] #[cfg(feature = "board_qemu")]
type BlockDeviceImpl = virtio_blk::VirtIOBlock; type BlockDeviceImpl = virtio_blk::VirtIOBlock;
@ -21,7 +21,9 @@ pub fn block_device_test() {
let mut write_buffer = [0u8; 512]; let mut write_buffer = [0u8; 512];
let mut read_buffer = [0u8; 512]; let mut read_buffer = [0u8; 512];
for i in 0..512 { for i in 0..512 {
for byte in write_buffer.iter_mut() { *byte = i as u8; } for byte in write_buffer.iter_mut() {
*byte = i as u8;
}
block_device.write_block(i as usize, &write_buffer); block_device.write_block(i as usize, &write_buffer);
block_device.read_block(i as usize, &mut read_buffer); block_device.read_block(i as usize, &mut read_buffer);
assert_eq!(write_buffer, read_buffer); assert_eq!(write_buffer, read_buffer);

View File

@ -2,21 +2,21 @@
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
#![allow(unused)] #![allow(unused)]
use k210_pac::{Peripherals, SPI0}; use super::BlockDevice;
use crate::sync::UPSafeCell;
use core::convert::TryInto;
use k210_hal::prelude::*; use k210_hal::prelude::*;
use k210_pac::{Peripherals, SPI0};
use k210_soc::{ use k210_soc::{
fpioa::{self, io},
//dmac::{dma_channel, DMAC, DMACExt}, //dmac::{dma_channel, DMAC, DMACExt},
gpio, gpio,
gpiohs, gpiohs,
spi::{aitm, frame_format, tmod, work_mode, SPI, SPIExt, SPIImpl},
fpioa::{self, io},
sysctl,
sleep::usleep, sleep::usleep,
spi::{aitm, frame_format, tmod, work_mode, SPIExt, SPIImpl, SPI},
sysctl,
}; };
use crate::sync::UPSafeCell;
use lazy_static::*; use lazy_static::*;
use super::BlockDevice;
use core::convert::TryInto;
pub struct SDCard<SPI> { pub struct SDCard<SPI> {
spi: SPI, spi: SPI,
@ -160,7 +160,11 @@ pub struct SDCardInfo {
} }
impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> { impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
pub fn new(spi: X, spi_cs: u32, cs_gpionum: u8/*, dmac: &'a DMAC, channel: dma_channel*/) -> Self { pub fn new(
spi: X,
spi_cs: u32,
cs_gpionum: u8, /*, dmac: &'a DMAC, channel: dma_channel*/
) -> Self {
Self { Self {
spi, spi,
spi_cs, spi_cs,
@ -606,7 +610,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
} }
let mut error = false; let mut error = false;
//let mut dma_chunk = [0u32; SEC_LEN]; //let mut dma_chunk = [0u32; SEC_LEN];
let mut tmp_chunk= [0u8; SEC_LEN]; let mut tmp_chunk = [0u8; SEC_LEN];
for chunk in data_buf.chunks_mut(SEC_LEN) { for chunk in data_buf.chunks_mut(SEC_LEN) {
if self.get_response() != SD_START_DATA_SINGLE_BLOCK_READ { if self.get_response() != SD_START_DATA_SINGLE_BLOCK_READ {
error = true; error = true;
@ -616,7 +620,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
//self.read_data_dma(&mut dma_chunk); //self.read_data_dma(&mut dma_chunk);
self.read_data(&mut tmp_chunk); self.read_data(&mut tmp_chunk);
/* Place the data received as u32 units from DMA into the u8 target buffer */ /* Place the data received as u32 units from DMA into the u8 target buffer */
for (a, b) in chunk.iter_mut().zip(/*dma_chunk*/tmp_chunk.iter()) { for (a, b) in chunk.iter_mut().zip(/*dma_chunk*/ tmp_chunk.iter()) {
//*a = (b & 0xff) as u8; //*a = (b & 0xff) as u8;
*a = *b; *a = *b;
} }
@ -675,7 +679,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
/* Send the data token to signify the start of the data */ /* Send the data token to signify the start of the data */
self.write_data(&frame); self.write_data(&frame);
/* Write the block data to SD : write count data by block */ /* Write the block data to SD : write count data by block */
for (a, &b) in /*dma_chunk*/tmp_chunk.iter_mut().zip(chunk.iter()) { for (a, &b) in /*dma_chunk*/ tmp_chunk.iter_mut().zip(chunk.iter()) {
//*a = b.into(); //*a = b.into();
*a = b; *a = b;
} }
@ -711,9 +715,8 @@ fn io_init() {
} }
lazy_static! { lazy_static! {
static ref PERIPHERALS: UPSafeCell<Peripherals> = unsafe { static ref PERIPHERALS: UPSafeCell<Peripherals> =
UPSafeCell::new(Peripherals::take().unwrap()) unsafe { UPSafeCell::new(Peripherals::take().unwrap()) };
};
} }
fn init_sdcard() -> SDCard<SPIImpl<SPI0>> { fn init_sdcard() -> SDCard<SPIImpl<SPI0>> {
@ -747,9 +750,15 @@ impl SDCardWrapper {
impl BlockDevice for SDCardWrapper { impl BlockDevice for SDCardWrapper {
fn read_block(&self, block_id: usize, buf: &mut [u8]) { fn read_block(&self, block_id: usize, buf: &mut [u8]) {
self.0.exclusive_access().read_sector(buf,block_id as u32).unwrap(); self.0
.exclusive_access()
.read_sector(buf, block_id as u32)
.unwrap();
} }
fn write_block(&self, block_id: usize, buf: &[u8]) { fn write_block(&self, block_id: usize, buf: &[u8]) {
self.0.exclusive_access().write_sector(buf,block_id as u32).unwrap(); self.0
.exclusive_access()
.write_sector(buf, block_id as u32)
.unwrap();
} }
} }

View File

@ -1,20 +1,12 @@
use virtio_drivers::{VirtIOBlk, VirtIOHeader};
use crate::mm::{
PhysAddr,
VirtAddr,
frame_alloc,
frame_dealloc,
PhysPageNum,
FrameTracker,
StepByOne,
PageTable,
kernel_token,
};
use super::BlockDevice; use super::BlockDevice;
use crate::mm::{
frame_alloc, frame_dealloc, kernel_token, FrameTracker, PageTable, PhysAddr, PhysPageNum,
StepByOne, VirtAddr,
};
use crate::sync::UPSafeCell; use crate::sync::UPSafeCell;
use alloc::vec::Vec; use alloc::vec::Vec;
use lazy_static::*; use lazy_static::*;
use virtio_drivers::{VirtIOBlk, VirtIOHeader};
#[allow(unused)] #[allow(unused)]
const VIRTIO0: usize = 0x10001000; const VIRTIO0: usize = 0x10001000;
@ -22,21 +14,21 @@ const VIRTIO0: usize = 0x10001000;
pub struct VirtIOBlock(UPSafeCell<VirtIOBlk<'static>>); pub struct VirtIOBlock(UPSafeCell<VirtIOBlk<'static>>);
lazy_static! { lazy_static! {
static ref QUEUE_FRAMES: UPSafeCell<Vec<FrameTracker>> = unsafe { static ref QUEUE_FRAMES: UPSafeCell<Vec<FrameTracker>> = unsafe { UPSafeCell::new(Vec::new()) };
UPSafeCell::new(Vec::new())
};
} }
impl BlockDevice for VirtIOBlock { impl BlockDevice for VirtIOBlock {
fn read_block(&self, block_id: usize, buf: &mut [u8]) { fn read_block(&self, block_id: usize, buf: &mut [u8]) {
self.0.exclusive_access() self.0
.read_block(block_id, buf) .exclusive_access()
.expect("Error when reading VirtIOBlk"); .read_block(block_id, buf)
.expect("Error when reading VirtIOBlk");
} }
fn write_block(&self, block_id: usize, buf: &[u8]) { fn write_block(&self, block_id: usize, buf: &[u8]) {
self.0.exclusive_access() self.0
.write_block(block_id, buf) .exclusive_access()
.expect("Error when writing VirtIOBlk"); .write_block(block_id, buf)
.expect("Error when writing VirtIOBlk");
} }
} }
@ -44,9 +36,9 @@ impl VirtIOBlock {
#[allow(unused)] #[allow(unused)]
pub fn new() -> Self { pub fn new() -> Self {
unsafe { unsafe {
Self(UPSafeCell::new(VirtIOBlk::new( Self(UPSafeCell::new(
&mut *(VIRTIO0 as *mut VirtIOHeader) VirtIOBlk::new(&mut *(VIRTIO0 as *mut VirtIOHeader)).unwrap(),
).unwrap())) ))
} }
} }
} }
@ -56,7 +48,9 @@ pub extern "C" fn virtio_dma_alloc(pages: usize) -> PhysAddr {
let mut ppn_base = PhysPageNum(0); let mut ppn_base = PhysPageNum(0);
for i in 0..pages { for i in 0..pages {
let frame = frame_alloc().unwrap(); let frame = frame_alloc().unwrap();
if i == 0 { ppn_base = frame.ppn; } if i == 0 {
ppn_base = frame.ppn;
}
assert_eq!(frame.ppn.0, ppn_base.0 + i); assert_eq!(frame.ppn.0, ppn_base.0 + i);
QUEUE_FRAMES.exclusive_access().push(frame); QUEUE_FRAMES.exclusive_access().push(frame);
} }
@ -80,5 +74,7 @@ pub extern "C" fn virtio_phys_to_virt(paddr: PhysAddr) -> VirtAddr {
#[no_mangle] #[no_mangle]
pub extern "C" fn virtio_virt_to_phys(vaddr: VirtAddr) -> PhysAddr { pub extern "C" fn virtio_virt_to_phys(vaddr: VirtAddr) -> PhysAddr {
PageTable::from_token(kernel_token()).translate_va(vaddr).unwrap() PageTable::from_token(kernel_token())
.translate_va(vaddr)
.unwrap()
} }

View File

@ -1,15 +1,12 @@
use easy_fs::{ use super::File;
EasyFileSystem,
Inode,
};
use crate::drivers::BLOCK_DEVICE; use crate::drivers::BLOCK_DEVICE;
use crate::mm::UserBuffer;
use crate::sync::UPSafeCell; use crate::sync::UPSafeCell;
use alloc::sync::Arc; use alloc::sync::Arc;
use lazy_static::*;
use bitflags::*;
use alloc::vec::Vec; use alloc::vec::Vec;
use super::File; use bitflags::*;
use crate::mm::UserBuffer; use easy_fs::{EasyFileSystem, Inode};
use lazy_static::*;
pub struct OSInode { pub struct OSInode {
readable: bool, readable: bool,
@ -23,18 +20,11 @@ pub struct OSInodeInner {
} }
impl OSInode { impl OSInode {
pub fn new( pub fn new(readable: bool, writable: bool, inode: Arc<Inode>) -> Self {
readable: bool,
writable: bool,
inode: Arc<Inode>,
) -> Self {
Self { Self {
readable, readable,
writable, writable,
inner: unsafe { UPSafeCell::new(OSInodeInner { inner: unsafe { UPSafeCell::new(OSInodeInner { offset: 0, inode }) },
offset: 0,
inode,
})},
} }
} }
pub fn read_all(&self) -> Vec<u8> { pub fn read_all(&self) -> Vec<u8> {
@ -98,40 +88,30 @@ pub fn open_file(name: &str, flags: OpenFlags) -> Option<Arc<OSInode>> {
if let Some(inode) = ROOT_INODE.find(name) { if let Some(inode) = ROOT_INODE.find(name) {
// clear size // clear size
inode.clear(); inode.clear();
Some(Arc::new(OSInode::new( Some(Arc::new(OSInode::new(readable, writable, inode)))
readable,
writable,
inode,
)))
} else { } else {
// create file // create file
ROOT_INODE.create(name) ROOT_INODE
.map(|inode| { .create(name)
Arc::new(OSInode::new( .map(|inode| Arc::new(OSInode::new(readable, writable, inode)))
readable,
writable,
inode,
))
})
} }
} else { } else {
ROOT_INODE.find(name) ROOT_INODE.find(name).map(|inode| {
.map(|inode| { if flags.contains(OpenFlags::TRUNC) {
if flags.contains(OpenFlags::TRUNC) { inode.clear();
inode.clear(); }
} Arc::new(OSInode::new(readable, writable, inode))
Arc::new(OSInode::new( })
readable,
writable,
inode
))
})
} }
} }
impl File for OSInode { impl File for OSInode {
fn readable(&self) -> bool { self.readable } fn readable(&self) -> bool {
fn writable(&self) -> bool { self.writable } self.readable
}
fn writable(&self) -> bool {
self.writable
}
fn read(&self, mut buf: UserBuffer) -> usize { fn read(&self, mut buf: UserBuffer) -> usize {
let mut inner = self.inner.exclusive_access(); let mut inner = self.inner.exclusive_access();
let mut total_read_size = 0usize; let mut total_read_size = 0usize;

View File

@ -1,14 +1,14 @@
mod stdio;
mod inode; mod inode;
mod stdio;
use crate::mm::UserBuffer; use crate::mm::UserBuffer;
pub trait File : Send + Sync { pub trait File: Send + Sync {
fn readable(&self) -> bool; fn readable(&self) -> bool;
fn writable(&self) -> bool; fn writable(&self) -> bool;
fn read(&self, buf: UserBuffer) -> usize; fn read(&self, buf: UserBuffer) -> usize;
fn write(&self, buf: UserBuffer) -> usize; fn write(&self, buf: UserBuffer) -> usize;
} }
pub use inode::{list_apps, open_file, OSInode, OpenFlags};
pub use stdio::{Stdin, Stdout}; pub use stdio::{Stdin, Stdout};
pub use inode::{OSInode, open_file, OpenFlags, list_apps};

View File

@ -1,5 +1,5 @@
use super::File; use super::File;
use crate::mm::{UserBuffer}; use crate::mm::UserBuffer;
use crate::sbi::console_getchar; use crate::sbi::console_getchar;
use crate::task::suspend_current_and_run_next; use crate::task::suspend_current_and_run_next;
@ -8,8 +8,12 @@ pub struct Stdin;
pub struct Stdout; pub struct Stdout;
impl File for Stdin { impl File for Stdin {
fn readable(&self) -> bool { true } fn readable(&self) -> bool {
fn writable(&self) -> bool { false } true
}
fn writable(&self) -> bool {
false
}
fn read(&self, mut user_buf: UserBuffer) -> usize { fn read(&self, mut user_buf: UserBuffer) -> usize {
assert_eq!(user_buf.len(), 1); assert_eq!(user_buf.len(), 1);
// busy loop // busy loop
@ -24,7 +28,9 @@ impl File for Stdin {
} }
} }
let ch = c as u8; let ch = c as u8;
unsafe { user_buf.buffers[0].as_mut_ptr().write_volatile(ch); } unsafe {
user_buf.buffers[0].as_mut_ptr().write_volatile(ch);
}
1 1
} }
fn write(&self, _user_buf: UserBuffer) -> usize { fn write(&self, _user_buf: UserBuffer) -> usize {
@ -33,9 +39,13 @@ impl File for Stdin {
} }
impl File for Stdout { impl File for Stdout {
fn readable(&self) -> bool { false } fn readable(&self) -> bool {
fn writable(&self) -> bool { true } false
fn read(&self, _user_buf: UserBuffer) -> usize{ }
fn writable(&self) -> bool {
true
}
fn read(&self, _user_buf: UserBuffer) -> usize {
panic!("Cannot read from stdout!"); panic!("Cannot read from stdout!");
} }
fn write(&self, user_buf: UserBuffer) -> usize { fn write(&self, user_buf: UserBuffer) -> usize {

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

@ -10,17 +10,17 @@ extern crate bitflags;
#[macro_use] #[macro_use]
mod console; mod console;
mod lang_items;
mod sbi;
mod syscall;
mod trap;
mod config; mod config;
mod drivers;
mod fs;
mod lang_items;
mod mm;
mod sbi;
mod sync;
mod syscall;
mod task; mod task;
mod timer; mod timer;
mod sync; mod trap;
mod mm;
mod fs;
mod drivers;
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;
@ -52,35 +52,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 {
@ -89,13 +113,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 {
@ -104,7 +138,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 {
@ -121,28 +157,20 @@ impl VirtPageNum {
impl PhysAddr { impl PhysAddr {
pub fn get_ref<T>(&self) -> &'static T { pub fn get_ref<T>(&self) -> &'static T {
unsafe { unsafe { (self.0 as *const T).as_ref().unwrap() }
(self.0 as *const T).as_ref().unwrap()
}
} }
pub fn get_mut<T>(&self) -> &'static mut T { pub fn get_mut<T>(&self) -> &'static mut T {
unsafe { unsafe { (self.0 as *mut T).as_mut().unwrap() }
(self.0 as *mut T).as_mut().unwrap()
}
} }
} }
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();
@ -165,41 +193,57 @@ impl StepByOne for PhysPageNum {
} }
#[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,
@ -62,22 +62,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
@ -88,18 +83,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> {
@ -110,9 +105,7 @@ pub fn frame_alloc() -> Option<FrameTracker> {
} }
pub fn frame_dealloc(ppn: PhysPageNum) { pub fn frame_dealloc(ppn: PhysPageNum) {
FRAME_ALLOCATOR FRAME_ALLOCATOR.exclusive_access().dealloc(ppn);
.exclusive_access()
.dealloc(ppn);
} }
#[allow(unused)] #[allow(unused)]

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,22 +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, MMIO, 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,
MMIO,
};
use core::arch::asm; use core::arch::asm;
use lazy_static::*;
use riscv::register::satp;
extern "C" { extern "C" {
fn stext(); fn stext();
@ -32,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 fn kernel_token() -> usize { pub fn kernel_token() -> usize {
@ -57,17 +49,24 @@ 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,
);
} }
pub fn remove_area_with_start_vpn(&mut self, start_vpn: VirtPageNum) { pub fn remove_area_with_start_vpn(&mut self, start_vpn: VirtPageNum) {
if let Some((idx, area)) = self.areas.iter_mut().enumerate() if let Some((idx, area)) = self
.find(|(_, area)| area.vpn_range.get_start() == start_vpn) { .areas
.iter_mut()
.enumerate()
.find(|(_, area)| area.vpn_range.get_start() == start_vpn)
{
area.unmap(&mut self.page_table); area.unmap(&mut self.page_table);
self.areas.remove(idx); self.areas.remove(idx);
} }
@ -96,50 +95,71 @@ 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,
), None);
println!("mapping .bss section");
memory_set.push(MapArea::new(
(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::new(
(ekernel as usize).into(),
MEMORY_END.into(),
MapType::Identical,
MapPermission::R | MapPermission::W,
), None);
println!("mapping memory-mapped registers");
for pair in MMIO {
memory_set.push(MapArea::new(
(*pair).0.into(),
((*pair).0 + (*pair).1).into(),
MapType::Identical, MapType::Identical,
MapPermission::R | MapPermission::W, MapPermission::R | MapPermission::W,
), None); ),
None,
);
println!("mapping .bss section");
memory_set.push(
MapArea::new(
(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::new(
(ekernel as usize).into(),
MEMORY_END.into(),
MapType::Identical,
MapPermission::R | MapPermission::W,
),
None,
);
println!("mapping memory-mapped registers");
for pair in MMIO {
memory_set.push(
MapArea::new(
(*pair).0.into(),
((*pair).0 + (*pair).1).into(),
MapType::Identical,
MapPermission::R | MapPermission::W,
),
None,
);
} }
memory_set memory_set
} }
@ -163,19 +183,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]),
); );
} }
} }
@ -185,20 +206,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 from_existed_user(user_space: &MemorySet) -> MemorySet { pub fn from_existed_user(user_space: &MemorySet) -> MemorySet {
let mut memory_set = Self::new_bare(); let mut memory_set = Self::new_bare();
@ -212,7 +243,9 @@ impl MemorySet {
for vpn in area.vpn_range { for vpn in area.vpn_range {
let src_ppn = user_space.translate(vpn).unwrap().ppn(); let src_ppn = user_space.translate(vpn).unwrap().ppn();
let dst_ppn = memory_set.translate(vpn).unwrap().ppn(); let dst_ppn = memory_set.translate(vpn).unwrap().ppn();
dst_ppn.get_bytes_array().copy_from_slice(src_ppn.get_bytes_array()); dst_ppn
.get_bytes_array()
.copy_from_slice(src_ppn.get_bytes_array());
} }
} }
memory_set memory_set
@ -245,7 +278,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();
@ -344,15 +377,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,25 +1,19 @@
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::PTEFlags;
use address::VPNRange; use address::VPNRange;
pub use address::{PhysAddr, VirtAddr, PhysPageNum, VirtPageNum, StepByOne}; pub use address::{PhysAddr, PhysPageNum, StepByOne, VirtAddr, VirtPageNum};
pub use frame_allocator::{FrameTracker, frame_alloc, frame_dealloc,}; pub use frame_allocator::{frame_alloc, frame_dealloc, FrameTracker};
pub use page_table::{
PageTable,
PageTableEntry,
translated_byte_buffer,
translated_str,
translated_ref,
translated_refmut,
UserBuffer,
UserBufferIterator,
};
pub use memory_set::{MemorySet, KERNEL_SPACE, MapPermission, kernel_token};
pub use memory_set::remap_test; pub use memory_set::remap_test;
pub use memory_set::{kernel_token, MapPermission, MemorySet, KERNEL_SPACE};
use page_table::PTEFlags;
pub use page_table::{
translated_byte_buffer, translated_ref, translated_refmut, translated_str, PageTable,
PageTableEntry, UserBuffer, UserBufferIterator,
};
pub fn init() { pub fn init() {
heap_allocator::init_heap(); heap_allocator::init_heap();

View File

@ -1,15 +1,7 @@
use super::{ use super::{frame_alloc, FrameTracker, PhysAddr, PhysPageNum, StepByOne, VirtAddr, VirtPageNum};
frame_alloc,
PhysPageNum,
FrameTracker,
VirtPageNum,
VirtAddr,
PhysAddr,
StepByOne
};
use alloc::vec::Vec;
use alloc::vec;
use alloc::string::String; use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use bitflags::*; use bitflags::*;
bitflags! { bitflags! {
@ -38,9 +30,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()
@ -132,17 +122,15 @@ 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 translate_va(&self, va: VirtAddr) -> Option<PhysAddr> { pub fn translate_va(&self, va: VirtAddr) -> Option<PhysAddr> {
self.find_pte(va.clone().floor()) self.find_pte(va.clone().floor()).map(|pte| {
.map(|pte| { let aligned_pa: PhysAddr = pte.ppn().into();
let aligned_pa: PhysAddr = pte.ppn().into(); let offset = va.page_offset();
let offset = va.page_offset(); let aligned_pa_usize: usize = aligned_pa.into();
let aligned_pa_usize: usize = aligned_pa.into(); (aligned_pa_usize + offset).into()
(aligned_pa_usize + offset).into() })
})
} }
pub fn token(&self) -> usize { pub fn token(&self) -> usize {
8usize << 60 | self.root_ppn.0 8usize << 60 | self.root_ppn.0
@ -157,10 +145,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));
@ -180,7 +165,10 @@ pub fn translated_str(token: usize, ptr: *const u8) -> String {
let mut string = String::new(); let mut string = String::new();
let mut va = ptr as usize; let mut va = ptr as usize;
loop { loop {
let ch: u8 = *(page_table.translate_va(VirtAddr::from(va)).unwrap().get_mut()); let ch: u8 = *(page_table
.translate_va(VirtAddr::from(va))
.unwrap()
.get_mut());
if ch == 0 { if ch == 0 {
break; break;
} }
@ -193,13 +181,19 @@ pub fn translated_str(token: usize, ptr: *const u8) -> String {
#[allow(unused)] #[allow(unused)]
pub fn translated_ref<T>(token: usize, ptr: *const T) -> &'static T { pub fn translated_ref<T>(token: usize, ptr: *const T) -> &'static T {
let page_table = PageTable::from_token(token); let page_table = PageTable::from_token(token);
page_table.translate_va(VirtAddr::from(ptr as usize)).unwrap().get_ref() page_table
.translate_va(VirtAddr::from(ptr as usize))
.unwrap()
.get_ref()
} }
pub fn translated_refmut<T>(token: usize, ptr: *mut T) -> &'static mut T { pub fn translated_refmut<T>(token: usize, ptr: *mut T) -> &'static mut T {
let page_table = PageTable::from_token(token); let page_table = PageTable::from_token(token);
let va = ptr as usize; let va = ptr as usize;
page_table.translate_va(VirtAddr::from(va)).unwrap().get_mut() page_table
.translate_va(VirtAddr::from(va))
.unwrap()
.get_mut()
} }
pub struct UserBuffer { pub struct UserBuffer {

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

@ -18,7 +18,9 @@ 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> {

View File

@ -1,10 +1,6 @@
use crate::mm::{ use crate::fs::{open_file, OpenFlags};
UserBuffer, use crate::mm::{translated_byte_buffer, translated_str, UserBuffer};
translated_byte_buffer, use crate::task::{current_task, current_user_token};
translated_str,
};
use crate::task::{current_user_token, current_task};
use crate::fs::{OpenFlags, open_file};
pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize { pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
let token = current_user_token(); let token = current_user_token();
@ -20,9 +16,7 @@ pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
let file = file.clone(); let file = file.clone();
// release current task TCB manually to avoid multi-borrow // release current task TCB manually to avoid multi-borrow
drop(inner); drop(inner);
file.write( file.write(UserBuffer::new(translated_byte_buffer(token, buf, len))) as isize
UserBuffer::new(translated_byte_buffer(token, buf, len))
) as isize
} else { } else {
-1 -1
} }
@ -42,9 +36,7 @@ pub fn sys_read(fd: usize, buf: *const u8, len: usize) -> isize {
} }
// release current task TCB manually to avoid multi-borrow // release current task TCB manually to avoid multi-borrow
drop(inner); drop(inner);
file.read( file.read(UserBuffer::new(translated_byte_buffer(token, buf, len))) as isize
UserBuffer::new(translated_byte_buffer(token, buf, len))
) as isize
} else { } else {
-1 -1
} }
@ -54,10 +46,7 @@ pub fn sys_open(path: *const u8, flags: u32) -> isize {
let task = current_task().unwrap(); let task = current_task().unwrap();
let token = current_user_token(); let token = current_user_token();
let path = translated_str(token, path); let path = translated_str(token, path);
if let Some(inode) = open_file( if let Some(inode) = open_file(path.as_str(), OpenFlags::from_bits(flags).unwrap()) {
path.as_str(),
OpenFlags::from_bits(flags).unwrap()
) {
let mut inner = task.inner_exclusive_access(); let mut inner = task.inner_exclusive_access();
let fd = inner.alloc_fd(); let fd = inner.alloc_fd();
inner.fd_table[fd] = Some(inode); inner.fd_table[fd] = Some(inode);

View File

@ -32,4 +32,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,19 +1,10 @@
use crate::fs::{open_file, OpenFlags};
use crate::mm::{translated_refmut, translated_str};
use crate::task::{ use crate::task::{
add_task, current_task, current_user_token, exit_current_and_run_next,
suspend_current_and_run_next, suspend_current_and_run_next,
exit_current_and_run_next,
current_task,
current_user_token,
add_task,
}; };
use crate::timer::get_time_ms; use crate::timer::get_time_ms;
use crate::mm::{
translated_str,
translated_refmut,
};
use crate::fs::{
open_file,
OpenFlags,
};
use alloc::sync::Arc; use alloc::sync::Arc;
pub fn sys_exit(exit_code: i32) -> ! { pub fn sys_exit(exit_code: i32) -> ! {
@ -69,21 +60,20 @@ pub fn sys_waitpid(pid: isize, exit_code_ptr: *mut i32) -> isize {
// ---- access current PCB exclusively // ---- access current PCB exclusively
let mut inner = task.inner_exclusive_access(); let mut inner = task.inner_exclusive_access();
if inner.children if inner
.children
.iter() .iter()
.find(|p| {pid == -1 || pid as usize == p.getpid()}) .find(|p| pid == -1 || pid as usize == p.getpid())
.is_none() { .is_none()
{
return -1; return -1;
// ---- release current PCB // ---- release current PCB
} }
let pair = inner.children let pair = inner.children.iter().enumerate().find(|(_, p)| {
.iter() // ++++ temporarily access child PCB exclusively
.enumerate() p.inner_exclusive_access().is_zombie() && (pid == -1 || pid as usize == p.getpid())
.find(|(_, p)| { // ++++ release child PCB
// ++++ temporarily access child PCB exclusively });
p.inner_exclusive_access().is_zombie() && (pid == -1 || pid as usize == p.getpid())
// ++++ release child PCB
});
if let Some((idx, _)) = pair { if let Some((idx, _)) = pair {
let child = inner.children.remove(idx); let child = inner.children.remove(idx);
// confirm that child will be deallocated after being removed from children list // confirm that child will be deallocated after being removed from children list

View File

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

View File

@ -1,5 +1,5 @@
use crate::sync::UPSafeCell;
use super::TaskControlBlock; use super::TaskControlBlock;
use crate::sync::UPSafeCell;
use alloc::collections::VecDeque; use alloc::collections::VecDeque;
use alloc::sync::Arc; use alloc::sync::Arc;
use lazy_static::*; use lazy_static::*;
@ -11,7 +11,9 @@ pub struct TaskManager {
/// A simple FIFO scheduler. /// A simple FIFO scheduler.
impl TaskManager { impl TaskManager {
pub fn new() -> Self { pub fn new() -> Self {
Self { ready_queue: VecDeque::new(), } Self {
ready_queue: VecDeque::new(),
}
} }
pub fn add(&mut self, task: Arc<TaskControlBlock>) { pub fn add(&mut self, task: Arc<TaskControlBlock>) {
self.ready_queue.push_back(task); self.ready_queue.push_back(task);
@ -22,9 +24,8 @@ impl TaskManager {
} }
lazy_static! { lazy_static! {
pub static ref TASK_MANAGER: UPSafeCell<TaskManager> = unsafe { pub static ref TASK_MANAGER: UPSafeCell<TaskManager> =
UPSafeCell::new(TaskManager::new()) unsafe { UPSafeCell::new(TaskManager::new()) };
};
} }
pub fn add_task(task: Arc<TaskControlBlock>) { pub fn add_task(task: Arc<TaskControlBlock>) {

View File

@ -1,28 +1,23 @@
mod context; mod context;
mod manager;
mod pid;
mod processor;
mod switch; mod switch;
mod task; mod task;
mod manager;
mod processor;
mod pid;
use crate::fs::{open_file, OpenFlags}; use crate::fs::{open_file, OpenFlags};
use alloc::sync::Arc;
pub use context::TaskContext;
use lazy_static::*;
use manager::fetch_task;
use switch::__switch; use switch::__switch;
use task::{TaskControlBlock, TaskStatus}; use task::{TaskControlBlock, TaskStatus};
use alloc::sync::Arc;
use manager::fetch_task;
use lazy_static::*;
pub use context::TaskContext;
pub use processor::{
run_tasks,
current_task,
current_user_token,
current_trap_cx,
take_current_task,
schedule,
};
pub use manager::add_task; pub use manager::add_task;
pub use pid::{PidHandle, pid_alloc, KernelStack}; pub use pid::{pid_alloc, KernelStack, PidHandle};
pub use processor::{
current_task, current_trap_cx, current_user_token, run_tasks, schedule, take_current_task,
};
pub fn suspend_current_and_run_next() { pub fn suspend_current_and_run_next() {
// There must be an application running. // There must be an application running.

View File

@ -1,12 +1,8 @@
use crate::config::{KERNEL_STACK_SIZE, PAGE_SIZE, TRAMPOLINE};
use crate::mm::{MapPermission, VirtAddr, KERNEL_SPACE};
use crate::sync::UPSafeCell;
use alloc::vec::Vec; use alloc::vec::Vec;
use lazy_static::*; use lazy_static::*;
use crate::sync::UPSafeCell;
use crate::mm::{KERNEL_SPACE, MapPermission, VirtAddr};
use crate::config::{
PAGE_SIZE,
TRAMPOLINE,
KERNEL_STACK_SIZE,
};
struct PidAllocator { struct PidAllocator {
current: usize, current: usize,
@ -32,16 +28,16 @@ impl PidAllocator {
assert!(pid < self.current); assert!(pid < self.current);
assert!( assert!(
self.recycled.iter().find(|ppid| **ppid == pid).is_none(), self.recycled.iter().find(|ppid| **ppid == pid).is_none(),
"pid {} has been deallocated!", pid "pid {} has been deallocated!",
pid
); );
self.recycled.push(pid); self.recycled.push(pid);
} }
} }
lazy_static! { lazy_static! {
static ref PID_ALLOCATOR : UPSafeCell<PidAllocator> = unsafe { static ref PID_ALLOCATOR: UPSafeCell<PidAllocator> =
UPSafeCell::new(PidAllocator::new()) unsafe { UPSafeCell::new(PidAllocator::new()) };
};
} }
pub struct PidHandle(pub usize); pub struct PidHandle(pub usize);
@ -72,23 +68,23 @@ impl KernelStack {
pub fn new(pid_handle: &PidHandle) -> Self { pub fn new(pid_handle: &PidHandle) -> Self {
let pid = pid_handle.0; let pid = pid_handle.0;
let (kernel_stack_bottom, kernel_stack_top) = kernel_stack_position(pid); let (kernel_stack_bottom, kernel_stack_top) = kernel_stack_position(pid);
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, KernelStack { pid: pid_handle.0 }
);
KernelStack {
pid: pid_handle.0,
}
} }
#[allow(unused)] #[allow(unused)]
pub fn push_on_top<T>(&self, value: T) -> *mut T where pub fn push_on_top<T>(&self, value: T) -> *mut T
T: Sized, { where
T: Sized,
{
let kernel_stack_top = self.get_top(); let kernel_stack_top = self.get_top();
let ptr_mut = (kernel_stack_top - core::mem::size_of::<T>()) as *mut T; let ptr_mut = (kernel_stack_top - core::mem::size_of::<T>()) as *mut T;
unsafe { *ptr_mut = value; } unsafe {
*ptr_mut = value;
}
ptr_mut ptr_mut
} }
pub fn get_top(&self) -> usize { pub fn get_top(&self) -> usize {

View File

@ -1,10 +1,10 @@
use super::__switch;
use super::{fetch_task, TaskStatus};
use super::{TaskContext, TaskControlBlock}; use super::{TaskContext, TaskControlBlock};
use crate::sync::UPSafeCell;
use crate::trap::TrapContext;
use alloc::sync::Arc; use alloc::sync::Arc;
use lazy_static::*; use lazy_static::*;
use super::{fetch_task, TaskStatus};
use super::__switch;
use crate::trap::TrapContext;
use crate::sync::UPSafeCell;
pub struct Processor { pub struct Processor {
current: Option<Arc<TaskControlBlock>>, current: Option<Arc<TaskControlBlock>>,
@ -30,9 +30,7 @@ impl Processor {
} }
lazy_static! { lazy_static! {
pub static ref PROCESSOR: UPSafeCell<Processor> = unsafe { pub static ref PROCESSOR: UPSafeCell<Processor> = unsafe { UPSafeCell::new(Processor::new()) };
UPSafeCell::new(Processor::new())
};
} }
pub fn run_tasks() { pub fn run_tasks() {
@ -50,10 +48,7 @@ pub fn run_tasks() {
// release processor manually // release processor manually
drop(processor); drop(processor);
unsafe { unsafe {
__switch( __switch(idle_task_cx_ptr, next_task_cx_ptr);
idle_task_cx_ptr,
next_task_cx_ptr,
);
} }
} }
} }
@ -74,7 +69,10 @@ pub fn current_user_token() -> usize {
} }
pub fn current_trap_cx() -> &'static mut TrapContext { pub fn current_trap_cx() -> &'static mut TrapContext {
current_task().unwrap().inner_exclusive_access().get_trap_cx() current_task()
.unwrap()
.inner_exclusive_access()
.get_trap_cx()
} }
pub fn schedule(switched_task_cx_ptr: *mut TaskContext) { pub fn schedule(switched_task_cx_ptr: *mut TaskContext) {
@ -82,9 +80,6 @@ pub fn schedule(switched_task_cx_ptr: *mut TaskContext) {
let idle_task_cx_ptr = processor.get_idle_task_cx_ptr(); let idle_task_cx_ptr = processor.get_idle_task_cx_ptr();
drop(processor); drop(processor);
unsafe { unsafe {
__switch( __switch(switched_task_cx_ptr, idle_task_cx_ptr);
switched_task_cx_ptr,
idle_task_cx_ptr,
);
} }
} }

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,19 +1,14 @@
use crate::mm::{
MemorySet,
PhysPageNum,
KERNEL_SPACE,
VirtAddr,
};
use crate::trap::{TrapContext, trap_handler};
use crate::config::TRAP_CONTEXT;
use crate::sync::UPSafeCell;
use core::cell::RefMut;
use super::TaskContext; use super::TaskContext;
use super::{PidHandle, pid_alloc, KernelStack}; use super::{pid_alloc, KernelStack, PidHandle};
use alloc::sync::{Weak, Arc}; use crate::config::TRAP_CONTEXT;
use crate::fs::{File, Stdin, Stdout};
use crate::mm::{MemorySet, PhysPageNum, VirtAddr, KERNEL_SPACE};
use crate::sync::UPSafeCell;
use crate::trap::{trap_handler, TrapContext};
use alloc::sync::{Arc, Weak};
use alloc::vec; use alloc::vec;
use alloc::vec::Vec; use alloc::vec::Vec;
use crate::fs::{File, Stdin, Stdout}; use core::cell::RefMut;
pub struct TaskControlBlock { pub struct TaskControlBlock {
// immutable // immutable
@ -49,8 +44,7 @@ impl TaskControlBlockInner {
self.get_status() == TaskStatus::Zombie self.get_status() == TaskStatus::Zombie
} }
pub fn alloc_fd(&mut self) -> usize { pub fn alloc_fd(&mut self) -> usize {
if let Some(fd) = (0..self.fd_table.len()) if let Some(fd) = (0..self.fd_table.len()).find(|fd| self.fd_table[*fd].is_none()) {
.find(|fd| self.fd_table[*fd].is_none()) {
fd fd
} else { } else {
self.fd_table.push(None); self.fd_table.push(None);
@ -77,24 +71,26 @@ impl TaskControlBlock {
let task_control_block = Self { let task_control_block = Self {
pid: pid_handle, pid: pid_handle,
kernel_stack, kernel_stack,
inner: unsafe { UPSafeCell::new(TaskControlBlockInner { inner: unsafe {
trap_cx_ppn, UPSafeCell::new(TaskControlBlockInner {
base_size: user_sp, trap_cx_ppn,
task_cx: TaskContext::goto_trap_return(kernel_stack_top), base_size: user_sp,
task_status: TaskStatus::Ready, task_cx: TaskContext::goto_trap_return(kernel_stack_top),
memory_set, task_status: TaskStatus::Ready,
parent: None, memory_set,
children: Vec::new(), parent: None,
exit_code: 0, children: Vec::new(),
fd_table: vec![ exit_code: 0,
// 0 -> stdin fd_table: vec![
Some(Arc::new(Stdin)), // 0 -> stdin
// 1 -> stdout Some(Arc::new(Stdin)),
Some(Arc::new(Stdout)), // 1 -> stdout
// 2 -> stderr Some(Arc::new(Stdout)),
Some(Arc::new(Stdout)), // 2 -> stderr
], Some(Arc::new(Stdout)),
})}, ],
})
},
}; };
// prepare TrapContext in user space // prepare TrapContext in user space
let trap_cx = task_control_block.inner_exclusive_access().get_trap_cx(); let trap_cx = task_control_block.inner_exclusive_access().get_trap_cx();
@ -136,9 +132,7 @@ impl TaskControlBlock {
// ---- hold parent PCB lock // ---- hold parent PCB lock
let mut parent_inner = self.inner_exclusive_access(); let mut parent_inner = self.inner_exclusive_access();
// copy user space(include trap context) // copy user space(include trap context)
let memory_set = MemorySet::from_existed_user( let memory_set = MemorySet::from_existed_user(&parent_inner.memory_set);
&parent_inner.memory_set
);
let trap_cx_ppn = memory_set let trap_cx_ppn = memory_set
.translate(VirtAddr::from(TRAP_CONTEXT).into()) .translate(VirtAddr::from(TRAP_CONTEXT).into())
.unwrap() .unwrap()
@ -159,17 +153,19 @@ impl TaskControlBlock {
let task_control_block = Arc::new(TaskControlBlock { let task_control_block = Arc::new(TaskControlBlock {
pid: pid_handle, pid: pid_handle,
kernel_stack, kernel_stack,
inner: unsafe { UPSafeCell::new(TaskControlBlockInner { inner: unsafe {
trap_cx_ppn, UPSafeCell::new(TaskControlBlockInner {
base_size: parent_inner.base_size, trap_cx_ppn,
task_cx: TaskContext::goto_trap_return(kernel_stack_top), base_size: parent_inner.base_size,
task_status: TaskStatus::Ready, task_cx: TaskContext::goto_trap_return(kernel_stack_top),
memory_set, task_status: TaskStatus::Ready,
parent: Some(Arc::downgrade(self)), memory_set,
children: Vec::new(), parent: Some(Arc::downgrade(self)),
exit_code: 0, children: Vec::new(),
fd_table: new_fd_table, exit_code: 0,
})}, fd_table: new_fd_table,
})
},
}); });
// add child // add child
parent_inner.children.push(task_control_block.clone()); parent_inner.children.push(task_control_block.clone());
@ -185,7 +181,6 @@ impl TaskControlBlock {
pub fn getpid(&self) -> usize { pub fn getpid(&self) -> usize {
self.pid.0 self.pid.0
} }
} }
#[derive(Copy, Clone, PartialEq)] #[derive(Copy, Clone, PartialEq)]

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)]
#[derive(Debug)] #[derive(Debug)]
@ -12,7 +12,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]
@ -61,12 +53,12 @@ pub fn trap_handler() -> ! {
cx = current_trap_cx(); cx = current_trap_cx();
cx.x[10] = result as usize; cx.x[10] = result as usize;
} }
Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StoreFault)
Trap::Exception(Exception::StorePageFault) | | Trap::Exception(Exception::StorePageFault)
Trap::Exception(Exception::InstructionFault) | | Trap::Exception(Exception::InstructionFault)
Trap::Exception(Exception::InstructionPageFault) | | Trap::Exception(Exception::InstructionPageFault)
Trap::Exception(Exception::LoadFault) | | Trap::Exception(Exception::LoadFault)
Trap::Exception(Exception::LoadPageFault) => { | Trap::Exception(Exception::LoadPageFault) => {
println!( println!(
"[kernel] {:?} in application, bad addr = {:#x}, bad instruction = {:#x}, kernel killed it.", "[kernel] {:?} in application, bad addr = {:#x}, bad instruction = {:#x}, kernel killed it.",
scause.cause(), scause.cause(),
@ -86,7 +78,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
);
} }
} }
//println!("before trap_return"); //println!("before trap_return");

View File

@ -3,7 +3,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{fork, yield_, waitpid, exit, wait}; use user_lib::{exit, fork, wait, waitpid, yield_};
const MAGIC: i32 = -0x10384; const MAGIC: i32 = -0x10384;
@ -13,7 +13,9 @@ pub fn main() -> i32 {
let pid = fork(); let pid = fork();
if pid == 0 { if pid == 0 {
println!("I am the child."); println!("I am the child.");
for _ in 0..7 { yield_(); } for _ in 0..7 {
yield_();
}
exit(MAGIC); exit(MAGIC);
} else { } else {
println!("I am parent, fork a child pid {}", pid); println!("I am parent, fork a child pid {}", pid);
@ -26,4 +28,3 @@ pub fn main() -> i32 {
println!("exit pass."); println!("exit pass.");
0 0
} }

View File

@ -4,13 +4,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{ use user_lib::{close, open, read, write, OpenFlags};
open,
close,
read,
write,
OpenFlags,
};
#[no_mangle] #[no_mangle]
pub fn main() -> i32 { pub fn main() -> i32 {
@ -29,10 +23,7 @@ pub fn main() -> i32 {
let read_len = read(fd, &mut buffer) as usize; let read_len = read(fd, &mut buffer) as usize;
close(fd); close(fd);
assert_eq!( assert_eq!(test_str, core::str::from_utf8(&buffer[..read_len]).unwrap(),);
test_str,
core::str::from_utf8(&buffer[..read_len]).unwrap(),
);
println!("file_test passed!"); println!("file_test passed!");
0 0
} }

View File

@ -4,7 +4,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{fork, wait, exit}; use user_lib::{exit, fork, wait};
const MAX_CHILD: usize = 30; const MAX_CHILD: usize = 30;

View File

@ -4,7 +4,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{fork, wait, getpid, exit, sleep, get_time}; use user_lib::{exit, fork, get_time, getpid, sleep, wait};
static NUM: usize = 30; static NUM: usize = 30;
@ -14,7 +14,8 @@ pub fn main() -> i32 {
let pid = fork(); let pid = fork();
if pid == 0 { if pid == 0 {
let current_time = get_time(); let current_time = get_time();
let sleep_length = (current_time as i32 as isize) * (current_time as i32 as isize) % 1000 + 1000; let sleep_length =
(current_time as i32 as isize) * (current_time as i32 as isize) % 1000 + 1000;
println!("pid {} sleep for {} ms", getpid(), sleep_length); println!("pid {} sleep for {} ms", getpid(), sleep_length);
sleep(sleep_length as usize); sleep(sleep_length as usize);
println!("pid {} OK!", getpid()); println!("pid {} OK!", getpid());

View File

@ -4,7 +4,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{sleep, getpid, fork, exit, yield_}; use user_lib::{exit, fork, getpid, sleep, yield_};
const DEPTH: usize = 4; const DEPTH: usize = 4;

View File

@ -4,19 +4,13 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{ use user_lib::{close, get_time, open, write, OpenFlags};
OpenFlags,
open,
close,
write,
get_time,
};
#[no_mangle] #[no_mangle]
pub fn main() -> i32 { pub fn main() -> i32 {
let mut buffer = [0u8; 1024]; // 1KiB let mut buffer = [0u8; 1024]; // 1KiB
for i in 0..buffer.len() { for (i, ch) in buffer.iter_mut().enumerate() {
buffer[i] = i as u8; *ch = i as u8;
} }
let f = open("testf\0", OpenFlags::CREATE | OpenFlags::WRONLY); let f = open("testf\0", OpenFlags::CREATE | OpenFlags::WRONLY);
if f < 0 { if f < 0 {
@ -25,12 +19,15 @@ pub fn main() -> i32 {
let f = f as usize; let f = f as usize;
let start = get_time(); let start = get_time();
let size_mb = 1usize; let size_mb = 1usize;
for _ in 0..1024*size_mb { for _ in 0..1024 * size_mb {
write(f, &buffer); write(f, &buffer);
} }
close(f); close(f);
let time_ms = (get_time() - start) as usize; let time_ms = (get_time() - start) as usize;
let speed_kbs = size_mb * 1000000 / time_ms; let speed_kbs = size_mb * 1000000 / time_ms;
println!("{}MiB written, time cost = {}ms, write speed = {}KiB/s", size_mb, time_ms, speed_kbs); println!(
"{}MiB written, time cost = {}ms, write speed = {}KiB/s",
size_mb, time_ms, speed_kbs
);
0 0
} }

View File

@ -4,12 +4,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{ use user_lib::{exec, fork, wait, yield_};
fork,
wait,
exec,
yield_,
};
#[no_mangle] #[no_mangle]
fn main() -> i32 { fn main() -> i32 {
@ -25,8 +20,7 @@ fn main() -> i32 {
} }
println!( println!(
"[initproc] Released a zombie process, pid={}, exit_code={}", "[initproc] Released a zombie process, pid={}, exit_code={}",
pid, pid, exit_code,
exit_code,
); );
} }
} }

View File

@ -1,10 +1,11 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#![allow(clippy::needless_range_loop)]
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{fork, wait, yield_, exit, getpid, get_time}; use user_lib::{exit, fork, get_time, getpid, wait, yield_};
static NUM: usize = 30; static NUM: usize = 30;
const N: usize = 10; const N: usize = 10;

View File

@ -4,7 +4,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{fork, exec, wait}; use user_lib::{exec, fork, wait};
#[no_mangle] #[no_mangle]
pub fn main() -> i32 { pub fn main() -> i32 {

View File

@ -4,7 +4,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
use user_lib::{sleep, exit, get_time, fork, waitpid}; use user_lib::{exit, fork, get_time, sleep, waitpid};
fn sleepy() { fn sleepy() {
let time: usize = 100; let time: usize = 100;

View File

@ -13,7 +13,11 @@ pub fn main() -> i32 {
println!("current time_msec = {}", start); println!("current time_msec = {}", start);
sleep(100); sleep(100);
let end = get_time(); let end = get_time();
println!("time_msec = {} after sleeping 100 ticks, delta = {}ms!", end, end - start); println!(
"time_msec = {} after sleeping 100 ticks, delta = {}ms!",
end,
end - start
);
println!("r_sleep passed!"); println!("r_sleep passed!");
0 0
} }

View File

@ -5,7 +5,7 @@
extern crate user_lib; extern crate user_lib;
fn f(d: usize) { fn f(d: usize) {
println!("d = {}",d); println!("d = {}", d);
f(d + 1); f(d + 1);
} }

View File

@ -1,5 +1,6 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#![allow(clippy::println_empty_string)]
extern crate alloc; extern crate alloc;
@ -12,8 +13,8 @@ const DL: u8 = 0x7fu8;
const BS: u8 = 0x08u8; const BS: u8 = 0x08u8;
use alloc::string::String; use alloc::string::String;
use user_lib::{fork, exec, waitpid};
use user_lib::console::getchar; use user_lib::console::getchar;
use user_lib::{exec, fork, waitpid};
#[no_mangle] #[no_mangle]
pub fn main() -> i32 { pub fn main() -> i32 {
@ -60,4 +61,3 @@ pub fn main() -> i32 {
} }
} }
} }

View File

@ -32,7 +32,10 @@ pub fn main() -> i32 {
let mut exit_code: i32 = Default::default(); let mut exit_code: i32 = Default::default();
let wait_pid = waitpid(pid as usize, &mut exit_code); let wait_pid = waitpid(pid as usize, &mut exit_code);
assert_eq!(pid, wait_pid); assert_eq!(pid, wait_pid);
println!("\x1b[32mUsertests: Test {} in Process {} exited with code {}\x1b[0m", test, pid, exit_code); println!(
"\x1b[32mUsertests: Test {} in Process {} exited with code {}\x1b[0m",
test, pid, exit_code
);
} }
} }
println!("Usertests passed!"); println!("Usertests passed!");

View File

@ -4,7 +4,12 @@ use super::exit;
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);
} }

View File

@ -5,15 +5,15 @@
#[macro_use] #[macro_use]
pub mod console; pub mod console;
mod syscall;
mod lang_items; mod lang_items;
mod syscall;
extern crate alloc; extern crate alloc;
#[macro_use] #[macro_use]
extern crate bitflags; extern crate bitflags;
use syscall::*;
use buddy_system_allocator::LockedHeap; use buddy_system_allocator::LockedHeap;
use syscall::*;
const USER_HEAP_SIZE: usize = 32768; const USER_HEAP_SIZE: usize = 32768;
@ -53,20 +53,42 @@ bitflags! {
} }
} }
pub fn open(path: &str, flags: OpenFlags) -> isize { sys_open(path, flags.bits) } pub fn open(path: &str, flags: OpenFlags) -> isize {
pub fn close(fd: usize) -> isize { sys_close(fd) } sys_open(path, flags.bits)
pub fn read(fd: usize, buf: &mut [u8]) -> isize { sys_read(fd, buf) } }
pub fn write(fd: usize, buf: &[u8]) -> isize { sys_write(fd, buf) } pub fn close(fd: usize) -> isize {
pub fn exit(exit_code: i32) -> ! { sys_exit(exit_code); } sys_close(fd)
pub fn yield_() -> isize { sys_yield() } }
pub fn get_time() -> isize { sys_get_time() } pub fn read(fd: usize, buf: &mut [u8]) -> isize {
pub fn getpid() -> isize { sys_getpid() } sys_read(fd, buf)
pub fn fork() -> isize { sys_fork() } }
pub fn exec(path: &str) -> isize { sys_exec(path) } pub fn write(fd: usize, buf: &[u8]) -> isize {
sys_write(fd, buf)
}
pub fn exit(exit_code: i32) -> ! {
sys_exit(exit_code);
}
pub fn yield_() -> isize {
sys_yield()
}
pub fn get_time() -> isize {
sys_get_time()
}
pub fn getpid() -> isize {
sys_getpid()
}
pub fn fork() -> isize {
sys_fork()
}
pub fn exec(path: &str) -> isize {
sys_exec(path)
}
pub fn wait(exit_code: &mut i32) -> isize { pub fn wait(exit_code: &mut i32) -> isize {
loop { loop {
match sys_waitpid(-1, exit_code as *mut _) { match sys_waitpid(-1, exit_code as *mut _) {
-2 => { yield_(); } -2 => {
yield_();
}
// -1 or a real pid // -1 or a real pid
exit_pid => return exit_pid, exit_pid => return exit_pid,
} }
@ -76,7 +98,9 @@ pub fn wait(exit_code: &mut i32) -> isize {
pub fn waitpid(pid: usize, exit_code: &mut i32) -> isize { pub fn waitpid(pid: usize, exit_code: &mut i32) -> isize {
loop { loop {
match sys_waitpid(pid as isize, exit_code as *mut _) { match sys_waitpid(pid as isize, exit_code as *mut _) {
-2 => { yield_(); } -2 => {
yield_();
}
// -1 or a real pid // -1 or a real pid
exit_pid => return exit_pid, exit_pid => return exit_pid,
} }

View File

@ -35,7 +35,10 @@ pub fn sys_close(fd: usize) -> isize {
} }
pub fn sys_read(fd: usize, buffer: &mut [u8]) -> isize { pub fn sys_read(fd: usize, buffer: &mut [u8]) -> isize {
syscall(SYSCALL_READ, [fd, buffer.as_mut_ptr() as usize, buffer.len()]) syscall(
SYSCALL_READ,
[fd, buffer.as_mut_ptr() as usize, buffer.len()],
)
} }
pub fn sys_write(fd: usize, buffer: &[u8]) -> isize { pub fn sys_write(fd: usize, buffer: &[u8]) -> isize {