Compare commits

..

26 Commits

Author SHA1 Message Date
Yu Chen 21bae8b034 add cargo fmt in Makefile, and exec make fmt
3 years ago
Yu Chen a773a977e7 udpate README
3 years ago
chyyuu d52256baa9
Merge pull request #78 from CL8192/forktree-fix
3 years ago
cl8192 7c83dd49e7 wait child exit in forktree
3 years ago
Yu Chen 9a95c7dcb4 update usr apps: usertests.rs cat.rs. now all apps in usertests can run correctly
3 years ago
chyyuu cc10cd10eb
Merge pull request #77 from CL8192/dev
3 years ago
yuoo655 b732da242d initiatively exit child in forktree
3 years ago
Yu Chen ca997784ab add comments for qemu-exit
3 years ago
Yu Chen a85cb98743 add VIRT_TEST support for qemu exit with exit_code, for CI autotest
3 years ago
Yu Chen 31a2873a61 update rustsbi-qemu 'commit id:c1761f2' :: setup PMP addr[base:0x0010_0000, len: 0x0000_2000] for VIRT_TEST/RTC
3 years ago
Yu Chen 1371aab236 add more apps for test
3 years ago
chyyuu e615ae4483
Merge pull request #45 from DeathWish5/main
3 years ago
chyyuu 18d4a89ab7
Merge branch 'main' into main
3 years ago
Yu Chen c234d1417b fix bug in sbi_shutdown
3 years ago
Yu Chen cf00c3ae5d update github CI for autotest
3 years ago
chyyuu 87cd106b67
Merge pull request #75 from CL8192/main
3 years ago
chyyuu 3d5e9ed9e6
Merge branch 'main' into main
3 years ago
chyyuu 2bd092dd64
Merge pull request #74 from YdrMaster/main
3 years ago
yuoo655 07675fcd00 add ci tests update usertests
3 years ago
YdrMaster c9a288c110 ci: cache qemu
3 years ago
Yu Chen 8e73480c99 cargo fmt
3 years ago
Yu Chen 8657b656e5 rust-toolchain nightly-2020-04-11
3 years ago
DeathWish5 1afa429e93 feat: CI run tests
3 years ago
DeathWish5 045c47e4ef user: add critical test for software-synchronous tests
4 years ago
DeathWish5 97fdd4f2a2 Merge branch 'main' of https://github.com/rcore-os/rCore-Tutorial-v3 into main
4 years ago
DeathWish5 22db3123d8 user: add peterson algorithm and Eisenberg & McGuire algorithm
4 years ago

@ -9,37 +9,58 @@ jobs:
build-doc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- 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: |
rustup target add riscv64gc-unknown-none-elf
rustup component add llvm-tools-preview
rustup component add rust-src
cd os
cargo doc --no-deps --verbose
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@v2
- 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
[ ! -d qemu-6.1.0 ] && wget https://download.qemu.org/qemu-6.1.0.tar.xz \
&& tar xJf qemu-6.1.0.tar.xz > /dev/null \
&& cd qemu-6.1.0 && ./configure --target-list=riscv64-softmmu && cd ..
cd qemu-6.1.0 && sudo make install -j
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
- name: Run usertests
run: cd os && make run TEST=1
timeout-minutes: 10

19
.gitignore vendored

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

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

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

