Merge branch 'main' into main

This commit is contained in:
chyyuu 2022-05-15 12:28:47 +08:00 committed by GitHub
commit 4f3308aa38
111 changed files with 3208 additions and 1555 deletions

66
.github/workflows/doc-and-test.yml vendored Normal file
View file

@ -0,0 +1,66 @@
name: Build Rust Doc And Run tests
on: [push]
env:
CARGO_TERM_COLOR: always
jobs:
build-doc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly-2022-04-11
components: rust-src, llvm-tools-preview
target: riscv64gc-unknown-none-elf
- name: Build doc
run: 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 }}
run-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly-2022-04-11
components: rust-src, llvm-tools-preview
target: riscv64gc-unknown-none-elf
- uses: actions-rs/install@v0.1
with:
crate: cargo-binutils
version: latest
use-tool-cache: true
- name: Cache QEMU
uses: actions/cache@v3
with:
path: qemu-7.0.0
key: qemu-7.0.0-x86_64-riscv64
- name: Install QEMU
run: |
sudo apt-get update
sudo apt-get install ninja-build -y
if [ ! -d qemu-7.0.0 ]; then
wget https://download.qemu.org/qemu-7.0.0.tar.xz
tar -xf qemu-7.0.0.tar.xz
cd qemu-7.0.0
./configure --target-list=riscv64-softmmu
make -j
else
cd qemu-7.0.0
fi
sudo make install
qemu-system-riscv64 --version
- name: Run usertests
run: cd os && make run TEST=1
timeout-minutes: 10

21
.gitignore vendored
View file

@ -1,16 +1,13 @@
.idea/* .*/*
os/target/* !.github/*
os/.idea/* !.vscode/settings.json
**/target/
**/Cargo.lock
os/src/link_app.S os/src/link_app.S
os/src/linker.ld
os/last-* os/last-*
os/Cargo.lock os/.gdb_history
os/last-*
user/target/*
user/.idea/*
user/Cargo.lock
easy-fs/Cargo.lock
easy-fs/target/*
easy-fs-fuse/Cargo.lock
easy-fs-fuse/target/*
tools/ tools/
pushall.sh pushall.sh

10
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,10 @@
{
// Prevent "can't find crate for `test`" error on no_std
// Ref: https://github.com/rust-lang/vscode-rust/issues/729
// For vscode-rust plugin users:
"rust.target": "riscv64gc-unknown-none-elf",
"rust.all_targets": false,
// For Rust Analyzer plugin users:
"rust-analyzer.cargo.target": "riscv64gc-unknown-none-elf",
"rust-analyzer.checkOnSave.allTargets": false
}

247
README.md
View file

@ -1,10 +1,12 @@
# rCore-Tutorial-v3 # rCore-Tutorial-v3
rCore-Tutorial version 3.5. See the [Documentation in Chinese](https://rcore-os.github.io/rCore-Tutorial-Book-v3/). rCore-Tutorial version 3.5. See the [Documentation in Chinese](https://rcore-os.github.io/rCore-Tutorial-Book-v3/).
rCore-Tutorial API Docs. See the [API Docs of Ten OSes ](#OS-API-DOCS)
Official QQ group number: 735045051 Official QQ group number: 735045051
## news ## news
- 2021.11.20: Now we are updating our labs. Please checkout chX-dev Branches for our current new labs. (Notice: please see the [Dependency] section in the end of this doc) - 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.
## Overview ## Overview
@ -14,7 +16,7 @@ This project aims to show how to write an **Unix-like OS** running on **RISC-V**
* 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) * 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 * OS
* concurrency of multiple processes * concurrency of multiple processes each of which contains mutiple native threads
* preemptive scheduling(Round-Robin algorithm) * preemptive scheduling(Round-Robin algorithm)
* dynamic memory management in kernel * dynamic memory management in kernel
* virtual memory * virtual memory
@ -23,15 +25,237 @@ This project aims to show how to write an **Unix-like OS** running on **RISC-V**
* **only 4K+ LoC** * **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) * [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 ## Run our project
TODO: ### 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.
## Show runtime debug info of OS kernel version
The branch of ch9-log contains a lot of debug info. You could try to run rcore tutorial
for understand the internal behavior of os kernel.
```sh
$ git clone https://github.com/rcore-os/rCore-Tutorial-v3.git
$ cd rCore-Tutorial-v3/os
$ git checkout ch9-log
$ make run
......
[rustsbi] RustSBI version 0.2.0-alpha.10, adapting to RISC-V SBI v0.3
.______ __ __ _______.___________. _______..______ __
| _ \ | | | | / | | / || _ \ | |
| |_) | | | | | | (----`---| |----`| (----`| |_) || |
| / | | | | \ \ | | \ \ | _ < | |
| |\ \----.| `--' |.----) | | | .----) | | |_) || |
| _| `._____| \______/ |_______/ |__| |_______/ |______/ |__|
[rustsbi] Implementation: RustSBI-QEMU Version 0.0.2
[rustsbi-dtb] Hart count: cluster0 with 1 cores
[rustsbi] misa: RV64ACDFIMSU
[rustsbi] mideleg: ssoft, stimer, sext (0x222)
[rustsbi] medeleg: ima, ia, bkpt, la, sa, uecall, ipage, lpage, spage (0xb1ab)
[rustsbi] pmp0: 0x10000000 ..= 0x10001fff (rw-)
[rustsbi] pmp1: 0x2000000 ..= 0x200ffff (rw-)
[rustsbi] pmp2: 0xc000000 ..= 0xc3fffff (rw-)
[rustsbi] pmp3: 0x80000000 ..= 0x8fffffff (rwx)
[rustsbi] enter supervisor 0x80200000
[KERN] rust_main() begin
[KERN] clear_bss() begin
[KERN] clear_bss() end
[KERN] mm::init() begin
[KERN] mm::init_heap() begin
[KERN] mm::init_heap() end
[KERN] mm::init_frame_allocator() begin
[KERN] mm::frame_allocator::lazy_static!FRAME_ALLOCATOR begin
......
```
## 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 ## Working in progress
Now we are still updating our project, you can find latest changes on branches `chX-dev` such as `ch1-dev`. We are intended to publish first release 3.5.0 after completing most of the tasks mentioned below. Our first release 3.5.0 (chapter 1-7) has been published.
Overall progress: ch7 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 ### Completed
@ -45,12 +269,18 @@ Overall progress: ch7
* [x] flush all block cache to disk after a fs transaction which involves write operation * [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] replace `spin::Mutex` with `UPSafeCell` before SMP chapter
* [x] add codes for a new chapter about synchronization & mutual exclusion(uniprocessor only) * [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) ### Todo(High priority)
* [ ] support Allwinner's RISC-V D1 chip * [ ] review documentation, current progress: 5/9
* [ ] bug fix: we should call `find_pte` rather than `find_pte_create` in `PageTable::unmap` * [ ] support user-level sync primitives in chapter 8
* [ ] bug fix: check validity of level-3 pte in `find_pte` instead of checking it outside this function * [ ] 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 * [ ] use old fs image optionally, do not always rebuild the image
* [ ] add new system calls: getdents64/fstat * [ ] add new system calls: getdents64/fstat
* [ ] shell functionality improvement(to be continued...) * [ ] shell functionality improvement(to be continued...)
@ -63,7 +293,6 @@ Overall progress: ch7
* [ ] provide smooth debug experience at a Rust source code level * [ ] provide smooth debug experience at a Rust source code level
* [ ] format the code using official tools * [ ] format the code using official tools
### Crates ### Crates
We will add them later. We will add them later.

Binary file not shown.

View file

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

View file

@ -9,3 +9,6 @@ edition = "2018"
[dependencies] [dependencies]
spin = "0.7.0" 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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -12,6 +12,7 @@ lazy_static = { version = "1.4.0", features = ["spin_no_std"] }
buddy_system_allocator = "0.6" buddy_system_allocator = "0.6"
bitflags = "1.2.1" bitflags = "1.2.1"
xmas-elf = "0.7.0" xmas-elf = "0.7.0"
volatile = "0.3"
virtio-drivers = { git = "https://github.com/rcore-os/virtio-drivers" } virtio-drivers = { git = "https://github.com/rcore-os/virtio-drivers" }
k210-pac = { git = "https://github.com/wyfcyx/k210-pac" } k210-pac = { git = "https://github.com/wyfcyx/k210-pac" }
k210-hal = { git = "https://github.com/wyfcyx/k210-hal" } k210-hal = { git = "https://github.com/wyfcyx/k210-hal" }
@ -21,3 +22,6 @@ easy-fs = { path = "../easy-fs" }
[features] [features]
board_qemu = [] board_qemu = []
board_k210 = [] board_k210 = []
[profile.release]
debug = true

View file

@ -14,6 +14,11 @@ SBI ?= rustsbi
BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin
K210_BOOTLOADER_SIZE := 131072 K210_BOOTLOADER_SIZE := 131072
# Building mode argument
ifeq ($(MODE), release)
MODE_ARG := --release
endif
# KERNEL ENTRY # KERNEL ENTRY
ifeq ($(BOARD), qemu) ifeq ($(BOARD), qemu)
KERNEL_ENTRY_PA := 0x80200000 KERNEL_ENTRY_PA := 0x80200000
@ -32,13 +37,16 @@ OBJCOPY := rust-objcopy --binary-architecture=riscv64
# Disassembly # Disassembly
DISASM ?= -x DISASM ?= -x
# Run usertests or usershell
TEST ?=
build: env switch-check $(KERNEL_BIN) fs-img build: env switch-check $(KERNEL_BIN) fs-img
switch-check: switch-check:
ifeq ($(BOARD), qemu) 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) 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 endif
env: env:
@ -56,8 +64,8 @@ $(KERNEL_BIN): kernel
@$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@
fs-img: $(APPS) fs-img: $(APPS)
@cd ../user && make build @cd ../user && make build TEST=$(TEST)
@rm $(FS_IMG) -f @rm -f $(FS_IMG)
@cd ../easy-fs-fuse && cargo run --release -- -s ../user/src/bin/ -t ../user/target/riscv64gc-unknown-none-elf/release/ @cd ../easy-fs-fuse && cargo run --release -- -s ../user/src/bin/ -t ../user/target/riscv64gc-unknown-none-elf/release/
$(APPS): $(APPS):
@ -76,7 +84,7 @@ disasm: kernel
disasm-vim: kernel disasm-vim: kernel
@$(OBJDUMP) $(DISASM) $(KERNEL_ELF) > $(DISASM_TMP) @$(OBJDUMP) $(DISASM) $(KERNEL_ELF) > $(DISASM_TMP)
@vim $(DISASM_TMP) @nvim $(DISASM_TMP)
@rm $(DISASM_TMP) @rm $(DISASM_TMP)
run: run-inner run: run-inner
@ -106,4 +114,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 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 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

30
os/src/boards/k210.rs Normal file
View file

@ -0,0 +1,30 @@
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;
pub fn device_init() {
unimplemented!();
}
pub fn irq_handler() {
unimplemented!();
}

45
os/src/boards/qemu.rs Normal file
View file

@ -0,0 +1,45 @@
pub const CLOCK_FREQ: usize = 12500000;
pub const MMIO: &[(usize, usize)] = &[
(0x1000_0000, 0x1000),
(0x1000_1000, 0x1000),
(0xC00_0000, 0x40_0000),
];
pub type BlockDeviceImpl = crate::drivers::block::VirtIOBlock;
pub type CharDeviceImpl = crate::drivers::chardev::NS16550a<VIRT_UART>;
pub const VIRT_PLIC: usize = 0xC00_0000;
pub const VIRT_UART: usize = 0x1000_0000;
use crate::drivers::block::BLOCK_DEVICE;
use crate::drivers::chardev::{CharDevice, UART};
use crate::drivers::plic::{IntrTargetPriority, PLIC};
pub fn device_init() {
use riscv::register::sie;
let mut plic = unsafe { PLIC::new(VIRT_PLIC) };
let hart_id: usize = 0;
let supervisor = IntrTargetPriority::Supervisor;
let machine = IntrTargetPriority::Machine;
plic.set_threshold(hart_id, supervisor, 0);
plic.set_threshold(hart_id, machine, 1);
for intr_src_id in [1usize, 10] {
plic.enable(hart_id, supervisor, intr_src_id);
plic.set_priority(intr_src_id, 1);
}
unsafe {
sie::set_sext();
}
}
pub fn irq_handler() {
let mut plic = unsafe { PLIC::new(VIRT_PLIC) };
let intr_src_id = plic.claim(0, IntrTargetPriority::Supervisor);
match intr_src_id {
1 => BLOCK_DEVICE.handle_irq(),
10 => UART.handle_irq(),
_ => panic!("unsupported IRQ {}", intr_src_id),
}
plic.complete(0, IntrTargetPriority::Supervisor, intr_src_id);
}

View file

@ -10,33 +10,4 @@ pub const PAGE_SIZE_BITS: usize = 0xc;
pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1; pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1;
pub const TRAP_CONTEXT_BASE: usize = TRAMPOLINE - PAGE_SIZE; pub const TRAP_CONTEXT_BASE: usize = TRAMPOLINE - PAGE_SIZE;
#[cfg(feature = "board_k210")] pub use crate::board::{CLOCK_FREQ, MMIO};
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 */
];

View file

@ -1,12 +1,12 @@
use crate::drivers::chardev::{CharDevice, UART};
use core::fmt::{self, Write}; use core::fmt::{self, Write};
use crate::sbi::console_putchar;
struct Stdout; struct Stdout;
impl Write for Stdout { impl Write for Stdout {
fn write_str(&mut self, s: &str) -> fmt::Result { fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.chars() { for c in s.chars() {
console_putchar(c as usize); UART.write(c as u8);
} }
Ok(()) Ok(())
} }
@ -29,5 +29,3 @@ macro_rules! println {
$crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)) $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?))
} }
} }

View file

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

View file

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

View file

