Compare commits

...

45 Commits
main ... ch7

Author SHA1 Message Date
Yu Chen 6906508d6c add cargo fmt in Makefile, and exec make fmt
3 years ago
Yifan Wu 8b8e48fd6d Fix #69.
3 years ago
Yu Chen 855dc0d393 add kernel print info for default sig action
3 years ago
Yu Chen aa91ba8a9e clean comments in kernel, and fix typo in usr app:sig_ctrlc
3 years ago
Yu Chen ce7e6bc668 default signal for ctrl_c can work now. p.s. add more debug info
3 years ago
Yu Chen 2ba356050d add ctrl-c response in fs/stdio.rs::read. But the default sig action for SIGINT is still wrong
3 years ago
Yu Chen 32098d61d3 add usr app: sig_ctrlc for sig testing
3 years ago
Yu Chen 40c84071c0 add usr app: getchar
3 years ago
Yu Chen 6a6dd5e948 fix little bug on SIGDEF
3 years ago
Yu Chen ad28f5f627 update signal impl and apps
3 years ago
liusm18 a6b278fe10 Fix coding style & add one more test
3 years ago
liusm18 ae1a50673d Remove sigret.S
3 years ago
liusm18 7a97faee6c Add signal user lib
3 years ago
liusm18 1d7b8141f0 Add sigret and finish signal handling
3 years ago
liusm18 fae8641f36 Add sigaction struct and sys_call
3 years ago
liusm18 598d8d4538 Add sigprocmask
3 years ago
liusm18 c8542d6107 Modify signal.rs and sys_kill to support more signals
3 years ago
csuastt 639643bc5f
Merge pull request #1 from rcore-os/ch7
3 years ago
Yifan Wu 3edce0932f Bump Rust to nightly-2022-04-11 && support debugging in release mode
3 years ago
Yu Chen 50db31e463 update README
3 years ago
Yu Chen 10fe9b8ffe add CI for build-doc
3 years ago
Yifan Wu 7408b1a7b2 Add boards/ && cargo clippy
3 years ago
Yifan Wu 91710ba1a5 Cargo fmt
3 years ago
Yifan Wu 9df03206f9 Add infloop&until_timeout
3 years ago
Yifan Wu d1233cbb69 Support SIGABRT when the application panics.
3 years ago
Yifan Wu 1f55fbe4a2 Add some tests from ch2 && support SIGSEGV&SIGILL
3 years ago
Yifan Wu 4a169450f8 Fix cat
3 years ago
Yifan Wu 0d189e9ad7 Cargo fmt
3 years ago
Yifan Wu 2f5cff7e21 cargo clippy
3 years ago
Yifan Wu ad85266da1 Remove unmeaningful messages of initproc/user_shell
3 years ago
Yifan Wu 87e61ef7e9 Drop fd_table when a process exits; user_shell supports pipes
3 years ago
Yifan Wu 2ec8a4d28b Bump Rust to nightly-2022-01-19
3 years ago
Yifan Wu 675fe88fea Maximum concurrent processes from 40/35->30.
3 years ago
Yifan Wu 53855b9997 Update .gitignore
3 years ago
Yifan Wu d01b99d3f9 Remove os/src/loader.rs && Update testcases cat and huge_write
4 years ago
Yifan Wu 4822f6253a Add easy-fs-fuse/.gitignore
4 years ago
Yifan Wu a97e29fdb1 Now PageTable::unmap calls PageTable::find_pte instead of PageTable::find_pte_create.
4 years ago
Yifan Wu 39c9c80d35 Kernel cannot dump now.
4 years ago
Yifan Wu 11cdc5f2e6 Bump to rust nightly-2022-01-01, feature global_asm,asm->stable
4 years ago
Yifan Wu b001d3c98e Bump to Rust nightly 2021-12-15
4 years ago
Yifan Wu c0d41dccf6 Update os/Makefile, rm ... -f -> rm -f ...
4 years ago
Yu Chen 913ea57a94 update .gitignore, README.md, dev-env-info.md
4 years ago
Yifan Wu 940e88a002 Now construction of PA/VA only uses 56/39 bits.
4 years ago
Yifan Wu bb98f7f88c rust->nightly-2021-10-15,cargo-binutils->0.3.3
4 years ago
Yifan Wu 7eda37a407 user base from 0x0->0x10000; user image size from 128MiB->16MiB
4 years ago

@ -0,0 +1,25 @@
name: Build Rust Doc
on: [push]
env:
CARGO_TERM_COLOR: always
jobs:
build-doc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build doc
run: |
rustup target add riscv64gc-unknown-none-elf
rustup component add llvm-tools-preview
rustup component add rust-src
cd os
cargo doc --no-deps --verbose
- name: Deploy to Github Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./os/target/riscv64gc-unknown-none-elf/doc
destination_dir: ${{ github.ref_name }}

10
.gitignore vendored