@ -3,6 +3,8 @@ rCore-Tutorial version 3.5. See the [Documentation in Chinese](https://rcore-os.
rCore-Tutorial API Docs. See the [API Docs of Ten OSes ](#OS-API-DOCS)
If you don't know Rust Language and try to learn it, please visit [Rust Learning Resources](https://github.com/rcore-os/rCore/wiki/study-resource-of-system-programming-in-RUST)
Official QQ group number: 735045051
## news

Binary file not shown.

@ -1,9 +1,10 @@
pub const CLOCK_FREQ: usize = 12500000;
pub const MMIO: &[(usize, usize)] = &[
(0x1000_0000, 0x1000),
(0x1000_1000, 0x1000),
(0xC00_0000, 0x40_0000),
(0x1000_0000, 0x1000), // VIRT_UART0 in virt machine
(0x1000_1000, 0x1000), // VIRT_VIRTIO in virt machine
(0x0C00_0000, 0x40_0000), // VIRT_PLIC in virt machine
(0x0010_0000, 0x00_2000), // VIRT_TEST/RTC in virt machine
];
pub type BlockDeviceImpl = crate::drivers::block::VirtIOBlock;
@ -43,3 +44,83 @@ pub fn irq_handler() {
}
plic.complete(0, IntrTargetPriority::Supervisor, intr_src_id);
}
//ref:: https://github.com/andre-richter/qemu-exit
use core::arch::asm;
const EXIT_SUCCESS: u32 = 0x5555; // Equals `exit(0)`. qemu successful exit
const EXIT_FAILURE_FLAG: u32 = 0x3333;
const EXIT_FAILURE: u32 = exit_code_encode(1); // Equals `exit(1)`. qemu failed exit
const EXIT_RESET: u32 = 0x7777; // qemu reset
pub trait QEMUExit {
/// Exit with specified return code.
///
/// Note: For `X86`, code is binary-OR'ed with `0x1` inside QEMU.
fn exit(&self, code: u32) -> !;
/// Exit QEMU using `EXIT_SUCCESS`, aka `0`, if possible.
///
/// Note: Not possible for `X86`.
fn exit_success(&self) -> !;
/// Exit QEMU using `EXIT_FAILURE`, aka `1`.
fn exit_failure(&self) -> !;
}
/// RISCV64 configuration
pub struct RISCV64 {
/// Address of the sifive_test mapped device.
addr: u64,
}
/// Encode the exit code using EXIT_FAILURE_FLAG.
const fn exit_code_encode(code: u32) -> u32 {
(code << 16) | EXIT_FAILURE_FLAG
}
impl RISCV64 {
/// Create an instance.
pub const fn new(addr: u64) -> Self {
RISCV64 { addr }
}
}
impl QEMUExit for RISCV64 {
/// Exit qemu with specified exit code.
fn exit(&self, code: u32) -> ! {
// If code is not a special value, we need to encode it with EXIT_FAILURE_FLAG.
let code_new = match code {
EXIT_SUCCESS | EXIT_FAILURE | EXIT_RESET => code,
_ => exit_code_encode(code),
};
unsafe {
asm!(
"sw {0}, 0({1})",
in(reg)code_new, in(reg)self.addr
);
// For the case that the QEMU exit attempt did not work, transition into an infinite
// loop. Calling `panic!()` here is unfeasible, since there is a good chance
// this function here is the last expression in the `panic!()` handler
// itself. This prevents a possible infinite loop.
loop {
asm!("wfi", options(nomem, nostack));
}
}
}
fn exit_success(&self) -> ! {
self.exit(EXIT_SUCCESS);
}
fn exit_failure(&self) -> ! {
self.exit(EXIT_FAILURE);
}
}
const VIRT_TEST: u64 = 0x100000;
pub const QEMU_EXIT_HANDLE: RISCV64 = RISCV64::new(VIRT_TEST);

@ -20,7 +20,8 @@ pub struct VirtIOBlock {
}
lazy_static! {
static ref QUEUE_FRAMES: UPIntrFreeCell<Vec<FrameTracker>> = unsafe { UPIntrFreeCell::new(Vec::new()) };
static ref QUEUE_FRAMES: UPIntrFreeCell<Vec<FrameTracker>> =
unsafe { UPIntrFreeCell::new(Vec::new()) };
}
impl BlockDevice for VirtIOBlock {

@ -1,7 +1,6 @@
///! 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;

@ -18,7 +18,7 @@ fn panic(info: &PanicInfo) -> ! {
unsafe {
backtrace();
}
shutdown()
shutdown(255)
}
unsafe fn backtrace() {

@ -46,7 +46,8 @@ use lazy_static::*;
use sync::UPIntrFreeCell;
lazy_static! {
pub static ref DEV_NON_BLOCKING_ACCESS: UPIntrFreeCell<bool> = unsafe { UPIntrFreeCell::new(false) };
pub static ref DEV_NON_BLOCKING_ACCESS: UPIntrFreeCell<bool> =
unsafe { UPIntrFreeCell::new(false) };
}
#[no_mangle]

@ -39,7 +39,9 @@ pub fn console_getchar() -> usize {
sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0)
}
pub fn shutdown() -> ! {
sbi_call(SBI_SHUTDOWN, 0, 0, 0);
use crate::board::QEMUExit;
pub fn shutdown(exit_code: usize) -> ! {
//sbi_call(SBI_SHUTDOWN, exit_code, 0, 0);
crate::board::QEMU_EXIT_HANDLE.exit_failure();
panic!("It should shutdown!");
}

@ -1,5 +1,8 @@
use crate::sync::{Mutex, UPIntrFreeCell};
use crate::task::{add_task, block_current_task, block_current_and_run_next, current_task, TaskControlBlock, TaskContext};
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 {

@ -1,7 +1,7 @@
use core::cell::{RefCell, RefMut, UnsafeCell};
use core::ops::{Deref, DerefMut};
use riscv::register::sstatus;
use lazy_static::*;
use riscv::register::sstatus;
/*
/// Wrap a static data structure inside it so that we are
@ -56,9 +56,8 @@ pub struct IntrMaskingInfo {
}
lazy_static! {
static ref INTR_MASKING_INFO: UPSafeCellRaw<IntrMaskingInfo> = unsafe {
UPSafeCellRaw::new(IntrMaskingInfo::new())
};
static ref INTR_MASKING_INFO: UPSafeCellRaw<IntrMaskingInfo> =
unsafe { UPSafeCellRaw::new(IntrMaskingInfo::new()) };
}
impl IntrMaskingInfo {
@ -71,7 +70,9 @@ impl IntrMaskingInfo {
pub fn enter(&mut self) {
let sie = sstatus::read().sie();
unsafe { sstatus::clear_sie(); }
unsafe {
sstatus::clear_sie();
}
if self.nested_level == 0 {
self.sie_before_masking = sie;
}
@ -81,7 +82,9 @@ impl IntrMaskingInfo {
pub fn exit(&mut self) {
self.nested_level -= 1;
if self.nested_level == 0 && self.sie_before_masking {
unsafe { sstatus::set_sie(); }
unsafe {
sstatus::set_sie();
}
}
}
}
@ -101,14 +104,17 @@ impl<T> UPIntrFreeCell<T> {
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 {
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())
}
@ -132,4 +138,3 @@ impl<'a, T> DerefMut for UPIntrRefMut<'a, T> {
self.0.as_mut().unwrap().deref_mut()
}
}

@ -26,7 +26,6 @@ pub use processor::{
pub use signal::SignalFlags;
pub use task::{TaskControlBlock, TaskStatus};
pub fn suspend_current_and_run_next() {
// There must be an application running.
let task = take_current_task().unwrap();
@ -54,10 +53,12 @@ pub fn block_current_task() -> *mut TaskContext {
}
pub fn block_current_and_run_next() {
let task_cx_ptr = block_current_task();
let task_cx_ptr = block_current_task();
schedule(task_cx_ptr);
}
use crate::board::QEMUExit;
pub fn exit_current_and_run_next(exit_code: i32) {
let task = take_current_task().unwrap();
let mut task_inner = task.inner_exclusive_access();
@ -75,8 +76,17 @@ pub fn exit_current_and_run_next(exit_code: i32) {
if tid == 0 {
let pid = process.getpid();
if pid == IDLE_PID {
println!("[kernel] Idle process exit ...");
crate::sbi::shutdown();
println!(
"[kernel] Idle process exit with exit_code {} ...",
exit_code
);
if exit_code != 0 {
//crate::sbi::shutdown(255); //255 == -1 for err hint
crate::board::QEMU_EXIT_HANDLE.exit_failure();
} else {
//crate::sbi::shutdown(0); //0 for success hint
crate::board::QEMU_EXIT_HANDLE.exit_success();
}
}
remove_from_pid2process(pid);
let mut process_inner = process.inner_exclusive_access();

@ -30,7 +30,8 @@ impl Processor {
}
lazy_static! {
pub static ref PROCESSOR: UPIntrFreeCell<Processor> = unsafe { UPIntrFreeCell::new(Processor::new()) };
pub static ref PROCESSOR: UPIntrFreeCell<Processor> =
unsafe { UPIntrFreeCell::new(Processor::new()) };
}
pub fn run_tasks() {
@ -94,9 +95,8 @@ pub fn current_kstack_top() -> usize {
}
pub fn schedule(switched_task_cx_ptr: *mut TaskContext) {
let idle_task_cx_ptr = PROCESSOR.exclusive_session(|processor| {
processor.get_idle_task_cx_ptr()
});
let idle_task_cx_ptr =
PROCESSOR.exclusive_session(|processor| processor.get_idle_task_cx_ptr());
unsafe {
__switch(switched_task_cx_ptr, idle_task_cx_ptr);
}

@ -1,7 +1,10 @@
use super::id::TaskUserRes;
use super::{kstack_alloc, KernelStack, ProcessControlBlock, TaskContext};
use crate::trap::TrapContext;
use crate::{mm::PhysPageNum, sync::{UPIntrFreeCell, UPIntrRefMut}};
use crate::{
mm::PhysPageNum,
sync::{UPIntrFreeCell, UPIntrRefMut},
};
use alloc::sync::{Arc, Weak};
pub struct TaskControlBlock {

@ -11,7 +11,7 @@ use core::arch::{asm, global_asm};
use riscv::register::{
mtvec::TrapMode,
scause::{self, Exception, Interrupt, Trap},
sie, stval, stvec, sstatus, sscratch,
sie, sscratch, sstatus, stval, stvec,
};
global_asm!(include_str!("trap.S"));
@ -23,7 +23,7 @@ pub fn init() {
fn set_kernel_trap_entry() {
extern "C" {
fn __alltraps();
fn __alltraps_k();
fn __alltraps_k();
}
let __alltraps_k_va = __alltraps_k as usize - __alltraps as usize + TRAMPOLINE;
unsafe {
@ -52,7 +52,7 @@ fn enable_supervisor_interrupt() {
fn disable_supervisor_interrupt() {
unsafe {
sstatus::clear_sie();
sstatus::clear_sie();
}
}
@ -67,7 +67,7 @@ pub fn trap_handler() -> ! {
// jump to next instruction anyway
let mut cx = current_trap_cx();
cx.sepc += 4;
enable_supervisor_interrupt();
// get system call return value
@ -150,19 +150,19 @@ pub fn trap_from_kernel(_trap_cx: &TrapContext) {
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
);
},
}
}
}

@ -1 +1 @@
nightly-2022-04-12
nightly-2022-04-11

@ -9,6 +9,10 @@ use user_lib::{close, open, read, OpenFlags};
#[no_mangle]
pub fn main(argc: usize, argv: &[&str]) -> i32 {
println!("argc = {}", argc);
for (i, arg) in argv.iter().enumerate() {
println!("argv[{}] = {}", i, arg);
}
assert!(argc == 2);
let fd = open(argv[1], OpenFlags::RDONLY);
if fd == -1 {

@ -0,0 +1,138 @@
#![no_std]
#![no_main]
#![feature(core_intrinsics)]
#[macro_use]
extern crate user_lib;
extern crate alloc;
extern crate core;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicUsize, Ordering};
use user_lib::{exit, sleep, thread_create, waittid};
const N: usize = 2;
const THREAD_NUM: usize = 10;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FlagState {
Out,
Want,
In,
}
static mut TURN: usize = 0;
static mut FLAG: [FlagState; THREAD_NUM] = [FlagState::Out; THREAD_NUM];
static GUARD: AtomicUsize = AtomicUsize::new(0);
fn critical_test_enter() {
assert_eq!(GUARD.fetch_add(1, Ordering::SeqCst), 0);
}
fn critical_test_claim() {
assert_eq!(GUARD.load(Ordering::SeqCst), 1);
}
fn critical_test_exit() {
assert_eq!(GUARD.fetch_sub(1, Ordering::SeqCst), 1);
}
fn eisenberg_enter_critical(id: usize) {
/* announce that we want to enter */
loop {
println!("Thread[{}] try enter", id);
vstore!(&FLAG[id], FlagState::Want);
loop {
/* check if any with higher priority is `Want` or `In` */
let mut prior_thread: Option<usize> = None;
let turn = vload!(&TURN);
let ring_id = if id < turn { id + THREAD_NUM } else { id };
// FLAG.iter() may lead to some errors, use for-loop instead
for i in turn..ring_id {
if vload!(&FLAG[i % THREAD_NUM]) != FlagState::Out {
prior_thread = Some(i % THREAD_NUM);
break;
}
}
if prior_thread.is_none() {
break;
}
println!(
"Thread[{}]: prior thread {} exist, sleep and retry",
id,
prior_thread.unwrap()
);
sleep(1);
}
/* now tentatively claim the resource */
vstore!(&FLAG[id], FlagState::In);
/* enforce the order of `claim` and `conflict check`*/
memory_fence!();
/* check if anthor thread is also `In`, which imply a conflict*/
let mut conflict = false;
for i in 0..THREAD_NUM {
if i != id && vload!(&FLAG[i]) == FlagState::In {
conflict = true;
}
}
if !conflict {
break;
}
println!("Thread[{}]: CONFLECT!", id);
/* no need to sleep */
}
/* clain the trun */
vstore!(&TURN, id);
println!("Thread[{}] enter", id);
}
fn eisenberg_exit_critical(id: usize) {
/* find next one who wants to enter and give the turn to it*/
let mut next = id;
let ring_id = id + THREAD_NUM;
for i in (id + 1)..ring_id {
let idx = i % THREAD_NUM;
if vload!(&FLAG[idx]) == FlagState::Want {
next = idx;
break;
}
}
vstore!(&TURN, next);
/* All done */
vstore!(&FLAG[id], FlagState::Out);
println!("Thread[{}] exit, give turn to {}", id, next);
}
pub fn thread_fn(id: usize) -> ! {
println!("Thread[{}] init.", id);
for _ in 0..N {
eisenberg_enter_critical(id);
critical_test_enter();
for _ in 0..3 {
critical_test_claim();
sleep(2);
}
critical_test_exit();
eisenberg_exit_critical(id);
}
exit(0)
}
#[no_mangle]
pub fn main() -> i32 {
let mut v = Vec::new();
// TODO: really shuffle
assert_eq!(THREAD_NUM, 10);
let shuffle: [usize; 10] = [0, 7, 4, 6, 2, 9, 8, 1, 3, 5];
for i in 0..THREAD_NUM {
v.push(thread_create(thread_fn as usize, shuffle[i]));
}
for tid in v.iter() {
let exit_code = waittid(*tid as usize);
assert_eq!(exit_code, 0, "thread conflict happened!");
println!("thread#{} exited with code {}", tid, exit_code);
}
println!("main thread exited.");
0
}

@ -4,7 +4,7 @@
#[macro_use]
extern crate user_lib;
use user_lib::{exit, fork, getpid, sleep, yield_};
use user_lib::{exit, fork, getpid, sleep, wait, yield_};
const DEPTH: usize = 4;
@ -27,11 +27,19 @@ fn fork_tree(cur: &str) {
println!("pid{}: {}", getpid(), cur);
fork_child(cur, '0');
fork_child(cur, '1');
let mut exit_code: i32 = 0;
for _ in 0..2 {
wait(&mut exit_code);
}
}
#[no_mangle]
pub fn main() -> i32 {
fork_tree("");
let mut exit_code: i32 = 0;
for _ in 0..2 {
wait(&mut exit_code);
}
sleep(3000);
0
}

@ -5,9 +5,9 @@
extern crate user_lib;
extern crate alloc;
use alloc::{vec::Vec, string::String, fmt::format};
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};
use user_lib::{close, get_time, open, write, OpenFlags, gettid};
fn worker(size_kib: usize) {
let mut buffer = [0u8; 1024]; // 1KiB
@ -17,11 +17,11 @@ fn worker(size_kib: usize) {
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!");
panic!("Open test file failed!");
}
let f = f as usize;
for _ in 0..size_kib {
write(f, &buffer);
write(f, &buffer);
}
close(f);
exit(0)
@ -34,18 +34,18 @@ pub fn main(argc: usize, argv: &[&str]) -> i32 {
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));
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!(

@ -0,0 +1,78 @@
#![no_std]
#![no_main]
#![feature(core_intrinsics)]
#![feature(asm)]
#[macro_use]
extern crate user_lib;
extern crate alloc;
extern crate core;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicUsize, Ordering};
use user_lib::{exit, sleep, thread_create, waittid};
const N: usize = 3;
static mut TURN: usize = 0;
static mut FLAG: [bool; 2] = [false; 2];
static GUARD: AtomicUsize = AtomicUsize::new(0);
fn critical_test_enter() {
assert_eq!(GUARD.fetch_add(1, Ordering::SeqCst), 0);
}
fn critical_test_claim() {
assert_eq!(GUARD.load(Ordering::SeqCst), 1);
}
fn critical_test_exit() {
assert_eq!(GUARD.fetch_sub(1, Ordering::SeqCst), 1);
}
fn peterson_enter_critical(id: usize, peer_id: usize) {
println!("Thread[{}] try enter", id);
vstore!(&FLAG[id], true);
vstore!(&TURN, peer_id);
memory_fence!();
while vload!(&FLAG[peer_id]) && vload!(&TURN) == peer_id {
println!("Thread[{}] enter fail", id);
sleep(1);
println!("Thread[{}] retry enter", id);
}
println!("Thread[{}] enter", id);
}
fn peterson_exit_critical(id: usize) {
vstore!(&FLAG[id], false);
println!("Thread[{}] exit", id);
}
pub fn thread_fn(id: usize) -> ! {
println!("Thread[{}] init.", id);
let peer_id: usize = id ^ 1;
for _ in 0..N {
peterson_enter_critical(id, peer_id);
critical_test_enter();
for _ in 0..3 {
critical_test_claim();
sleep(2);
}
critical_test_exit();
peterson_exit_critical(id);
}
exit(0)
}
#[no_mangle]
pub fn main() -> i32 {
let mut v = Vec::new();
v.push(thread_create(thread_fn as usize, 0));
// v.push(thread_create(thread_fn as usize, 1));
for tid in v.iter() {
let exit_code = waittid(*tid as usize);
assert_eq!(exit_code, 0, "thread conflict happened!");
println!("thread#{} exited with code {}", tid, exit_code);
}
println!("main thread exited.");
0
}

@ -34,7 +34,10 @@ pub fn main(argc: usize, argv: &[&str]) -> i32 {
} else if argc == 2 {
count = argv[1].to_string().parse::<usize>().unwrap();
} else {
println!("ERROR in argv");
println!(
"ERROR in argv, argc is {}, argv[0] {} , argv[1] {} , argv[2] {}",
argc, argv[0], argv[1], argv[2]
);
exit(-1);
}

@ -8,7 +8,7 @@ use user_lib::{exec, fork, wait};
#[no_mangle]
pub fn main() -> i32 {
for i in 0..1000 {
for i in 0..50 {
if fork() == 0 {
exec("pipe_large_test\0", &[core::ptr::null::<u8>()]);
} else {

@ -4,49 +4,138 @@
#[macro_use]
extern crate user_lib;
static SUCC_TESTS: &[&str] = &[
"exit\0",
"fantastic_text\0",
"forktest\0",
"forktest2\0",
"forktest_simple\0",
"hello_world\0",
"matrix\0",
"sleep\0",
"sleep_simple\0",
"yield\0",
// not in SUCC_TESTS & FAIL_TESTS
// count_lines, infloop, user_shell, usertests
// item of TESTS : app_name(argv_0), argv_1, argv_2, argv_3, exit_code
static SUCC_TESTS: &[(&str, &str, &str, &str, i32)] = &[
("filetest_simple\0", "\0", "\0", "\0", 0),
("cat\0", "filea\0", "\0", "\0", 0),
("cmdline_args\0", "1\0", "2\0", "3\0", 0),
("eisenberg\0", "\0", "\0", "\0", 0),
("exit\0", "\0", "\0", "\0", 0),
("fantastic_text\0", "\0", "\0", "\0", 0),
("forktest_simple\0", "\0", "\0", "\0", 0),
("forktest\0", "\0", "\0", "\0", 0),
("forktest2\0", "\0", "\0", "\0", 0),
("forktree\0", "\0", "\0", "\0", 0),
("hello_world\0", "\0", "\0", "\0", 0),
("huge_write\0", "\0", "\0", "\0", 0),
("matrix\0", "\0", "\0", "\0", 0),
("mpsc_sem\0", "\0", "\0", "\0", 0),
("peterson\0", "\0", "\0", "\0", 0),
("phil_din_mutex\0", "\0", "\0", "\0", 0),
("pipe_large_test\0", "\0", "\0", "\0", 0),
("pipetest\0", "\0", "\0", "\0", 0),
("race_adder_arg\0", "3\0", "\0", "\0", 0),
("race_adder_atomic\0", "\0", "\0", "\0", 0),
("race_adder_mutex_blocking\0", "\0", "\0", "\0", 0),
("race_adder_mutex_spin\0", "\0", "\0", "\0", 0),
("run_pipe_test\0", "\0", "\0", "\0", 0),
("sleep_simple\0", "\0", "\0", "\0", 0),
("sleep\0", "\0", "\0", "\0", 0),
("sleep_simple\0", "\0", "\0", "\0", 0),
("sync_sem\0", "\0", "\0", "\0", 0),
("test_condvar\0", "\0", "\0", "\0", 0),
("threads_arg\0", "\0", "\0", "\0", 0),
("threads\0", "\0", "\0", "\0", 0),
("yield\0", "\0", "\0", "\0", 0),
];
static FAIL_TESTS: &[&str] = &[
"stack_overflow\0",
static FAIL_TESTS: &[(&str, &str, &str, &str, i32)] = &[
("stack_overflow\0", "\0", "\0", "\0", -11),
("race_adder_loop\0", "\0", "\0", "\0", -6),
("priv_csr\0", "\0", "\0", "\0", -4),
("priv_inst\0", "\0", "\0", "\0", -4),
("store_fault\0", "\0", "\0", "\0", -11),
("until_timeout\0", "\0", "\0", "\0", -6),
("race_adder\0", "\0", "\0", "\0", -6),
("huge_write_mt\0", "\0", "\0", "\0", -6),
];
use user_lib::{exec, fork, waitpid};
fn run_tests<F: Fn(i32)>(tests: &[&str], judge: F) {
fn run_tests(tests: &[(&str, &str, &str, &str, i32)]) -> i32 {
let mut pass_num = 0;
let mut arr: [*const u8; 4] = [
core::ptr::null::<u8>(),
core::ptr::null::<u8>(),
core::ptr::null::<u8>(),
core::ptr::null::<u8>(),
];
for test in tests {
println!("Usertests: Running {}", test);
println!("Usertests: Running {}", test.0);
arr[0] = test.0.as_ptr();
if test.1 != "\0" {
arr[1] = test.1.as_ptr();
arr[2] = core::ptr::null::<u8>();
arr[3] = core::ptr::null::<u8>();
if test.2 != "\0" {
arr[2] = test.2.as_ptr();
arr[3] = core::ptr::null::<u8>();
if test.3 != "\0" {
arr[3] = test.3.as_ptr();
} else {
arr[3] = core::ptr::null::<u8>();
}
} else {
arr[2] = core::ptr::null::<u8>();
arr[3] = core::ptr::null::<u8>();
}
} else {
arr[1] = core::ptr::null::<u8>();
arr[2] = core::ptr::null::<u8>();
arr[3] = core::ptr::null::<u8>();
}
let pid = fork();
if pid == 0 {
exec(*test, &[core::ptr::null::<u8>()]);
exec(test.0, &arr[..]);
panic!("unreachable!");
} else {
let mut exit_code: i32 = Default::default();
let wait_pid = waitpid(pid as usize, &mut exit_code);
assert_eq!(pid, wait_pid);
judge(exit_code);
if exit_code == test.4 {
// summary apps with exit_code
pass_num = pass_num + 1;
}
println!(
"\x1b[32mUsertests: Test {} in Process {} exited with code {}\x1b[0m",
test, pid, exit_code
test.0, pid, exit_code
);
}
}
pass_num
}
#[no_mangle]
pub fn main() -> i32 {
run_tests(SUCC_TESTS, |code| assert!(code == 0));
run_tests(FAIL_TESTS, |code| assert!(code != 0));
println!("Usertests passed!");
0
let succ_num = run_tests(SUCC_TESTS);
let err_num = run_tests(FAIL_TESTS);
if succ_num == SUCC_TESTS.len() as i32 && err_num == FAIL_TESTS.len() as i32 {
println!(
"{} of sueecssed apps, {} of failed apps run correctly. \nUsertests passed!",
SUCC_TESTS.len(),
FAIL_TESTS.len()
);
return 0;
}
if succ_num != SUCC_TESTS.len() as i32 {
println!(
"all successed app_num is {} , but only passed {}",
SUCC_TESTS.len(),
succ_num
);
}
if err_num != FAIL_TESTS.len() as i32 {
println!(
"all failed app_num is {} , but only passed {}",
FAIL_TESTS.len(),
err_num
);
}
println!(" Usertests failed!");
return -1;
}

@ -2,6 +2,7 @@
#![feature(linkage)]
#![feature(panic_info_message)]
#![feature(alloc_error_handler)]
#![feature(core_intrinsics)]
#[macro_use]
pub mod console;
@ -197,3 +198,24 @@ pub fn condvar_signal(condvar_id: usize) {
pub fn condvar_wait(condvar_id: usize, mutex_id: usize) {
sys_condvar_wait(condvar_id, mutex_id);
}
#[macro_export]
macro_rules! vstore {
($var_ref: expr, $value: expr) => {
unsafe { core::intrinsics::volatile_store($var_ref as *const _ as _, $value) }
};
}
#[macro_export]
macro_rules! vload {
($var_ref: expr) => {
unsafe { core::intrinsics::volatile_load($var_ref as *const _ as _) }
};
}
#[macro_export]
macro_rules! memory_fence {
() => {
core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst)
};
}

Loading…
Cancel
Save