@ -1,52 +1,95 @@
use virtio_drivers::{VirtIOBlk, VirtIOHeader};
use crate::mm::{
PhysAddr,
VirtAddr,
frame_alloc,
frame_dealloc,
PhysPageNum,
FrameTracker,
StepByOne,
PageTable,
kernel_token,
};
use super::BlockDevice; use super::BlockDevice;
use crate::sync::UPSafeCell; use crate::mm::{
frame_alloc, frame_dealloc, kernel_token, FrameTracker, PageTable, PhysAddr, PhysPageNum,
StepByOne, VirtAddr,
};
use crate::sync::{Condvar, UPIntrFreeCell};
use crate::task::schedule;
use crate::DEV_NON_BLOCKING_ACCESS;
use alloc::collections::BTreeMap;
use alloc::vec::Vec; use alloc::vec::Vec;
use lazy_static::*; use lazy_static::*;
use virtio_drivers::{BlkResp, RespStatus, VirtIOBlk, VirtIOHeader};
#[allow(unused)] #[allow(unused)]
const VIRTIO0: usize = 0x10001000; const VIRTIO0: usize = 0x10001000;
pub struct VirtIOBlock(UPSafeCell<VirtIOBlk<'static>>); pub struct VirtIOBlock {
virtio_blk: UPIntrFreeCell<VirtIOBlk<'static>>,
condvars: BTreeMap<u16, Condvar>,
}
lazy_static! { lazy_static! {
static ref QUEUE_FRAMES: UPSafeCell<Vec<FrameTracker>> = unsafe { static ref QUEUE_FRAMES: UPIntrFreeCell<Vec<FrameTracker>> =
UPSafeCell::new(Vec::new()) unsafe { UPIntrFreeCell::new(Vec::new()) };
};
} }
impl BlockDevice for VirtIOBlock { impl BlockDevice for VirtIOBlock {
fn read_block(&self, block_id: usize, buf: &mut [u8]) { fn read_block(&self, block_id: usize, buf: &mut [u8]) {
self.0.exclusive_access() let nb = *DEV_NON_BLOCKING_ACCESS.exclusive_access();
if nb {
let mut resp = BlkResp::default();
let task_cx_ptr = self.virtio_blk.exclusive_session(|blk| {
let token = unsafe { blk.read_block_nb(block_id, buf, &mut resp).unwrap() };
self.condvars.get(&token).unwrap().wait_no_sched()
});
schedule(task_cx_ptr);
assert_eq!(
resp.status(),
RespStatus::Ok,
"Error when reading VirtIOBlk"
);
} else {
self.virtio_blk
.exclusive_access()
.read_block(block_id, buf) .read_block(block_id, buf)
.expect("Error when reading VirtIOBlk"); .expect("Error when reading VirtIOBlk");
} }
}
fn write_block(&self, block_id: usize, buf: &[u8]) { fn write_block(&self, block_id: usize, buf: &[u8]) {
self.0.exclusive_access() let nb = *DEV_NON_BLOCKING_ACCESS.exclusive_access();
if nb {
let mut resp = BlkResp::default();
let task_cx_ptr = self.virtio_blk.exclusive_session(|blk| {
let token = unsafe { blk.write_block_nb(block_id, buf, &mut resp).unwrap() };
self.condvars.get(&token).unwrap().wait_no_sched()
});
schedule(task_cx_ptr);
assert_eq!(
resp.status(),
RespStatus::Ok,
"Error when writing VirtIOBlk"
);
} else {
self.virtio_blk
.exclusive_access()
.write_block(block_id, buf) .write_block(block_id, buf)
.expect("Error when writing VirtIOBlk"); .expect("Error when writing VirtIOBlk");
} }
}
fn handle_irq(&self) {
self.virtio_blk.exclusive_session(|blk| {
while let Ok(token) = blk.pop_used() {
self.condvars.get(&token).unwrap().signal();
}
});
}
} }
impl VirtIOBlock { impl VirtIOBlock {
#[allow(unused)]
pub fn new() -> Self { pub fn new() -> Self {
unsafe { let virtio_blk = unsafe {
Self(UPSafeCell::new(VirtIOBlk::new( UPIntrFreeCell::new(VirtIOBlk::new(&mut *(VIRTIO0 as *mut VirtIOHeader)).unwrap())
&mut *(VIRTIO0 as *mut VirtIOHeader) };
).unwrap())) let mut condvars = BTreeMap::new();
let channels = virtio_blk.exclusive_access().virt_queue_size();
for i in 0..channels {
let condvar = Condvar::new();
condvars.insert(i, condvar);
}
Self {
virtio_blk,
condvars,
} }
} }
} }
@ -56,7 +99,9 @@ pub extern "C" fn virtio_dma_alloc(pages: usize) -> PhysAddr {
let mut ppn_base = PhysPageNum(0); let mut ppn_base = PhysPageNum(0);
for i in 0..pages { for i in 0..pages {
let frame = frame_alloc().unwrap(); let frame = frame_alloc().unwrap();
if i == 0 { ppn_base = frame.ppn; } if i == 0 {
ppn_base = frame.ppn;
}
assert_eq!(frame.ppn.0, ppn_base.0 + i); assert_eq!(frame.ppn.0, ppn_base.0 + i);
QUEUE_FRAMES.exclusive_access().push(frame); QUEUE_FRAMES.exclusive_access().push(frame);
} }
@ -80,5 +125,7 @@ pub extern "C" fn virtio_phys_to_virt(paddr: PhysAddr) -> VirtAddr {
#[no_mangle] #[no_mangle]
pub extern "C" fn virtio_virt_to_phys(vaddr: VirtAddr) -> PhysAddr { pub extern "C" fn virtio_virt_to_phys(vaddr: VirtAddr) -> PhysAddr {
PageTable::from_token(kernel_token()).translate_va(vaddr).unwrap() PageTable::from_token(kernel_token())
.translate_va(vaddr)
.unwrap()
} }

View file

@ -0,0 +1,17 @@
mod ns16550a;
pub use ns16550a::NS16550a;
use crate::board::CharDeviceImpl;
use alloc::sync::Arc;
use lazy_static::*;
pub trait CharDevice {
fn read(&self) -> u8;
fn write(&self, ch: u8);
fn handle_irq(&self);
}
lazy_static! {
pub static ref UART: Arc<CharDeviceImpl> = Arc::new(CharDeviceImpl::new());
}

View file

@ -0,0 +1,175 @@
///! Ref: https://www.lammertbies.nl/comm/info/serial-uart
///! Ref: ns16550a datasheet: https://datasheetspdf.com/pdf-file/605590/NationalSemiconductor/NS16550A/1
///! Ref: ns16450 datasheet: https://datasheetspdf.com/pdf-file/1311818/NationalSemiconductor/NS16450/1
use super::CharDevice;
use crate::sync::{Condvar, UPIntrFreeCell};
use crate::task::schedule;
use alloc::collections::VecDeque;
use bitflags::*;
use volatile::{ReadOnly, Volatile, WriteOnly};
bitflags! {
/// InterruptEnableRegister
pub struct IER: u8 {
const RX_AVAILABLE = 1 << 0;
const TX_EMPTY = 1 << 1;
}
/// LineStatusRegister
pub struct LSR: u8 {
const DATA_AVAILABLE = 1 << 0;
const THR_EMPTY = 1 << 5;
}
/// Model Control Register
pub struct MCR: u8 {
const DATA_TERMINAL_READY = 1 << 0;
const REQUEST_TO_SEND = 1 << 1;
const AUX_OUTPUT1 = 1 << 2;
const AUX_OUTPUT2 = 1 << 3;
}
}
#[repr(C)]
#[allow(dead_code)]
struct ReadWithoutDLAB {
/// receiver buffer register
pub rbr: ReadOnly<u8>,
/// interrupt enable register
pub ier: Volatile<IER>,
/// interrupt identification register
pub iir: ReadOnly<u8>,
/// line control register
pub lcr: Volatile<u8>,
/// model control register
pub mcr: Volatile<MCR>,
/// line status register
pub lsr: ReadOnly<LSR>,
/// ignore MSR
_padding1: ReadOnly<u8>,
/// ignore SCR
_padding2: ReadOnly<u8>,
}
#[repr(C)]
#[allow(dead_code)]
struct WriteWithoutDLAB {
/// transmitter holding register
pub thr: WriteOnly<u8>,
/// interrupt enable register
pub ier: Volatile<IER>,
/// ignore FCR
_padding0: ReadOnly<u8>,
/// line control register
pub lcr: Volatile<u8>,
/// modem control register
pub mcr: Volatile<MCR>,
/// line status register
pub lsr: ReadOnly<LSR>,
/// ignore other registers
_padding1: ReadOnly<u16>,
}
pub struct NS16550aRaw {
base_addr: usize,
}
impl NS16550aRaw {
fn read_end(&mut self) -> &mut ReadWithoutDLAB {
unsafe { &mut *(self.base_addr as *mut ReadWithoutDLAB) }
}
fn write_end(&mut self) -> &mut WriteWithoutDLAB {
unsafe { &mut *(self.base_addr as *mut WriteWithoutDLAB) }
}
pub fn new(base_addr: usize) -> Self {
Self { base_addr }
}
pub fn init(&mut self) {
let read_end = self.read_end();
let mut mcr = MCR::empty();
mcr |= MCR::DATA_TERMINAL_READY;
mcr |= MCR::REQUEST_TO_SEND;
mcr |= MCR::AUX_OUTPUT2;
read_end.mcr.write(mcr);
let ier = IER::RX_AVAILABLE;
read_end.ier.write(ier);
}
pub fn read(&mut self) -> Option<u8> {
let read_end = self.read_end();
let lsr = read_end.lsr.read();
if lsr.contains(LSR::DATA_AVAILABLE) {
Some(read_end.rbr.read())
} else {
None
}
}
pub fn write(&mut self, ch: u8) {
let write_end = self.write_end();
loop {
if write_end.lsr.read().contains(LSR::THR_EMPTY) {
write_end.thr.write(ch);
break;
}
}
}
}
struct NS16550aInner {
ns16550a: NS16550aRaw,
read_buffer: VecDeque<u8>,
}
pub struct NS16550a<const BASE_ADDR: usize> {
inner: UPIntrFreeCell<NS16550aInner>,
condvar: Condvar,
}
impl<const BASE_ADDR: usize> NS16550a<BASE_ADDR> {
pub fn new() -> Self {
let mut inner = NS16550aInner {
ns16550a: NS16550aRaw::new(BASE_ADDR),
read_buffer: VecDeque::new(),
};
inner.ns16550a.init();
Self {
inner: unsafe { UPIntrFreeCell::new(inner) },
condvar: Condvar::new(),
}
}
}
impl<const BASE_ADDR: usize> CharDevice for NS16550a<BASE_ADDR> {
fn read(&self) -> u8 {
loop {
let mut inner = self.inner.exclusive_access();
if let Some(ch) = inner.read_buffer.pop_front() {
return ch;
} else {
let task_cx_ptr = self.condvar.wait_no_sched();
drop(inner);
schedule(task_cx_ptr);
}
}
}
fn write(&self, ch: u8) {
let mut inner = self.inner.exclusive_access();
inner.ns16550a.write(ch);
}
fn handle_irq(&self) {
let mut count = 0;
self.inner.exclusive_session(|inner| {
while let Some(ch) = inner.ns16550a.read() {
count += 1;
inner.read_buffer.push_back(ch);
}
});
if count > 0 {
self.condvar.signal();
}
}
}

View file

@ -1,3 +1,6 @@
mod block; pub mod block;
pub mod chardev;
pub mod plic;
pub use block::BLOCK_DEVICE; pub use block::BLOCK_DEVICE;
pub use chardev::UART;

124
os/src/drivers/plic.rs Normal file
View file

@ -0,0 +1,124 @@
#[allow(clippy::upper_case_acronyms)]
pub struct PLIC {
base_addr: usize,
}
#[derive(Copy, Clone)]
pub enum IntrTargetPriority {
Machine = 0,
Supervisor = 1,
}
impl IntrTargetPriority {
pub fn supported_number() -> usize {
2
}
}
impl PLIC {
fn priority_ptr(&self, intr_source_id: usize) -> *mut u32 {
assert!(intr_source_id > 0 && intr_source_id <= 132);
(self.base_addr + intr_source_id * 4) as *mut u32
}
fn hart_id_with_priority(hart_id: usize, target_priority: IntrTargetPriority) -> usize {
let priority_num = IntrTargetPriority::supported_number();
hart_id * priority_num + target_priority as usize
}
fn enable_ptr(
&self,
hart_id: usize,
target_priority: IntrTargetPriority,
intr_source_id: usize,
) -> (*mut u32, usize) {
let id = Self::hart_id_with_priority(hart_id, target_priority);
let (reg_id, reg_shift) = (intr_source_id / 32, intr_source_id % 32);
(
(self.base_addr + 0x2000 + 0x80 * id + 0x4 * reg_id) as *mut u32,
reg_shift,
)
}
fn threshold_ptr_of_hart_with_priority(
&self,
hart_id: usize,
target_priority: IntrTargetPriority,
) -> *mut u32 {
let id = Self::hart_id_with_priority(hart_id, target_priority);
(self.base_addr + 0x20_0000 + 0x1000 * id) as *mut u32
}
fn claim_comp_ptr_of_hart_with_priority(
&self,
hart_id: usize,
target_priority: IntrTargetPriority,
) -> *mut u32 {
let id = Self::hart_id_with_priority(hart_id, target_priority);
(self.base_addr + 0x20_0004 + 0x1000 * id) as *mut u32
}
pub unsafe fn new(base_addr: usize) -> Self {
Self { base_addr }
}
pub fn set_priority(&mut self, intr_source_id: usize, priority: u32) {
assert!(priority < 8);
unsafe {
self.priority_ptr(intr_source_id).write_volatile(priority);
}
}
#[allow(unused)]
pub fn get_priority(&mut self, intr_source_id: usize) -> u32 {
unsafe { self.priority_ptr(intr_source_id).read_volatile() & 7 }
}
pub fn enable(
&mut self,
hart_id: usize,
target_priority: IntrTargetPriority,
intr_source_id: usize,
) {
let (reg_ptr, shift) = self.enable_ptr(hart_id, target_priority, intr_source_id);
unsafe {
reg_ptr.write_volatile(reg_ptr.read_volatile() | 1 << shift);
}
}
#[allow(unused)]
pub fn disable(
&mut self,
hart_id: usize,
target_priority: IntrTargetPriority,
intr_source_id: usize,
) {
let (reg_ptr, shift) = self.enable_ptr(hart_id, target_priority, intr_source_id);
unsafe {
reg_ptr.write_volatile(reg_ptr.read_volatile() & (!(1u32 << shift)));
}
}
pub fn set_threshold(
&mut self,
hart_id: usize,
target_priority: IntrTargetPriority,
threshold: u32,
) {
assert!(threshold < 8);
let threshold_ptr = self.threshold_ptr_of_hart_with_priority(hart_id, target_priority);
unsafe {
threshold_ptr.write_volatile(threshold);
}
}
#[allow(unused)]
pub fn get_threshold(&mut self, hart_id: usize, target_priority: IntrTargetPriority) -> u32 {
let threshold_ptr = self.threshold_ptr_of_hart_with_priority(hart_id, target_priority);
unsafe { threshold_ptr.read_volatile() & 7 }
}
pub fn claim(&mut self, hart_id: usize, target_priority: IntrTargetPriority) -> u32 {
let claim_comp_ptr = self.claim_comp_ptr_of_hart_with_priority(hart_id, target_priority);
unsafe { claim_comp_ptr.read_volatile() }
}
pub fn complete(
&mut self,
hart_id: usize,
target_priority: IntrTargetPriority,
completion: u32,
) {
let claim_comp_ptr = self.claim_comp_ptr_of_hart_with_priority(hart_id, target_priority);
unsafe {
claim_comp_ptr.write_volatile(completion);
}
}
}

View file

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

View file

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

View file

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

View file

@ -1,30 +1,24 @@
use super::File; use super::File;
use crate::mm::{UserBuffer}; use crate::drivers::chardev::{CharDevice, UART};
use crate::sbi::console_getchar; use crate::mm::UserBuffer;
use crate::task::suspend_current_and_run_next;
pub struct Stdin; pub struct Stdin;
pub struct Stdout; pub struct Stdout;
impl File for Stdin { impl File for Stdin {
fn readable(&self) -> bool { true } fn readable(&self) -> bool {
fn writable(&self) -> bool { false } true
}
fn writable(&self) -> bool {
false
}
fn read(&self, mut user_buf: UserBuffer) -> usize { fn read(&self, mut user_buf: UserBuffer) -> usize {
assert_eq!(user_buf.len(), 1); assert_eq!(user_buf.len(), 1);
// busy loop //println!("before UART.read() in Stdin::read()");
let mut c: usize; let ch = UART.read();
loop { unsafe {
c = console_getchar(); user_buf.buffers[0].as_mut_ptr().write_volatile(ch);
if c == 0 {
suspend_current_and_run_next();
continue;
} else {
break;
} }
}
let ch = c as u8;
unsafe { user_buf.buffers[0].as_mut_ptr().write_volatile(ch); }
1 1
} }
fn write(&self, _user_buf: UserBuffer) -> usize { fn write(&self, _user_buf: UserBuffer) -> usize {
@ -33,9 +27,13 @@ impl File for Stdin {
} }
impl File for Stdout { impl File for Stdout {
fn readable(&self) -> bool { false } fn readable(&self) -> bool {
fn writable(&self) -> bool { true } false
fn read(&self, _user_buf: UserBuffer) -> usize{ }
fn writable(&self) -> bool {
true
}
fn read(&self, _user_buf: UserBuffer) -> usize {
panic!("Cannot read from stdout!"); panic!("Cannot read from stdout!");
} }
fn write(&self, user_buf: UserBuffer) -> usize { fn write(&self, user_buf: UserBuffer) -> usize {

View file

@ -1,22 +1,24 @@
use core::panic::PanicInfo;
use crate::sbi::shutdown; use crate::sbi::shutdown;
use crate::task::current_kstack_top; use crate::task::current_kstack_top;
use core::arch::asm;
use core::panic::PanicInfo;
#[panic_handler] #[panic_handler]
fn panic(info: &PanicInfo) -> ! { fn panic(info: &PanicInfo) -> ! {
match info.location() { if let Some(location) = info.location() {
Some(location) => { println!(
println!("[kernel] panicked at '{}', {}:{}:{}", "[kernel] Panicked at {}:{} {}",
info.message().unwrap(),
location.file(), location.file(),
location.line(), location.line(),
location.column() info.message().unwrap()
); );
} else {
println!("[kernel] Panicked: {}", info.message().unwrap());
} }
None => println!("[kernel] panicked at '{}'", info.message().unwrap()) unsafe {
backtrace();
} }
unsafe { backtrace(); } shutdown(255)
shutdown()
} }
unsafe fn backtrace() { unsafe fn backtrace() {
@ -25,9 +27,11 @@ unsafe fn backtrace() {
asm!("mv {}, s0", out(reg) fp); asm!("mv {}, s0", out(reg) fp);
println!("---START BACKTRACE---"); println!("---START BACKTRACE---");
for i in 0..10 { for i in 0..10 {
if fp == stop { break; } if fp == stop {
println!("#{}:ra={:#x}", i, *((fp-8) as *const usize)); break;
fp = *((fp-16) as *const usize); }
println!("#{}:ra={:#x}", i, *((fp - 8) as *const usize));
fp = *((fp - 16) as *const usize);
} }
println!("---END BACKTRACE---"); println!("---END BACKTRACE---");
} }

View file

@ -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!("**************/");
}

View file

@ -1,7 +1,5 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#![feature(global_asm)]
#![feature(asm)]
#![feature(panic_info_message)] #![feature(panic_info_message)]
#![feature(alloc_error_handler)] #![feature(alloc_error_handler)]
@ -10,21 +8,28 @@ extern crate alloc;
#[macro_use] #[macro_use]
extern crate bitflags; 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] #[macro_use]
mod console; mod console;
mod lang_items;
mod sbi;
mod syscall;
mod trap;
mod config; mod config;
mod drivers;
mod fs;
mod lang_items;
mod mm;
mod sbi;
mod sync;
mod syscall;
mod task; mod task;
mod timer; mod timer;
mod sync; mod trap;
mod mm;
mod fs;
mod drivers;
global_asm!(include_str!("entry.asm")); core::arch::global_asm!(include_str!("entry.asm"));
fn clear_bss() { fn clear_bss() {
extern "C" { extern "C" {
@ -32,24 +37,30 @@ fn clear_bss() {
fn ebss(); fn ebss();
} }
unsafe { unsafe {
core::slice::from_raw_parts_mut( core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize)
sbss as usize as *mut u8, .fill(0);
ebss as usize - sbss as usize,
).fill(0);
} }
} }
use lazy_static::*;
use sync::UPIntrFreeCell;
lazy_static! {
pub static ref DEV_NON_BLOCKING_ACCESS: UPIntrFreeCell<bool> =
unsafe { UPIntrFreeCell::new(false) };
}
#[no_mangle] #[no_mangle]
pub fn rust_main() -> ! { pub fn rust_main() -> ! {
clear_bss(); clear_bss();
println!("[kernel] Hello, world!");
mm::init(); mm::init();
mm::remap_test();
trap::init(); trap::init();
trap::enable_timer_interrupt(); trap::enable_timer_interrupt();
timer::set_next_trigger(); timer::set_next_trigger();
board::device_init();
fs::list_apps(); fs::list_apps();
task::add_initproc(); task::add_initproc();
*DEV_NON_BLOCKING_ACCESS.exclusive_access() = true;
task::run_tasks(); task::run_tasks();
panic!("Unreachable in rust_main!"); panic!("Unreachable in rust_main!");
} }

View file

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

View file

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

View file

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

View file

@ -1,19 +1,15 @@
use super::{PageTable, PageTableEntry, PTEFlags}; use super::{frame_alloc, FrameTracker};
use super::{VirtPageNum, VirtAddr, PhysPageNum, PhysAddr}; use super::{PTEFlags, PageTable, PageTableEntry};
use super::{FrameTracker, frame_alloc}; use super::{PhysAddr, PhysPageNum, VirtAddr, VirtPageNum};
use super::{VPNRange, StepByOne}; use super::{StepByOne, VPNRange};
use crate::config::{MEMORY_END, MMIO, PAGE_SIZE, TRAMPOLINE};
use crate::sync::UPIntrFreeCell;
use alloc::collections::BTreeMap; use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use riscv::register::satp;
use alloc::sync::Arc; use alloc::sync::Arc;
use alloc::vec::Vec;
use core::arch::asm;
use lazy_static::*; use lazy_static::*;
use crate::sync::UPSafeCell; use riscv::register::satp;
use crate::config::{
MEMORY_END,
PAGE_SIZE,
TRAMPOLINE,
MMIO,
};
extern "C" { extern "C" {
fn stext(); fn stext();
@ -29,9 +25,8 @@ extern "C" {
} }
lazy_static! { lazy_static! {
pub static ref KERNEL_SPACE: Arc<UPSafeCell<MemorySet>> = Arc::new(unsafe { pub static ref KERNEL_SPACE: Arc<UPIntrFreeCell<MemorySet>> =
UPSafeCell::new(MemorySet::new_kernel()) Arc::new(unsafe { UPIntrFreeCell::new(MemorySet::new_kernel()) });
});
} }
pub fn kernel_token() -> usize { pub fn kernel_token() -> usize {
@ -54,17 +49,24 @@ impl MemorySet {
self.page_table.token() self.page_table.token()
} }
/// Assume that no conflicts. /// Assume that no conflicts.
pub fn insert_framed_area(&mut self, start_va: VirtAddr, end_va: VirtAddr, permission: MapPermission) { pub fn insert_framed_area(
self.push(MapArea::new( &mut self,
start_va, start_va: VirtAddr,
end_va, end_va: VirtAddr,
MapType::Framed, permission: MapPermission,
permission, ) {
), None); self.push(
MapArea::new(start_va, end_va, MapType::Framed, permission),
None,
);
} }
pub fn remove_area_with_start_vpn(&mut self, start_vpn: VirtPageNum) { pub fn remove_area_with_start_vpn(&mut self, start_vpn: VirtPageNum) {
if let Some((idx, area)) = self.areas.iter_mut().enumerate() if let Some((idx, area)) = self
.find(|(_, area)| area.vpn_range.get_start() == start_vpn) { .areas
.iter_mut()
.enumerate()
.find(|(_, area)| area.vpn_range.get_start() == start_vpn)
{
area.unmap(&mut self.page_table); area.unmap(&mut self.page_table);
self.areas.remove(idx); self.areas.remove(idx);
} }
@ -93,50 +95,71 @@ impl MemorySet {
println!(".text [{:#x}, {:#x})", stext as usize, etext as usize); println!(".text [{:#x}, {:#x})", stext as usize, etext as usize);
println!(".rodata [{:#x}, {:#x})", srodata as usize, erodata as usize); println!(".rodata [{:#x}, {:#x})", srodata as usize, erodata as usize);
println!(".data [{:#x}, {:#x})", sdata as usize, edata as usize); println!(".data [{:#x}, {:#x})", sdata as usize, edata as usize);
println!(".bss [{:#x}, {:#x})", sbss_with_stack as usize, ebss as usize); println!(
".bss [{:#x}, {:#x})",
sbss_with_stack as usize, ebss as usize
);
println!("mapping .text section"); println!("mapping .text section");
memory_set.push(MapArea::new( memory_set.push(
MapArea::new(
(stext as usize).into(), (stext as usize).into(),
(etext as usize).into(), (etext as usize).into(),
MapType::Identical, MapType::Identical,
MapPermission::R | MapPermission::X, MapPermission::R | MapPermission::X,
), None); ),
None,
);
println!("mapping .rodata section"); println!("mapping .rodata section");
memory_set.push(MapArea::new( memory_set.push(
MapArea::new(
(srodata as usize).into(), (srodata as usize).into(),
(erodata as usize).into(), (erodata as usize).into(),
MapType::Identical, MapType::Identical,
MapPermission::R, MapPermission::R,
), None); ),
None,
);
println!("mapping .data section"); println!("mapping .data section");
memory_set.push(MapArea::new( memory_set.push(
MapArea::new(
(sdata as usize).into(), (sdata as usize).into(),
(edata as usize).into(), (edata as usize).into(),
MapType::Identical, MapType::Identical,
MapPermission::R | MapPermission::W, MapPermission::R | MapPermission::W,
), None); ),
None,
);
println!("mapping .bss section"); println!("mapping .bss section");
memory_set.push(MapArea::new( memory_set.push(
MapArea::new(
(sbss_with_stack as usize).into(), (sbss_with_stack as usize).into(),
(ebss as usize).into(), (ebss as usize).into(),
MapType::Identical, MapType::Identical,
MapPermission::R | MapPermission::W, MapPermission::R | MapPermission::W,
), None); ),
None,
);
println!("mapping physical memory"); println!("mapping physical memory");
memory_set.push(MapArea::new( memory_set.push(
MapArea::new(
(ekernel as usize).into(), (ekernel as usize).into(),
MEMORY_END.into(), MEMORY_END.into(),
MapType::Identical, MapType::Identical,
MapPermission::R | MapPermission::W, MapPermission::R | MapPermission::W,
), None); ),
None,
);
println!("mapping memory-mapped registers"); println!("mapping memory-mapped registers");
for pair in MMIO { for pair in MMIO {
memory_set.push(MapArea::new( memory_set.push(
MapArea::new(
(*pair).0.into(), (*pair).0.into(),
((*pair).0 + (*pair).1).into(), ((*pair).0 + (*pair).1).into(),
MapType::Identical, MapType::Identical,
MapPermission::R | MapPermission::W, MapPermission::R | MapPermission::W,
), None); ),
None,
);
} }
memory_set memory_set
} }
@ -160,26 +183,31 @@ impl MemorySet {
let end_va: VirtAddr = ((ph.virtual_addr() + ph.mem_size()) as usize).into(); let end_va: VirtAddr = ((ph.virtual_addr() + ph.mem_size()) as usize).into();
let mut map_perm = MapPermission::U; let mut map_perm = MapPermission::U;
let ph_flags = ph.flags(); let ph_flags = ph.flags();
if ph_flags.is_read() { map_perm |= MapPermission::R; } if ph_flags.is_read() {
if ph_flags.is_write() { map_perm |= MapPermission::W; } map_perm |= MapPermission::R;
if ph_flags.is_execute() { map_perm |= MapPermission::X; } }
let map_area = MapArea::new( if ph_flags.is_write() {
start_va, map_perm |= MapPermission::W;
end_va, }
MapType::Framed, if ph_flags.is_execute() {
map_perm, map_perm |= MapPermission::X;
); }
let map_area = MapArea::new(start_va, end_va, MapType::Framed, map_perm);
max_end_vpn = map_area.vpn_range.get_end(); max_end_vpn = map_area.vpn_range.get_end();
memory_set.push( memory_set.push(
map_area, map_area,
Some(&elf.input[ph.offset() as usize..(ph.offset() + ph.file_size()) as usize]) Some(&elf.input[ph.offset() as usize..(ph.offset() + ph.file_size()) as usize]),
); );
} }
} }
let max_end_va: VirtAddr = max_end_vpn.into(); let max_end_va: VirtAddr = max_end_vpn.into();
let mut user_stack_base: usize = max_end_va.into(); let mut user_stack_base: usize = max_end_va.into();
user_stack_base += PAGE_SIZE; user_stack_base += PAGE_SIZE;
(memory_set, user_stack_base, elf.header.pt2.entry_point() as usize) (
memory_set,
user_stack_base,
elf.header.pt2.entry_point() as usize,
)
} }
pub fn from_existed_user(user_space: &MemorySet) -> MemorySet { pub fn from_existed_user(user_space: &MemorySet) -> MemorySet {
let mut memory_set = Self::new_bare(); let mut memory_set = Self::new_bare();
@ -193,7 +221,9 @@ impl MemorySet {
for vpn in area.vpn_range { for vpn in area.vpn_range {
let src_ppn = user_space.translate(vpn).unwrap().ppn(); let src_ppn = user_space.translate(vpn).unwrap().ppn();
let dst_ppn = memory_set.translate(vpn).unwrap().ppn(); let dst_ppn = memory_set.translate(vpn).unwrap().ppn();
dst_ppn.get_bytes_array().copy_from_slice(src_ppn.get_bytes_array()); dst_ppn
.get_bytes_array()
.copy_from_slice(src_ppn.get_bytes_array());
} }
} }
memory_set memory_set
@ -226,7 +256,7 @@ impl MapArea {
start_va: VirtAddr, start_va: VirtAddr,
end_va: VirtAddr, end_va: VirtAddr,
map_type: MapType, map_type: MapType,
map_perm: MapPermission map_perm: MapPermission,
) -> Self { ) -> Self {
let start_vpn: VirtPageNum = start_va.floor(); let start_vpn: VirtPageNum = start_va.floor();
let end_vpn: VirtPageNum = end_va.ceil(); let end_vpn: VirtPageNum = end_va.ceil();
@ -261,12 +291,9 @@ impl MapArea {
page_table.map(vpn, ppn, pte_flags); page_table.map(vpn, ppn, pte_flags);
} }
pub fn unmap_one(&mut self, page_table: &mut PageTable, vpn: VirtPageNum) { pub fn unmap_one(&mut self, page_table: &mut PageTable, vpn: VirtPageNum) {
match self.map_type { if self.map_type == MapType::Framed {
MapType::Framed => {
self.data_frames.remove(&vpn); self.data_frames.remove(&vpn);
} }
_ => {}
}
page_table.unmap(vpn); page_table.unmap(vpn);
} }
pub fn map(&mut self, page_table: &mut PageTable) { pub fn map(&mut self, page_table: &mut PageTable) {
@ -324,17 +351,20 @@ pub fn remap_test() {
let mid_text: VirtAddr = ((stext as usize + etext as usize) / 2).into(); 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_rodata: VirtAddr = ((srodata as usize + erodata as usize) / 2).into();
let mid_data: VirtAddr = ((sdata as usize + edata as usize) / 2).into(); let mid_data: VirtAddr = ((sdata as usize + edata as usize) / 2).into();
assert_eq!( assert!(!kernel_space
kernel_space.page_table.translate(mid_text.floor()).unwrap().writable(), .page_table
false .translate(mid_text.floor())
); .unwrap()
assert_eq!( .writable(),);
kernel_space.page_table.translate(mid_rodata.floor()).unwrap().writable(), assert!(!kernel_space
false, .page_table
); .translate(mid_rodata.floor())
assert_eq!( .unwrap()
kernel_space.page_table.translate(mid_data.floor()).unwrap().executable(), .writable(),);
false, assert!(!kernel_space
); .page_table
.translate(mid_data.floor())
.unwrap()
.executable(),);
println!("remap_test passed!"); println!("remap_test passed!");
} }

View file

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

View file

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

View file

@ -1,5 +1,7 @@
#![allow(unused)] #![allow(unused)]
use core::arch::asm;
const SBI_SET_TIMER: usize = 0; const SBI_SET_TIMER: usize = 0;
const SBI_CONSOLE_PUTCHAR: usize = 1; const SBI_CONSOLE_PUTCHAR: usize = 1;
const SBI_CONSOLE_GETCHAR: usize = 2; const SBI_CONSOLE_GETCHAR: usize = 2;
@ -14,7 +16,7 @@ const SBI_SHUTDOWN: usize = 8;
fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize {
let mut ret; let mut ret;
unsafe { unsafe {
asm!( core::arch::asm!(
"ecall", "ecall",
inlateout("x10") arg0 => ret, inlateout("x10") arg0 => ret,
in("x11") arg1, in("x11") arg1,
@ -37,8 +39,7 @@ pub fn console_getchar() -> usize {
sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0)
} }
pub fn shutdown() -> ! { pub fn shutdown(exit_code: usize) -> ! {
sbi_call(SBI_SHUTDOWN, 0, 0, 0); sbi_call(SBI_SHUTDOWN, exit_code, 0, 0);
panic!("It should shutdown!"); panic!("It should shutdown!");
} }

58
os/src/sync/condvar.rs Normal file
View file

@ -0,0 +1,58 @@
use crate::sync::{Mutex, UPIntrFreeCell};
use crate::task::{
add_task, block_current_and_run_next, block_current_task, current_task, TaskContext,
TaskControlBlock,
};
use alloc::{collections::VecDeque, sync::Arc};
pub struct Condvar {
pub inner: UPIntrFreeCell<CondvarInner>,
}
pub struct CondvarInner {
pub wait_queue: VecDeque<Arc<TaskControlBlock>>,
}
impl Condvar {
pub fn new() -> Self {
Self {
inner: unsafe {
UPIntrFreeCell::new(CondvarInner {
wait_queue: VecDeque::new(),
})
},
}
}
pub fn signal(&self) {
let mut inner = self.inner.exclusive_access();
if let Some(task) = inner.wait_queue.pop_front() {
add_task(task);
}
}
/*
pub fn wait(&self) {
let mut inner = self.inner.exclusive_access();
inner.wait_queue.push_back(current_task().unwrap());
drop(inner);
block_current_and_run_next();
}
*/
pub fn wait_no_sched(&self) -> *mut TaskContext {
self.inner.exclusive_session(|inner| {
inner.wait_queue.push_back(current_task().unwrap());
});
block_current_task()
}
pub fn wait_with_mutex(&self, mutex: Arc<dyn Mutex>) {
mutex.unlock();
self.inner.exclusive_session(|inner| {
inner.wait_queue.push_back(current_task().unwrap());
});
block_current_and_run_next();
mutex.lock();
}
}

View file

@ -1,7 +1,9 @@
mod up; mod condvar;
mod mutex; mod mutex;
mod semaphore; mod semaphore;
mod up;
pub use up::UPSafeCell; pub use condvar::Condvar;
pub use mutex::{Mutex, MutexSpin, MutexBlocking}; pub use mutex::{Mutex, MutexBlocking, MutexSpin};
pub use semaphore::Semaphore; pub use semaphore::Semaphore;
pub use up::{UPIntrFreeCell, UPIntrRefMut};

View file

@ -1,8 +1,8 @@
use super::UPSafeCell; use super::UPIntrFreeCell;
use crate::task::{block_current_and_run_next, suspend_current_and_run_next};
use crate::task::TaskControlBlock; use crate::task::TaskControlBlock;
use crate::task::{add_task, current_task}; use crate::task::{add_task, current_task};
use alloc::{sync::Arc, collections::VecDeque}; use crate::task::{block_current_and_run_next, suspend_current_and_run_next};
use alloc::{collections::VecDeque, sync::Arc};
pub trait Mutex: Sync + Send { pub trait Mutex: Sync + Send {
fn lock(&self); fn lock(&self);
@ -10,13 +10,13 @@ pub trait Mutex: Sync + Send {
} }
pub struct MutexSpin { pub struct MutexSpin {
locked: UPSafeCell<bool>, locked: UPIntrFreeCell<bool>,
} }
impl MutexSpin { impl MutexSpin {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
locked: unsafe { UPSafeCell::new(false) }, locked: unsafe { UPIntrFreeCell::new(false) },
} }
} }
} }
@ -43,7 +43,7 @@ impl Mutex for MutexSpin {
} }
pub struct MutexBlocking { pub struct MutexBlocking {
inner: UPSafeCell<MutexBlockingInner>, inner: UPIntrFreeCell<MutexBlockingInner>,
} }
pub struct MutexBlockingInner { pub struct MutexBlockingInner {
@ -55,7 +55,7 @@ impl MutexBlocking {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
inner: unsafe { inner: unsafe {
UPSafeCell::new(MutexBlockingInner { UPIntrFreeCell::new(MutexBlockingInner {
locked: false, locked: false,
wait_queue: VecDeque::new(), wait_queue: VecDeque::new(),
}) })
@ -78,10 +78,11 @@ impl Mutex for MutexBlocking {
fn unlock(&self) { fn unlock(&self) {
let mut mutex_inner = self.inner.exclusive_access(); let mut mutex_inner = self.inner.exclusive_access();
assert_eq!(mutex_inner.locked, true); assert!(mutex_inner.locked);
mutex_inner.locked = false;
if let Some(waking_task) = mutex_inner.wait_queue.pop_front() { if let Some(waking_task) = mutex_inner.wait_queue.pop_front() {
add_task(waking_task); add_task(waking_task);
} else {
mutex_inner.locked = false;
} }
} }
} }

View file

@ -1,9 +1,9 @@
use alloc::{sync::Arc, collections::VecDeque}; use crate::sync::UPIntrFreeCell;
use crate::task::{add_task, TaskControlBlock, current_task, block_current_and_run_next}; use crate::task::{add_task, block_current_and_run_next, current_task, TaskControlBlock};
use crate::sync::UPSafeCell; use alloc::{collections::VecDeque, sync::Arc};
pub struct Semaphore { pub struct Semaphore {
pub inner: UPSafeCell<SemaphoreInner>, pub inner: UPIntrFreeCell<SemaphoreInner>,
} }
pub struct SemaphoreInner { pub struct SemaphoreInner {
@ -14,12 +14,12 @@ pub struct SemaphoreInner {
impl Semaphore { impl Semaphore {
pub fn new(res_count: usize) -> Self { pub fn new(res_count: usize) -> Self {
Self { Self {
inner: unsafe { UPSafeCell::new( inner: unsafe {
SemaphoreInner { UPIntrFreeCell::new(SemaphoreInner {
count: res_count as isize, count: res_count as isize,
wait_queue: VecDeque::new(), wait_queue: VecDeque::new(),
} })
)}, },
} }
} }

View file

@ -1,5 +1,9 @@
use core::cell::{RefCell, RefMut}; use core::cell::{RefCell, RefMut, UnsafeCell};
use core::ops::{Deref, DerefMut};
use lazy_static::*;
use riscv::register::sstatus;
/*
/// Wrap a static data structure inside it so that we are /// Wrap a static data structure inside it so that we are
/// able to access it without any `unsafe`. /// able to access it without any `unsafe`.
/// ///
@ -18,10 +22,119 @@ impl<T> UPSafeCell<T> {
/// User is responsible to guarantee that inner struct is only used in /// User is responsible to guarantee that inner struct is only used in
/// uniprocessor. /// uniprocessor.
pub unsafe fn new(value: T) -> Self { pub unsafe fn new(value: T) -> Self {
Self { inner: RefCell::new(value) } Self {
inner: RefCell::new(value),
}
} }
/// Panic if the data has been borrowed. /// Panic if the data has been borrowed.
pub fn exclusive_access(&self) -> RefMut<'_, T> { pub fn exclusive_access(&self) -> RefMut<'_, T> {
self.inner.borrow_mut() self.inner.borrow_mut()
} }
} }
*/
pub struct UPSafeCellRaw<T> {
inner: UnsafeCell<T>,
}
unsafe impl<T> Sync for UPSafeCellRaw<T> {}
impl<T> UPSafeCellRaw<T> {
pub unsafe fn new(value: T) -> Self {
Self {
inner: UnsafeCell::new(value),
}
}
pub fn get_mut(&self) -> &mut T {
unsafe { &mut (*self.inner.get()) }
}
}
pub struct IntrMaskingInfo {
nested_level: usize,
sie_before_masking: bool,
}
lazy_static! {
static ref INTR_MASKING_INFO: UPSafeCellRaw<IntrMaskingInfo> =
unsafe { UPSafeCellRaw::new(IntrMaskingInfo::new()) };
}
impl IntrMaskingInfo {
pub fn new() -> Self {
Self {
nested_level: 0,
sie_before_masking: false,
}
}
pub fn enter(&mut self) {
let sie = sstatus::read().sie();
unsafe {
sstatus::clear_sie();
}
if self.nested_level == 0 {
self.sie_before_masking = sie;
}
self.nested_level += 1;
}
pub fn exit(&mut self) {
self.nested_level -= 1;
if self.nested_level == 0 && self.sie_before_masking {
unsafe {
sstatus::set_sie();
}
}
}
}
pub struct UPIntrFreeCell<T> {
/// inner data
inner: RefCell<T>,
}
unsafe impl<T> Sync for UPIntrFreeCell<T> {}
pub struct UPIntrRefMut<'a, T>(Option<RefMut<'a, T>>);
impl<T> UPIntrFreeCell<T> {
pub unsafe fn new(value: T) -> Self {
Self {
inner: RefCell::new(value),
}
}
/// Panic if the data has been borrowed.
pub fn exclusive_access(&self) -> UPIntrRefMut<'_, T> {
INTR_MASKING_INFO.get_mut().enter();
UPIntrRefMut(Some(self.inner.borrow_mut()))
}
pub fn exclusive_session<F, V>(&self, f: F) -> V
where
F: FnOnce(&mut T) -> V,
{
let mut inner = self.exclusive_access();
f(inner.deref_mut())
}
}
impl<'a, T> Drop for UPIntrRefMut<'a, T> {
fn drop(&mut self) {
self.0 = None;
INTR_MASKING_INFO.get_mut().exit();
}
}
impl<'a, T> Deref for UPIntrRefMut<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.as_ref().unwrap().deref()
}
}
impl<'a, T> DerefMut for UPIntrRefMut<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.as_mut().unwrap().deref_mut()
}
}

View file

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

View file

@ -7,6 +7,7 @@ const SYSCALL_WRITE: usize = 64;
const SYSCALL_EXIT: usize = 93; const SYSCALL_EXIT: usize = 93;
const SYSCALL_SLEEP: usize = 101; const SYSCALL_SLEEP: usize = 101;
const SYSCALL_YIELD: usize = 124; const SYSCALL_YIELD: usize = 124;
const SYSCALL_KILL: usize = 129;
const SYSCALL_GET_TIME: usize = 169; const SYSCALL_GET_TIME: usize = 169;
const SYSCALL_GETPID: usize = 172; const SYSCALL_GETPID: usize = 172;
const SYSCALL_FORK: usize = 220; const SYSCALL_FORK: usize = 220;
@ -21,20 +22,23 @@ const SYSCALL_MUTEX_UNLOCK: usize = 1012;
const SYSCALL_SEMAPHORE_CREATE: usize = 1020; const SYSCALL_SEMAPHORE_CREATE: usize = 1020;
const SYSCALL_SEMAPHORE_UP: usize = 1021; const SYSCALL_SEMAPHORE_UP: usize = 1021;
const SYSCALL_SEMAPHORE_DOWN: usize = 1022; const SYSCALL_SEMAPHORE_DOWN: usize = 1022;
const SYSCALL_CONDVAR_CREATE: usize = 1030;
const SYSCALL_CONDVAR_SIGNAL: usize = 1031;
const SYSCALL_CONDVAR_WAIT: usize = 1032;
mod fs; mod fs;
mod process; mod process;
mod thread;
mod sync; mod sync;
mod thread;
use fs::*; use fs::*;
use process::*; use process::*;
use thread::*;
use sync::*; use sync::*;
use thread::*;
pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize { pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize {
match syscall_id { 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_OPEN => sys_open(args[0] as *const u8, args[1] as u32),
SYSCALL_CLOSE => sys_close(args[0]), SYSCALL_CLOSE => sys_close(args[0]),
SYSCALL_PIPE => sys_pipe(args[0] as *mut usize), SYSCALL_PIPE => sys_pipe(args[0] as *mut usize),
@ -43,6 +47,7 @@ pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize {
SYSCALL_EXIT => sys_exit(args[0] as i32), SYSCALL_EXIT => sys_exit(args[0] as i32),
SYSCALL_SLEEP => sys_sleep(args[0]), SYSCALL_SLEEP => sys_sleep(args[0]),
SYSCALL_YIELD => sys_yield(), SYSCALL_YIELD => sys_yield(),
SYSCALL_KILL => sys_kill(args[0], args[1] as u32),
SYSCALL_GET_TIME => sys_get_time(), SYSCALL_GET_TIME => sys_get_time(),
SYSCALL_GETPID => sys_getpid(), SYSCALL_GETPID => sys_getpid(),
SYSCALL_FORK => sys_fork(), SYSCALL_FORK => sys_fork(),
@ -54,10 +59,12 @@ pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize {
SYSCALL_MUTEX_CREATE => sys_mutex_create(args[0] == 1), SYSCALL_MUTEX_CREATE => sys_mutex_create(args[0] == 1),
SYSCALL_MUTEX_LOCK => sys_mutex_lock(args[0]), SYSCALL_MUTEX_LOCK => sys_mutex_lock(args[0]),
SYSCALL_MUTEX_UNLOCK => sys_mutex_unlock(args[0]), SYSCALL_MUTEX_UNLOCK => sys_mutex_unlock(args[0]),
SYSCALL_SEMAPHORE_CREATE => sys_semaphore_creare(args[0]), SYSCALL_SEMAPHORE_CREATE => sys_semaphore_create(args[0]),
SYSCALL_SEMAPHORE_UP => sys_semaphore_up(args[0]), SYSCALL_SEMAPHORE_UP => sys_semaphore_up(args[0]),
SYSCALL_SEMAPHORE_DOWN => sys_semaphore_down(args[0]), SYSCALL_SEMAPHORE_DOWN => sys_semaphore_down(args[0]),
SYSCALL_CONDVAR_CREATE => sys_condvar_create(args[0]),
SYSCALL_CONDVAR_SIGNAL => sys_condvar_signal(args[0]),
SYSCALL_CONDVAR_WAIT => sys_condvar_wait(args[0], args[1]),
_ => panic!("Unsupported syscall_id: {}", syscall_id), _ => panic!("Unsupported syscall_id: {}", syscall_id),
} }
} }

View file

@ -1,23 +1,13 @@
use crate::fs::{open_file, OpenFlags};
use crate::mm::{translated_ref, translated_refmut, translated_str};
use crate::task::{ use crate::task::{
suspend_current_and_run_next, current_process, current_task, current_user_token, exit_current_and_run_next, pid2process,
exit_current_and_run_next, suspend_current_and_run_next, SignalFlags,
current_task,
current_process,
current_user_token,
}; };
use crate::timer::get_time_ms; use crate::timer::get_time_ms;
use crate::mm::{ use alloc::string::String;
translated_str,
translated_refmut,
translated_ref,
};
use crate::fs::{
open_file,
OpenFlags,
};
use alloc::sync::Arc; use alloc::sync::Arc;
use alloc::vec::Vec; use alloc::vec::Vec;
use alloc::string::String;
pub fn sys_exit(exit_code: i32) -> ! { pub fn sys_exit(exit_code: i32) -> ! {
exit_current_and_run_next(exit_code); exit_current_and_run_next(exit_code);
@ -61,7 +51,9 @@ pub fn sys_exec(path: *const u8, mut args: *const usize) -> isize {
break; break;
} }
args_vec.push(translated_str(token, arg_str_ptr as *const u8)); 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) { if let Some(app_inode) = open_file(path.as_str(), OpenFlags::RDONLY) {
let all_data = app_inode.read_all(); let all_data = app_inode.read_all();
@ -82,17 +74,15 @@ pub fn sys_waitpid(pid: isize, exit_code_ptr: *mut i32) -> isize {
// find a child process // find a child process
let mut inner = process.inner_exclusive_access(); let mut inner = process.inner_exclusive_access();
if inner.children if !inner
.children
.iter() .iter()
.find(|p| {pid == -1 || pid as usize == p.getpid()}) .any(|p| pid == -1 || pid as usize == p.getpid())
.is_none() { {
return -1; return -1;
// ---- release current PCB // ---- release current PCB
} }
let pair = inner.children let pair = inner.children.iter().enumerate().find(|(_, p)| {
.iter()
.enumerate()
.find(|(_, p)| {
// ++++ temporarily access child PCB exclusively // ++++ temporarily access child PCB exclusively
p.inner_exclusive_access().is_zombie && (pid == -1 || pid as usize == p.getpid()) p.inner_exclusive_access().is_zombie && (pid == -1 || pid as usize == p.getpid())
// ++++ release child PCB // ++++ release child PCB
@ -112,3 +102,16 @@ pub fn sys_waitpid(pid: isize, exit_code_ptr: *mut i32) -> isize {
} }
// ---- release current PCB automatically // ---- release current PCB automatically
} }
pub fn sys_kill(pid: usize, signal: u32) -> isize {
if let Some(process) = pid2process(pid) {
if let Some(flag) = SignalFlags::from_bits(signal) {
process.inner_exclusive_access().signals |= flag;
0
} else {
-1
}
} else {
-1
}
}

View file

@ -1,6 +1,6 @@
use crate::task::{current_task, current_process, block_current_and_run_next}; use crate::sync::{Condvar, Mutex, MutexBlocking, MutexSpin, Semaphore};
use crate::sync::{MutexSpin, MutexBlocking, Semaphore}; use crate::task::{block_current_and_run_next, current_process, current_task};
use crate::timer::{get_time_ms, add_timer}; use crate::timer::{add_timer, get_time_ms};
use alloc::sync::Arc; use alloc::sync::Arc;
pub fn sys_sleep(ms: usize) -> isize { pub fn sys_sleep(ms: usize) -> isize {
@ -13,21 +13,23 @@ pub fn sys_sleep(ms: usize) -> isize {
pub fn sys_mutex_create(blocking: bool) -> isize { pub fn sys_mutex_create(blocking: bool) -> isize {
let process = current_process(); let process = current_process();
let mutex: Option<Arc<dyn Mutex>> = if !blocking {
Some(Arc::new(MutexSpin::new()))
} else {
Some(Arc::new(MutexBlocking::new()))
};
let mut process_inner = process.inner_exclusive_access(); let mut process_inner = process.inner_exclusive_access();
if let Some(id) = process_inner if let Some(id) = process_inner
.mutex_list .mutex_list
.iter() .iter()
.enumerate() .enumerate()
.find(|(_, item)| item.is_none()) .find(|(_, item)| item.is_none())
.map(|(id, _)| id) { .map(|(id, _)| id)
process_inner.mutex_list[id] = if !blocking { {
Some(Arc::new(MutexSpin::new())) process_inner.mutex_list[id] = mutex;
} else {
Some(Arc::new(MutexBlocking::new()))
};
id as isize id as isize
} else { } else {
process_inner.mutex_list.push(Some(Arc::new(MutexSpin::new()))); process_inner.mutex_list.push(mutex);
process_inner.mutex_list.len() as isize - 1 process_inner.mutex_list.len() as isize - 1
} }
} }
@ -52,7 +54,7 @@ pub fn sys_mutex_unlock(mutex_id: usize) -> isize {
0 0
} }
pub fn sys_semaphore_creare(res_count: usize) -> isize { pub fn sys_semaphore_create(res_count: usize) -> isize {
let process = current_process(); let process = current_process();
let mut process_inner = process.inner_exclusive_access(); let mut process_inner = process.inner_exclusive_access();
let id = if let Some(id) = process_inner let id = if let Some(id) = process_inner
@ -60,11 +62,14 @@ pub fn sys_semaphore_creare(res_count: usize) -> isize {
.iter() .iter()
.enumerate() .enumerate()
.find(|(_, item)| item.is_none()) .find(|(_, item)| item.is_none())
.map(|(id, _)| id) { .map(|(id, _)| id)
{
process_inner.semaphore_list[id] = Some(Arc::new(Semaphore::new(res_count))); process_inner.semaphore_list[id] = Some(Arc::new(Semaphore::new(res_count)));
id id
} else { } else {
process_inner.semaphore_list.push(Some(Arc::new(Semaphore::new(res_count)))); process_inner
.semaphore_list
.push(Some(Arc::new(Semaphore::new(res_count))));
process_inner.semaphore_list.len() - 1 process_inner.semaphore_list.len() - 1
}; };
id as isize id as isize
@ -87,3 +92,43 @@ pub fn sys_semaphore_down(sem_id: usize) -> isize {
sem.down(); sem.down();
0 0
} }
pub fn sys_condvar_create(_arg: usize) -> isize {
let process = current_process();
let mut process_inner = process.inner_exclusive_access();
let id = if let Some(id) = process_inner
.condvar_list
.iter()
.enumerate()
.find(|(_, item)| item.is_none())
.map(|(id, _)| id)
{
process_inner.condvar_list[id] = Some(Arc::new(Condvar::new()));
id
} else {
process_inner
.condvar_list
.push(Some(Arc::new(Condvar::new())));
process_inner.condvar_list.len() - 1
};
id as isize
}
pub fn sys_condvar_signal(condvar_id: usize) -> isize {
let process = current_process();
let process_inner = process.inner_exclusive_access();
let condvar = Arc::clone(process_inner.condvar_list[condvar_id].as_ref().unwrap());
drop(process_inner);
condvar.signal();
0
}
pub fn sys_condvar_wait(condvar_id: usize, mutex_id: usize) -> isize {
let process = current_process();
let process_inner = process.inner_exclusive_access();
let condvar = Arc::clone(process_inner.condvar_list[condvar_id].as_ref().unwrap());
let mutex = Arc::clone(process_inner.mutex_list[mutex_id].as_ref().unwrap());
drop(process_inner);
condvar.wait_with_mutex(mutex);
0
}

View file

@ -1,5 +1,9 @@
use crate::{
mm::kernel_token,
task::{add_task, current_task, TaskControlBlock},
trap::{trap_handler, TrapContext},
};
use alloc::sync::Arc; use alloc::sync::Arc;
use crate::{mm::kernel_token, task::{TaskControlBlock, add_task, current_task}, trap::{TrapContext, trap_handler}};
pub fn sys_thread_create(entry: usize, arg: usize) -> isize { pub fn sys_thread_create(entry: usize, arg: usize) -> isize {
let task = current_task().unwrap(); let task = current_task().unwrap();
@ -7,7 +11,11 @@ pub fn sys_thread_create(entry: usize, arg: usize) -> isize {
// create a new thread // create a new thread
let new_task = Arc::new(TaskControlBlock::new( let new_task = Arc::new(TaskControlBlock::new(
Arc::clone(&process), Arc::clone(&process),
task.inner_exclusive_access().res.as_ref().unwrap().ustack_base, task.inner_exclusive_access()
.res
.as_ref()
.unwrap()
.ustack_base,
true, true,
)); ));
// add new task to scheduler // add new task to scheduler
@ -35,7 +43,13 @@ pub fn sys_thread_create(entry: usize, arg: usize) -> isize {
} }
pub fn sys_gettid() -> isize { pub fn sys_gettid() -> isize {
current_task().unwrap().inner_exclusive_access().res.as_ref().unwrap().tid as isize current_task()
.unwrap()
.inner_exclusive_access()
.res
.as_ref()
.unwrap()
.tid as isize
} }
/// thread does not exist, return -1 /// thread does not exist, return -1

View file

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

View file

@ -1,9 +1,12 @@
use alloc::{vec::Vec, sync::{Arc, Weak}};
use lazy_static::*;
use crate::sync::UPSafeCell;
use crate::mm::{KERNEL_SPACE, MapPermission, PhysPageNum, VirtAddr};
use crate::config::{KERNEL_STACK_SIZE, PAGE_SIZE, TRAMPOLINE, TRAP_CONTEXT_BASE, USER_STACK_SIZE};
use super::ProcessControlBlock; use super::ProcessControlBlock;
use crate::config::{KERNEL_STACK_SIZE, PAGE_SIZE, TRAMPOLINE, TRAP_CONTEXT_BASE, USER_STACK_SIZE};
use crate::mm::{MapPermission, PhysPageNum, VirtAddr, KERNEL_SPACE};
use crate::sync::UPIntrFreeCell;
use alloc::{
sync::{Arc, Weak},
vec::Vec,
};
use lazy_static::*;
pub struct RecycleAllocator { pub struct RecycleAllocator {
current: usize, current: usize,
@ -28,23 +31,23 @@ impl RecycleAllocator {
pub fn dealloc(&mut self, id: usize) { pub fn dealloc(&mut self, id: usize) {
assert!(id < self.current); assert!(id < self.current);
assert!( assert!(
self.recycled.iter().find(|i| **i == id).is_none(), !self.recycled.iter().any(|i| *i == id),
"id {} has been deallocated!", id "id {} has been deallocated!",
id
); );
self.recycled.push(id); self.recycled.push(id);
} }
} }
lazy_static! { lazy_static! {
static ref PID_ALLOCATOR: UPSafeCell<RecycleAllocator> = unsafe { static ref PID_ALLOCATOR: UPIntrFreeCell<RecycleAllocator> =
UPSafeCell::new(RecycleAllocator::new()) unsafe { UPIntrFreeCell::new(RecycleAllocator::new()) };
}; static ref KSTACK_ALLOCATOR: UPIntrFreeCell<RecycleAllocator> =
unsafe { UPIntrFreeCell::new(RecycleAllocator::new()) };
static ref KSTACK_ALLOCATOR: UPSafeCell<RecycleAllocator> = unsafe {
UPSafeCell::new(RecycleAllocator::new())
};
} }
pub const IDLE_PID: usize = 0;
pub struct PidHandle(pub usize); pub struct PidHandle(pub usize);
pub fn pid_alloc() -> PidHandle { pub fn pid_alloc() -> PidHandle {
@ -69,9 +72,7 @@ pub struct KernelStack(pub usize);
pub fn kstack_alloc() -> KernelStack { pub fn kstack_alloc() -> KernelStack {
let kstack_id = KSTACK_ALLOCATOR.exclusive_access().alloc(); let kstack_id = KSTACK_ALLOCATOR.exclusive_access().alloc();
let (kstack_bottom, kstack_top) = kernel_stack_position(kstack_id); let (kstack_bottom, kstack_top) = kernel_stack_position(kstack_id);
KERNEL_SPACE KERNEL_SPACE.exclusive_access().insert_framed_area(
.exclusive_access()
.insert_framed_area(
kstack_bottom.into(), kstack_bottom.into(),
kstack_top.into(), kstack_top.into(),
MapPermission::R | MapPermission::W, MapPermission::R | MapPermission::W,
@ -91,11 +92,15 @@ impl Drop for KernelStack {
impl KernelStack { impl KernelStack {
#[allow(unused)] #[allow(unused)]
pub fn push_on_top<T>(&self, value: T) -> *mut T where pub fn push_on_top<T>(&self, value: T) -> *mut T
T: Sized, { where
T: Sized,
{
let kernel_stack_top = self.get_top(); let kernel_stack_top = self.get_top();
let ptr_mut = (kernel_stack_top - core::mem::size_of::<T>()) as *mut T; let ptr_mut = (kernel_stack_top - core::mem::size_of::<T>()) as *mut T;
unsafe { *ptr_mut = value; } unsafe {
*ptr_mut = value;
}
ptr_mut ptr_mut
} }
pub fn get_top(&self) -> usize { pub fn get_top(&self) -> usize {
@ -142,9 +147,7 @@ impl TaskUserRes {
// alloc user stack // alloc user stack
let ustack_bottom = ustack_bottom_from_tid(self.ustack_base, self.tid); let ustack_bottom = ustack_bottom_from_tid(self.ustack_base, self.tid);
let ustack_top = ustack_bottom + USER_STACK_SIZE; let ustack_top = ustack_bottom + USER_STACK_SIZE;
process_inner process_inner.memory_set.insert_framed_area(
.memory_set
.insert_framed_area(
ustack_bottom.into(), ustack_bottom.into(),
ustack_top.into(), ustack_top.into(),
MapPermission::R | MapPermission::W | MapPermission::U, MapPermission::R | MapPermission::W | MapPermission::U,
@ -152,9 +155,7 @@ impl TaskUserRes {
// alloc trap_cx // alloc trap_cx
let trap_cx_bottom = trap_cx_bottom_from_tid(self.tid); let trap_cx_bottom = trap_cx_bottom_from_tid(self.tid);
let trap_cx_top = trap_cx_bottom + PAGE_SIZE; let trap_cx_top = trap_cx_bottom + PAGE_SIZE;
process_inner process_inner.memory_set.insert_framed_area(
.memory_set
.insert_framed_area(
trap_cx_bottom.into(), trap_cx_bottom.into(),
trap_cx_top.into(), trap_cx_top.into(),
MapPermission::R | MapPermission::W, MapPermission::R | MapPermission::W,
@ -167,10 +168,14 @@ impl TaskUserRes {
let mut process_inner = process.inner_exclusive_access(); let mut process_inner = process.inner_exclusive_access();
// dealloc ustack manually // dealloc ustack manually
let ustack_bottom_va: VirtAddr = ustack_bottom_from_tid(self.ustack_base, self.tid).into(); let ustack_bottom_va: VirtAddr = ustack_bottom_from_tid(self.ustack_base, self.tid).into();
process_inner.memory_set.remove_area_with_start_vpn(ustack_bottom_va.into()); process_inner
.memory_set
.remove_area_with_start_vpn(ustack_bottom_va.into());
// dealloc trap_cx manually // dealloc trap_cx manually
let trap_cx_bottom_va: VirtAddr = trap_cx_bottom_from_tid(self.tid).into(); let trap_cx_bottom_va: VirtAddr = trap_cx_bottom_from_tid(self.tid).into();
process_inner.memory_set.remove_area_with_start_vpn(trap_cx_bottom_va.into()); process_inner
.memory_set
.remove_area_with_start_vpn(trap_cx_bottom_va.into());
} }
#[allow(unused)] #[allow(unused)]
@ -197,10 +202,16 @@ impl TaskUserRes {
let process = self.process.upgrade().unwrap(); let process = self.process.upgrade().unwrap();
let process_inner = process.inner_exclusive_access(); let process_inner = process.inner_exclusive_access();
let trap_cx_bottom_va: VirtAddr = trap_cx_bottom_from_tid(self.tid).into(); let trap_cx_bottom_va: VirtAddr = trap_cx_bottom_from_tid(self.tid).into();
process_inner.memory_set.translate(trap_cx_bottom_va.into()).unwrap().ppn() process_inner
.memory_set
.translate(trap_cx_bottom_va.into())
.unwrap()
.ppn()
} }
pub fn ustack_base(&self) -> usize { self.ustack_base } pub fn ustack_base(&self) -> usize {
self.ustack_base
}
pub fn ustack_top(&self) -> usize { pub fn ustack_top(&self) -> usize {
ustack_bottom_from_tid(self.ustack_base, self.tid) + USER_STACK_SIZE ustack_bottom_from_tid(self.ustack_base, self.tid) + USER_STACK_SIZE
} }
@ -212,4 +223,3 @@ impl Drop for TaskUserRes {
self.dealloc_user_res(); self.dealloc_user_res();
} }
} }

View file

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

View file

@ -1,38 +1,30 @@
mod context; mod context;
mod switch;
mod task;
mod manager;
mod processor;
mod id; mod id;
mod manager;
mod process; mod process;
mod processor;
mod signal;
mod switch;
#[allow(clippy::module_inception)]
mod task;
use self::id::TaskUserRes;
use crate::fs::{open_file, OpenFlags}; use crate::fs::{open_file, OpenFlags};
use switch::__switch; use alloc::{sync::Arc, vec::Vec};
use alloc::sync::Arc;
use manager::fetch_task;
use lazy_static::*; use lazy_static::*;
use manager::fetch_task;
use process::ProcessControlBlock; use process::ProcessControlBlock;
use switch::__switch;
pub use context::TaskContext; pub use context::TaskContext;
pub use id::{kstack_alloc, pid_alloc, KernelStack, PidHandle, IDLE_PID};
pub use manager::{add_task, pid2process, remove_from_pid2process};
pub use processor::{ pub use processor::{
run_tasks, current_kstack_top, current_process, current_task, current_trap_cx, current_trap_cx_user_va,
current_task, current_user_token, run_tasks, schedule, take_current_task,
current_process,
current_user_token,
current_trap_cx_user_va,
current_trap_cx,
current_kstack_top,
take_current_task,
schedule,
}; };
pub use signal::SignalFlags;
pub use task::{TaskControlBlock, TaskStatus}; pub use task::{TaskControlBlock, TaskStatus};
pub use manager::add_task;
pub use id::{
PidHandle,
pid_alloc,
KernelStack,
kstack_alloc,
};
pub fn suspend_current_and_run_next() { pub fn suspend_current_and_run_next() {
// There must be an application running. // There must be an application running.
@ -52,12 +44,16 @@ pub fn suspend_current_and_run_next() {
schedule(task_cx_ptr); schedule(task_cx_ptr);
} }
pub fn block_current_and_run_next() { /// This function must be followed by a schedule
pub fn block_current_task() -> *mut TaskContext {
let task = take_current_task().unwrap(); let task = take_current_task().unwrap();
let mut task_inner = task.inner_exclusive_access(); let mut task_inner = task.inner_exclusive_access();
let task_cx_ptr = &mut task_inner.task_cx as *mut TaskContext;
task_inner.task_status = TaskStatus::Blocking; task_inner.task_status = TaskStatus::Blocking;
drop(task_inner); &mut task_inner.task_cx as *mut TaskContext
}
pub fn block_current_and_run_next() {
let task_cx_ptr = block_current_task();
schedule(task_cx_ptr); schedule(task_cx_ptr);
} }
@ -76,6 +72,19 @@ pub fn exit_current_and_run_next(exit_code: i32) {
// however, if this is the main thread of current process // however, if this is the main thread of current process
// the process should terminate at once // the process should terminate at once
if tid == 0 { if tid == 0 {
let pid = process.getpid();
if pid == IDLE_PID {
println!(
"[kernel] Idle process exit with exit_code {} ...",
exit_code
);
if exit_code != 0 {
crate::sbi::shutdown(255); //255 == -1 for err hint
} else {
crate::sbi::shutdown(0); //0 for success hint
}
}
remove_from_pid2process(pid);
let mut process_inner = process.inner_exclusive_access(); let mut process_inner = process.inner_exclusive_access();
// mark this process as a zombie process // mark this process as a zombie process
process_inner.is_zombie = true; process_inner.is_zombie = true;
@ -94,15 +103,26 @@ pub fn exit_current_and_run_next(exit_code: i32) {
// deallocate user res (including tid/trap_cx/ustack) of all threads // deallocate user res (including tid/trap_cx/ustack) of all threads
// it has to be done before we dealloc the whole memory_set // it has to be done before we dealloc the whole memory_set
// otherwise they will be deallocated twice // otherwise they will be deallocated twice
let mut recycle_res = Vec::<TaskUserRes>::new();
for task in process_inner.tasks.iter().filter(|t| t.is_some()) { for task in process_inner.tasks.iter().filter(|t| t.is_some()) {
let task = task.as_ref().unwrap(); let task = task.as_ref().unwrap();
let mut task_inner = task.inner_exclusive_access(); let mut task_inner = task.inner_exclusive_access();
task_inner.res = None; if let Some(res) = task_inner.res.take() {
recycle_res.push(res);
} }
}
// dealloc_tid and dealloc_user_res require access to PCB inner, so we
// need to collect those user res first, then release process_inner
// for now to avoid deadlock/double borrow problem.
drop(process_inner);
recycle_res.clear();
let mut process_inner = process.inner_exclusive_access();
process_inner.children.clear(); process_inner.children.clear();
// deallocate other data in user space i.e. program code/data section // deallocate other data in user space i.e. program code/data section
process_inner.memory_set.recycle_data_pages(); process_inner.memory_set.recycle_data_pages();
// drop file descriptors
process_inner.fd_table.clear();
} }
drop(process); drop(process);
// we do not have to save task context // we do not have to save task context
@ -121,3 +141,15 @@ lazy_static! {
pub fn add_initproc() { pub fn add_initproc() {
let _initproc = INITPROC.clone(); let _initproc = INITPROC.clone();
} }
pub fn check_signals_of_current() -> Option<(i32, &'static str)> {
let process = current_process();
let process_inner = process.inner_exclusive_access();
process_inner.signals.check_error()
}
pub fn current_add_signal(signal: SignalFlags) {
let process = current_process();
let mut process_inner = process.inner_exclusive_access();
process_inner.signals |= signal;
}

View file

@ -1,26 +1,22 @@
use crate::mm::{
MemorySet,
KERNEL_SPACE,
translated_refmut,
};
use crate::trap::{TrapContext, trap_handler};
use crate::sync::{UPSafeCell, Mutex, Semaphore};
use core::cell::RefMut;
use super::id::RecycleAllocator; use super::id::RecycleAllocator;
use super::manager::insert_into_pid2process;
use super::TaskControlBlock; use super::TaskControlBlock;
use super::{PidHandle, pid_alloc}; use super::{add_task, SignalFlags};
use super::add_task; use super::{pid_alloc, PidHandle};
use alloc::sync::{Weak, Arc}; use crate::fs::{File, Stdin, Stdout};
use crate::mm::{translated_refmut, MemorySet, KERNEL_SPACE};
use crate::sync::{Condvar, Mutex, Semaphore, UPIntrFreeCell, UPIntrRefMut};
use crate::trap::{trap_handler, TrapContext};
use alloc::string::String;
use alloc::sync::{Arc, Weak};
use alloc::vec; use alloc::vec;
use alloc::vec::Vec; use alloc::vec::Vec;
use alloc::string::String;
use crate::fs::{File, Stdin, Stdout};
pub struct ProcessControlBlock { pub struct ProcessControlBlock {
// immutable // immutable
pub pid: PidHandle, pub pid: PidHandle,
// mutable // mutable
inner: UPSafeCell<ProcessControlBlockInner>, inner: UPIntrFreeCell<ProcessControlBlockInner>,
} }
pub struct ProcessControlBlockInner { pub struct ProcessControlBlockInner {
@ -30,10 +26,12 @@ pub struct ProcessControlBlockInner {
pub children: Vec<Arc<ProcessControlBlock>>, pub children: Vec<Arc<ProcessControlBlock>>,
pub exit_code: i32, pub exit_code: i32,
pub fd_table: Vec<Option<Arc<dyn File + Send + Sync>>>, pub fd_table: Vec<Option<Arc<dyn File + Send + Sync>>>,
pub signals: SignalFlags,
pub tasks: Vec<Option<Arc<TaskControlBlock>>>, pub tasks: Vec<Option<Arc<TaskControlBlock>>>,
pub task_res_allocator: RecycleAllocator, pub task_res_allocator: RecycleAllocator,
pub mutex_list: Vec<Option<Arc<dyn Mutex>>>, pub mutex_list: Vec<Option<Arc<dyn Mutex>>>,
pub semaphore_list: Vec<Option<Arc<Semaphore>>>, pub semaphore_list: Vec<Option<Arc<Semaphore>>>,
pub condvar_list: Vec<Option<Arc<Condvar>>>,
} }
impl ProcessControlBlockInner { impl ProcessControlBlockInner {
@ -43,8 +41,7 @@ impl ProcessControlBlockInner {
} }
pub fn alloc_fd(&mut self) -> usize { pub fn alloc_fd(&mut self) -> usize {
if let Some(fd) = (0..self.fd_table.len()) if let Some(fd) = (0..self.fd_table.len()).find(|fd| self.fd_table[*fd].is_none()) {
.find(|fd| self.fd_table[*fd].is_none()) {
fd fd
} else { } else {
self.fd_table.push(None); self.fd_table.push(None);
@ -56,7 +53,7 @@ impl ProcessControlBlockInner {
self.task_res_allocator.alloc() self.task_res_allocator.alloc()
} }
pub fn dealloc_tid(&mut self, tid: usize){ pub fn dealloc_tid(&mut self, tid: usize) {
self.task_res_allocator.dealloc(tid) self.task_res_allocator.dealloc(tid)
} }
@ -70,7 +67,7 @@ impl ProcessControlBlockInner {
} }
impl ProcessControlBlock { impl ProcessControlBlock {
pub fn inner_exclusive_access(&self) -> RefMut<'_, ProcessControlBlockInner> { pub fn inner_exclusive_access(&self) -> UPIntrRefMut<'_, ProcessControlBlockInner> {
self.inner.exclusive_access() self.inner.exclusive_access()
} }
@ -81,7 +78,8 @@ impl ProcessControlBlock {
let pid_handle = pid_alloc(); let pid_handle = pid_alloc();
let process = Arc::new(Self { let process = Arc::new(Self {
pid: pid_handle, pid: pid_handle,
inner: unsafe { UPSafeCell::new(ProcessControlBlockInner { inner: unsafe {
UPIntrFreeCell::new(ProcessControlBlockInner {
is_zombie: false, is_zombie: false,
memory_set, memory_set,
parent: None, parent: None,
@ -95,11 +93,14 @@ impl ProcessControlBlock {
// 2 -> stderr // 2 -> stderr
Some(Arc::new(Stdout)), Some(Arc::new(Stdout)),
], ],
signals: SignalFlags::empty(),
tasks: Vec::new(), tasks: Vec::new(),
task_res_allocator: RecycleAllocator::new(), task_res_allocator: RecycleAllocator::new(),
mutex_list: Vec::new(), mutex_list: Vec::new(),
semaphore_list: Vec::new(), semaphore_list: Vec::new(),
})} condvar_list: Vec::new(),
})
},
}); });
// create a main thread, we should allocate ustack and trap_cx here // create a main thread, we should allocate ustack and trap_cx here
let task = Arc::new(TaskControlBlock::new( let task = Arc::new(TaskControlBlock::new(
@ -124,6 +125,7 @@ impl ProcessControlBlock {
let mut process_inner = process.inner_exclusive_access(); let mut process_inner = process.inner_exclusive_access();
process_inner.tasks.push(Some(Arc::clone(&task))); process_inner.tasks.push(Some(Arc::clone(&task)));
drop(process_inner); drop(process_inner);
insert_into_pid2process(process.getpid(), Arc::clone(&process));
// add main thread to scheduler // add main thread to scheduler
add_task(task); add_task(task);
process process
@ -152,7 +154,7 @@ impl ProcessControlBlock {
.map(|arg| { .map(|arg| {
translated_refmut( translated_refmut(
new_token, new_token,
(argv_base + arg * core::mem::size_of::<usize>()) as *mut usize (argv_base + arg * core::mem::size_of::<usize>()) as *mut usize,
) )
}) })
.collect(); .collect();
@ -202,25 +204,35 @@ impl ProcessControlBlock {
// create child process pcb // create child process pcb
let child = Arc::new(Self { let child = Arc::new(Self {
pid, pid,
inner: unsafe { UPSafeCell::new(ProcessControlBlockInner { inner: unsafe {
UPIntrFreeCell::new(ProcessControlBlockInner {
is_zombie: false, is_zombie: false,
memory_set, memory_set,
parent: Some(Arc::downgrade(self)), parent: Some(Arc::downgrade(self)),
children: Vec::new(), children: Vec::new(),
exit_code: 0, exit_code: 0,
fd_table: new_fd_table, fd_table: new_fd_table,
signals: SignalFlags::empty(),
tasks: Vec::new(), tasks: Vec::new(),
task_res_allocator: RecycleAllocator::new(), task_res_allocator: RecycleAllocator::new(),
mutex_list: Vec::new(), mutex_list: Vec::new(),
semaphore_list: Vec::new(), semaphore_list: Vec::new(),
})} condvar_list: Vec::new(),
})
},
}); });
// add child // add child
parent.children.push(Arc::clone(&child)); parent.children.push(Arc::clone(&child));
// create main thread of child process // create main thread of child process
let task = Arc::new(TaskControlBlock::new( let task = Arc::new(TaskControlBlock::new(
Arc::clone(&child), Arc::clone(&child),
parent.get_task(0).inner_exclusive_access().res.as_ref().unwrap().ustack_base(), parent
.get_task(0)
.inner_exclusive_access()
.res
.as_ref()
.unwrap()
.ustack_base(),
// here we do not allocate trap_cx or ustack again // here we do not allocate trap_cx or ustack again
// but mention that we allocate a new kstack here // but mention that we allocate a new kstack here
false, false,
@ -234,6 +246,7 @@ impl ProcessControlBlock {
let trap_cx = task_inner.get_trap_cx(); let trap_cx = task_inner.get_trap_cx();
trap_cx.kernel_sp = task.kstack.get_top(); trap_cx.kernel_sp = task.kstack.get_top();
drop(task_inner); drop(task_inner);
insert_into_pid2process(child.getpid(), Arc::clone(&child));
// add this thread to scheduler // add this thread to scheduler
add_task(task); add_task(task);
child child
@ -243,4 +256,3 @@ impl ProcessControlBlock {
self.pid.0 self.pid.0
} }
} }

View file

@ -1,10 +1,10 @@
use super::{TaskContext, TaskControlBlock, ProcessControlBlock}; use super::__switch;
use super::{fetch_task, TaskStatus};
use super::{ProcessControlBlock, TaskContext, TaskControlBlock};
use crate::sync::UPIntrFreeCell;
use crate::trap::TrapContext;
use alloc::sync::Arc; use alloc::sync::Arc;
use lazy_static::*; use lazy_static::*;
use super::{fetch_task, TaskStatus};
use super::__switch;
use crate::trap::TrapContext;
use crate::sync::UPSafeCell;
pub struct Processor { pub struct Processor {
current: Option<Arc<TaskControlBlock>>, current: Option<Arc<TaskControlBlock>>,
@ -25,14 +25,13 @@ impl Processor {
self.current.take() self.current.take()
} }
pub fn current(&self) -> Option<Arc<TaskControlBlock>> { 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! { lazy_static! {
pub static ref PROCESSOR: UPSafeCell<Processor> = unsafe { pub static ref PROCESSOR: UPIntrFreeCell<Processor> =
UPSafeCell::new(Processor::new()) unsafe { UPIntrFreeCell::new(Processor::new()) };
};
} }
pub fn run_tasks() { pub fn run_tasks() {
@ -41,19 +40,15 @@ pub fn run_tasks() {
if let Some(task) = fetch_task() { if let Some(task) = fetch_task() {
let idle_task_cx_ptr = processor.get_idle_task_cx_ptr(); let idle_task_cx_ptr = processor.get_idle_task_cx_ptr();
// access coming task TCB exclusively // access coming task TCB exclusively
let mut task_inner = task.inner_exclusive_access(); let next_task_cx_ptr = task.inner.exclusive_session(|task_inner| {
let next_task_cx_ptr = &task_inner.task_cx as *const TaskContext;
task_inner.task_status = TaskStatus::Running; task_inner.task_status = TaskStatus::Running;
drop(task_inner); &task_inner.task_cx as *const TaskContext
// release coming task TCB manually });
processor.current = Some(task); processor.current = Some(task);
// release processor manually // release processor manually
drop(processor); drop(processor);
unsafe { unsafe {
__switch( __switch(idle_task_cx_ptr, next_task_cx_ptr);
idle_task_cx_ptr,
next_task_cx_ptr,
);
} }
} else { } else {
println!("no tasks available in run_tasks"); println!("no tasks available in run_tasks");
@ -75,12 +70,14 @@ pub fn current_process() -> Arc<ProcessControlBlock> {
pub fn current_user_token() -> usize { pub fn current_user_token() -> usize {
let task = current_task().unwrap(); let task = current_task().unwrap();
let token = task.get_user_token(); task.get_user_token()
token
} }
pub fn current_trap_cx() -> &'static mut TrapContext { pub fn current_trap_cx() -> &'static mut TrapContext {
current_task().unwrap().inner_exclusive_access().get_trap_cx() current_task()
.unwrap()
.inner_exclusive_access()
.get_trap_cx()
} }
pub fn current_trap_cx_user_va() -> usize { pub fn current_trap_cx_user_va() -> usize {
@ -94,20 +91,13 @@ pub fn current_trap_cx_user_va() -> usize {
} }
pub fn current_kstack_top() -> usize { pub fn current_kstack_top() -> usize {
current_task() current_task().unwrap().kstack.get_top()
.unwrap()
.kstack
.get_top()
} }
pub fn schedule(switched_task_cx_ptr: *mut TaskContext) { pub fn schedule(switched_task_cx_ptr: *mut TaskContext) {
let mut processor = PROCESSOR.exclusive_access(); let idle_task_cx_ptr =
let idle_task_cx_ptr = processor.get_idle_task_cx_ptr(); PROCESSOR.exclusive_session(|processor| processor.get_idle_task_cx_ptr());
drop(processor);
unsafe { unsafe {
__switch( __switch(switched_task_cx_ptr, idle_task_cx_ptr);
switched_task_cx_ptr,
idle_task_cx_ptr,
);
} }
} }

29
os/src/task/signal.rs Normal file
View file

@ -0,0 +1,29 @@
use bitflags::*;
bitflags! {
pub struct SignalFlags: u32 {
const SIGINT = 1 << 2;
const SIGILL = 1 << 4;
const SIGABRT = 1 << 6;
const SIGFPE = 1 << 8;
const SIGSEGV = 1 << 11;
}
}
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::SIGSEGV) {
Some((-11, "Segmentation Fault, SIGSEGV=11"))
} else {
None
}
}
}

View file

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

View file

@ -1,20 +1,22 @@
use alloc::sync::{Arc, Weak};
use crate::{mm::PhysPageNum, sync::UPSafeCell};
use crate::trap::TrapContext;
use super::id::TaskUserRes; use super::id::TaskUserRes;
use super::{KernelStack, ProcessControlBlock, TaskContext, kstack_alloc}; use super::{kstack_alloc, KernelStack, ProcessControlBlock, TaskContext};
use core::cell::RefMut; use crate::trap::TrapContext;
use crate::{
mm::PhysPageNum,
sync::{UPIntrFreeCell, UPIntrRefMut},
};
use alloc::sync::{Arc, Weak};
pub struct TaskControlBlock { pub struct TaskControlBlock {
// immutable // immutable
pub process: Weak<ProcessControlBlock>, pub process: Weak<ProcessControlBlock>,
pub kstack: KernelStack, pub kstack: KernelStack,
// mutable // mutable
inner: UPSafeCell<TaskControlBlockInner>, pub inner: UPIntrFreeCell<TaskControlBlockInner>,
} }
impl TaskControlBlock { impl TaskControlBlock {
pub fn inner_exclusive_access(&self) -> RefMut<'_, TaskControlBlockInner> { pub fn inner_exclusive_access(&self) -> UPIntrRefMut<'_, TaskControlBlockInner> {
self.inner.exclusive_access() self.inner.exclusive_access()
} }
@ -48,7 +50,7 @@ impl TaskControlBlock {
pub fn new( pub fn new(
process: Arc<ProcessControlBlock>, process: Arc<ProcessControlBlock>,
ustack_base: usize, ustack_base: usize,
alloc_user_res: bool alloc_user_res: bool,
) -> Self { ) -> Self {
let res = TaskUserRes::new(Arc::clone(&process), ustack_base, alloc_user_res); let res = TaskUserRes::new(Arc::clone(&process), ustack_base, alloc_user_res);
let trap_cx_ppn = res.trap_cx_ppn(); let trap_cx_ppn = res.trap_cx_ppn();
@ -57,15 +59,15 @@ impl TaskControlBlock {
Self { Self {
process: Arc::downgrade(&process), process: Arc::downgrade(&process),
kstack, kstack,
inner: unsafe { UPSafeCell::new( inner: unsafe {
TaskControlBlockInner { UPIntrFreeCell::new(TaskControlBlockInner {
res: Some(res), res: Some(res),
trap_cx_ppn, trap_cx_ppn,
task_cx: TaskContext::goto_trap_return(kstack_top), task_cx: TaskContext::goto_trap_return(kstack_top),
task_status: TaskStatus::Ready, task_status: TaskStatus::Ready,
exit_code: None, exit_code: None,
} })
)}, },
} }
} }
} }

View file

@ -1,13 +1,13 @@
use core::cmp::Ordering; use core::cmp::Ordering;
use riscv::register::time;
use crate::sbi::set_timer;
use crate::config::CLOCK_FREQ; use crate::config::CLOCK_FREQ;
use crate::task::{TaskControlBlock, add_task}; use crate::sbi::set_timer;
use crate::sync::UPSafeCell; use crate::sync::UPIntrFreeCell;
use crate::task::{add_task, TaskControlBlock};
use alloc::collections::BinaryHeap; use alloc::collections::BinaryHeap;
use alloc::sync::Arc; use alloc::sync::Arc;
use lazy_static::*; use lazy_static::*;
use riscv::register::time;
const TICKS_PER_SEC: usize = 100; const TICKS_PER_SEC: usize = 100;
const MSEC_PER_SEC: usize = 1000; const MSEC_PER_SEC: usize = 1000;
@ -50,17 +50,13 @@ impl Ord for TimerCondVar {
} }
lazy_static! { lazy_static! {
static ref TIMERS: UPSafeCell<BinaryHeap<TimerCondVar>> = unsafe { UPSafeCell::new( static ref TIMERS: UPIntrFreeCell<BinaryHeap<TimerCondVar>> =
BinaryHeap::<TimerCondVar>::new() unsafe { UPIntrFreeCell::new(BinaryHeap::<TimerCondVar>::new()) };
)};
} }
pub fn add_timer(expire_ms: usize, task: Arc<TaskControlBlock>) { pub fn add_timer(expire_ms: usize, task: Arc<TaskControlBlock>) {
let mut timers = TIMERS.exclusive_access(); let mut timers = TIMERS.exclusive_access();
timers.push(TimerCondVar { timers.push(TimerCondVar { expire_ms, task });
expire_ms,
task,
});
} }
pub fn check_timer() { pub fn check_timer() {
@ -69,8 +65,9 @@ pub fn check_timer() {
while let Some(timer) = timers.peek() { while let Some(timer) = timers.peek() {
if timer.expire_ms <= current_ms { if timer.expire_ms <= current_ms {
add_task(Arc::clone(&timer.task)); add_task(Arc::clone(&timer.task));
drop(timer);
timers.pop(); timers.pop();
} else { break; } } else {
break;
}
} }
} }

View file

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

View file

@ -1,27 +1,18 @@
mod context; mod context;
use riscv::register::{ use crate::config::TRAMPOLINE;
mtvec::TrapMode,
stvec,
scause::{
self,
Trap,
Exception,
Interrupt,
},
stval,
sie,
};
use crate::syscall::syscall; use crate::syscall::syscall;
use crate::task::{ use crate::task::{
exit_current_and_run_next, check_signals_of_current, current_add_signal, current_trap_cx, current_trap_cx_user_va,
suspend_current_and_run_next, current_user_token, exit_current_and_run_next, suspend_current_and_run_next, SignalFlags,
current_user_token, };
current_trap_cx, use crate::timer::{check_timer, set_next_trigger};
current_trap_cx_user_va, use core::arch::{asm, global_asm};
use riscv::register::{
mtvec::TrapMode,
scause::{self, Exception, Interrupt, Trap},
sie, sscratch, sstatus, stval, stvec,
}; };
use crate::timer::{set_next_trigger, check_timer};
use crate::config::TRAMPOLINE;
global_asm!(include_str!("trap.S")); global_asm!(include_str!("trap.S"));
@ -30,8 +21,14 @@ pub fn init() {
} }
fn set_kernel_trap_entry() { fn set_kernel_trap_entry() {
extern "C" {
fn __alltraps();
fn __alltraps_k();
}
let __alltraps_k_va = __alltraps_k as usize - __alltraps as usize + TRAMPOLINE;
unsafe { unsafe {
stvec::write(trap_from_kernel as usize, TrapMode::Direct); stvec::write(__alltraps_k_va, TrapMode::Direct);
sscratch::write(trap_from_kernel as usize);
} }
} }
@ -42,7 +39,21 @@ fn set_user_trap_entry() {
} }
pub fn enable_timer_interrupt() { pub fn enable_timer_interrupt() {
unsafe { sie::set_stimer(); } unsafe {
sie::set_stimer();
}
}
fn enable_supervisor_interrupt() {
unsafe {
sstatus::set_sie();
}
}
fn disable_supervisor_interrupt() {
unsafe {
sstatus::clear_sie();
}
} }
#[no_mangle] #[no_mangle]
@ -50,52 +61,67 @@ pub fn trap_handler() -> ! {
set_kernel_trap_entry(); set_kernel_trap_entry();
let scause = scause::read(); let scause = scause::read();
let stval = stval::read(); let stval = stval::read();
//println!("into {:?}", scause.cause());
match scause.cause() { match scause.cause() {
Trap::Exception(Exception::UserEnvCall) => { Trap::Exception(Exception::UserEnvCall) => {
// jump to next instruction anyway // jump to next instruction anyway
let mut cx = current_trap_cx(); let mut cx = current_trap_cx();
cx.sepc += 4; cx.sepc += 4;
enable_supervisor_interrupt();
// get system call return value // get system call return value
let result = syscall(cx.x[17], [cx.x[10], cx.x[11], cx.x[12]]); let result = syscall(cx.x[17], [cx.x[10], cx.x[11], cx.x[12]]);
// cx is changed during sys_exec, so we have to call it again // cx is changed during sys_exec, so we have to call it again
cx = current_trap_cx(); cx = current_trap_cx();
cx.x[10] = result as usize; cx.x[10] = result as usize;
} }
Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StoreFault)
Trap::Exception(Exception::StorePageFault) | | Trap::Exception(Exception::StorePageFault)
Trap::Exception(Exception::InstructionFault) | | Trap::Exception(Exception::InstructionFault)
Trap::Exception(Exception::InstructionPageFault) | | Trap::Exception(Exception::InstructionPageFault)
Trap::Exception(Exception::LoadFault) | | Trap::Exception(Exception::LoadFault)
Trap::Exception(Exception::LoadPageFault) => { | Trap::Exception(Exception::LoadPageFault) => {
/*
println!( println!(
"[kernel] {:?} in application, bad addr = {:#x}, bad instruction = {:#x}, core dumped.", "[kernel] {:?} in application, bad addr = {:#x}, bad instruction = {:#x}, kernel killed it.",
scause.cause(), scause.cause(),
stval, stval,
current_trap_cx().sepc, current_trap_cx().sepc,
); );
// page fault exit code */
exit_current_and_run_next(-2); current_add_signal(SignalFlags::SIGSEGV);
} }
Trap::Exception(Exception::IllegalInstruction) => { Trap::Exception(Exception::IllegalInstruction) => {
println!("[kernel] IllegalInstruction in application, core dumped."); current_add_signal(SignalFlags::SIGILL);
// illegal instruction exit code
exit_current_and_run_next(-3);
} }
Trap::Interrupt(Interrupt::SupervisorTimer) => { Trap::Interrupt(Interrupt::SupervisorTimer) => {
set_next_trigger(); set_next_trigger();
check_timer(); check_timer();
suspend_current_and_run_next(); suspend_current_and_run_next();
} }
Trap::Interrupt(Interrupt::SupervisorExternal) => {
crate::board::irq_handler();
}
_ => { _ => {
panic!("Unsupported trap {:?}, stval = {:#x}!", scause.cause(), stval); panic!(
"Unsupported trap {:?}, stval = {:#x}!",
scause.cause(),
stval
);
} }
} }
//println!("before trap_return"); // check signals
if let Some((errno, msg)) = check_signals_of_current() {
println!("[kernel] {}", msg);
exit_current_and_run_next(errno);
}
trap_return(); trap_return();
} }
#[no_mangle] #[no_mangle]
pub fn trap_return() -> ! { pub fn trap_return() -> ! {
disable_supervisor_interrupt();
set_user_trap_entry(); set_user_trap_entry();
let trap_cx_user_va = current_trap_cx_user_va(); let trap_cx_user_va = current_trap_cx_user_va();
let user_satp = current_user_token(); let user_satp = current_user_token();
@ -104,6 +130,7 @@ pub fn trap_return() -> ! {
fn __restore(); fn __restore();
} }
let restore_va = __restore as usize - __alltraps as usize + TRAMPOLINE; let restore_va = __restore as usize - __alltraps as usize + TRAMPOLINE;
//println!("before return");
unsafe { unsafe {
asm!( asm!(
"fence.i", "fence.i",
@ -117,10 +144,26 @@ pub fn trap_return() -> ! {
} }
#[no_mangle] #[no_mangle]
pub fn trap_from_kernel() -> ! { pub fn trap_from_kernel(_trap_cx: &TrapContext) {
use riscv::register::sepc; let scause = scause::read();
println!("stval = {:#x}, sepc = {:#x}", stval::read(), sepc::read()); let stval = stval::read();
panic!("a trap {:?} from kernel!", scause::read().cause()); match scause.cause() {
Trap::Interrupt(Interrupt::SupervisorExternal) => {
crate::board::irq_handler();
}
Trap::Interrupt(Interrupt::SupervisorTimer) => {
set_next_trigger();
check_timer();
// do not schedule now
}
_ => {
panic!(
"Unsupported trap from kernel: {:?}, stval = {:#x}!",
scause.cause(),
stval
);
}
}
} }
pub use context::TrapContext; pub use context::TrapContext;

View file

@ -8,6 +8,8 @@
.section .text.trampoline .section .text.trampoline
.globl __alltraps .globl __alltraps
.globl __restore .globl __restore
.globl __alltraps_k
.globl __restore_k
.align 2 .align 2
__alltraps: __alltraps:
csrrw sp, sscratch, sp csrrw sp, sscratch, sp
@ -67,3 +69,36 @@ __restore:
# back to user stack # back to user stack
ld sp, 2*8(sp) ld sp, 2*8(sp)
sret sret
.align 2
__alltraps_k:
addi sp, sp, -34*8
sd x1, 1*8(sp)
sd x3, 3*8(sp)
.set n, 5
.rept 27
SAVE_GP %n
.set n, n+1
.endr
csrr t0, sstatus
csrr t1, sepc
sd t0, 32*8(sp)
sd t1, 33*8(sp)
mv a0, sp
csrr t2, sscratch
jalr t2
__restore_k:
ld t0, 32*8(sp)
ld t1, 33*8(sp)
csrw sstatus, t0
csrw sepc, t1
ld x1, 1*8(sp)
ld x3, 3*8(sp)
.set n, 5
.rept 27
LOAD_GP %n
.set n, n+1
.endr
addi sp, sp, 34*8
sret

View file

@ -1 +1 @@
nightly-2021-10-15 nightly-2022-04-11

View file

@ -9,3 +9,7 @@ edition = "2018"
[dependencies] [dependencies]
buddy_system_allocator = "0.6" 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

View file

@ -8,9 +8,15 @@ BINS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%.bin, $(APPS))
OBJDUMP := rust-objdump --arch-name=riscv64 OBJDUMP := rust-objdump --arch-name=riscv64
OBJCOPY := rust-objcopy --binary-architecture=riscv64 OBJCOPY := rust-objcopy --binary-architecture=riscv64
CP := cp
TEST ?=
elf: $(APPS) elf: $(APPS)
@cargo build --release @cargo build --release
ifeq ($(TEST), 1)
@$(CP) $(TARGET_DIR)/usertests $(TARGET_DIR)/initproc
endif
binary: elf binary: elf
$(foreach elf, $(ELFS), $(OBJCOPY) $(elf) --strip-all -O binary $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.bin, $(elf));) $(foreach elf, $(ELFS), $(OBJCOPY) $(elf) --strip-all -O binary $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.bin, $(elf));)

View file

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

View file

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

View file

@ -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
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,56 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
extern crate alloc;
use alloc::{fmt::format, string::String, vec::Vec};
use user_lib::{close, get_time, gettid, open, write, OpenFlags};
use user_lib::{exit, thread_create, waittid};
fn worker(size_kib: usize) {
let mut buffer = [0u8; 1024]; // 1KiB
for (i, ch) in buffer.iter_mut().enumerate() {
*ch = i as u8;
}
let filename = format(format_args!("testf{}\0", gettid()));
let f = open(filename.as_str(), OpenFlags::CREATE | OpenFlags::WRONLY);
if f < 0 {
panic!("Open test file failed!");
}
let f = f as usize;
for _ in 0..size_kib {
write(f, &buffer);
}
close(f);
exit(0)
}
#[no_mangle]
pub fn main(argc: usize, argv: &[&str]) -> i32 {
assert_eq!(argc, 2, "wrong argument");
let size_mb = 1usize;
let size_kb = size_mb << 10;
let workers = argv[1].parse::<usize>().expect("wrong argument");
assert!(workers >= 1 && size_kb % workers == 0, "wrong argument");
let start = get_time();
let mut v = Vec::new();
let size_mb = 1usize;
for _ in 0..workers {
v.push(thread_create(worker as usize, size_kb / workers));
}
for tid in v.iter() {
assert_eq!(0, waittid(*tid as usize));
}
let time_ms = (get_time() - start) as usize;
let speed_kbs = size_kb * 1000 / time_ms;
println!(
"{}MiB written by {} threads, time cost = {}ms, write speed = {}KiB/s",
size_mb, workers, time_ms, speed_kbs
);
0
}

10
user/src/bin/infloop.rs Normal file
View file

@ -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 {}
}

View file

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

View file

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

View file

@ -1,15 +1,16 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#![allow(clippy::println_empty_string)]
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
extern crate alloc; extern crate alloc;
use user_lib::{semaphore_create, semaphore_up, semaphore_down};
use user_lib::{thread_create, waittid};
use user_lib::exit;
use alloc::vec::Vec; use alloc::vec::Vec;
use user_lib::exit;
use user_lib::{semaphore_create, semaphore_down, semaphore_up};
use user_lib::{thread_create, waittid};
const SEM_MUTEX: usize = 0; const SEM_MUTEX: usize = 0;
const SEM_EMPTY: usize = 1; const SEM_EMPTY: usize = 1;
@ -57,7 +58,10 @@ pub fn main() -> i32 {
let ids: Vec<_> = (0..PRODUCER_COUNT).collect(); let ids: Vec<_> = (0..PRODUCER_COUNT).collect();
let mut threads = Vec::new(); let mut threads = Vec::new();
for i in 0..PRODUCER_COUNT { for i in 0..PRODUCER_COUNT {
threads.push(thread_create(producer as usize, &ids.as_slice()[i] as *const _ as usize)); threads.push(thread_create(
producer as usize,
&ids.as_slice()[i] as *const _ as usize,
));
} }
threads.push(thread_create(consumer as usize, 0)); threads.push(thread_create(consumer as usize, 0));
// wait for all threads to complete // wait for all threads to complete

View file

@ -1,14 +1,15 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#![allow(clippy::println_empty_string)]
#[macro_use] #[macro_use]
extern crate user_lib; extern crate user_lib;
extern crate alloc; extern crate alloc;
use alloc::vec::Vec;
use user_lib::{exit, get_time, sleep};
use user_lib::{mutex_blocking_create, mutex_lock, mutex_unlock}; use user_lib::{mutex_blocking_create, mutex_lock, mutex_unlock};
use user_lib::{thread_create, waittid}; use user_lib::{thread_create, waittid};
use user_lib::{sleep, exit, get_time};
use alloc::vec::Vec;
const N: usize = 5; const N: usize = 5;
const ROUND: usize = 4; const ROUND: usize = 4;
@ -38,16 +39,24 @@ fn philosopher_dining_problem(id: *const usize) {
let max = left + right - min; let max = left + right - min;
for round in 0..ROUND { for round in 0..ROUND {
// thinking // thinking
unsafe { THINK[id][2 * round] = get_time_u(); } unsafe {
THINK[id][2 * round] = get_time_u();
}
sleep(ARR[id][2 * round]); sleep(ARR[id][2 * round]);
unsafe { THINK[id][2 * round + 1] = get_time_u(); } unsafe {
THINK[id][2 * round + 1] = get_time_u();
}
// wait for forks // wait for forks
mutex_lock(min); mutex_lock(min);
mutex_lock(max); mutex_lock(max);
// eating // eating
unsafe { EAT[id][2 * round] = get_time_u(); } unsafe {
EAT[id][2 * round] = get_time_u();
}
sleep(ARR[id][2 * round + 1]); sleep(ARR[id][2 * round + 1]);
unsafe { EAT[id][2 * round + 1] = get_time_u(); } unsafe {
EAT[id][2 * round + 1] = get_time_u();
}
mutex_unlock(max); mutex_unlock(max);
mutex_unlock(min); mutex_unlock(min);
} }
@ -61,7 +70,10 @@ pub fn main() -> i32 {
let start = get_time_u(); let start = get_time_u();
for i in 0..N { for i in 0..N {
assert_eq!(mutex_blocking_create(), i as isize); assert_eq!(mutex_blocking_create(), i as isize);
v.push(thread_create(philosopher_dining_problem as usize, &ids.as_slice()[i] as *const _ as usize)); v.push(thread_create(
philosopher_dining_problem as usize,
&ids.as_slice()[i] as *const _ as usize,
));
} }
for tid in v.iter() { for tid in v.iter() {
waittid(*tid as usize); waittid(*tid as usize);
@ -71,19 +83,19 @@ pub fn main() -> i32 {
println!("'-' -> THINKING; 'x' -> EATING; ' ' -> WAITING "); println!("'-' -> THINKING; 'x' -> EATING; ' ' -> WAITING ");
for id in (0..N).into_iter().chain(0..=0) { for id in (0..N).into_iter().chain(0..=0) {
print!("#{}:", id); print!("#{}:", id);
for j in 0..time_cost/GRAPH_SCALE { for j in 0..time_cost / GRAPH_SCALE {
let current_time = j * GRAPH_SCALE + start; let current_time = j * GRAPH_SCALE + start;
if (0..ROUND).find(|round| unsafe { if (0..ROUND).any(|round| unsafe {
let start_thinking = THINK[id][2 * round]; let start_thinking = THINK[id][2 * round];
let end_thinking = THINK[id][2 * round + 1]; let end_thinking = THINK[id][2 * round + 1];
start_thinking <= current_time && current_time <= end_thinking start_thinking <= current_time && current_time <= end_thinking
}).is_some() { }) {
print!("-"); print!("-");
} else if (0..ROUND).find(|round| unsafe { } else if (0..ROUND).any(|round| unsafe {
let start_eating = EAT[id][2 * round]; let start_eating = EAT[id][2 * round];
let end_eating = EAT[id][2 * round + 1]; let end_eating = EAT[id][2 * round + 1];
start_eating <= current_time && current_time <= end_eating start_eating <= current_time && current_time <= end_eating
}).is_some() { }) {
print!("x"); print!("x");
} else { } else {
print!(" "); print!(" ");

View file

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

View file

@ -4,7 +4,7 @@
#[macro_use] #[macro_use]
extern crate user_lib; 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!"; static STR: &str = "Hello, world!";

17
user/src/bin/priv_csr.rs Normal file
View file

@ -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
}

17
user/src/bin/priv_inst.rs Normal file
View file

@ -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
}

View file

@ -5,8 +5,8 @@
extern crate user_lib; extern crate user_lib;
extern crate alloc; extern crate alloc;
use user_lib::{exit, thread_create, waittid, get_time};
use alloc::vec::Vec; use alloc::vec::Vec;
use user_lib::{exit, get_time, thread_create, waittid};
static mut A: usize = 0; static mut A: usize = 0;
const PER_THREAD: usize = 1000; const PER_THREAD: usize = 1000;
@ -17,7 +17,9 @@ unsafe fn f() -> ! {
for _ in 0..PER_THREAD { for _ in 0..PER_THREAD {
let a = &mut A as *mut usize; let a = &mut A as *mut usize;
let cur = a.read_volatile(); let cur = a.read_volatile();
for _ in 0..500 { t = t * t % 10007; } for _ in 0..500 {
t = t * t % 10007;
}
a.write_volatile(cur + 1); a.write_volatile(cur + 1);
} }
exit(t as i32) exit(t as i32)

View file

@ -0,0 +1,56 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
extern crate alloc;
use crate::alloc::string::ToString;
use alloc::vec::Vec;
use user_lib::{exit, get_time, thread_create, waittid};
static mut A: usize = 0;
const PER_THREAD: usize = 1000;
const THREAD_COUNT: usize = 16;
unsafe fn f(count: usize) -> ! {
let mut t = 2usize;
for _ in 0..PER_THREAD {
let a = &mut A as *mut usize;
let cur = a.read_volatile();
for _ in 0..count {
t = t * t % 10007;
}
a.write_volatile(cur + 1);
}
exit(t as i32)
}
#[no_mangle]
pub fn main(argc: usize, argv: &[&str]) -> i32 {
let count: usize;
if argc == 1 {
count = THREAD_COUNT;
} else if argc == 2 {
count = argv[1].to_string().parse::<usize>().unwrap();
} else {
println!(
"ERROR in argv, argc is {}, argv[0] {} , argv[1] {} , argv[2] {}",
argc, argv[0], argv[1], argv[2]
);
exit(-1);
}
let start = get_time();
let mut v = Vec::new();
for _ in 0..THREAD_COUNT {
v.push(thread_create(f as usize, count) as usize);
}
let mut time_cost = Vec::new();
for tid in v.iter() {
time_cost.push(waittid(*tid));
}
println!("time cost is {}ms", get_time() - start);
assert_eq!(unsafe { A }, PER_THREAD * THREAD_COUNT);
0
}

View file

@ -5,9 +5,9 @@
extern crate user_lib; extern crate user_lib;
extern crate alloc; extern crate alloc;
use user_lib::{exit, thread_create, waittid, get_time, yield_};
use alloc::vec::Vec; use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, Ordering}; use core::sync::atomic::{AtomicBool, Ordering};
use user_lib::{exit, get_time, thread_create, waittid, yield_};
static mut A: usize = 0; static mut A: usize = 0;
static OCCUPIED: AtomicBool = AtomicBool::new(false); static OCCUPIED: AtomicBool = AtomicBool::new(false);
@ -17,12 +17,17 @@ const THREAD_COUNT: usize = 16;
unsafe fn f() -> ! { unsafe fn f() -> ! {
let mut t = 2usize; let mut t = 2usize;
for _ in 0..PER_THREAD { for _ in 0..PER_THREAD {
while OCCUPIED.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed).is_err() { while OCCUPIED
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
yield_(); yield_();
} }
let a = &mut A as *mut usize; let a = &mut A as *mut usize;
let cur = a.read_volatile(); let cur = a.read_volatile();
for _ in 0..500 { t = t * t % 10007; } for _ in 0..500 {
t = t * t % 10007;
}
a.write_volatile(cur + 1); a.write_volatile(cur + 1);
OCCUPIED.store(false, Ordering::Relaxed); OCCUPIED.store(false, Ordering::Relaxed);
} }

View file

@ -5,8 +5,8 @@
extern crate user_lib; extern crate user_lib;
extern crate alloc; extern crate alloc;
use user_lib::{exit, thread_create, waittid, get_time, yield_};
use alloc::vec::Vec; use alloc::vec::Vec;
use user_lib::{exit, get_time, thread_create, waittid, yield_};
static mut A: usize = 0; static mut A: usize = 0;
static mut OCCUPIED: bool = false; static mut OCCUPIED: bool = false;
@ -16,12 +16,16 @@ const THREAD_COUNT: usize = 16;
unsafe fn f() -> ! { unsafe fn f() -> ! {
let mut t = 2usize; let mut t = 2usize;
for _ in 0..PER_THREAD { for _ in 0..PER_THREAD {
while OCCUPIED { yield_(); } while OCCUPIED {
yield_();
}
OCCUPIED = true; OCCUPIED = true;
// enter critical section // enter critical section
let a = &mut A as *mut usize; let a = &mut A as *mut usize;
let cur = a.read_volatile(); let cur = a.read_volatile();
for _ in 0..500 { t = t * t % 10007; } for _ in 0..500 {
t = t * t % 10007;
}
a.write_volatile(cur + 1); a.write_volatile(cur + 1);
// exit critical section // exit critical section
OCCUPIED = false; OCCUPIED = false;

View file

@ -5,9 +5,9 @@
extern crate user_lib; extern crate user_lib;
extern crate alloc; extern crate alloc;
use user_lib::{exit, thread_create, waittid, get_time};
use user_lib::{mutex_blocking_create, mutex_lock, mutex_unlock};
use alloc::vec::Vec; use alloc::vec::Vec;
use user_lib::{exit, get_time, thread_create, waittid};
use user_lib::{mutex_blocking_create, mutex_lock, mutex_unlock};
static mut A: usize = 0; static mut A: usize = 0;
const PER_THREAD: usize = 1000; const PER_THREAD: usize = 1000;
@ -19,7 +19,9 @@ unsafe fn f() -> ! {
mutex_lock(0); mutex_lock(0);
let a = &mut A as *mut usize; let a = &mut A as *mut usize;
let cur = a.read_volatile(); let cur = a.read_volatile();
for _ in 0..500 { t = t * t % 10007; } for _ in 0..500 {
t = t * t % 10007;
}
a.write_volatile(cur + 1); a.write_volatile(cur + 1);
mutex_unlock(0); mutex_unlock(0);
} }

View file

@ -5,9 +5,9 @@
extern crate user_lib; extern crate user_lib;
extern crate alloc; extern crate alloc;
use user_lib::{exit, thread_create, waittid, get_time};
use user_lib::{mutex_create, mutex_lock, mutex_unlock};
use alloc::vec::Vec; use alloc::vec::Vec;
use user_lib::{exit, get_time, thread_create, waittid};
use user_lib::{mutex_create, mutex_lock, mutex_unlock};
static mut A: usize = 0; static mut A: usize = 0;
const PER_THREAD: usize = 1000; const PER_THREAD: usize = 1000;
@ -19,7 +19,9 @@ unsafe fn f() -> ! {
mutex_lock(0); mutex_lock(0);
let a = &mut A as *mut usize; let a = &mut A as *mut usize;
let cur = a.read_volatile(); let cur = a.read_volatile();
for _ in 0..500 { t = t * t % 10007; } for _ in 0..500 {
t = t * t % 10007;
}
a.write_volatile(cur + 1); a.write_volatile(cur + 1);
mutex_unlock(0); mutex_unlock(0);
} }

View file

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

View file

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

View file

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

View file

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

View file

@ -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
}

45
user/src/bin/sync_sem.rs Normal file
View file

@ -0,0 +1,45 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
extern crate alloc;
use alloc::vec;
use user_lib::exit;
use user_lib::{semaphore_create, semaphore_down, semaphore_up};
use user_lib::{sleep, thread_create, waittid};
const SEM_SYNC: usize = 0;
unsafe fn first() -> ! {
sleep(10);
println!("First work and wakeup Second");
semaphore_up(SEM_SYNC);
exit(0)
}
unsafe fn second() -> ! {
println!("Second want to continue,but need to wait first");
semaphore_down(SEM_SYNC);
println!("Second can work now");
exit(0)
}
#[no_mangle]
pub fn main() -> i32 {
// create semaphores
assert_eq!(semaphore_create(0) as usize, SEM_SYNC);
// create threads
let threads = vec![
thread_create(first as usize, 0),
thread_create(second as usize, 0),
];
// wait for all threads to complete
for thread in threads.iter() {
waittid(*thread as usize);
}
println!("sync_sem passed!");
0
}

View file

@ -0,0 +1,59 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
extern crate alloc;
use alloc::vec;
use user_lib::exit;
use user_lib::{
condvar_create, condvar_signal, condvar_wait, mutex_blocking_create, mutex_lock, mutex_unlock,
};
use user_lib::{sleep, thread_create, waittid};
static mut A: usize = 0;
const CONDVAR_ID: usize = 0;
const MUTEX_ID: usize = 0;
unsafe fn first() -> ! {
sleep(10);
println!("First work, Change A --> 1 and wakeup Second");
mutex_lock(MUTEX_ID);
A = 1;
condvar_signal(CONDVAR_ID);
mutex_unlock(MUTEX_ID);
exit(0)
}
unsafe fn second() -> ! {
println!("Second want to continue,but need to wait A=1");
mutex_lock(MUTEX_ID);
while A == 0 {
println!("Second: A is {}", A);
condvar_wait(CONDVAR_ID, MUTEX_ID);
}
mutex_unlock(MUTEX_ID);
println!("A is {}, Second can work now", A);
exit(0)
}
#[no_mangle]
pub fn main() -> i32 {
// create condvar & mutex
assert_eq!(condvar_create() as usize, CONDVAR_ID);
assert_eq!(mutex_blocking_create() as usize, MUTEX_ID);
// create threads
let threads = vec![
thread_create(first as usize, 0),
thread_create(second as usize, 0),
];
// wait for all threads to complete
for thread in threads.iter() {
waittid(*thread as usize);
}
println!("test_condvar passed!");
0
}

View file

@ -5,30 +5,37 @@
extern crate user_lib; extern crate user_lib;
extern crate alloc; extern crate alloc;
use user_lib::{thread_create, waittid, exit}; use alloc::vec;
use alloc::vec::Vec; use user_lib::{exit, thread_create, waittid};
pub fn thread_a() -> ! { pub fn thread_a() -> ! {
for _ in 0..1000 { print!("a"); } for _ in 0..1000 {
print!("a");
}
exit(1) exit(1)
} }
pub fn thread_b() -> ! { pub fn thread_b() -> ! {
for _ in 0..1000 { print!("b"); } for _ in 0..1000 {
print!("b");
}
exit(2) exit(2)
} }
pub fn thread_c() -> ! { pub fn thread_c() -> ! {
for _ in 0..1000 { print!("c"); } for _ in 0..1000 {
print!("c");
}
exit(3) exit(3)
} }
#[no_mangle] #[no_mangle]
pub fn main() -> i32 { pub fn main() -> i32 {
let mut v = Vec::new(); let v = vec![
v.push(thread_create(thread_a as usize, 0)); thread_create(thread_a as usize, 0),
v.push(thread_create(thread_b as usize, 0)); thread_create(thread_b as usize, 0),
v.push(thread_create(thread_c as usize, 0)); thread_create(thread_c as usize, 0),
];
for tid in v.iter() { for tid in v.iter() {
let exit_code = waittid(*tid as usize); let exit_code = waittid(*tid as usize);
println!("thread#{} exited with code {}", tid, exit_code); println!("thread#{} exited with code {}", tid, exit_code);

Some files were not shown because too many files have changed in this diff Show more