@ -1,9 +1,12 @@
.idea/*
os/target/*
os/.idea/*
.idea
Cargo.lock
target
os/src/link_app.S
os/src/linker.ld
os/last-*
os/Cargo.lock
os/.gdb_history
user/build
user/target/*
user/.idea/*
user/Cargo.lock
@ -12,3 +15,4 @@ easy-fs/target/*
easy-fs-fuse/Cargo.lock
easy-fs-fuse/target/*
tools/
pushall.sh

@ -6,3 +6,5 @@ docker:
build_docker:
docker build -t ${DOCKER_NAME} .
fmt:
cd easy-fs; cargo fmt; cd ../easy-fs-fuse cargo fmt; cd ../os ; cargo fmt; cd ../user; cargo fmt; cd ..

@ -1,16 +1,260 @@
# rCore-Tutorial-v3
rCore-Tutorial version 3.x
rCore-Tutorial version 3.5. See the [Documentation in Chinese](https://rcore-os.github.io/rCore-Tutorial-Book-v3/).
## Dependency
rCore-Tutorial API Docs. See the [API Docs of Ten OSes ](#OS-API-DOCS)
### Binaries
Official QQ group number: 735045051
* rustc 1.56.0-nightly (08095fc1f 2021-07-26)
## news
- 25/01/2022: Version 3.6.0 is on the way! Now we directly update the code on chX branches, please periodically check if there are any updates.
* qemu: 5.0.0
## Overview
* rustsbi-lib: 0.2.0-alpha.4
This project aims to show how to write an **Unix-like OS** running on **RISC-V** platforms **from scratch** in **[Rust](https://www.rust-lang.org/)** for **beginners** without any background knowledge about **computer architectures, assembly languages or operating systems**.
rustsbi-qemu: d4968dd2
## Features
rustsbi-k210: b689314e
* Platform supported: `qemu-system-riscv64` simulator or dev boards based on [Kendryte K210 SoC](https://canaan.io/product/kendryteai) such as [Maix Dock](https://www.seeedstudio.com/Sipeed-MAIX-Dock-p-4815.html)
* OS
* concurrency of multiple processes each of which contains mutiple native threads
* preemptive scheduling(Round-Robin algorithm)
* dynamic memory management in kernel
* virtual memory
* a simple file system with a block cache
* an interactive shell in the userspace
* **only 4K+ LoC**
* [A detailed documentation in Chinese](https://rcore-os.github.io/rCore-Tutorial-Book-v3/) in spite of the lack of comments in the code(English version is not available at present)
## Prerequisites
### Install Rust
See [official guide](https://www.rust-lang.org/tools/install).
Install some tools:
```sh
$ rustup target add riscv64gc-unknown-none-elf
$ cargo install cargo-binutils --vers =0.3.3
$ rustup component add llvm-tools-preview
$ rustup component add rust-src
```
### Install Qemu
Here we manually compile and install Qemu 5.0.0. For example, on Ubuntu 18.04:
```sh
# install dependency packages
$ sudo apt install autoconf automake autotools-dev curl libmpc-dev libmpfr-dev libgmp-dev \
gawk build-essential bison flex texinfo gperf libtool patchutils bc \
zlib1g-dev libexpat-dev pkg-config libglib2.0-dev libpixman-1-dev git tmux python3 python3-pip
# download Qemu source code
$ wget https://download.qemu.org/qemu-5.0.0.tar.xz
# extract to qemu-5.0.0/
$ tar xvJf qemu-5.0.0.tar.xz
$ cd qemu-5.0.0
# build
$ ./configure --target-list=riscv64-softmmu,riscv64-linux-user
$ make -j$(nproc)
```
Then, add following contents to `~/.bashrc`(please adjust these paths according to your environment):
```
export PATH=$PATH:/home/shinbokuow/Downloads/built/qemu-5.0.0
export PATH=$PATH:/home/shinbokuow/Downloads/built/qemu-5.0.0/riscv64-softmmu
export PATH=$PATH:/home/shinbokuow/Downloads/built/qemu-5.0.0/riscv64-linux-user
```
Finally, update the current shell:
```sh
$ source ~/.bashrc
```
Now we can check the version of Qemu:
```sh
$ qemu-system-riscv64 --version
QEMU emulator version 5.0.0
Copyright (c) 2003-2020 Fabrice Bellard and the QEMU Project developers
```
### Install RISC-V GNU Embedded Toolchain(including GDB)
Download the compressed file according to your platform From [Sifive website](https://www.sifive.com/software)(Ctrl+F 'toolchain').
Extract it and append the location of the 'bin' directory under its root directory to `$PATH`.
For example, we can check the version of GDB:
```sh
$ riscv64-unknown-elf-gdb --version
GNU gdb (SiFive GDB-Metal 10.1.0-2020.12.7) 10.1
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
```
### Install serial tools(Optional, if you want to run on K210)
```sh
$ pip3 install pyserial
$ sudo apt install python3-serial
```
## Run our project
### Qemu
```sh
$ git clone https://github.com/rcore-os/rCore-Tutorial-v3.git
$ cd rCore-Tutorial-v3/os
$ make run
```
After outputing some debug messages, the kernel lists all the applications available and enter the user shell:
```
/**** APPS ****
mpsc_sem
usertests
pipetest
forktest2
cat
initproc
race_adder_loop
threads_arg
race_adder_mutex_spin
race_adder_mutex_blocking
forktree
user_shell
huge_write
race_adder
race_adder_atomic
threads
stack_overflow
filetest_simple
forktest_simple
cmdline_args
run_pipe_test
forktest
matrix
exit
fantastic_text
sleep_simple
yield
hello_world
pipe_large_test
sleep
phil_din_mutex
**************/
Rust user shell
>>
```
You can run any application except for `initproc` and `user_shell` itself. To run an application, just input its filename and hit enter. `usertests` can run a bunch of applications, thus it is recommended.
Type `Ctrl+a` then `x` to exit Qemu.
### K210
Before chapter 6, you do not need a SD card:
```sh
$ git clone https://github.com/rcore-os/rCore-Tutorial-v3.git
$ cd rCore-Tutorial-v3/os
$ make run BOARD=k210
```
From chapter 6, before running the kernel, we should insert a SD card into PC and manually write the filesystem image to it:
```sh
$ cd rCore-Tutorial-v3/os
$ make sdcard
```
By default it will overwrite the device `/dev/sdb` which is the SD card, but you can provide another location. For example, `make sdcard SDCARD=/dev/sdc`.
After that, remove the SD card from PC and insert it to the slot of K210. Connect the K210 to PC and then:
```sh
$ git clone https://github.com/rcore-os/rCore-Tutorial-v3.git
$ cd rCore-Tutorial-v3/os
$ make run BOARD=k210
```
Type `Ctrl+]` to disconnect from K210.
## Rustdoc
Currently it can only help you view the code since only a tiny part of the code has been documented.
You can open a doc html of `os` using `cargo doc --no-deps --open` under `os` directory.
### OS-API-DOCS
The API Docs for Ten OS
1. [Lib-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch1/os/index.html)
1. [Batch-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch2/os/index.html)
1. [MultiProg-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch3-coop/os/index.html)
1. [TimeSharing-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch3/os/index.html)
1. [AddrSpace-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch4/os/index.html)
1. [Process-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch5/os/index.html)
1. [FileSystem-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch6/os/index.html)
1. [IPC-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch7/os/index.html)
1. [SyncMutex-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch8/os/index.html)
1. [IODevice-OS API doc](https://learningos.github.io/rCore-Tutorial-v3/ch9/os/index.html)
## Working in progress
Our first release 3.5.0 (chapter 1-7) has been published.
There will be 9 chapters in our next release 3.6.0, where 2 new chapters will be added:
* chapter 8: synchronization on a uniprocessor
* chapter 9: I/O devices
Current version is 3.6.0-alpha.1 and we are still working on it.
Here are the updates since 3.5.0:
### Completed
* [x] automatically clean up and rebuild before running our project on a different platform
* [x] fix `power` series application in early chapters, now you can find modulus in the output
* [x] use `UPSafeCell` instead of `RefCell` or `spin::Mutex` in order to access static data structures and adjust its API so that it cannot be borrowed twice at a time(mention `& .exclusive_access().task[0]` in `run_first_task`)
* [x] move `TaskContext` into `TaskControlBlock` instead of restoring it in place on kernel stack(since ch3), eliminating annoying `task_cx_ptr2`
* [x] replace `llvm_asm!` with `asm!`
* [x] expand the fs image size generated by `rcore-fs-fuse` to 128MiB
* [x] add a new test named `huge_write` which evaluates the fs performance(qemu\~500KiB/s k210\~50KiB/s)
* [x] flush all block cache to disk after a fs transaction which involves write operation
* [x] replace `spin::Mutex` with `UPSafeCell` before SMP chapter
* [x] add codes for a new chapter about synchronization & mutual exclusion(uniprocessor only)
* [x] bug fix: we should call `find_pte` rather than `find_pte_create` in `PageTable::unmap`
* [x] clarify: "check validity of level-3 pte in `find_pte` instead of checking it outside this function" should not be a bug
* [x] code of chapter 8: synchronization on a uniprocessor
* [x] switch the code of chapter 6 and chapter 7
* [x] support signal mechanism in chapter 7/8(only works for apps with a single thread)
* [x] Add boards/ directory and support rustdoc, for example you can use `cargo doc --no-deps --open` to view the documentation of a crate
### Todo(High priority)
* [ ] review documentation, current progress: 5/9
* [ ] support user-level sync primitives in chapter 8
* [ ] code of chapter 9: device drivers based on interrupts, including UART and block devices
* [ ] use old fs image optionally, do not always rebuild the image
* [ ] add new system calls: getdents64/fstat
* [ ] shell functionality improvement(to be continued...)
* [ ] give every non-zero process exit code an unique and clear error type
* [ ] effective error handling of mm module
### Todo(Low priority)
* [ ] rewrite practice doc and remove some inproper questions
* [ ] provide smooth debug experience at a Rust source code level
* [ ] format the code using official tools
### Crates
We will add them later.

@ -0,0 +1,18 @@
# rCore-Tutorial-v3
rCore-Tutorial version 3.x
## Dependency
### Binaries
* rustc: 1.57.0-nightly (e1e9319d9 2021-10-14)
* cargo-binutils: 0.3.3
* qemu: 5.0.0
* rustsbi-lib: 0.2.0-alpha.4
rustsbi-qemu: d4968dd2
rustsbi-k210: b689314e

@ -0,0 +1,3 @@
.idea/
target/
Cargo.lock

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

@ -8,4 +8,7 @@ edition = "2018"
[dependencies]
spin = "0.7.0"
lazy_static = { version = "1.4.0", features = ["spin_no_std"] }
lazy_static = { version = "1.4.0", features = ["spin_no_std"] }
[profile.release]
debug = true

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

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

@ -1,6 +1,6 @@
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 write_block(&self, block_id: usize, buf: &[u8]);
}

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

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

@ -2,17 +2,17 @@
extern crate alloc;
mod bitmap;
mod block_cache;
mod block_dev;
mod layout;
mod efs;
mod bitmap;
mod layout;
mod vfs;
mod block_cache;
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 efs::EasyFileSystem;
pub use vfs::Inode;
use layout::*;
use bitmap::Bitmap;
use block_cache::{get_block_cache, block_cache_sync_all};
pub use vfs::Inode;

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

@ -20,4 +20,7 @@ easy-fs = { path = "../easy-fs" }
[features]
board_qemu = []
board_k210 = []
board_k210 = []
[profile.release]
debug = true

@ -14,6 +14,11 @@ SBI ?= rustsbi
BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin
K210_BOOTLOADER_SIZE := 131072
# Building mode argument
ifeq ($(MODE), release)
MODE_ARG := --release
endif
# KERNEL ENTRY
ifeq ($(BOARD), qemu)
KERNEL_ENTRY_PA := 0x80200000
@ -36,20 +41,20 @@ build: env switch-check $(KERNEL_BIN) fs-img
switch-check:
ifeq ($(BOARD), qemu)
(which last-qemu) || (rm last-k210 -f && touch last-qemu && make clean)
(which last-qemu) || (rm -f last-k210 && touch last-qemu && make clean)
else ifeq ($(BOARD), k210)
(which last-k210) || (rm last-qemu -f && touch last-k210 && make clean)
(which last-k210) || (rm -f last-qemu && touch last-k210 && make clean)
endif
env:
(rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET)
cargo install cargo-binutils --vers ~0.2
cargo install cargo-binutils --vers =0.3.3
rustup component add rust-src
rustup component add llvm-tools-preview
sdcard: fs-img
@echo "Are you sure write to $(SDCARD) ? [y/N] " && read ans && [ $${ans:-N} = y ]
@sudo dd if=/dev/zero of=$(SDCARD) bs=1048576 count=256
@sudo dd if=/dev/zero of=$(SDCARD) bs=1048576 count=32
@sudo dd if=$(FS_IMG) of=$(SDCARD)
$(KERNEL_BIN): kernel
@ -57,7 +62,7 @@ $(KERNEL_BIN): kernel
fs-img: $(APPS)
@cd ../user && make build
@rm $(FS_IMG)
@rm -f $(FS_IMG)
@cd ../easy-fs-fuse && cargo run --release -- -s ../user/src/bin/ -t ../user/target/riscv64gc-unknown-none-elf/release/
$(APPS):
@ -106,4 +111,11 @@ debug: build
tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \
tmux -2 attach-session -d
.PHONY: build env kernel clean disasm disasm-vim run-inner switch-check fs-img
gdbserver: build
@qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -s -S
gdbclient:
@riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'
.PHONY: build env kernel clean disasm disasm-vim run-inner switch-check fs-img gdbserver gdbclient

@ -0,0 +1,22 @@
pub const CLOCK_FREQ: usize = 403000000 / 62;
pub const MMIO: &[(usize, usize)] = &[
// we don't need clint in S priv when running
// we only need claim/complete for target0 after initializing
(0x0C00_0000, 0x3000), /* PLIC */
(0x0C20_0000, 0x1000), /* PLIC */
(0x3800_0000, 0x1000), /* UARTHS */
(0x3800_1000, 0x1000), /* GPIOHS */
(0x5020_0000, 0x1000), /* GPIO */
(0x5024_0000, 0x1000), /* SPI_SLAVE */
(0x502B_0000, 0x1000), /* FPIOA */
(0x502D_0000, 0x1000), /* TIMER0 */
(0x502E_0000, 0x1000), /* TIMER1 */
(0x502F_0000, 0x1000), /* TIMER2 */
(0x5044_0000, 0x1000), /* SYSCTL */
(0x5200_0000, 0x1000), /* SPI0 */
(0x5300_0000, 0x1000), /* SPI1 */
(0x5400_0000, 0x1000), /* SPI2 */
];
pub type BlockDeviceImpl = crate::drivers::block::SDCardWrapper;

@ -0,0 +1,5 @@
pub const CLOCK_FREQ: usize = 12500000;
pub const MMIO: &[(usize, usize)] = &[(0x10001000, 0x1000)];
pub type BlockDeviceImpl = crate::drivers::block::VirtIOBlock;

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

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

@ -1,15 +1,13 @@
mod virtio_blk;
mod sdcard;
mod virtio_blk;
use lazy_static::*;
pub use sdcard::SDCardWrapper;
pub use virtio_blk::VirtIOBlock;
use crate::board::BlockDeviceImpl;
use alloc::sync::Arc;
use easy_fs::BlockDevice;
#[cfg(feature = "board_qemu")]
type BlockDeviceImpl = virtio_blk::VirtIOBlock;
#[cfg(feature = "board_k210")]
type BlockDeviceImpl = sdcard::SDCardWrapper;
use lazy_static::*;
lazy_static! {
pub static ref BLOCK_DEVICE: Arc<dyn BlockDevice> = Arc::new(BlockDeviceImpl::new());
@ -21,10 +19,12 @@ pub fn block_device_test() {
let mut write_buffer = [0u8; 512];
let mut read_buffer = [0u8; 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.read_block(i as usize, &mut read_buffer);
assert_eq!(write_buffer, read_buffer);
}
println!("block device test passed!");
}
}

@ -2,21 +2,21 @@
#![allow(non_camel_case_types)]
#![allow(unused)]
use k210_pac::{Peripherals, SPI0};
use super::BlockDevice;
use crate::sync::UPSafeCell;
use core::convert::TryInto;
use k210_hal::prelude::*;
use k210_pac::{Peripherals, SPI0};
use k210_soc::{
fpioa::{self, io},
//dmac::{dma_channel, DMAC, DMACExt},
gpio,
gpiohs,
spi::{aitm, frame_format, tmod, work_mode, SPI, SPIExt, SPIImpl},
fpioa::{self, io},
sysctl,
sleep::usleep,
spi::{aitm, frame_format, tmod, work_mode, SPIExt, SPIImpl, SPI},
sysctl,
};
use crate::sync::UPSafeCell;
use lazy_static::*;
use super::BlockDevice;
use core::convert::TryInto;
pub struct SDCard<SPI> {
spi: SPI,
@ -160,7 +160,11 @@ pub struct SDCardInfo {
}
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 {
spi,
spi_cs,
@ -310,7 +314,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
timeout -= 1;
}
/* After time out */
return 0xFF;
0xFF
}
/*
@ -337,7 +341,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
self.read_data(response);
}
/* Return response */
return 0;
0
}
/*
@ -367,7 +371,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
self.read_data(&mut csd_tab);
self.end_cmd();
/* see also: https://cdn-shop.adafruit.com/datasheets/TS16GUSDHC6.pdf */
return Ok(SDCardCSD {
Ok(SDCardCSD {
/* Byte 0 */
CSDStruct: (csd_tab[0] & 0xC0) >> 6,
SysSpecVersion: (csd_tab[0] & 0x3C) >> 2,
@ -420,7 +424,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
CSD_CRC: (csd_tab[15] & 0xFE) >> 1,
Reserved4: 1,
/* Return the reponse */
});
})
}
/*
@ -449,7 +453,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
/* Get CRC bytes (not really needed by us, but required by SD) */
self.read_data(&mut cid_tab);
self.end_cmd();
return Ok(SDCardCID {
Ok(SDCardCID {
/* Byte 0 */
ManufacturerID: cid_tab[0],
/* Byte 1, 2 */
@ -474,7 +478,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
/* Byte 15 */
CID_CRC: (cid_tab[15] & 0xFE) >> 1,
Reserved2: 1,
});
})
}
/*
@ -606,7 +610,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
}
let mut error = false;
//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) {
if self.get_response() != SD_START_DATA_SINGLE_BLOCK_READ {
error = true;
@ -616,7 +620,7 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
//self.read_data_dma(&mut dma_chunk);
self.read_data(&mut tmp_chunk);
/* 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;
}
@ -675,12 +679,12 @@ impl</*'a,*/ X: SPI> SDCard</*'a,*/ X> {
/* Send the data token to signify the start of the data */
self.write_data(&frame);
/* 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;
}
//self.write_data_dma(&mut dma_chunk);
self.write_data(&mut tmp_chunk);
self.write_data(&tmp_chunk);
/* Put dummy CRC bytes */
self.write_data(&[0xff, 0xff]);
/* Read data response */
@ -711,9 +715,8 @@ fn io_init() {
}
lazy_static! {
static ref PERIPHERALS: UPSafeCell<Peripherals> = unsafe {
UPSafeCell::new(Peripherals::take().unwrap())
};
static ref PERIPHERALS: UPSafeCell<Peripherals> =
unsafe { UPSafeCell::new(Peripherals::take().unwrap()) };
}
fn init_sdcard() -> SDCard<SPIImpl<SPI0>> {
@ -747,9 +750,15 @@ impl SDCardWrapper {
impl BlockDevice for SDCardWrapper {
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]) {
self.0.exclusive_access().write_sector(buf,block_id as u32).unwrap();
self.0
.exclusive_access()
.write_sector(buf, block_id as u32)
.unwrap();
}
}
}

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

@ -1,3 +1,3 @@
mod block;
pub mod block;
pub use block::BLOCK_DEVICE;
pub use block::BLOCK_DEVICE;

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

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

@ -1,7 +1,7 @@
use super::File;
use alloc::sync::{Arc, Weak};
use crate::sync::UPSafeCell;
use crate::mm::UserBuffer;
use crate::sync::UPSafeCell;
use alloc::sync::{Arc, Weak};
use crate::task::suspend_current_and_run_next;
@ -32,9 +32,9 @@ const RING_BUFFER_SIZE: usize = 32;
#[derive(Copy, Clone, PartialEq)]
enum RingBufferStatus {
FULL,
EMPTY,
NORMAL,
Full,
Empty,
Normal,
}
pub struct PipeRingBuffer {
@ -51,7 +51,7 @@ impl PipeRingBuffer {
arr: [0; RING_BUFFER_SIZE],
head: 0,
tail: 0,
status: RingBufferStatus::EMPTY,
status: RingBufferStatus::Empty,
write_end: None,
}
}
@ -59,35 +59,33 @@ impl PipeRingBuffer {
self.write_end = Some(Arc::downgrade(write_end));
}
pub fn write_byte(&mut self, byte: u8) {
self.status = RingBufferStatus::NORMAL;
self.status = RingBufferStatus::Normal;
self.arr[self.tail] = byte;
self.tail = (self.tail + 1) % RING_BUFFER_SIZE;
if self.tail == self.head {
self.status = RingBufferStatus::FULL;
self.status = RingBufferStatus::Full;
}
}
pub fn read_byte(&mut self) -> u8 {
self.status = RingBufferStatus::NORMAL;
self.status = RingBufferStatus::Normal;
let c = self.arr[self.head];
self.head = (self.head + 1) % RING_BUFFER_SIZE;
if self.head == self.tail {
self.status = RingBufferStatus::EMPTY;
self.status = RingBufferStatus::Empty;
}
c
}
pub fn available_read(&self) -> usize {
if self.status == RingBufferStatus::EMPTY {
if self.status == RingBufferStatus::Empty {
0
} else if self.tail > self.head {
self.tail - self.head
} else {
if self.tail > self.head {
self.tail - self.head
} else {
self.tail + RING_BUFFER_SIZE - self.head
}
self.tail + RING_BUFFER_SIZE - self.head
}
}
pub fn available_write(&self) -> usize {
if self.status == RingBufferStatus::FULL {
if self.status == RingBufferStatus::Full {
0
} else {
RING_BUFFER_SIZE - self.available_read()
@ -100,24 +98,22 @@ impl PipeRingBuffer {
/// Return (read_end, write_end)
pub fn make_pipe() -> (Arc<Pipe>, Arc<Pipe>) {
let buffer = Arc::new(unsafe {
UPSafeCell::new(PipeRingBuffer::new())
});
let read_end = Arc::new(
Pipe::read_end_with_buffer(buffer.clone())
);
let write_end = Arc::new(
Pipe::write_end_with_buffer(buffer.clone())
);
let buffer = Arc::new(unsafe { UPSafeCell::new(PipeRingBuffer::new()) });
let read_end = Arc::new(Pipe::read_end_with_buffer(buffer.clone()));
let write_end = Arc::new(Pipe::write_end_with_buffer(buffer.clone()));
buffer.exclusive_access().set_write_end(&write_end);
(read_end, write_end)
}
impl File for Pipe {
fn readable(&self) -> bool { self.readable }
fn writable(&self) -> bool { self.writable }
fn readable(&self) -> bool {
self.readable
}
fn writable(&self) -> bool {
self.writable
}
fn read(&self, buf: UserBuffer) -> usize {
assert_eq!(self.readable(), true);
assert!(self.readable());
let mut buf_iter = buf.into_iter();
let mut read_size = 0usize;
loop {
@ -134,7 +130,9 @@ impl File for Pipe {
// read at most loop_read bytes
for _ in 0..loop_read {
if let Some(byte_ref) = buf_iter.next() {
unsafe { *byte_ref = ring_buffer.read_byte(); }
unsafe {
*byte_ref = ring_buffer.read_byte();
}
read_size += 1;
} else {
return read_size;
@ -143,7 +141,7 @@ impl File for Pipe {
}
}
fn write(&self, buf: UserBuffer) -> usize {
assert_eq!(self.writable(), true);
assert!(self.writable());
let mut buf_iter = buf.into_iter();
let mut write_size = 0usize;
loop {
@ -165,4 +163,4 @@ impl File for Pipe {
}
}
}
}
}

@ -1,15 +1,19 @@
use super::File;
use crate::mm::{UserBuffer};
use crate::mm::UserBuffer;
use crate::sbi::console_getchar;
use crate::task::suspend_current_and_run_next;
use crate::task::{current_add_signal, suspend_current_and_run_next, SignalFlags};
pub struct Stdin;
pub struct Stdout;
impl File for Stdin {
fn readable(&self) -> bool { true }
fn writable(&self) -> bool { false }
fn readable(&self) -> bool {
true
}
fn writable(&self) -> bool {
false
}
fn read(&self, mut user_buf: UserBuffer) -> usize {
assert_eq!(user_buf.len(), 1);
// busy loop
@ -19,12 +23,19 @@ impl File for Stdin {
if c == 0 {
suspend_current_and_run_next();
continue;
} else if c == 3 {
// 3 is ctrl_c
//println!("[K] os/fs/stdio/read: Got Ctrl_C");
current_add_signal(SignalFlags::SIGINT);
break;
} else {
break;
}
}
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
}
fn write(&self, _user_buf: UserBuffer) -> usize {
@ -33,9 +44,13 @@ impl File for Stdin {
}
impl File for Stdout {
fn readable(&self) -> bool { false }
fn writable(&self) -> bool { true }
fn read(&self, _user_buf: UserBuffer) -> usize{
fn readable(&self) -> bool {
false
}
fn writable(&self) -> bool {
true
}
fn read(&self, _user_buf: UserBuffer) -> usize {
panic!("Cannot read from stdout!");
}
fn write(&self, user_buf: UserBuffer) -> usize {
@ -44,4 +59,4 @@ impl File for Stdout {
}
user_buf.len()
}
}
}

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

@ -1,62 +0,0 @@
use alloc::vec::Vec;
use lazy_static::*;
pub fn get_num_app() -> usize {
extern "C" { fn _num_app(); }
unsafe { (_num_app as usize as *const usize).read_volatile() }
}
pub fn get_app_data(app_id: usize) -> &'static [u8] {
extern "C" { fn _num_app(); }
let num_app_ptr = _num_app as usize as *const usize;
let num_app = get_num_app();
let app_start = unsafe {
core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1)
};
assert!(app_id < num_app);
unsafe {
core::slice::from_raw_parts(
app_start[app_id] as *const u8,
app_start[app_id + 1] - app_start[app_id]
)
}
}
lazy_static! {
static ref APP_NAMES: Vec<&'static str> = {
let num_app = get_num_app();
extern "C" { fn _app_names(); }
let mut start = _app_names as usize as *const u8;
let mut v = Vec::new();
unsafe {
for _ in 0..num_app {
let mut end = start;
while end.read_volatile() != '\0' as u8 {
end = end.add(1);
}
let slice = core::slice::from_raw_parts(start, end as usize - start as usize);
let str = core::str::from_utf8(slice).unwrap();
v.push(str);
start = end.add(1);
}
}
v
};
}
#[allow(unused)]
pub fn get_app_data_by_name(name: &str) -> Option<&'static [u8]> {
let num_app = get_num_app();
(0..num_app)
.find(|&i| APP_NAMES[i] == name)
.map(|i| get_app_data(i))
}
pub fn list_apps() {
println!("/**** APPS ****");
for app in APP_NAMES.iter() {
println!("{}", app);
}
println!("**************/");
}

@ -1,7 +1,5 @@
#![no_std]
#![no_main]
#![feature(global_asm)]
#![feature(asm)]
#![feature(panic_info_message)]
#![feature(alloc_error_handler)]
@ -10,19 +8,28 @@ extern crate alloc;
#[macro_use]
extern crate bitflags;
#[cfg(feature = "board_k210")]
#[path = "boards/k210.rs"]
mod board;
#[cfg(not(any(feature = "board_k210")))]
#[path = "boards/qemu.rs"]
mod board;
#[macro_use]
mod console;
mod config;
mod drivers;
mod fs;
mod lang_items;
mod mm;
mod sbi;
mod sync;
mod syscall;
mod trap;
mod config;
mod task;
mod timer;
mod sync;
mod mm;
mod fs;
mod drivers;
mod trap;
use core::arch::global_asm;
global_asm!(include_str!("entry.asm"));
@ -32,10 +39,8 @@ fn clear_bss() {
fn ebss();
}
unsafe {
core::slice::from_raw_parts_mut(
sbss as usize as *mut u8,
ebss as usize - sbss as usize,
).fill(0);
core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize)
.fill(0);
}
}
@ -52,4 +57,4 @@ pub fn rust_main() -> ! {
task::add_initproc();
task::run_tasks();
panic!("Unreachable in rust_main!");
}
}

@ -1,7 +1,12 @@
use crate::config::{PAGE_SIZE, PAGE_SIZE_BITS};
use super::PageTableEntry;
use crate::config::{PAGE_SIZE, PAGE_SIZE_BITS};
use core::fmt::{self, Debug, Formatter};
const PA_WIDTH_SV39: usize = 56;
const VA_WIDTH_SV39: usize = 39;
const PPN_WIDTH_SV39: usize = PA_WIDTH_SV39 - PAGE_SIZE_BITS;
const VPN_WIDTH_SV39: usize = VA_WIDTH_SV39 - PAGE_SIZE_BITS;
/// Definitions
#[repr(C)]
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
@ -47,35 +52,63 @@ impl Debug for PhysPageNum {
/// usize -> T: usize.into()
impl From<usize> for PhysAddr {
fn from(v: usize) -> Self { Self(v) }
fn from(v: usize) -> Self {
Self(v & ((1 << PA_WIDTH_SV39) - 1))
}
}
impl From<usize> for PhysPageNum {
fn from(v: usize) -> Self { Self(v) }
fn from(v: usize) -> Self {
Self(v & ((1 << PPN_WIDTH_SV39) - 1))
}
}
impl From<usize> for VirtAddr {
fn from(v: usize) -> Self { Self(v) }
fn from(v: usize) -> Self {
Self(v & ((1 << VA_WIDTH_SV39) - 1))
}
}
impl From<usize> for VirtPageNum {
fn from(v: usize) -> Self { Self(v) }
fn from(v: usize) -> Self {
Self(v & ((1 << VPN_WIDTH_SV39) - 1))
}
}
impl From<PhysAddr> for usize {
fn from(v: PhysAddr) -> Self { v.0 }
fn from(v: PhysAddr) -> Self {
v.0
}
}
impl From<PhysPageNum> for usize {
fn from(v: PhysPageNum) -> Self { v.0 }
fn from(v: PhysPageNum) -> Self {
v.0
}
}
impl From<VirtAddr> for usize {
fn from(v: VirtAddr) -> Self { v.0 }
fn from(v: VirtAddr) -> Self {
if v.0 >= (1 << (VA_WIDTH_SV39 - 1)) {
v.0 | (!((1 << VA_WIDTH_SV39) - 1))
} else {
v.0
}
}
}
impl From<VirtPageNum> for usize {
fn from(v: VirtPageNum) -> Self { v.0 }
fn from(v: VirtPageNum) -> Self {
v.0
}
}
impl VirtAddr {
pub fn floor(&self) -> VirtPageNum { VirtPageNum(self.0 / PAGE_SIZE) }
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 }
pub fn floor(&self) -> VirtPageNum {
VirtPageNum(self.0 / PAGE_SIZE)
}
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 {
fn from(v: VirtAddr) -> Self {
@ -84,13 +117,23 @@ impl From<VirtAddr> for VirtPageNum {
}
}
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 {
pub fn floor(&self) -> PhysPageNum { PhysPageNum(self.0 / PAGE_SIZE) }
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 }
pub fn floor(&self) -> PhysPageNum {
PhysPageNum(self.0 / PAGE_SIZE)
}
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 {
fn from(v: PhysAddr) -> Self {
@ -99,7 +142,9 @@ impl From<PhysAddr> for PhysPageNum {
}
}
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 {
@ -116,31 +161,23 @@ impl VirtPageNum {
impl PhysAddr {
pub fn get_ref<T>(&self) -> &'static T {
unsafe {
(self.0 as *const T).as_ref().unwrap()
}
unsafe { (self.0 as *const T).as_ref().unwrap() }
}
pub fn get_mut<T>(&self) -> &'static mut T {
unsafe {
(self.0 as *mut T).as_mut().unwrap()
}
unsafe { (self.0 as *mut T).as_mut().unwrap() }
}
}
impl PhysPageNum {
pub fn get_pte_array(&self) -> &'static mut [PageTableEntry] {
let pa: PhysAddr = self.clone().into();
unsafe {
core::slice::from_raw_parts_mut(pa.0 as *mut PageTableEntry, 512)
}
let pa: PhysAddr = (*self).into();
unsafe { core::slice::from_raw_parts_mut(pa.0 as *mut PageTableEntry, 512) }
}
pub fn get_bytes_array(&self) -> &'static mut [u8] {
let pa: PhysAddr = self.clone().into();
unsafe {
core::slice::from_raw_parts_mut(pa.0 as *mut u8, 4096)
}
let pa: PhysAddr = (*self).into();
unsafe { core::slice::from_raw_parts_mut(pa.0 as *mut u8, 4096) }
}
pub fn get_mut<T>(&self) -> &'static mut T {
let pa: PhysAddr = self.clone().into();
let pa: PhysAddr = (*self).into();
pa.get_mut()
}
}
@ -160,41 +197,57 @@ impl StepByOne for PhysPageNum {
}
#[derive(Copy, Clone)]
pub struct SimpleRange<T> where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, {
pub struct SimpleRange<T>
where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
l: T,
r: T,
}
impl<T> SimpleRange<T> where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, {
impl<T> SimpleRange<T>
where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
pub fn new(start: T, end: T) -> Self {
assert!(start <= end, "start {:?} > end {:?}!", start, end);
Self { l: start, r: end }
}
pub fn get_start(&self) -> T { self.l }
pub fn get_end(&self) -> T { self.r }
pub fn get_start(&self) -> T {
self.l
}
pub fn get_end(&self) -> T {
self.r
}
}
impl<T> IntoIterator for SimpleRange<T> where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, {
impl<T> IntoIterator for SimpleRange<T>
where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
type Item = T;
type IntoIter = SimpleRangeIterator<T>;
fn into_iter(self) -> Self::IntoIter {
SimpleRangeIterator::new(self.l, self.r)
}
}
pub struct SimpleRangeIterator<T> where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, {
pub struct SimpleRangeIterator<T>
where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
current: T,
end: T,
}
impl<T> SimpleRangeIterator<T> where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, {
impl<T> SimpleRangeIterator<T>
where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
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
T: StepByOne + Copy + PartialEq + PartialOrd + Debug, {
impl<T> Iterator for SimpleRangeIterator<T>
where
T: StepByOne + Copy + PartialEq + PartialOrd + Debug,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.current == self.end {
@ -206,4 +259,4 @@ impl<T> Iterator for SimpleRangeIterator<T> where
}
}
}
pub type VPNRange = SimpleRange<VirtPageNum>;
pub type VPNRange = SimpleRange<VirtPageNum>;

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

@ -1,5 +1,5 @@
use buddy_system_allocator::LockedHeap;
use crate::config::KERNEL_HEAP_SIZE;
use buddy_system_allocator::LockedHeap;
#[global_allocator]
static HEAP_ALLOCATOR: LockedHeap = LockedHeap::empty();
@ -36,8 +36,8 @@ pub fn heap_test() {
for i in 0..500 {
v.push(i);
}
for i in 0..500 {
assert_eq!(v[i], i);
for (i, val) in v.iter().take(500).enumerate() {
assert_eq!(*val, i);
}
assert!(bss_range.contains(&(v.as_ptr() as usize)));
drop(v);

@ -1,21 +1,15 @@
use super::{PageTable, PageTableEntry, PTEFlags};
use super::{VirtPageNum, VirtAddr, PhysPageNum, PhysAddr};
use super::{FrameTracker, frame_alloc};
use super::{VPNRange, StepByOne};
use super::{frame_alloc, FrameTracker};
use super::{PTEFlags, PageTable, PageTableEntry};
use super::{PhysAddr, PhysPageNum, VirtAddr, VirtPageNum};
use super::{StepByOne, VPNRange};
use crate::config::{MEMORY_END, MMIO, PAGE_SIZE, TRAMPOLINE, TRAP_CONTEXT, USER_STACK_SIZE};
use crate::sync::UPSafeCell;
use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use riscv::register::satp;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::arch::asm;
use lazy_static::*;
use crate::sync::UPSafeCell;
use crate::config::{
MEMORY_END,
PAGE_SIZE,
TRAMPOLINE,
TRAP_CONTEXT,
USER_STACK_SIZE,
MMIO,
};
use riscv::register::satp;
extern "C" {
fn stext();
@ -31,9 +25,8 @@ extern "C" {
}
lazy_static! {
pub static ref KERNEL_SPACE: Arc<UPSafeCell<MemorySet>> = Arc::new(unsafe {
UPSafeCell::new(MemorySet::new_kernel())
});
pub static ref KERNEL_SPACE: Arc<UPSafeCell<MemorySet>> =
Arc::new(unsafe { UPSafeCell::new(MemorySet::new_kernel()) });
}
pub fn kernel_token() -> usize {
@ -56,17 +49,24 @@ impl MemorySet {
self.page_table.token()
}
/// Assume that no conflicts.
pub fn insert_framed_area(&mut self, start_va: VirtAddr, end_va: VirtAddr, permission: MapPermission) {
self.push(MapArea::new(
start_va,
end_va,
MapType::Framed,
permission,
), None);
pub fn insert_framed_area(
&mut self,
start_va: VirtAddr,
end_va: VirtAddr,
permission: MapPermission,
) {
self.push(
MapArea::new(start_va, end_va, MapType::Framed, permission),
None,
);
}
pub fn remove_area_with_start_vpn(&mut self, start_vpn: VirtPageNum) {
if let Some((idx, area)) = self.areas.iter_mut().enumerate()
.find(|(_, area)| area.vpn_range.get_start() == start_vpn) {
if let Some((idx, area)) = self
.areas
.iter_mut()
.enumerate()
.find(|(_, area)| area.vpn_range.get_start() == start_vpn)
{
area.unmap(&mut self.page_table);
self.areas.remove(idx);
}
@ -95,50 +95,71 @@ impl MemorySet {
println!(".text [{:#x}, {:#x})", stext as usize, etext as usize);
println!(".rodata [{:#x}, {:#x})", srodata as usize, erodata as usize);
println!(".data [{:#x}, {:#x})", sdata as usize, edata as usize);
println!(".bss [{:#x}, {:#x})", sbss_with_stack as usize, ebss as usize);
println!(
".bss [{:#x}, {:#x})",
sbss_with_stack as usize, ebss as usize
);
println!("mapping .text section");
memory_set.push(MapArea::new(
(stext as usize).into(),
(etext as usize).into(),
MapType::Identical,
MapPermission::R | MapPermission::X,
), None);
memory_set.push(
MapArea::new(
(stext as usize).into(),
(etext as usize).into(),
MapType::Identical,
MapPermission::R | MapPermission::X,
),
None,
);
println!("mapping .rodata section");
memory_set.push(MapArea::new(
(srodata as usize).into(),
(erodata as usize).into(),
MapType::Identical,
MapPermission::R,
), None);
memory_set.push(
MapArea::new(
(srodata as usize).into(),
(erodata as usize).into(),
MapType::Identical,
MapPermission::R,
),
None,
);
println!("mapping .data section");
memory_set.push(MapArea::new(
(sdata as usize).into(),
(edata as usize).into(),
MapType::Identical,
MapPermission::R | MapPermission::W,
), None);
memory_set.push(
MapArea::new(
(sdata as usize).into(),
(edata as usize).into(),
MapType::Identical,
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);
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(),
memory_set.push(
MapArea::new(
(ekernel as usize).into(),
MEMORY_END.into(),
MapType::Identical,
MapPermission::R | MapPermission::W,
), None);
),
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
}
@ -162,19 +183,20 @@ impl MemorySet {
let end_va: VirtAddr = ((ph.virtual_addr() + ph.mem_size()) as usize).into();
let mut map_perm = MapPermission::U;
let ph_flags = ph.flags();
if ph_flags.is_read() { map_perm |= MapPermission::R; }
if ph_flags.is_write() { map_perm |= MapPermission::W; }
if ph_flags.is_execute() { map_perm |= MapPermission::X; }
let map_area = MapArea::new(
start_va,
end_va,
MapType::Framed,
map_perm,
);
if ph_flags.is_read() {
map_perm |= MapPermission::R;
}
if ph_flags.is_write() {
map_perm |= MapPermission::W;
}
if ph_flags.is_execute() {
map_perm |= MapPermission::X;
}
let map_area = MapArea::new(start_va, end_va, MapType::Framed, map_perm);
max_end_vpn = map_area.vpn_range.get_end();
memory_set.push(
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]),
);
}
}
@ -184,20 +206,30 @@ impl MemorySet {
// guard page
user_stack_bottom += PAGE_SIZE;
let user_stack_top = user_stack_bottom + USER_STACK_SIZE;
memory_set.push(MapArea::new(
user_stack_bottom.into(),
user_stack_top.into(),
MapType::Framed,
MapPermission::R | MapPermission::W | MapPermission::U,
), None);
memory_set.push(
MapArea::new(
user_stack_bottom.into(),
user_stack_top.into(),
MapType::Framed,
MapPermission::R | MapPermission::W | MapPermission::U,
),
None,
);
// map TrapContext
memory_set.push(MapArea::new(
TRAP_CONTEXT.into(),
TRAMPOLINE.into(),
MapType::Framed,
MapPermission::R | MapPermission::W,
), None);
(memory_set, user_stack_top, elf.header.pt2.entry_point() as usize)
memory_set.push(
MapArea::new(
TRAP_CONTEXT.into(),
TRAMPOLINE.into(),
MapType::Framed,
MapPermission::R | MapPermission::W,
),
None,
);
(
memory_set,
user_stack_top,
elf.header.pt2.entry_point() as usize,
)
}
pub fn from_existed_user(user_space: &MemorySet) -> MemorySet {
let mut memory_set = Self::new_bare();
@ -211,7 +243,9 @@ impl MemorySet {
for vpn in area.vpn_range {
let src_ppn = user_space.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
@ -244,7 +278,7 @@ impl MapArea {
start_va: VirtAddr,
end_va: VirtAddr,
map_type: MapType,
map_perm: MapPermission
map_perm: MapPermission,
) -> Self {
let start_vpn: VirtPageNum = start_va.floor();
let end_vpn: VirtPageNum = end_va.ceil();
@ -279,11 +313,8 @@ impl MapArea {
page_table.map(vpn, ppn, pte_flags);
}
pub fn unmap_one(&mut self, page_table: &mut PageTable, vpn: VirtPageNum) {
match self.map_type {
MapType::Framed => {
self.data_frames.remove(&vpn);
}
_ => {}
if self.map_type == MapType::Framed {
self.data_frames.remove(&vpn);
}
page_table.unmap(vpn);
}
@ -342,17 +373,20 @@ pub fn remap_test() {
let mid_text: VirtAddr = ((stext as usize + etext as usize) / 2).into();
let mid_rodata: VirtAddr = ((srodata as usize + erodata as usize) / 2).into();
let mid_data: VirtAddr = ((sdata as usize + edata as usize) / 2).into();
assert_eq!(
kernel_space.page_table.translate(mid_text.floor()).unwrap().writable(),
false
);
assert_eq!(
kernel_space.page_table.translate(mid_rodata.floor()).unwrap().writable(),
false,
);
assert_eq!(
kernel_space.page_table.translate(mid_data.floor()).unwrap().executable(),
false,
);
assert!(!kernel_space
.page_table
.translate(mid_text.floor())
.unwrap()
.writable(),);
assert!(!kernel_space
.page_table
.translate(mid_rodata.floor())
.unwrap()
.writable(),);
assert!(!kernel_space
.page_table
.translate(mid_data.floor())
.unwrap()
.executable(),);
println!("remap_test passed!");
}
}

@ -1,28 +1,22 @@
mod heap_allocator;
mod address;
mod frame_allocator;
mod page_table;
mod heap_allocator;
mod memory_set;
mod page_table;
use page_table::PTEFlags;
use address::VPNRange;
pub use address::{PhysAddr, VirtAddr, PhysPageNum, VirtPageNum, StepByOne};
pub use frame_allocator::{FrameTracker, frame_alloc, frame_dealloc,};
pub use address::{PhysAddr, PhysPageNum, StepByOne, VirtAddr, VirtPageNum};
pub use frame_allocator::{frame_alloc, frame_dealloc, FrameTracker};
pub use memory_set::remap_test;
pub use memory_set::{kernel_token, MapPermission, MemorySet, KERNEL_SPACE};
use page_table::PTEFlags;
pub use page_table::{
PageTable,
PageTableEntry,
translated_byte_buffer,
translated_str,
translated_ref,
translated_refmut,
UserBuffer,
UserBufferIterator,
translated_byte_buffer, translated_ref, translated_refmut, translated_str, PageTable,
PageTableEntry, UserBuffer, UserBufferIterator,
};
pub use memory_set::{MemorySet, KERNEL_SPACE, MapPermission, kernel_token};
pub use memory_set::remap_test;
pub fn init() {
heap_allocator::init_heap();
frame_allocator::init_frame_allocator();
KERNEL_SPACE.exclusive_access().activate();
}
}

@ -1,15 +1,7 @@
use super::{
frame_alloc,
PhysPageNum,
FrameTracker,
VirtPageNum,
VirtAddr,
PhysAddr,
StepByOne
};
use alloc::vec::Vec;
use alloc::vec;
use super::{frame_alloc, FrameTracker, PhysAddr, PhysPageNum, StepByOne, VirtAddr, VirtPageNum};
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use bitflags::*;
bitflags! {
@ -38,9 +30,7 @@ impl PageTableEntry {
}
}
pub fn empty() -> Self {
PageTableEntry {
bits: 0,
}
PageTableEntry { bits: 0 }
}
pub fn ppn(&self) -> PhysPageNum {
(self.bits >> 10 & ((1usize << 44) - 1)).into()
@ -87,8 +77,8 @@ impl PageTable {
let idxs = vpn.indexes();
let mut ppn = self.root_ppn;
let mut result: Option<&mut PageTableEntry> = None;
for i in 0..3 {
let pte = &mut ppn.get_pte_array()[idxs[i]];
for (i, idx) in idxs.iter().enumerate() {
let pte = &mut ppn.get_pte_array()[*idx];
if i == 2 {
result = Some(pte);
break;
@ -102,12 +92,12 @@ impl PageTable {
}
result
}
fn find_pte(&self, vpn: VirtPageNum) -> Option<&PageTableEntry> {
fn find_pte(&self, vpn: VirtPageNum) -> Option<&mut PageTableEntry> {
let idxs = vpn.indexes();
let mut ppn = self.root_ppn;
let mut result: Option<&PageTableEntry> = None;
for i in 0..3 {
let pte = &ppn.get_pte_array()[idxs[i]];
let mut result: Option<&mut PageTableEntry> = None;
for (i, idx) in idxs.iter().enumerate() {
let pte = &mut ppn.get_pte_array()[*idx];
if i == 2 {
result = Some(pte);
break;
@ -127,22 +117,20 @@ impl PageTable {
}
#[allow(unused)]
pub fn unmap(&mut self, vpn: VirtPageNum) {
let pte = self.find_pte_create(vpn).unwrap();
let pte = self.find_pte(vpn).unwrap();
assert!(pte.is_valid(), "vpn {:?} is invalid before unmapping", vpn);
*pte = PageTableEntry::empty();
}
pub fn translate(&self, vpn: VirtPageNum) -> Option<PageTableEntry> {
self.find_pte(vpn)
.map(|pte| {pte.clone()})
self.find_pte(vpn).map(|pte| *pte)
}
pub fn translate_va(&self, va: VirtAddr) -> Option<PhysAddr> {
self.find_pte(va.clone().floor())
.map(|pte| {
let aligned_pa: PhysAddr = pte.ppn().into();
let offset = va.page_offset();
let aligned_pa_usize: usize = aligned_pa.into();
(aligned_pa_usize + offset).into()
})
self.find_pte(va.clone().floor()).map(|pte| {
let aligned_pa: PhysAddr = pte.ppn().into();
let offset = va.page_offset();
let aligned_pa_usize: usize = aligned_pa.into();
(aligned_pa_usize + offset).into()
})
}
pub fn token(&self) -> usize {
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 {
let start_va = VirtAddr::from(start);
let mut vpn = start_va.floor();
let ppn = page_table
.translate(vpn)
.unwrap()
.ppn();
let ppn = page_table.translate(vpn).unwrap().ppn();
vpn.step();
let mut end_va: VirtAddr = vpn.into();
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 va = ptr as usize;
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 {
break;
}
@ -192,13 +180,19 @@ pub fn translated_str(token: usize, ptr: *const u8) -> String {
pub fn translated_ref<T>(token: usize, ptr: *const T) -> &'static T {
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 {
let page_table = PageTable::from_token(token);
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 {
@ -252,4 +246,4 @@ impl Iterator for UserBufferIterator {
Some(r)
}
}
}
}

@ -1,5 +1,7 @@
#![allow(unused)]
use core::arch::asm;
const SBI_SET_TIMER: usize = 0;
const SBI_CONSOLE_PUTCHAR: usize = 1;
const SBI_CONSOLE_GETCHAR: usize = 2;
@ -41,4 +43,3 @@ pub fn shutdown() -> ! {
sbi_call(SBI_SHUTDOWN, 0, 0, 0);
panic!("It should shutdown!");
}

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

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

@ -1,11 +1,6 @@
use crate::mm::{
UserBuffer,
translated_byte_buffer,
translated_refmut,
translated_str,
};
use crate::task::{current_user_token, current_task};
use crate::fs::{make_pipe, OpenFlags, open_file};
use crate::fs::{make_pipe, open_file, OpenFlags};
use crate::mm::{translated_byte_buffer, translated_refmut, translated_str, UserBuffer};
use crate::task::{current_task, current_user_token};
use alloc::sync::Arc;
pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
@ -22,9 +17,7 @@ pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
let file = file.clone();
// release current task TCB manually to avoid multi-borrow
drop(inner);
file.write(
UserBuffer::new(translated_byte_buffer(token, buf, len))
) as isize
file.write(UserBuffer::new(translated_byte_buffer(token, buf, len))) as isize
} else {
-1
}
@ -44,9 +37,7 @@ pub fn sys_read(fd: usize, buf: *const u8, len: usize) -> isize {
}
// release current task TCB manually to avoid multi-borrow
drop(inner);
file.read(
UserBuffer::new(translated_byte_buffer(token, buf, len))
) as isize
file.read(UserBuffer::new(translated_byte_buffer(token, buf, len))) as isize
} else {
-1
}
@ -56,10 +47,7 @@ pub fn sys_open(path: *const u8, flags: u32) -> isize {
let task = current_task().unwrap();
let token = current_user_token();
let path = translated_str(token, path);
if let Some(inode) = open_file(
path.as_str(),
OpenFlags::from_bits(flags).unwrap()
) {
if let Some(inode) = open_file(path.as_str(), OpenFlags::from_bits(flags).unwrap()) {
let mut inner = task.inner_exclusive_access();
let fd = inner.alloc_fd();
inner.fd_table[fd] = Some(inode);
@ -108,4 +96,4 @@ pub fn sys_dup(fd: usize) -> isize {
let new_fd = inner.alloc_fd();
inner.fd_table[new_fd] = Some(Arc::clone(inner.fd_table[fd].as_ref().unwrap()));
new_fd as isize
}
}

@ -6,6 +6,10 @@ const SYSCALL_READ: usize = 63;
const SYSCALL_WRITE: usize = 64;
const SYSCALL_EXIT: usize = 93;
const SYSCALL_YIELD: usize = 124;
const SYSCALL_KILL: usize = 129;
const SYSCALL_SIGACTION: usize = 134;
const SYSCALL_SIGPROCMASK: usize = 135;
const SYSCALL_SIGRETURN: usize = 139;
const SYSCALL_GET_TIME: usize = 169;
const SYSCALL_GETPID: usize = 172;
const SYSCALL_FORK: usize = 220;
@ -18,9 +22,11 @@ mod process;
use fs::*;
use process::*;
use crate::task::SignalAction;
pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize {
match syscall_id {
SYSCALL_DUP=> sys_dup(args[0]),
SYSCALL_DUP => sys_dup(args[0]),
SYSCALL_OPEN => sys_open(args[0] as *const u8, args[1] as u32),
SYSCALL_CLOSE => sys_close(args[0]),
SYSCALL_PIPE => sys_pipe(args[0] as *mut usize),
@ -28,6 +34,14 @@ pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize {
SYSCALL_WRITE => sys_write(args[0], args[1] as *const u8, args[2]),
SYSCALL_EXIT => sys_exit(args[0] as i32),
SYSCALL_YIELD => sys_yield(),
SYSCALL_KILL => sys_kill(args[0], args[1] as i32),
SYSCALL_SIGACTION => sys_sigaction(
args[0] as i32,
args[1] as *const SignalAction,
args[2] as *mut SignalAction,
),
SYSCALL_SIGPROCMASK => sys_sigprocmask(args[0] as u32),
SYSCALL_SIGRETURN => sys_sigretrun(),
SYSCALL_GET_TIME => sys_get_time(),
SYSCALL_GETPID => sys_getpid(),
SYSCALL_FORK => sys_fork(),
@ -36,4 +50,3 @@ pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize {
_ => panic!("Unsupported syscall_id: {}", syscall_id),
}
}

@ -1,23 +1,13 @@
use crate::fs::{open_file, OpenFlags};
use crate::mm::{translated_ref, translated_refmut, translated_str};
use crate::task::{
suspend_current_and_run_next,
exit_current_and_run_next,
current_task,
current_user_token,
add_task,
add_task, current_task, current_user_token, exit_current_and_run_next, pid2task,
suspend_current_and_run_next, SignalAction, SignalFlags, MAX_SIG,
};
use crate::timer::get_time_ms;
use crate::mm::{
translated_str,
translated_refmut,
translated_ref,
};
use crate::fs::{
open_file,
OpenFlags,
};
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use alloc::string::String;
pub fn sys_exit(exit_code: i32) -> ! {
exit_current_and_run_next(exit_code);
@ -61,7 +51,9 @@ pub fn sys_exec(path: *const u8, mut args: *const usize) -> isize {
break;
}
args_vec.push(translated_str(token, arg_str_ptr as *const u8));
unsafe { args = args.add(1); }
unsafe {
args = args.add(1);
}
}
if let Some(app_inode) = open_file(path.as_str(), OpenFlags::RDONLY) {
let all_data = app_inode.read_all();
@ -83,21 +75,19 @@ pub fn sys_waitpid(pid: isize, exit_code_ptr: *mut i32) -> isize {
// ---- access current PCB exclusively
let mut inner = task.inner_exclusive_access();
if inner.children
if !inner
.children
.iter()
.find(|p| {pid == -1 || pid as usize == p.getpid()})
.is_none() {
.any(|p| pid == -1 || pid as usize == p.getpid())
{
return -1;
// ---- release current PCB
}
let pair = inner.children
.iter()
.enumerate()
.find(|(_, p)| {
// ++++ temporarily access child PCB exclusively
p.inner_exclusive_access().is_zombie() && (pid == -1 || pid as usize == p.getpid())
// ++++ release child PCB
});
let pair = inner.children.iter().enumerate().find(|(_, p)| {
// ++++ 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 {
let child = inner.children.remove(idx);
// confirm that child will be deallocated after being removed from children list
@ -112,4 +102,92 @@ pub fn sys_waitpid(pid: isize, exit_code_ptr: *mut i32) -> isize {
-2
}
// ---- release current PCB automatically
}
}
pub fn sys_kill(pid: usize, signum: i32) -> isize {
if let Some(task) = pid2task(pid) {
if let Some(flag) = SignalFlags::from_bits(1 << signum) {
// insert the signal if legal
let mut task_ref = task.inner_exclusive_access();
if task_ref.signals.contains(flag) {
return -1;
}
task_ref.signals.insert(flag);
0
} else {
-1
}
} else {
-1
}
}
pub fn sys_sigprocmask(mask: u32) -> isize {
if let Some(task) = current_task() {
let mut inner = task.inner_exclusive_access();
let old_mask = inner.signal_mask;
if let Some(flag) = SignalFlags::from_bits(mask) {
inner.signal_mask = flag;
old_mask.bits() as isize
} else {
-1
}
} else {
-1
}
}
pub fn sys_sigretrun() -> isize {
if let Some(task) = current_task() {
let mut inner = task.inner_exclusive_access();
inner.handling_sig = -1;
// restore the trap context
let trap_ctx = inner.get_trap_cx();
*trap_ctx = inner.trap_ctx_backup.unwrap();
0
} else {
-1
}
}
fn check_sigaction_error(signal: SignalFlags, action: usize, old_action: usize) -> bool {
if action == 0
|| old_action == 0
|| signal == SignalFlags::SIGKILL
|| signal == SignalFlags::SIGSTOP
{
true
} else {
false
}
}
pub fn sys_sigaction(
signum: i32,
action: *const SignalAction,
old_action: *mut SignalAction,
) -> isize {
let token = current_user_token();
if let Some(task) = current_task() {
let mut inner = task.inner_exclusive_access();
if signum as usize > MAX_SIG {
return -1;
}
if let Some(flag) = SignalFlags::from_bits(1 << signum) {
if check_sigaction_error(flag, action as usize, old_action as usize) {
return -1;
}
let old_kernel_action = inner.signal_actions.table[signum as usize];
if old_kernel_action.mask != SignalFlags::from_bits(40).unwrap() {
*translated_refmut(token, old_action) = old_kernel_action;
} else {
let mut ref_old_action = *translated_refmut(token, old_action);
ref_old_action.handler = old_kernel_action.handler;
}
let ref_action = translated_ref(token, action);
inner.signal_actions.table[signum as usize] = *ref_action;
return 0;
}
}
-1
}

@ -0,0 +1,31 @@
use crate::task::{SignalFlags, MAX_SIG};
/// Action for a signal
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct SignalAction {
pub handler: usize,
pub mask: SignalFlags,
}
impl Default for SignalAction {
fn default() -> Self {
Self {
handler: 0,
mask: SignalFlags::from_bits(40).unwrap(),
}
}
}
#[derive(Clone)]
pub struct SignalActions {
pub table: [SignalAction; MAX_SIG + 1],
}
impl Default for SignalActions {
fn default() -> Self {
Self {
table: [SignalAction::default(); MAX_SIG + 1],
}
}
}

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

@ -1,6 +1,6 @@
use crate::sync::UPSafeCell;
use super::TaskControlBlock;
use alloc::collections::VecDeque;
use crate::sync::UPSafeCell;
use alloc::collections::{BTreeMap, VecDeque};
use alloc::sync::Arc;
use lazy_static::*;
@ -11,7 +11,9 @@ pub struct TaskManager {
/// A simple FIFO scheduler.
impl TaskManager {
pub fn new() -> Self {
Self { ready_queue: VecDeque::new(), }
Self {
ready_queue: VecDeque::new(),
}
}
pub fn add(&mut self, task: Arc<TaskControlBlock>) {
self.ready_queue.push_back(task);
@ -22,15 +24,31 @@ impl TaskManager {
}
lazy_static! {
pub static ref TASK_MANAGER: UPSafeCell<TaskManager> = unsafe {
UPSafeCell::new(TaskManager::new())
};
pub static ref TASK_MANAGER: UPSafeCell<TaskManager> =
unsafe { UPSafeCell::new(TaskManager::new()) };
pub static ref PID2TCB: UPSafeCell<BTreeMap<usize, Arc<TaskControlBlock>>> =
unsafe { UPSafeCell::new(BTreeMap::new()) };
}
pub fn add_task(task: Arc<TaskControlBlock>) {
PID2TCB
.exclusive_access()
.insert(task.getpid(), Arc::clone(&task));
TASK_MANAGER.exclusive_access().add(task);
}
pub fn fetch_task() -> Option<Arc<TaskControlBlock>> {
TASK_MANAGER.exclusive_access().fetch()
}
}
pub fn pid2task(pid: usize) -> Option<Arc<TaskControlBlock>> {
let map = PID2TCB.exclusive_access();
map.get(&pid).map(Arc::clone)
}
pub fn remove_from_pid2task(pid: usize) {
let mut map = PID2TCB.exclusive_access();
if map.remove(&pid).is_none() {
panic!("cannot find pid {} in pid2task!", pid);
}
}

@ -1,28 +1,29 @@
mod action;
mod context;
mod switch;
mod task;
mod manager;
mod processor;
mod pid;
mod processor;
mod signal;
mod switch;
#[allow(clippy::module_inception)]
mod task;
use crate::fs::{open_file, OpenFlags};
use switch::__switch;
use task::{TaskControlBlock, TaskStatus};
use alloc::sync::Arc;
use manager::fetch_task;
use lazy_static::*;
pub use context::TaskContext;
use lazy_static::*;
use manager::fetch_task;
use manager::remove_from_pid2task;
use switch::__switch;
use task::{TaskControlBlock, TaskStatus};
pub use action::{SignalAction, SignalActions};
pub use manager::{add_task, pid2task};
pub use pid::{pid_alloc, KernelStack, PidHandle};
pub use processor::{
run_tasks,
current_task,
current_user_token,
current_trap_cx,
take_current_task,
schedule,
current_task, current_trap_cx, current_user_token, run_tasks, schedule, take_current_task,
};
pub use manager::add_task;
pub use pid::{PidHandle, pid_alloc, KernelStack};
pub use signal::{SignalFlags, MAX_SIG};
pub fn suspend_current_and_run_next() {
// There must be an application running.
@ -45,6 +46,8 @@ pub fn suspend_current_and_run_next() {
pub fn exit_current_and_run_next(exit_code: i32) {
// take from Processor
let task = take_current_task().unwrap();
// remove from pid2task
remove_from_pid2task(task.getpid());
// **** access current TCB exclusively
let mut inner = task.inner_exclusive_access();
// Change status to Zombie
@ -66,6 +69,8 @@ pub fn exit_current_and_run_next(exit_code: i32) {
inner.children.clear();
// deallocate user space
inner.memory_set.recycle_data_pages();
// drop file descriptors
inner.fd_table.clear();
drop(inner);
// **** release current PCB
// drop task manually to maintain rc correctly
@ -86,3 +91,139 @@ lazy_static! {
pub fn add_initproc() {
add_task(INITPROC.clone());
}
pub fn check_signals_error_of_current() -> Option<(i32, &'static str)> {
let task = current_task().unwrap();
let task_inner = task.inner_exclusive_access();
// println!(
// "[K] check_signals_error_of_current {:?}",
// task_inner.signals
// );
task_inner.signals.check_error()
}
pub fn current_add_signal(signal: SignalFlags) {
let task = current_task().unwrap();
let mut task_inner = task.inner_exclusive_access();
task_inner.signals |= signal;
// println!(
// "[K] current_add_signal:: current task sigflag {:?}",
// task_inner.signals
// );
}
fn call_kernel_signal_handler(signal: SignalFlags) {
let task = current_task().unwrap();
let mut task_inner = task.inner_exclusive_access();
match signal {
SignalFlags::SIGSTOP => {
task_inner.frozen = true;
task_inner.signals ^= SignalFlags::SIGSTOP;
}
SignalFlags::SIGCONT => {
if task_inner.signals.contains(SignalFlags::SIGCONT) {
task_inner.signals ^= SignalFlags::SIGCONT;
task_inner.frozen = false;
}
}
_ => {
// println!(
// "[K] call_kernel_signal_handler:: current task sigflag {:?}",
// task_inner.signals
// );
task_inner.killed = true;
}
}
}
fn call_user_signal_handler(sig: usize, signal: SignalFlags) {
let task = current_task().unwrap();
let mut task_inner = task.inner_exclusive_access();
let handler = task_inner.signal_actions.table[sig].handler;
if handler != 0 {
// user handler
// change current mask
task_inner.signal_mask = task_inner.signal_actions.table[sig].mask;
// handle flag
task_inner.handling_sig = sig as isize;
task_inner.signals ^= signal;
// backup trapframe
let mut trap_ctx = task_inner.get_trap_cx();
task_inner.trap_ctx_backup = Some(*trap_ctx);
// modify trapframe
trap_ctx.sepc = handler;
// put args (a0)
trap_ctx.x[10] = sig;
} else {
// default action
println!("[K] task/call_user_signal_handler: default action: ignore it or kill process");
}
}
fn check_pending_signals() {
for sig in 0..(MAX_SIG + 1) {
let task = current_task().unwrap();
let task_inner = task.inner_exclusive_access();
let signal = SignalFlags::from_bits(1 << sig).unwrap();
if task_inner.signals.contains(signal) && (!task_inner.signal_mask.contains(signal)) {
if task_inner.handling_sig == -1 {
drop(task_inner);
drop(task);
if signal == SignalFlags::SIGKILL
|| signal == SignalFlags::SIGSTOP
|| signal == SignalFlags::SIGCONT
|| signal == SignalFlags::SIGDEF
{
// signal is a kernel signal
call_kernel_signal_handler(signal);
} else {
// signal is a user signal
call_user_signal_handler(sig, signal);
return;
}
} else {
if !task_inner.signal_actions.table[task_inner.handling_sig as usize]
.mask
.contains(signal)
{
drop(task_inner);
drop(task);
if signal == SignalFlags::SIGKILL
|| signal == SignalFlags::SIGSTOP
|| signal == SignalFlags::SIGCONT
|| signal == SignalFlags::SIGDEF
{
// signal is a kernel signal
call_kernel_signal_handler(signal);
} else {
// signal is a user signal
call_user_signal_handler(sig, signal);
return;
}
}
}
}
}
}
pub fn handle_signals() {
check_pending_signals();
loop {
let task = current_task().unwrap();
let task_inner = task.inner_exclusive_access();
let frozen_flag = task_inner.frozen;
let killed_flag = task_inner.killed;
drop(task_inner);
drop(task);
if (!frozen_flag) || killed_flag {
break;
}
check_pending_signals();
suspend_current_and_run_next()
}
}

@ -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 lazy_static::*;
use crate::sync::UPSafeCell;
use crate::mm::{KERNEL_SPACE, MapPermission, VirtAddr};
use crate::config::{
PAGE_SIZE,
TRAMPOLINE,
KERNEL_STACK_SIZE,
};
struct PidAllocator {
current: usize,
@ -31,17 +27,17 @@ impl PidAllocator {
pub fn dealloc(&mut self, pid: usize) {
assert!(pid < self.current);
assert!(
self.recycled.iter().find(|ppid| **ppid == pid).is_none(),
"pid {} has been deallocated!", pid
!self.recycled.iter().any(|ppid| *ppid == pid),
"pid {} has been deallocated!",
pid
);
self.recycled.push(pid);
}
}
lazy_static! {
static ref PID_ALLOCATOR : UPSafeCell<PidAllocator> = unsafe {
UPSafeCell::new(PidAllocator::new())
};
static ref PID_ALLOCATOR: UPSafeCell<PidAllocator> =
unsafe { UPSafeCell::new(PidAllocator::new()) };
}
pub struct PidHandle(pub usize);
@ -72,23 +68,23 @@ impl KernelStack {
pub fn new(pid_handle: &PidHandle) -> Self {
let pid = pid_handle.0;
let (kernel_stack_bottom, kernel_stack_top) = kernel_stack_position(pid);
KERNEL_SPACE
.exclusive_access()
.insert_framed_area(
kernel_stack_bottom.into(),
kernel_stack_top.into(),
MapPermission::R | MapPermission::W,
);
KernelStack {
pid: pid_handle.0,
}
KERNEL_SPACE.exclusive_access().insert_framed_area(
kernel_stack_bottom.into(),
kernel_stack_top.into(),
MapPermission::R | MapPermission::W,
);
KernelStack { pid: pid_handle.0 }
}
#[allow(unused)]
pub fn push_on_top<T>(&self, value: T) -> *mut T where
T: Sized, {
pub fn push_on_top<T>(&self, value: T) -> *mut T
where
T: Sized,
{
let kernel_stack_top = self.get_top();
let ptr_mut = (kernel_stack_top - core::mem::size_of::<T>()) as *mut T;
unsafe { *ptr_mut = value; }
unsafe {
*ptr_mut = value;
}
ptr_mut
}
pub fn get_top(&self) -> usize {
@ -105,4 +101,4 @@ impl Drop for KernelStack {
.exclusive_access()
.remove_area_with_start_vpn(kernel_stack_bottom_va.into());
}
}
}

@ -1,10 +1,10 @@
use super::__switch;
use super::{fetch_task, TaskStatus};
use super::{TaskContext, TaskControlBlock};
use crate::sync::UPSafeCell;
use crate::trap::TrapContext;
use alloc::sync::Arc;
use lazy_static::*;
use super::{fetch_task, TaskStatus};
use super::__switch;
use crate::trap::TrapContext;
use crate::sync::UPSafeCell;
pub struct Processor {
current: Option<Arc<TaskControlBlock>>,
@ -25,14 +25,12 @@ impl Processor {
self.current.take()
}
pub fn current(&self) -> Option<Arc<TaskControlBlock>> {
self.current.as_ref().map(|task| Arc::clone(task))
self.current.as_ref().map(Arc::clone)
}
}
lazy_static! {
pub static ref PROCESSOR: UPSafeCell<Processor> = unsafe {
UPSafeCell::new(Processor::new())
};
pub static ref PROCESSOR: UPSafeCell<Processor> = unsafe { UPSafeCell::new(Processor::new()) };
}
pub fn run_tasks() {
@ -50,10 +48,7 @@ pub fn run_tasks() {
// release processor manually
drop(processor);
unsafe {
__switch(
idle_task_cx_ptr,
next_task_cx_ptr,
);
__switch(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 {
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) {
@ -82,9 +80,6 @@ pub fn schedule(switched_task_cx_ptr: *mut TaskContext) {
let idle_task_cx_ptr = processor.get_idle_task_cx_ptr();
drop(processor);
unsafe {
__switch(
switched_task_cx_ptr,
idle_task_cx_ptr,
);
__switch(switched_task_cx_ptr, idle_task_cx_ptr);
}
}

@ -0,0 +1,61 @@
use bitflags::*;
pub const MAX_SIG: usize = 31;
bitflags! {
pub struct SignalFlags: u32 {
const SIGDEF = 1; // Default signal handling
const SIGHUP = 1 << 1;
const SIGINT = 1 << 2;
const SIGQUIT = 1 << 3;
const SIGILL = 1 << 4;
const SIGTRAP = 1 << 5;
const SIGABRT = 1 << 6;
const SIGBUS = 1 << 7;
const SIGFPE = 1 << 8;
const SIGKILL = 1 << 9;
const SIGUSR1 = 1 << 10;
const SIGSEGV = 1 << 11;
const SIGUSR2 = 1 << 12;
const SIGPIPE = 1 << 13;
const SIGALRM = 1 << 14;
const SIGTERM = 1 << 15;
const SIGSTKFLT = 1 << 16;
const SIGCHLD = 1 << 17;
const SIGCONT = 1 << 18;
const SIGSTOP = 1 << 19;
const SIGTSTP = 1 << 20;
const SIGTTIN = 1 << 21;
const SIGTTOU = 1 << 22;
const SIGURG = 1 << 23;
const SIGXCPU = 1 << 24;
const SIGXFSZ = 1 << 25;
const SIGVTALRM = 1 << 26;
const SIGPROF = 1 << 27;
const SIGWINCH = 1 << 28;
const SIGIO = 1 << 29;
const SIGPWR = 1 << 30;
const SIGSYS = 1 << 31;
}
}
impl SignalFlags {
pub fn check_error(&self) -> Option<(i32, &'static str)> {
if self.contains(Self::SIGINT) {
Some((-2, "Killed, SIGINT=2"))
} else if self.contains(Self::SIGILL) {
Some((-4, "Illegal Instruction, SIGILL=4"))
} else if self.contains(Self::SIGABRT) {
Some((-6, "Aborted, SIGABRT=6"))
} else if self.contains(Self::SIGFPE) {
Some((-8, "Erroneous Arithmetic Operation, SIGFPE=8"))
} else if self.contains(Self::SIGKILL) {
Some((-9, "Killed, SIGKILL=9"))
} else if self.contains(Self::SIGSEGV) {
Some((-11, "Segmentation Fault, SIGSEGV=11"))
} else {
//println!("[K] signalflags check_error {:?}", self);
None
}
}
}

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

@ -1,21 +1,15 @@
use crate::mm::{
MemorySet,
PhysPageNum,
KERNEL_SPACE,
VirtAddr,
translated_refmut,
};
use crate::trap::{TrapContext, trap_handler};
use super::{pid_alloc, KernelStack, PidHandle, SignalFlags};
use super::{SignalActions, TaskContext};
use crate::config::TRAP_CONTEXT;
use crate::fs::{File, Stdin, Stdout};
use crate::mm::{translated_refmut, MemorySet, PhysPageNum, VirtAddr, KERNEL_SPACE};
use crate::sync::UPSafeCell;
use core::cell::RefMut;
use super::TaskContext;
use super::{PidHandle, pid_alloc, KernelStack};
use alloc::sync::{Weak, Arc};
use crate::trap::{trap_handler, TrapContext};
use alloc::string::String;
use alloc::sync::{Arc, Weak};
use alloc::vec;
use alloc::vec::Vec;
use alloc::string::String;
use crate::fs::{File, Stdin, Stdout};
use core::cell::RefMut;
pub struct TaskControlBlock {
// immutable
@ -35,6 +29,17 @@ pub struct TaskControlBlockInner {
pub children: Vec<Arc<TaskControlBlock>>,
pub exit_code: i32,
pub fd_table: Vec<Option<Arc<dyn File + Send + Sync>>>,
pub signals: SignalFlags,
pub signal_mask: SignalFlags,
// the signal which is being handling
pub handling_sig: isize,
// Signal actions
pub signal_actions: SignalActions,
// if the task is killed
pub killed: bool,
// if the task is frozen by a signal
pub frozen: bool,
pub trap_ctx_backup: Option<TrapContext>,
}
impl TaskControlBlockInner {
@ -51,8 +56,7 @@ impl TaskControlBlockInner {
self.get_status() == TaskStatus::Zombie
}
pub fn alloc_fd(&mut self) -> usize {
if let Some(fd) = (0..self.fd_table.len())
.find(|fd| self.fd_table[*fd].is_none()) {
if let Some(fd) = (0..self.fd_table.len()).find(|fd| self.fd_table[*fd].is_none()) {
fd
} else {
self.fd_table.push(None);
@ -79,24 +83,33 @@ impl TaskControlBlock {
let task_control_block = Self {
pid: pid_handle,
kernel_stack,
inner: unsafe { UPSafeCell::new(TaskControlBlockInner {
trap_cx_ppn,
base_size: user_sp,
task_cx: TaskContext::goto_trap_return(kernel_stack_top),
task_status: TaskStatus::Ready,
memory_set,
parent: None,
children: Vec::new(),
exit_code: 0,
fd_table: vec![
// 0 -> stdin
Some(Arc::new(Stdin)),
// 1 -> stdout
Some(Arc::new(Stdout)),
// 2 -> stderr
Some(Arc::new(Stdout)),
],
})},
inner: unsafe {
UPSafeCell::new(TaskControlBlockInner {
trap_cx_ppn,
base_size: user_sp,
task_cx: TaskContext::goto_trap_return(kernel_stack_top),
task_status: TaskStatus::Ready,
memory_set,
parent: None,
children: Vec::new(),
exit_code: 0,
fd_table: vec![
// 0 -> stdin
Some(Arc::new(Stdin)),
// 1 -> stdout
Some(Arc::new(Stdout)),
// 2 -> stderr
Some(Arc::new(Stdout)),
],
signals: SignalFlags::empty(),
signal_mask: SignalFlags::empty(),
handling_sig: -1,
signal_actions: SignalActions::default(),
killed: false,
frozen: false,
trap_ctx_backup: None,
})
},
};
// prepare TrapContext in user space
let trap_cx = task_control_block.inner_exclusive_access().get_trap_cx();
@ -123,7 +136,7 @@ impl TaskControlBlock {
.map(|arg| {
translated_refmut(
memory_set.token(),
(argv_base + arg * core::mem::size_of::<usize>()) as *mut usize
(argv_base + arg * core::mem::size_of::<usize>()) as *mut usize,
)
})
.collect();
@ -164,9 +177,7 @@ impl TaskControlBlock {
// ---- hold parent PCB lock
let mut parent_inner = self.inner_exclusive_access();
// copy user space(include trap context)
let memory_set = MemorySet::from_existed_user(
&parent_inner.memory_set
);
let memory_set = MemorySet::from_existed_user(&parent_inner.memory_set);
let trap_cx_ppn = memory_set
.translate(VirtAddr::from(TRAP_CONTEXT).into())
.unwrap()
@ -187,17 +198,27 @@ impl TaskControlBlock {
let task_control_block = Arc::new(TaskControlBlock {
pid: pid_handle,
kernel_stack,
inner: unsafe { UPSafeCell::new(TaskControlBlockInner {
trap_cx_ppn,
base_size: parent_inner.base_size,
task_cx: TaskContext::goto_trap_return(kernel_stack_top),
task_status: TaskStatus::Ready,
memory_set,
parent: Some(Arc::downgrade(self)),
children: Vec::new(),
exit_code: 0,
fd_table: new_fd_table,
})},
inner: unsafe {
UPSafeCell::new(TaskControlBlockInner {
trap_cx_ppn,
base_size: parent_inner.base_size,
task_cx: TaskContext::goto_trap_return(kernel_stack_top),
task_status: TaskStatus::Ready,
memory_set,
parent: Some(Arc::downgrade(self)),
children: Vec::new(),
exit_code: 0,
fd_table: new_fd_table,
signals: SignalFlags::empty(),
// inherit the signal_mask and signal_action
signal_mask: parent_inner.signal_mask,
handling_sig: -1,
signal_actions: parent_inner.signal_actions.clone(),
killed: false,
frozen: false,
trap_ctx_backup: None,
})
},
});
// add child
parent_inner.children.push(task_control_block.clone());
@ -213,7 +234,6 @@ impl TaskControlBlock {
pub fn getpid(&self) -> usize {
self.pid.0
}
}
#[derive(Copy, Clone, PartialEq)]
@ -221,4 +241,4 @@ pub enum TaskStatus {
Ready,
Running,
Zombie,
}
}

@ -1,6 +1,6 @@
use riscv::register::time;
use crate::sbi::set_timer;
use crate::config::CLOCK_FREQ;
use crate::sbi::set_timer;
use riscv::register::time;
const TICKS_PER_SEC: usize = 100;
const MSEC_PER_SEC: usize = 1000;
@ -15,4 +15,4 @@ pub fn get_time_ms() -> usize {
pub fn set_next_trigger() {
set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC);
}
}

@ -1,7 +1,7 @@
use riscv::register::sstatus::{Sstatus, self, SPP};
use riscv::register::sstatus::{self, Sstatus, SPP};
#[repr(C)]
#[derive(Debug)]
#[derive(Debug, Clone, Copy)]
pub struct TrapContext {
pub x: [usize; 32],
pub sstatus: Sstatus,
@ -12,7 +12,9 @@ pub struct TrapContext {
}
impl TrapContext {
pub fn set_sp(&mut self, sp: usize) { self.x[2] = sp; }
pub fn set_sp(&mut self, sp: usize) {
self.x[2] = sp;
}
pub fn app_init_context(
entry: usize,
sp: usize,

@ -1,26 +1,18 @@
mod context;
use riscv::register::{
mtvec::TrapMode,
stvec,
scause::{
self,
Trap,
Exception,
Interrupt,
},
stval,
sie,
};
use crate::config::{TRAMPOLINE, TRAP_CONTEXT};
use crate::syscall::syscall;
use crate::task::{
exit_current_and_run_next,
suspend_current_and_run_next,
current_user_token,
current_trap_cx,
check_signals_error_of_current, current_add_signal, current_trap_cx, current_user_token,
exit_current_and_run_next, handle_signals, suspend_current_and_run_next, SignalFlags,
};
use crate::timer::set_next_trigger;
use crate::config::{TRAP_CONTEXT, TRAMPOLINE};
use core::arch::{asm, global_asm};
use riscv::register::{
mtvec::TrapMode,
scause::{self, Exception, Interrupt, Trap},
sie, stval, stvec,
};
global_asm!(include_str!("trap.S"));
@ -41,7 +33,9 @@ fn set_user_trap_entry() {
}
pub fn enable_timer_interrupt() {
unsafe { sie::set_stimer(); }
unsafe {
sie::set_stimer();
}
}
#[no_mangle]
@ -60,35 +54,46 @@ pub fn trap_handler() -> ! {
cx = current_trap_cx();
cx.x[10] = result as usize;
}
Trap::Exception(Exception::StoreFault) |
Trap::Exception(Exception::StorePageFault) |
Trap::Exception(Exception::InstructionFault) |
Trap::Exception(Exception::InstructionPageFault) |
Trap::Exception(Exception::LoadFault) |
Trap::Exception(Exception::LoadPageFault) => {
Trap::Exception(Exception::StoreFault)
| Trap::Exception(Exception::StorePageFault)
| Trap::Exception(Exception::InstructionFault)
| Trap::Exception(Exception::InstructionPageFault)
| Trap::Exception(Exception::LoadFault)
| Trap::Exception(Exception::LoadPageFault) => {
/*
println!(
"[kernel] {:?} in application, bad addr = {:#x}, bad instruction = {:#x}, core dumped.",
"[kernel] {:?} in application, bad addr = {:#x}, bad instruction = {:#x}, kernel killed it.",
scause.cause(),
stval,
current_trap_cx().sepc,
);
// page fault exit code
exit_current_and_run_next(-2);
*/
current_add_signal(SignalFlags::SIGSEGV);
}
Trap::Exception(Exception::IllegalInstruction) => {
println!("[kernel] IllegalInstruction in application, core dumped.");
// illegal instruction exit code
exit_current_and_run_next(-3);
current_add_signal(SignalFlags::SIGILL);
}
Trap::Interrupt(Interrupt::SupervisorTimer) => {
set_next_trigger();
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");
// handle signals (handle the sent signal)
//println!("[K] trap_handler:: handle_signals");
handle_signals();
// check error signals (if error then exit)
if let Some((errno, msg)) = check_signals_error_of_current() {
println!("[kernel] {}", msg);
exit_current_and_run_next(errno);
}
trap_return();
}

@ -1 +1 @@
nightly-2021-08-25
nightly-2022-04-11

@ -8,4 +8,8 @@ edition = "2018"
[dependencies]
buddy_system_allocator = "0.6"
bitflags = "1.2.1"
bitflags = "1.2.1"
riscv = { git = "https://github.com/rcore-os/riscv", features = ["inline-asm"] }
[profile.release]
debug = true

@ -5,13 +5,7 @@
extern crate user_lib;
extern crate alloc;
use user_lib::{
open,
OpenFlags,
close,
read,
};
use alloc::string::String;
use user_lib::{close, open, read, OpenFlags};
#[no_mangle]
pub fn main(argc: usize, argv: &[&str]) -> i32 {
@ -21,14 +15,14 @@ pub fn main(argc: usize, argv: &[&str]) -> i32 {
panic!("Error occured when opening file");
}
let fd = fd as usize;
let mut buf = [0u8; 16];
let mut s = String::new();
let mut buf = [0u8; 256];
loop {
let size = read(fd, &mut buf) as usize;
if size == 0 { break; }
s.push_str(core::str::from_utf8(&buf[..size]).unwrap());
if size == 0 {
break;
}
print!("{}", core::str::from_utf8(&buf[..size]).unwrap());
}
println!("{}", s);
close(fd);
0
}
}

@ -9,8 +9,8 @@ extern crate user_lib;
#[no_mangle]
pub fn main(argc: usize, argv: &[&str]) -> i32 {
println!("argc = {}", argc);
for i in 0..argc {
println!("argv[{}] = {}", i, argv[i]);
for (i, arg) in argv.iter().enumerate() {
println!("argv[{}] = {}", i, arg);
}
0
}
}

@ -0,0 +1,30 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use user_lib::read;
#[no_mangle]
pub fn main(_argc: usize, _argv: &[&str]) -> i32 {
let mut buf = [0u8; 256];
let mut lines = 0usize;
let mut total_size = 0usize;
loop {
let len = read(0, &mut buf) as usize;
if len == 0 {
break;
}
total_size += len;
let string = core::str::from_utf8(&buf[..len]).unwrap();
lines += string
.chars()
.fold(0, |acc, c| acc + if c == '\n' { 1 } else { 0 });
}
if total_size > 0 {
lines += 1;
}
println!("{}", lines);
0
}

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

@ -41,4 +41,4 @@ pub fn main() -> i32 {
println!("{}", color_text!(text, i));
}
0
}
}

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

@ -4,9 +4,9 @@
#[macro_use]
extern crate user_lib;
use user_lib::{fork, wait, exit};
use user_lib::{exit, fork, wait};
const MAX_CHILD: usize = 40;
const MAX_CHILD: usize = 30;
#[no_mangle]
pub fn main() -> i32 {
@ -31,4 +31,4 @@ pub fn main() -> i32 {
}
println!("forktest pass.");
0
}
}

@ -4,7 +4,7 @@
#[macro_use]
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;
@ -14,7 +14,8 @@ pub fn main() -> i32 {
let pid = fork();
if pid == 0 {
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);
sleep(sleep_length as usize);
println!("pid {} OK!", getpid());
@ -30,4 +31,4 @@ pub fn main() -> i32 {
assert!(wait(&mut exit_code) < 0);
println!("forktest2 test passed!");
0
}
}

@ -25,4 +25,4 @@ pub fn main() -> i32 {
println!("child process pid = {}, exit code = {}", pid, exit_code);
0
}
}
}

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

@ -0,0 +1,26 @@
#![no_std]
#![no_main]
extern crate alloc;
#[macro_use]
extern crate user_lib;
use user_lib::console::getchar;
const LF: u8 = 0x0au8;
const CR: u8 = 0x0du8;
#[no_mangle]
pub fn main() -> i32 {
println!("getchar starting.... Press 'ENTER' will quit.");
loop {
let c = getchar();
println!("Got Char {}", c);
if c == LF || c == CR {
println!("exit(0)");
return 0;
}
}
}

@ -8,4 +8,4 @@ extern crate user_lib;
pub fn main() -> i32 {
println!("Hello world from user mode program!");
0
}
}

@ -4,33 +4,30 @@
#[macro_use]
extern crate user_lib;
use user_lib::{
OpenFlags,
open,
close,
write,
get_time,
};
use user_lib::{close, get_time, open, write, OpenFlags};
#[no_mangle]
pub fn main() -> i32 {
let mut buffer = [0u8; 1024]; // 1KiB
for i in 0..buffer.len() {
buffer[i] = i as u8;
for (i, ch) in buffer.iter_mut().enumerate() {
*ch = i as u8;
}
let f = open("testf", OpenFlags::CREATE | OpenFlags::WRONLY);
let f = open("testf\0", OpenFlags::CREATE | OpenFlags::WRONLY);
if f < 0 {
panic!("Open test file failed!");
}
let f = f as usize;
let start = get_time();
let size_mb = 1usize;
for _ in 0..1024*size_mb {
for _ in 0..1024 * size_mb {
write(f, &buffer);
}
close(f);
let time_ms = (get_time() - start) as usize;
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,0 +1,10 @@
#![no_std]
#![no_main]
#![allow(clippy::empty_loop)]
extern crate user_lib;
#[no_mangle]
pub fn main(_argc: usize, _argv: &[&str]) -> ! {
loop {}
}

@ -1,20 +1,14 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use user_lib::{
fork,
wait,
exec,
yield_,
};
use user_lib::{exec, fork, wait, yield_};
#[no_mangle]
fn main() -> i32 {
if fork() == 0 {
exec("user_shell\0", &[0 as *const u8]);
exec("user_shell\0", &[core::ptr::null::<u8>()]);
} else {
loop {
let mut exit_code: i32 = 0;
@ -23,12 +17,14 @@ fn main() -> i32 {
yield_();
continue;
}
/*
println!(
"[initproc] Released a zombie process, pid={}, exit_code={}",
pid,
exit_code,
);
*/
}
}
0
}
}

@ -1,12 +1,13 @@
#![no_std]
#![no_main]
#![allow(clippy::needless_range_loop)]
#[macro_use]
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 = 35;
static NUM: usize = 30;
const N: usize = 10;
static P: i32 = 10007;
type Arr = [[i32; N]; N];
@ -65,4 +66,4 @@ pub fn main() -> i32 {
assert!(wait(&mut exit_code) < 0);
println!("matrix passed.");
0
}
}

@ -6,8 +6,8 @@ extern crate user_lib;
extern crate alloc;
use user_lib::{fork, close, pipe, read, write, wait, get_time};
use alloc::format;
use user_lib::{close, fork, get_time, pipe, read, wait, write};
const LENGTH: usize = 3000;
#[no_mangle]
@ -40,11 +40,14 @@ pub fn main() -> i32 {
// close write end of up pipe
close(up_pipe_fd[1]);
// generate a long random string
for i in 0..LENGTH {
random_str[i] = get_time() as u8;
for ch in random_str.iter_mut() {
*ch = get_time() as u8;
}
// send it
assert_eq!(write(down_pipe_fd[1], &random_str) as usize, random_str.len());
assert_eq!(
write(down_pipe_fd[1], &random_str) as usize,
random_str.len()
);
// close write end of down pipe
close(down_pipe_fd[1]);
// calculate sum(parent)
@ -57,13 +60,12 @@ pub fn main() -> i32 {
// check
assert_eq!(
sum,
str::parse::<usize>(
core::str::from_utf8(&child_result[..result_len]).unwrap()
).unwrap()
str::parse::<usize>(core::str::from_utf8(&child_result[..result_len]).unwrap())
.unwrap()
);
let mut _unused: i32 = 0;
wait(&mut _unused);
println!("pipe_large_test passed!");
0
}
}
}

@ -4,7 +4,7 @@
#[macro_use]
extern crate user_lib;
use user_lib::{fork, close, pipe, read, write, wait};
use user_lib::{close, fork, pipe, read, wait, write};
static STR: &str = "Hello, world!";
@ -41,4 +41,4 @@ pub fn main() -> i32 {
println!("pipetest passed!");
0
}
}
}

@ -0,0 +1,17 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use riscv::register::sstatus::{self, SPP};
#[no_mangle]
fn main() -> i32 {
println!("Try to access privileged CSR in U Mode");
println!("Kernel should kill this application!");
unsafe {
sstatus::set_spp(SPP::User);
}
0
}

@ -0,0 +1,17 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use core::arch::asm;
#[no_mangle]
fn main() -> i32 {
println!("Try to execute privileged instruction in U Mode");
println!("Kernel should kill this application!");
unsafe {
asm!("sret");
}
0
}

@ -4,13 +4,13 @@
#[macro_use]
extern crate user_lib;
use user_lib::{fork, exec, wait};
use user_lib::{exec, fork, wait};
#[no_mangle]
pub fn main() -> i32 {
for i in 0..1000 {
if fork() == 0 {
exec("pipe_large_test\0", &[0 as *const u8]);
exec("pipe_large_test\0", &[core::ptr::null::<u8>()]);
} else {
let mut _unused: i32 = 0;
wait(&mut _unused);
@ -18,4 +18,4 @@ pub fn main() -> i32 {
}
}
0
}
}

@ -0,0 +1,42 @@
#![no_std]
#![no_main]
extern crate alloc;
#[macro_use]
extern crate user_lib;
use user_lib::console::getchar;
use user_lib::*;
const LF: u8 = 0x0au8;
const CR: u8 = 0x0du8;
fn func() {
println!("signal_handler: caught signal SIGINT, and exit(1)");
exit(1);
}
#[no_mangle]
pub fn main() -> i32 {
println!("sig_ctrlc starting.... Press 'ctrl-c' or 'ENTER' will quit.");
let mut new = SignalAction::default();
let old = SignalAction::default();
new.handler = func as usize;
println!("sig_ctrlc: sigaction");
if sigaction(SIGINT, &new, &old) < 0 {
panic!("Sigaction failed!");
}
println!("sig_ctrlc: getchar....");
loop {
let c = getchar();
println!("Got Char {}", c);
if c == LF || c == CR {
return 0;
}
}
println!("sig_ctrlc: Done");
0
}

@ -0,0 +1,32 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
// use user_lib::{sigaction, sigprocmask, SignalAction, SignalFlags, fork, exit, wait, kill, getpid, sleep, sigreturn};
use user_lib::*;
fn func() {
println!("user_sig_test succsess");
sigreturn();
}
#[no_mangle]
pub fn main() -> i32 {
let mut new = SignalAction::default();
let old = SignalAction::default();
new.handler = func as usize;
println!("signal_simple: sigaction");
if sigaction(SIGUSR1, &new, &old) < 0 {
panic!("Sigaction failed!");
}
println!("signal_simple: kill");
if kill(getpid() as usize, SIGUSR1) < 0 {
println!("Kill failed!");
exit(1);
}
println!("signal_simple: Done");
0
}

@ -0,0 +1,47 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use user_lib::{
exit, fork, getpid, kill, sigaction, sigprocmask, sigreturn, sleep, waitpid, SignalAction,
SignalFlags,
};
fn func() {
println!("user_sig_test succsess");
sigreturn();
}
#[no_mangle]
pub fn main() -> i32 {
let pid = fork();
if pid == 0 {
let mut new = SignalAction::default();
let old = SignalAction::default();
new.handler = func as usize;
println!("signal_simple2: child sigaction");
if sigaction(10, &new, &old) < 0 {
panic!("Sigaction failed!");
}
sleep(1000);
println!("signal_simple2: child done");
exit(0);
} else if pid > 0 {
println!("signal_simple2: parent kill child");
sleep(500);
if kill(pid as usize, 1 << 10) < 0 {
println!("Kill failed!");
exit(1);
}
println!("signal_simple2: parent wait child");
let mut exit_code = 0;
waitpid(pid as usize, &mut exit_code);
println!("signal_simple2: parent Done");
exit(0);
}
0
}

@ -0,0 +1,209 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
// use user_lib::{sigaction, sigprocmask, SignalAction, SignalFlags, fork, exit, wait, kill, getpid, sleep, sigreturn};
use user_lib::*;
fn func() {
println!("user_sig_test succsess");
sigreturn();
}
fn func2() {
loop {
print!("");
}
}
fn func3() {
println!("interrupt");
sigreturn();
}
fn user_sig_test_failsignum() {
let mut new = SignalAction::default();
let old = SignalAction::default();
new.handler = func as usize;
if sigaction(50, &new, &old) >= 0 {
panic!("Wrong sigaction but success!");
}
}
fn user_sig_test_kill() {
let mut new = SignalAction::default();
let old = SignalAction::default();
new.handler = func as usize;
if sigaction(SIGUSR1, &new, &old) < 0 {
panic!("Sigaction failed!");
}
if kill(getpid() as usize, SIGUSR1) < 0 {
println!("Kill failed!");
exit(1);
}
}
fn user_sig_test_multiprocsignals() {
let pid = fork();
if pid == 0 {
let mut new = SignalAction::default();
let old = SignalAction::default();
new.handler = func as usize;
if sigaction(SIGUSR1, &new, &old) < 0 {
panic!("Sigaction failed!");
}
} else {
if kill(pid as usize, SIGUSR1) < 0 {
println!("Kill failed!");
exit(1);
}
let mut exit_code = 0;
wait(&mut exit_code);
}
}
fn user_sig_test_restore() {
let mut new = SignalAction::default();
let old = SignalAction::default();
let old2 = SignalAction::default();
new.handler = func as usize;
if sigaction(SIGUSR1, &new, &old) < 0 {
panic!("Sigaction failed!");
}
if sigaction(SIGUSR1, &old, &old2) < 0 {
panic!("Sigaction failed!");
}
if old2.handler != new.handler {
println!("Restore failed!");
exit(-1);
}
}
fn kernel_sig_test_ignore() {
sigprocmask(SignalFlags::SIGSTOP.bits() as u32);
if kill(getpid() as usize, SignalFlags::SIGSTOP.bits()) < 0 {
println!("kill faild\n");
exit(-1);
}
}
fn kernel_sig_test_stop_cont() {
let pid = fork();
if pid == 0 {
kill(getpid() as usize, SignalFlags::SIGSTOP.bits());
sleep(1000);
exit(-1);
} else {
sleep(5000);
kill(pid as usize, SignalFlags::SIGCONT.bits());
let mut exit_code = 0;
wait(&mut exit_code);
}
}
fn kernel_sig_test_failignorekill() {
let mut new = SignalAction::default();
let old = SignalAction::default();
new.handler = func as usize;
if sigaction(9, &new, &old) >= 0 {
panic!("Should not set sigaction to kill!");
}
if sigaction(9, &new, 0 as *const SignalAction) >= 0 {
panic!("Should not set sigaction to kill!");
}
if sigaction(9, 0 as *const SignalAction, &old) >= 0 {
panic!("Should not set sigaction to kill!");
}
}
fn final_sig_test() {
let mut new = SignalAction::default();
let old = SignalAction::default();
new.handler = func2 as usize;
let mut new2 = SignalAction::default();
let old2 = SignalAction::default();
new2.handler = func3 as usize;
let pid = fork();
if pid == 0 {
if sigaction(SIGUSR1, &new, &old) < 0 {
panic!("Sigaction failed!");
}
if sigaction(14, &new2, &old2) < 0 {
panic!("Sigaction failed!");
}
if kill(getpid() as usize, SIGUSR1) < 0 {
println!("Kill failed!");
exit(-1);
}
} else {
sleep(1000);
if kill(pid as usize, 1 << 14) < 0 {
println!("Kill failed!");
exit(-1);
}
sleep(1000);
kill(pid as usize, SignalFlags::SIGKILL.bits());
}
}
fn run(f: fn()) -> bool {
let pid = fork();
if pid == 0 {
f();
exit(0);
} else {
let mut exit_code: i32 = 0;
wait(&mut exit_code);
if exit_code != 0 {
println!("FAILED!");
} else {
println!("OK!");
}
exit_code == 0
}
}
#[no_mangle]
pub fn main() -> i32 {
let tests: [(fn(), &str); 8] = [
(user_sig_test_failsignum, "user_sig_test_failsignum"),
(user_sig_test_kill, "user_sig_test_kill"),
(
user_sig_test_multiprocsignals,
"user_sig_test_multiprocsignals",
),
(user_sig_test_restore, "user_sig_test_restore"),
(kernel_sig_test_ignore, "kernel_sig_test_ignore"),
(kernel_sig_test_stop_cont, "kernel_sig_test_stop_cont"),
(
kernel_sig_test_failignorekill,
"kernel_sig_test_failignorekill",
),
(final_sig_test, "final_sig_test"),
];
let mut fail_num = 0;
for test in tests {
println!("Testing {}", test.1);
if !run(test.0) {
fail_num += 1;
}
}
if fail_num == 0 {
println!("ALL TESTS PASSED");
0
} else {
println!("SOME TESTS FAILED");
-1
}
}

@ -4,10 +4,10 @@
#[macro_use]
extern crate user_lib;
use user_lib::{sleep, exit, get_time, fork, waitpid};
use user_lib::{exit, fork, get_time, sleep, waitpid};
fn sleepy() {
let time: usize = 1000;
let time: usize = 100;
for i in 0..5 {
sleep(time);
println!("sleep {} x {} msecs.", i + 1, time);
@ -27,4 +27,4 @@ pub fn main() -> i32 {
println!("use {} msecs.", get_time() - current_time);
println!("sleep pass.");
0
}
}

@ -13,7 +13,11 @@ pub fn main() -> i32 {
println!("current time_msec = {}", start);
sleep(100);
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!");
0
}
}

@ -5,7 +5,7 @@
extern crate user_lib;
fn f(d: usize) {
println!("d = {}",d);
println!("d = {}", d);
f(d + 1);
}
@ -14,4 +14,4 @@ pub fn main() -> i32 {
println!("It should trigger segmentation fault!");
f(0);
0
}
}

@ -0,0 +1,15 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
#[no_mangle]
fn main() -> i32 {
println!("Into Test store_fault, we will insert an invalid store operation...");
println!("Kernel should kill this application!");
unsafe {
core::ptr::null_mut::<u8>().write_volatile(0);
}
0
}

@ -0,0 +1,46 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use user_lib::{exec, fork, get_time, kill, waitpid, waitpid_nb, SignalFlags};
#[no_mangle]
pub fn main(argc: usize, argv: &[&str]) -> i32 {
assert_eq!(argc, 3, "argc must be 3!");
let timeout_ms = argv[2]
.parse::<isize>()
.expect("Error when parsing timeout!");
let pid = fork() as usize;
if pid == 0 {
if exec(argv[1], &[core::ptr::null::<u8>()]) != 0 {
println!("Error when executing '{}'", argv[1]);
return -4;
}
} else {
let start_time = get_time();
let mut child_exited = false;
let mut exit_code: i32 = 0;
loop {
if get_time() - start_time > timeout_ms {
break;
}
if waitpid_nb(pid, &mut exit_code) as usize == pid {
child_exited = true;
println!(
"child exited in {}ms, exit_code = {}",
get_time() - start_time,
exit_code,
);
}
}
if !child_exited {
println!("child has run for {}ms, kill it!", timeout_ms);
kill(pid, SignalFlags::SIGINT.bits());
assert_eq!(waitpid(pid, &mut exit_code) as usize, pid);
println!("exit code of the child is {}", exit_code);
}
}
0
}

@ -1,5 +1,6 @@
#![no_std]
#![no_main]
#![allow(clippy::println_empty_string)]
extern crate alloc;
@ -10,116 +11,191 @@ const LF: u8 = 0x0au8;
const CR: u8 = 0x0du8;
const DL: u8 = 0x7fu8;
const BS: u8 = 0x08u8;
const LINE_START: &str = ">> ";
use alloc::string::String;
use alloc::vec::Vec;
use user_lib::{
fork,
exec,
waitpid,
open,
OpenFlags,
close,
dup,
};
use user_lib::console::getchar;
use user_lib::{close, dup, exec, fork, open, pipe, waitpid, OpenFlags};
#[derive(Debug)]
struct ProcessArguments {
input: String,
output: String,
args_copy: Vec<String>,
args_addr: Vec<*const u8>,
}
impl ProcessArguments {
pub fn new(command: &str) -> Self {
let args: Vec<_> = command.split(' ').collect();
let mut args_copy: Vec<String> = args
.iter()
.filter(|&arg| !arg.is_empty())
.map(|&arg| {
let mut string = String::new();
string.push_str(arg);
string.push('\0');
string
})
.collect();
// redirect input
let mut input = String::new();
if let Some((idx, _)) = args_copy
.iter()
.enumerate()
.find(|(_, arg)| arg.as_str() == "<\0")
{
input = args_copy[idx + 1].clone();
args_copy.drain(idx..=idx + 1);
}
// redirect output
let mut output = String::new();
if let Some((idx, _)) = args_copy
.iter()
.enumerate()
.find(|(_, arg)| arg.as_str() == ">\0")
{
output = args_copy[idx + 1].clone();
args_copy.drain(idx..=idx + 1);
}
let mut args_addr: Vec<*const u8> = args_copy.iter().map(|arg| arg.as_ptr()).collect();
args_addr.push(core::ptr::null::<u8>());
Self {
input,
output,
args_copy,
args_addr,
}
}
}
#[no_mangle]
pub fn main() -> i32 {
println!("Rust user shell");
let mut line: String = String::new();
print!(">> ");
print!("{}", LINE_START);
loop {
let c = getchar();
match c {
LF | CR => {
println!("");
if !line.is_empty() {
let args: Vec<_> = line.as_str().split(' ').collect();
let mut args_copy: Vec<String> = args
.iter()
.map(|&arg| {
let mut string = String::new();
string.push_str(arg);
string
})
.collect();
args_copy
.iter_mut()
.for_each(|string| {
string.push('\0');
});
// redirect input
let mut input = String::new();
if let Some((idx, _)) = args_copy
.iter()
.enumerate()
.find(|(_, arg)| arg.as_str() == "<\0") {
input = args_copy[idx + 1].clone();
args_copy.drain(idx..=idx + 1);
}
// redirect output
let mut output = String::new();
if let Some((idx, _)) = args_copy
.iter()
.enumerate()
.find(|(_, arg)| arg.as_str() == ">\0") {
output = args_copy[idx + 1].clone();
args_copy.drain(idx..=idx + 1);
}
let mut args_addr: Vec<*const u8> = args_copy
let splited: Vec<_> = line.as_str().split('|').collect();
let process_arguments_list: Vec<_> = splited
.iter()
.map(|arg| arg.as_ptr())
.map(|&cmd| ProcessArguments::new(cmd))
.collect();
args_addr.push(0 as *const u8);
let pid = fork();
if pid == 0 {
// input redirection
if !input.is_empty() {
let input_fd = open(input.as_str(), OpenFlags::RDONLY);
if input_fd == -1 {
println!("Error when opening file {}", input);
return -4;
let mut valid = true;
for (i, process_args) in process_arguments_list.iter().enumerate() {
if i == 0 {
if !process_args.output.is_empty() {
valid = false;
}
} else if i == process_arguments_list.len() - 1 {
if !process_args.input.is_empty() {
valid = false;
}
} else if !process_args.output.is_empty() || !process_args.input.is_empty()
{
valid = false;
}
}
if process_arguments_list.len() == 1 {
valid = true;
}
if !valid {
println!("Invalid command: Inputs/Outputs cannot be correctly binded!");
} else {
// create pipes
let mut pipes_fd: Vec<[usize; 2]> = Vec::new();
if !process_arguments_list.is_empty() {
for _ in 0..process_arguments_list.len() - 1 {
let mut pipe_fd = [0usize; 2];
pipe(&mut pipe_fd);
pipes_fd.push(pipe_fd);
}
let input_fd = input_fd as usize;
close(0);
assert_eq!(dup(input_fd), 0);
close(input_fd);
}
// output redirection
if !output.is_empty() {
let output_fd = open(
output.as_str(),
OpenFlags::CREATE | OpenFlags::WRONLY
);
if output_fd == -1 {
println!("Error when opening file {}", output);
return -4;
let mut children: Vec<_> = Vec::new();
for (i, process_argument) in process_arguments_list.iter().enumerate() {
let pid = fork();
if pid == 0 {
let input = &process_argument.input;
let output = &process_argument.output;
let args_copy = &process_argument.args_copy;
let args_addr = &process_argument.args_addr;
// redirect input
if !input.is_empty() {
let input_fd = open(input.as_str(), OpenFlags::RDONLY);
if input_fd == -1 {
println!("Error when opening file {}", input);
return -4;
}
let input_fd = input_fd as usize;
close(0);
assert_eq!(dup(input_fd), 0);
close(input_fd);
}
// redirect output
if !output.is_empty() {
let output_fd = open(
output.as_str(),
OpenFlags::CREATE | OpenFlags::WRONLY,
);
if output_fd == -1 {
println!("Error when opening file {}", output);
return -4;
}
let output_fd = output_fd as usize;
close(1);
assert_eq!(dup(output_fd), 1);
close(output_fd);
}
// receive input from the previous process
if i > 0 {
close(0);
let read_end = pipes_fd.get(i - 1).unwrap()[0];
assert_eq!(dup(read_end), 0);
}
// send output to the next process
if i < process_arguments_list.len() - 1 {
close(1);
let write_end = pipes_fd.get(i).unwrap()[1];
assert_eq!(dup(write_end), 1);
}
// close all pipe ends inherited from the parent process
for pipe_fd in pipes_fd.iter() {
close(pipe_fd[0]);
close(pipe_fd[1]);
}
// execute new application
if exec(args_copy[0].as_str(), args_addr.as_slice()) == -1 {
println!("Error when executing!");
return -4;
}
unreachable!();
} else {
children.push(pid);
}
let output_fd = output_fd as usize;
close(1);
assert_eq!(dup(output_fd), 1);
close(output_fd);
}
// child process
if exec(args_copy[0].as_str(), args_addr.as_slice()) == -1 {
println!("Error when executing!");
return -4;
for pipe_fd in pipes_fd.iter() {
close(pipe_fd[0]);
close(pipe_fd[1]);
}
unreachable!();
} else {
let mut exit_code: i32 = 0;
let exit_pid = waitpid(pid as usize, &mut exit_code);
assert_eq!(pid, exit_pid);
println!("Shell: Process {} exited with code {}", pid, exit_code);
for pid in children.into_iter() {
let exit_pid = waitpid(pid as usize, &mut exit_code);
assert_eq!(pid, exit_pid);
//println!("Shell: Process {} exited with code {}", pid, exit_code);
}
}
line.clear();
}
print!(">> ");
print!("{}", LINE_START);
}
BS | DL => {
if !line.is_empty() {
@ -135,4 +211,4 @@ pub fn main() -> i32 {
}
}
}
}
}

@ -26,15 +26,18 @@ pub fn main() -> i32 {
println!("Usertests: Running {}", test);
let pid = fork();
if pid == 0 {
exec(*test, &[0 as *const u8]);
exec(*test, &[core::ptr::null::<u8>()]);
panic!("unreachable!");
} else {
let mut exit_code: i32 = Default::default();
let wait_pid = waitpid(pid as usize, &mut exit_code);
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!");
0
}
}

@ -14,4 +14,4 @@ pub fn main() -> i32 {
}
println!("yield pass.");
0
}
}

@ -1,12 +1,18 @@
use super::exit;
use super::{getpid, kill, SignalFlags};
#[panic_handler]
fn panic_handler(panic_info: &core::panic::PanicInfo) -> ! {
let err = panic_info.message().unwrap();
if let Some(location) = panic_info.location() {
println!("Panicked at {}:{}, {}", location.file(), location.line(), err);
println!(
"Panicked at {}:{}, {}",
location.file(),
location.line(),
err
);
} else {
println!("Panicked: {}", err);
}
exit(-1);
}
kill(getpid() as usize, SignalFlags::SIGABRT.bits());
unreachable!()
}

@ -1,21 +1,20 @@
#![no_std]
#![feature(asm)]
#![feature(linkage)]
#![feature(panic_info_message)]
#![feature(alloc_error_handler)]
#[macro_use]
pub mod console;
mod syscall;
mod lang_items;
mod syscall;
extern crate alloc;
#[macro_use]
extern crate bitflags;
use syscall::*;
use buddy_system_allocator::LockedHeap;
use alloc::vec::Vec;
use buddy_system_allocator::LockedHeap;
use syscall::*;
const USER_HEAP_SIZE: usize = 32768;
@ -38,16 +37,16 @@ pub extern "C" fn _start(argc: usize, argv: usize) -> ! {
}
let mut v: Vec<&'static str> = Vec::new();
for i in 0..argc {
let str_start = unsafe {
((argv + i * core::mem::size_of::<usize>()) as *const usize).read_volatile()
};
let len = (0usize..).find(|i| unsafe {
((str_start + *i) as *const u8).read_volatile() == 0
}).unwrap();
let str_start =
unsafe { ((argv + i * core::mem::size_of::<usize>()) as *const usize).read_volatile() };
let len = (0usize..)
.find(|i| unsafe { ((str_start + *i) as *const u8).read_volatile() == 0 })
.unwrap();
v.push(
core::str::from_utf8(unsafe {
core::slice::from_raw_parts(str_start as *const u8, len)
}).unwrap()
})
.unwrap(),
);
}
exit(main(argc, v.as_slice()));
@ -69,22 +68,48 @@ bitflags! {
}
}
pub fn dup(fd: usize) -> isize { sys_dup(fd) }
pub fn open(path: &str, flags: OpenFlags) -> isize { sys_open(path, flags.bits) }
pub fn close(fd: usize) -> isize { sys_close(fd) }
pub fn pipe(pipe_fd: &mut [usize]) -> isize { sys_pipe(pipe_fd) }
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 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, args: &[*const u8]) -> isize { sys_exec(path, args) }
pub fn dup(fd: usize) -> isize {
sys_dup(fd)
}
pub fn open(path: &str, flags: OpenFlags) -> isize {
sys_open(path, flags.bits)
}
pub fn close(fd: usize) -> isize {
sys_close(fd)
}
pub fn pipe(pipe_fd: &mut [usize]) -> isize {
sys_pipe(pipe_fd)
}
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 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, args: &[*const u8]) -> isize {
sys_exec(path, args)
}
pub fn wait(exit_code: &mut i32) -> isize {
loop {
match sys_waitpid(-1, exit_code as *mut _) {
-2 => { yield_(); }
-2 => {
yield_();
}
// -1 or a real pid
exit_pid => return exit_pid,
}
@ -94,15 +119,129 @@ pub fn wait(exit_code: &mut i32) -> isize {
pub fn waitpid(pid: usize, exit_code: &mut i32) -> isize {
loop {
match sys_waitpid(pid as isize, exit_code as *mut _) {
-2 => { yield_(); }
-2 => {
yield_();
}
// -1 or a real pid
exit_pid => return exit_pid,
}
}
}
pub fn waitpid_nb(pid: usize, exit_code: &mut i32) -> isize {
sys_waitpid(pid as isize, exit_code as *mut _)
}
pub fn sleep(period_ms: usize) {
let start = sys_get_time();
while sys_get_time() < start + period_ms as isize {
sys_yield();
}
}
}
/// Action for a signal
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct SignalAction {
pub handler: usize,
pub mask: SignalFlags,
}
impl Default for SignalAction {
fn default() -> Self {
Self {
handler: 0,
mask: SignalFlags::empty(),
}
}
}
pub const SIGDEF: i32 = 0; // Default signal handling
pub const SIGHUP: i32 = 1;
pub const SIGINT: i32 = 2;
pub const SIGQUIT: i32 = 3;
pub const SIGILL: i32 = 4;
pub const SIGTRAP: i32 = 5;
pub const SIGABRT: i32 = 6;
pub const SIGBUS: i32 = 7;
pub const SIGFPE: i32 = 8;
pub const SIGKILL: i32 = 9;
pub const SIGUSR1: i32 = 10;
pub const SIGSEGV: i32 = 11;
pub const SIGUSR2: i32 = 12;
pub const SIGPIPE: i32 = 13;
pub const SIGALRM: i32 = 14;
pub const SIGTERM: i32 = 15;
pub const SIGSTKFLT: i32 = 16;
pub const SIGCHLD: i32 = 17;
pub const SIGCONT: i32 = 18;
pub const SIGSTOP: i32 = 19;
pub const SIGTSTP: i32 = 20;
pub const SIGTTIN: i32 = 21;
pub const SIGTTOU: i32 = 22;
pub const SIGURG: i32 = 23;
pub const SIGXCPU: i32 = 24;
pub const SIGXFSZ: i32 = 25;
pub const SIGVTALRM: i32 = 26;
pub const SIGPROF: i32 = 27;
pub const SIGWINCH: i32 = 28;
pub const SIGIO: i32 = 29;
pub const SIGPWR: i32 = 30;
pub const SIGSYS: i32 = 31;
bitflags! {
pub struct SignalFlags: i32 {
const SIGDEF = 1; // Default signal handling
const SIGHUP = 1 << 1;
const SIGINT = 1 << 2;
const SIGQUIT = 1 << 3;
const SIGILL = 1 << 4;
const SIGTRAP = 1 << 5;
const SIGABRT = 1 << 6;
const SIGBUS = 1 << 7;
const SIGFPE = 1 << 8;
const SIGKILL = 1 << 9;
const SIGUSR1 = 1 << 10;
const SIGSEGV = 1 << 11;
const SIGUSR2 = 1 << 12;
const SIGPIPE = 1 << 13;
const SIGALRM = 1 << 14;
const SIGTERM = 1 << 15;
const SIGSTKFLT = 1 << 16;
const SIGCHLD = 1 << 17;
const SIGCONT = 1 << 18;
const SIGSTOP = 1 << 19;
const SIGTSTP = 1 << 20;
const SIGTTIN = 1 << 21;
const SIGTTOU = 1 << 22;
const SIGURG = 1 << 23;
const SIGXCPU = 1 << 24;
const SIGXFSZ = 1 << 25;
const SIGVTALRM = 1 << 26;
const SIGPROF = 1 << 27;
const SIGWINCH = 1 << 28;
const SIGIO = 1 << 29;
const SIGPWR = 1 << 30;
const SIGSYS = 1 << 31;
}
}
pub fn kill(pid: usize, signal: i32) -> isize {
sys_kill(pid, signal)
}
pub fn sigaction(
signum: i32,
action: *const SignalAction,
old_action: *const SignalAction,
) -> isize {
sys_sigaction(signum, action, old_action)
}
pub fn sigprocmask(mask: u32) -> isize {
sys_sigprocmask(mask)
}
pub fn sigreturn() -> isize {
sys_sigreturn()
}

@ -2,7 +2,7 @@
OUTPUT_ARCH(riscv)
ENTRY(_start)
BASE_ADDRESS = 0x0;
BASE_ADDRESS = 0x10000;
SECTIONS
{
@ -29,4 +29,4 @@ SECTIONS
*(.eh_frame)
*(.debug*)
}
}
}

@ -1,3 +1,7 @@
use core::arch::asm;
use crate::SignalAction;
const SYSCALL_DUP: usize = 24;
const SYSCALL_OPEN: usize = 56;
const SYSCALL_CLOSE: usize = 57;
@ -6,6 +10,10 @@ const SYSCALL_READ: usize = 63;
const SYSCALL_WRITE: usize = 64;
const SYSCALL_EXIT: usize = 93;
const SYSCALL_YIELD: usize = 124;
const SYSCALL_KILL: usize = 129;
const SYSCALL_SIGACTION: usize = 134;
const SYSCALL_SIGPROCMASK: usize = 135;
const SYSCALL_SIGRETURN: usize = 139;
const SYSCALL_GET_TIME: usize = 169;
const SYSCALL_GETPID: usize = 172;
const SYSCALL_FORK: usize = 220;
@ -43,7 +51,10 @@ pub fn sys_pipe(pipe: &mut [usize]) -> 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 {
@ -59,6 +70,10 @@ pub fn sys_yield() -> isize {
syscall(SYSCALL_YIELD, [0, 0, 0])
}
pub fn sys_kill(pid: usize, signal: i32) -> isize {
syscall(SYSCALL_KILL, [pid, signal as usize, 0])
}
pub fn sys_get_time() -> isize {
syscall(SYSCALL_GET_TIME, [0, 0, 0])
}
@ -72,9 +87,31 @@ pub fn sys_fork() -> isize {
}
pub fn sys_exec(path: &str, args: &[*const u8]) -> isize {
syscall(SYSCALL_EXEC, [path.as_ptr() as usize, args.as_ptr() as usize, 0])
syscall(
SYSCALL_EXEC,
[path.as_ptr() as usize, args.as_ptr() as usize, 0],
)
}
pub fn sys_waitpid(pid: isize, exit_code: *mut i32) -> isize {
syscall(SYSCALL_WAITPID, [pid as usize, exit_code as usize, 0])
}
}
pub fn sys_sigaction(
signum: i32,
action: *const SignalAction,
old_action: *const SignalAction,
) -> isize {
syscall(
SYSCALL_SIGACTION,
[signum as usize, action as usize, old_action as usize],
)
}
pub fn sys_sigprocmask(mask: u32) -> isize {
syscall(SYSCALL_SIGPROCMASK, [mask as usize, 0, 0])
}
pub fn sys_sigreturn() -> isize {
syscall(SYSCALL_SIGRETURN, [0, 0, 0])
}

Loading…
Cancel
Save